diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 36bb0650a36730fcd8c2da6c0e050d21d52a2960..c1fdabd1261da8726fb5e96ebef7b772b47278b5 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,11 +1,11 @@ stages: - build - - test variables: GIT_DEPTH: "3" SIMPLECOV: "true" RUST_BACKTRACE: "1" - RUSTFLAGS: "-D warnings" + RUSTFLAGS: "" + CARGOFLAGS: "" cache: key: "$CI_BUILD_NAME/$CI_BUILD_REF_NAME" untracked: true @@ -18,13 +18,20 @@ linux-stable: - tags - stable script: - - cargo build --release --verbose + - cargo build --release $CARGOFLAGS - strip target/release/parity - - md5sum target/release/parity >> checksum + - md5sum target/release/parity >> parity.md5 + - sh scripts/deb-build.sh amd64 + - cp target/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"_amd64.deb" + - md5sum "parity_"$VER"_amd64.deb" >> "parity_"$VER"_amd64.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/x86_64-unknown-linux-gnu/parity --body target/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-linux-gnu/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-linux-gnu/parity.md5 --body parity.md5 + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-linux-gnu/"parity_"$VER"_amd64.deb" --body "parity_"$VER"_amd64.deb" + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-linux-gnu/"parity_"$VER"_amd64.deb.md5" --body "parity_"$VER"_amd64.deb.md5" tags: - rust - rust-stable @@ -41,13 +48,20 @@ linux-stable-14.04: - tags - stable script: - - cargo build --release --verbose + - cargo build --release $CARGOFLAGS - strip target/release/parity - - md5sum target/release/parity >> checksum + - md5sum target/release/parity >> parity.md5 + - sh scripts/deb-build.sh amd64 + - cp target/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"_amd64.deb" + - md5sum "parity_"$VER"_amd64.deb" >> "parity_"$VER"_amd64.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/x86_64-unknown-ubuntu_14_04-gnu/parity --body target/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-ubuntu_14_04-gnu/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-ubuntu_14_04-gnu/parity.md5 --body parity.md5 + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-ubuntu_14_04-gnu/"parity_"$VER"_amd64.deb" --body "parity_"$VER"_amd64.deb" + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-ubuntu_14_04-gnu/"parity_"$VER"_amd64.deb.md5" --body "parity_"$VER"_amd64.deb.md5" tags: - rust - rust-14.04 @@ -64,7 +78,7 @@ linux-beta: - tags - stable script: - - cargo build --release --verbose + - cargo build --release $CARGOFLAGS - strip target/release/parity tags: - rust @@ -83,7 +97,7 @@ linux-nightly: - tags - stable script: - - cargo build --release --verbose + - cargo build --release $CARGOFLAGS - strip target/release/parity tags: - rust @@ -104,13 +118,13 @@ linux-centos: script: - export CXX="g++" - export CC="gcc" - - cargo build --release --verbose + - cargo build --release $CARGOFLAGS - strip target/release/parity - - md5sum target/release/parity >> checksum + - md5sum target/release/parity >> parity.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/x86_64-unknown-centos-gnu/parity --body target/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-centos-gnu/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-unknown-centos-gnu/parity.md5 --body parity.md5 tags: - rust - rust-centos @@ -127,18 +141,29 @@ linux-armv7: - tags - stable script: + - export CC=arm-linux-gnueabihf-gcc + - export CXX=arm-linux-gnueabihf-g++ + - export HOST_CC=gcc + - export HOST_CXX=g++ - rm -rf .cargo - mkdir -p .cargo - echo "[target.armv7-unknown-linux-gnueabihf]" >> .cargo/config - echo "linker= \"arm-linux-gnueabihf-gcc\"" >> .cargo/config - cat .cargo/config - - cargo build --target armv7-unknown-linux-gnueabihf --release --verbose + - cargo build --target armv7-unknown-linux-gnueabihf --release $CARGOFLAGS - arm-linux-gnueabihf-strip target/armv7-unknown-linux-gnueabihf/release/parity - - md5sum target/armv7-unknown-linux-gnueabihf/release/parity >> checksum + - md5sum target/armv7-unknown-linux-gnueabihf/release/parity >> parity.md5 + - sh scripts/deb-build.sh armhf + - cp target/armv7-unknown-linux-gnueabihf/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"_armhf.deb" + - md5sum "parity_"$VER"_armhf.deb" >> "parity_"$VER"_armhf.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/armv7-unknown-linux-gnueabihf/parity --body target/armv7-unknown-linux-gnueabihf/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/armv7-unknown-linux-gnueabihf/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/armv7-unknown-linux-gnueabihf/parity.md5 --body parity.md5 + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/armv7-unknown-linux-gnueabihf/"parity_"$VER"_armhf.deb" --body "parity_"$VER"_armhf.deb" + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/armv7-unknown-linux-gnueabihf/"parity_"$VER"_armhf.deb.md5" --body "parity_"$VER"_armhf.deb.md5" tags: - rust - rust-arm @@ -156,18 +181,29 @@ linux-arm: - tags - stable script: + - export CC=arm-linux-gnueabihf-gcc + - export CXX=arm-linux-gnueabihf-g++ + - export HOST_CC=gcc + - export HOST_CXX=g++ - rm -rf .cargo - mkdir -p .cargo - echo "[target.arm-unknown-linux-gnueabihf]" >> .cargo/config - echo "linker= \"arm-linux-gnueabihf-gcc\"" >> .cargo/config - cat .cargo/config - - cargo build --target arm-unknown-linux-gnueabihf --release --verbose + - cargo build --target arm-unknown-linux-gnueabihf --release $CARGOFLAGS - arm-linux-gnueabihf-strip target/arm-unknown-linux-gnueabihf/release/parity - - md5sum target/arm-unknown-linux-gnueabihf/release/parity >> checksum + - md5sum target/arm-unknown-linux-gnueabihf/release/parity >> parity.md5 + - sh scripts/deb-build.sh armhf + - cp target/arm-unknown-linux-gnueabihf/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"_armhf.deb" + - md5sum "parity_"$VER"_armhf.deb" >> "parity_"$VER"_armhf.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/arm-unknown-linux-gnueabihf/parity --body target/arm-unknown-linux-gnueabihf/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/arm-unknown-linux-gnueabihf/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/arm-unknown-linux-gnueabihf/parity.md5 --body parity.md5 + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/arm-unknown-linux-gnueabihf/"parity_"$VER"_armhf.deb" --body "parity_"$VER"_armhf.deb" + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/arm-unknown-linux-gnueabihf/"parity_"$VER"_armhf.deb.md5" --body "parity_"$VER"_armhf.deb.md5" tags: - rust - rust-arm @@ -180,23 +216,26 @@ linux-armv6: stage: build image: ethcore/rust-armv6:latest only: - - master - beta - tags - stable script: + - export CC=arm-linux-gnueabi-gcc + - export CXX=arm-linux-gnueabi-g++ + - export HOST_CC=gcc + - export HOST_CXX=g++ - rm -rf .cargo - mkdir -p .cargo - echo "[target.arm-unknown-linux-gnueabi]" >> .cargo/config - echo "linker= \"arm-linux-gnueabi-gcc\"" >> .cargo/config - cat .cargo/config - - cargo build --target arm-unknown-linux-gnueabi --release --verbose + - cargo build --target arm-unknown-linux-gnueabi --release $CARGOFLAGS - arm-linux-gnueabi-strip target/arm-unknown-linux-gnueabi/release/parity - - md5sum target/arm-unknown-linux-gnueabi/release/parity >> checksum + - md5sum target/arm-unknown-linux-gnueabi/release/parity >> parity.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/arm-unknown-linux-gnueabi/parity --body target/arm-unknown-linux-gnueabi/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/arm-unknown-linux-gnueabi/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/arm-unknown-linux-gnueabi/parity.md5 --body parity.md5 tags: - rust - rust-arm @@ -214,18 +253,29 @@ linux-aarch64: - tags - stable script: + - export CC=aarch64-linux-gnu-gcc + - export CXX=aarch64-linux-gnu-g++ + - export HOST_CC=gcc + - export HOST_CXX=g++ - rm -rf .cargo - mkdir -p .cargo - echo "[target.aarch64-unknown-linux-gnu]" >> .cargo/config - echo "linker= \"aarch64-linux-gnu-gcc\"" >> .cargo/config - cat .cargo/config - - cargo build --target aarch64-unknown-linux-gnu --release --verbose + - cargo build --target aarch64-unknown-linux-gnu --release $CARGOFLAGS - aarch64-linux-gnu-strip target/aarch64-unknown-linux-gnu/release/parity - - md5sum target/aarch64-unknown-linux-gnu/release/parity >> checksum + - md5sum target/aarch64-unknown-linux-gnu/release/parity >> parity.md5 + - sh scripts/deb-build.sh arm64 + - cp target/aarch64-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"_arm64.deb" + - md5sum "parity_"$VER"_arm64.deb" >> "parity_"$VER"_arm64.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/aarch64-unknown-linux-gnu/parity --body target/aarch64-unknown-linux-gnu/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/aarch64-unknown-linux-gnu/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/aarch64-unknown-linux-gnu/parity.md5 --body parity.md5 + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/aarch64-unknown-linux-gnu/"parity_"$VER"_arm64.deb" --body "parity_"$VER"_arm64.deb" + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/aarch64-unknown-linux-gnu/"parity_"$VER"_arm64.deb.md5" --body "parity_"$VER"_arm64.deb.md5" tags: - rust - rust-arm @@ -242,12 +292,13 @@ darwin: - tags - stable script: - - cargo build --release --verbose - - md5sum target/release/parity >> checksum + - cargo build --release $CARGOFLAGS + - rm -rf parity.md5 + - md5sum target/release/parity >> parity.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/x86_64-apple-darwin/parity --body target/release/parity - - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-apple-darwin/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/x86_64-apple-darwin/parity.md5 --body parity.md5 tags: - osx artifacts: @@ -267,28 +318,105 @@ windows: - set RUST_BACKTRACE=1 - set RUSTFLAGS=%RUSTFLAGS% -Zorbit=off - rustup default stable-x86_64-pc-windows-msvc - - cargo build --release --verbose - - cmd md5sum target\release\parity >> checksum + - cargo build --release %CARGOFLAGS% + - 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 + - cd nsis + - makensis.exe installer.nsi + - copy installer.exe InstallParity.exe + - signtool sign /f %keyfile% /p %certpass% InstallParity.exe + - md5sums InstallParity.exe > InstallParity.exe.md5 + - zip win-installer.zip InstallParity.exe InstallParity.exe.md5 + - md5sums win-installer.zip > win-installer.zip.md5 + - cd ..\target\release\ + - md5sums parity.exe parity.pdb > parity.md5 + - md5sums parity.exe > parity.exe.md5 + - zip parity.zip parity.exe parity.pdb parity.md5 + - md5sums parity.zip > parity.zip.md5 + - cd ..\.. - 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%/x86_64-pc-windows-msvc/parity --body target\release\parity.exe - - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/parity --body target\release\parity.pdb - - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/checksum --body checksum + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/parity.exe --body target\release\parity.exe + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/parity.exe.md5 --body target\release\parity.exe.md5 + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/parity.zip --body target\release\parity.zip + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/parity.zip.md5 --body target\release\parity.zip.md5 + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/InstallParity.exe --body nsis\InstallParity.exe + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/InstallParity.exe.md5 --body nsis\InstallParity.exe.md5 + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/win-installer.zip --body nsis\win-installer.zip + - aws s3api put-object --bucket builds-parity --key %CI_BUILD_REF_NAME%/x86_64-pc-windows-msvc/win-installer.zip.md5 --body nsis\win-installer.zip.md5 tags: - rust-windows artifacts: paths: - target/release/parity.exe - 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: test + stage: build before_script: - git submodule update --init --recursive script: - export RUST_BACKTRACE=1 - - ./test.sh --verbose + - ./test.sh $CARGOFLAGS --no-release tags: - rust-test - dependencies: - - linux-stable +js-release: + stage: build + image: ethcore/javascript:latest + only: + - master + before_script: + - ./js/scripts/install-deps.sh + script: + - ./js/scripts/build.sh + - ./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/.travis.yml b/.travis.yml index d9cda5715b636813a6fd7ed00e653e5a78bc2a48..80bf9ba109923a19bd5e89ff0a50ff1a7b244315 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,6 +32,7 @@ env: - RUN_DOCS="false" - TEST_OPTIONS="" - RUSTFLAGS="-D warnings" + - TRAVIS_NODE_VERSION="6" # GH_TOKEN for documentation - secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw= - KCOV_CMD="./kcov-master/tmp/usr/local/bin/kcov" @@ -41,6 +42,7 @@ cache: directories: - $TRAVIS_BUILD_DIR/target - $TRAVIS_BUILD_DIR/kcov-master + - $TRAVIS_BUILD_DIR/js/node_modules - $HOME/.cargo addons: @@ -64,9 +66,14 @@ install: make && make install DESTDIR=../tmp && cd ) + - nvm install $TRAVIS_NODE_VERSION && nvm use $TRAVIS_NODE_VERSION && ./js/scripts/install-deps.sh script: - - if [ "$RUN_TESTS" = "true" ]; then ./test.sh $TEST_OPTIONS --verbose; fi + - if [ "$RUN_TESTS" = "true" ]; then + ./js/scripts/lint.sh && + ./js/scripts/test.sh && + ./test.sh $TEST_OPTIONS --verbose; + fi - if [ "$RUN_COVERAGE" = "true" ]; then ./scripts/cov.sh "$KCOV_CMD"; fi after_success: | diff --git a/Cargo.lock b/Cargo.lock index a092325ead1eff44cf4565f3e2c9e9c420d683da..cf860c18ec9daa459a8503c4a4f222af80a3f3ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,7 +3,7 @@ name = "parity" version = "1.4.0" dependencies = [ "ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", - "clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", + "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", "ctrlc 1.1.1 (git+https://github.com/ethcore/rust-ctrlc.git)", "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)", @@ -145,15 +145,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "clippy" -version = "0.0.90" +version = "0.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "clippy_lints 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", + "clippy_lints 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "clippy_lints" -version = "0.0.90" +version = "0.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -222,8 +222,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "elastic-array" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" +version = "0.6.0" +source = "git+https://github.com/ethcore/elastic-array#70e4012e691b732c7c4cb04e9232799e6aa268bc" +dependencies = [ + "heapsize 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "env_logger" @@ -264,7 +267,7 @@ name = "ethash" version = "1.4.0" dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "primal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "sha3 0.1.0", ] @@ -276,7 +279,7 @@ 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)", "byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", - "clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", + "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "ethash 1.4.0", @@ -295,7 +298,7 @@ dependencies = [ "hyper 0.9.4 (git+https://github.com/ethcore/hyper)", "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)", - "lru-cache 0.0.7 (registry+https://github.com/rust-lang/crates.io-index)", + "lru-cache 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rayon 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -304,6 +307,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", + "transient-hashmap 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -319,12 +323,16 @@ dependencies = [ [[package]] name = "ethcore-bloom-journal" version = "0.1.0" +dependencies = [ + "siphasher 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "ethcore-dapps" version = "1.4.0" dependencies = [ - "clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", + "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", @@ -332,14 +340,13 @@ dependencies = [ "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)", - "jsonrpc-http-server 6.1.0 (git+https://github.com/ethcore/jsonrpc-http-server.git)", + "jsonrpc-http-server 6.1.1 (git+https://github.com/ethcore/jsonrpc-http-server.git)", "linked-hash-map 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "mime_guess 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-dapps 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", - "parity-dapps-home 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", - "parity-dapps-status 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", - "parity-dapps-wallet 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", + "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-ui 1.4.0", "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)", "serde 0.8.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -363,8 +370,8 @@ version = "1.4.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.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)", - "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.0 (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)", ] @@ -444,6 +451,7 @@ name = "ethcore-network" version = "1.4.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", @@ -452,8 +460,8 @@ dependencies = [ "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)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)", - "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.0 (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", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", @@ -467,7 +475,7 @@ dependencies = [ name = "ethcore-rpc" version = "1.4.0" dependencies = [ - "clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", + "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", "ethash 1.4.0", "ethcore 1.4.0", "ethcore-devtools 1.4.0", @@ -482,7 +490,7 @@ dependencies = [ "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)", - "jsonrpc-http-server 6.1.0 (git+https://github.com/ethcore/jsonrpc-http-server.git)", + "jsonrpc-http-server 6.1.1 (git+https://github.com/ethcore/jsonrpc-http-server.git)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.1.0", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", @@ -497,7 +505,7 @@ dependencies = [ name = "ethcore-signer" version = "1.4.0" dependencies = [ - "clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", + "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", @@ -505,10 +513,11 @@ dependencies = [ "ethcore-util 1.4.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-signer 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", + "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-ui 1.4.0", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", - "ws 0.5.2 (git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable)", + "ws 0.5.3 (git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable)", ] [[package]] @@ -535,8 +544,8 @@ version = "1.4.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)", - "clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", - "elastic-array 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", + "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", @@ -547,8 +556,10 @@ dependencies = [ "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)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.2.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)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 0.1.68 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.1.0", "rocksdb 0.4.5 (git+https://github.com/ethcore/rust-rocksdb)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", @@ -608,6 +619,7 @@ dependencies = [ "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)", + "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)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", @@ -622,7 +634,7 @@ dependencies = [ name = "ethsync" version = "1.4.0" dependencies = [ - "clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)", + "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", @@ -633,7 +645,7 @@ dependencies = [ "ethcore-util 1.4.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.2.6 (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)", "rlp 0.1.0", "semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -807,7 +819,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "json-ipc-server" version = "0.2.4" -source = "git+https://github.com/ethcore/json-ipc-server.git#5fbd0253750d3097b9a8fb27effa84c18d630bbb" +source = "git+https://github.com/ethcore/json-ipc-server.git#4642cd03ec1d23db89df80d22d5a88e7364ab885" dependencies = [ "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -839,7 +851,7 @@ version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.2.8 (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)", "serde_json 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -847,8 +859,8 @@ dependencies = [ [[package]] name = "jsonrpc-http-server" -version = "6.1.0" -source = "git+https://github.com/ethcore/jsonrpc-http-server.git#2766c6708f66f6f4e667211461d220b49c0d9fdf" +version = "6.1.1" +source = "git+https://github.com/ethcore/jsonrpc-http-server.git#cd6d4cb37d672cc3057aecd0692876f9e85f3ba5" dependencies = [ "hyper 0.9.4 (git+https://github.com/ethcore/hyper)", "jsonrpc-core 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -875,6 +887,11 @@ name = "lazy_static" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "lazycell" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "libc" version = "0.2.15" @@ -882,7 +899,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "linked-hash-map" -version = "0.0.9" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -897,10 +914,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "lru-cache" -version = "0.0.7" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "linked-hash-map 0.0.9 (registry+https://github.com/rust-lang/crates.io-index)", + "linked-hash-map 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -979,7 +996,7 @@ dependencies = [ [[package]] name = "mio" version = "0.6.0-dev" -source = "git+https://github.com/carllerche/mio?rev=62ec763c9cc34d8a452ed0392c575c50ddd5fc8d#62ec763c9cc34d8a452ed0392c575c50ddd5fc8d" +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)", @@ -991,6 +1008,22 @@ dependencies = [ "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "mio" +version = "0.6.0" +source = "git+https://github.com/carllerche/mio#9f17b70d6fecbf912168267ea74cf536f2cba705" +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)", + "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)", + "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)", +] + [[package]] name = "miow" version = "0.1.3" @@ -1165,9 +1198,14 @@ version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "parity-dapps" +name = "owning_ref" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "parity-dapps-glue" version = "1.4.0" -source = "git+https://github.com/ethcore/parity-ui.git#926b09b66c4940b09dc82c52adb4afd9e31155bc" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1179,44 +1217,57 @@ dependencies = [ ] [[package]] -name = "parity-dapps-home" +name = "parity-ui" version = "1.4.0" -source = "git+https://github.com/ethcore/parity-ui.git#926b09b66c4940b09dc82c52adb4afd9e31155bc" dependencies = [ - "parity-dapps 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", + "parity-ui-dev 1.4.0", + "parity-ui-precompiled 1.4.0 (git+https://github.com/ethcore/js-precompiled.git)", + "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "parity-dapps-signer" +name = "parity-ui-dev" version = "1.4.0" -source = "git+https://github.com/ethcore/parity-ui.git#926b09b66c4940b09dc82c52adb4afd9e31155bc" dependencies = [ - "parity-dapps 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", + "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "parity-dapps-status" +name = "parity-ui-precompiled" version = "1.4.0" -source = "git+https://github.com/ethcore/parity-ui.git#926b09b66c4940b09dc82c52adb4afd9e31155bc" +source = "git+https://github.com/ethcore/js-precompiled.git#10a57a7df153360b4abeddff99e5b8f34a85ff53" dependencies = [ - "parity-dapps 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", + "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "parity-dapps-wallet" -version = "1.4.0" -source = "git+https://github.com/ethcore/parity-ui.git#926b09b66c4940b09dc82c52adb4afd9e31155bc" +name = "parking_lot" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "parity-dapps 1.4.0 (git+https://github.com/ethcore/parity-ui.git)", + "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)", + "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)", ] [[package]] name = "parking_lot" -version = "0.2.6" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "owning_ref 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot_core 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "parking_lot_core" +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)", + "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)", ] @@ -1397,7 +1448,7 @@ dependencies = [ name = "rlp" version = "0.1.0" dependencies = [ - "elastic-array 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "elastic-array 0.6.0 (git+https://github.com/ethcore/elastic-array)", "ethcore-bigint 0.1.1", "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)", @@ -1406,7 +1457,7 @@ dependencies = [ [[package]] name = "rocksdb" version = "0.4.5" -source = "git+https://github.com/ethcore/rust-rocksdb#ffc7c82380fe8569f85ae6743f7f620af2d4a679" +source = "git+https://github.com/ethcore/rust-rocksdb#64c63ccbe1f62c2e2b39262486f9ba813793af58" dependencies = [ "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", "rocksdb-sys 0.3.0 (git+https://github.com/ethcore/rust-rocksdb)", @@ -1415,7 +1466,7 @@ dependencies = [ [[package]] name = "rocksdb-sys" version = "0.3.0" -source = "git+https://github.com/ethcore/rust-rocksdb#ffc7c82380fe8569f85ae6743f7f620af2d4a679" +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)", @@ -1544,6 +1595,11 @@ dependencies = [ "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "siphasher" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "slab" version = "0.1.3" @@ -1559,6 +1615,11 @@ name = "slab" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "slab" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "smallvec" version = "0.1.8" @@ -1850,13 +1911,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "ws" -version = "0.5.2" -source = "git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable#afbff59776ce16ccec5ee9e218b8891830ee6fdf" +version = "0.5.3" +source = "git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable#0cd6c5e3e9d5e61a37d53eb8dcbad523dcc69314" dependencies = [ "bytes 0.4.0-dev (git+https://github.com/carllerche/bytes)", "httparse 1.1.2 (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-dev (git+https://github.com/carllerche/mio?rev=62ec763c9cc34d8a452ed0392c575c50ddd5fc8d)", + "mio 0.6.0-dev (git+https://github.com/ethcore/mio?branch=timer-fix)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "sha1 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.2.0 (git+https://github.com/carllerche/slab?rev=5476efcafb)", @@ -1916,8 +1977,8 @@ dependencies = [ "checksum bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c129aff112dcc562970abb69e2508b40850dd24c274761bb50fb8a0067ba6c27" "checksum bytes 0.4.0-dev (git+https://github.com/carllerche/bytes)" = "" "checksum cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de1e760d7b6535af4241fca8bd8adf68e2e7edacc6b29f5d399050c5e48cf88c" -"checksum clippy 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)" = "d19bda68c3db98e3a780342f6101b44312fef20a5f13ce756d1202a35922b01b" -"checksum clippy_lints 0.0.90 (registry+https://github.com/rust-lang/crates.io-index)" = "3d4ed67c69b9bb35169be2538691d290a3aa0cbfd4b9f0bfb7c221fc1d399a96" +"checksum clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)" = "6eacf01b0aad84a0817703498f72d252df7c0faf6a5b86d0be4265f1829e459f" +"checksum clippy_lints 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)" = "a49960c9aab544ce86b004dcb61620e8b898fea5fc0f697a028f460f48221ed6" "checksum cookie 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "90266f45846f14a1e986c77d1e9c2626b8c342ed806fe60241ec38cc8697b245" "checksum crossbeam 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "fb974f835e90390c5f9dfac00f05b06dc117299f5ea4e85fbc7bb443af4911cc" "checksum ctrlc 1.1.1 (git+https://github.com/ethcore/rust-ctrlc.git)" = "" @@ -1925,7 +1986,7 @@ dependencies = [ "checksum deque 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1614659040e711785ed8ea24219140654da1729f3ec8a47a9719d041112fe7bf" "checksum docopt 0.6.80 (registry+https://github.com/rust-lang/crates.io-index)" = "4cc0acb4ce0828c6a5a11d47baa432fe885881c27428c3a4e473e454ffe57a76" "checksum dtoa 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0dd841b58510c9618291ffa448da2e4e0f699d984d436122372f446dae62263d" -"checksum elastic-array 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4bc9250a632e7c001b741eb0ec6cee93c9a5b6d5f1879696a4b94d62b012210a" +"checksum elastic-array 0.6.0 (git+https://github.com/ethcore/elastic-array)" = "" "checksum env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "aba65b63ffcc17ffacd6cf5aa843da7c5a25e3bd4bbe0b7def8b214e411250e5" "checksum eth-secp256k1 0.5.4 (git+https://github.com/ethcore/rust-secp256k1)" = "" "checksum ethabi 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f7b0c53453517f620847be51943db329276ae52f2e210cfc659e81182864be2f" @@ -1946,15 +2007,16 @@ dependencies = [ "checksum json-ipc-server 0.2.4 (git+https://github.com/ethcore/json-ipc-server.git)" = "" "checksum json-tcp-server 0.1.0 (git+https://github.com/ethcore/json-tcp-server)" = "" "checksum jsonrpc-core 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3c5094610b07f28f3edaf3947b732dadb31dbba4941d4d0c1c7a8350208f4414" -"checksum jsonrpc-http-server 6.1.0 (git+https://github.com/ethcore/jsonrpc-http-server.git)" = "" +"checksum jsonrpc-http-server 6.1.1 (git+https://github.com/ethcore/jsonrpc-http-server.git)" = "" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" "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 linked-hash-map 0.0.9 (registry+https://github.com/rust-lang/crates.io-index)" = "83f7ff3baae999fdf921cccf54b61842bb3b26868d50d02dff48052ebec8dd79" +"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" -"checksum lru-cache 0.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "42d50dcb5d9f145df83b1043207e1ac0c37c9c779c4e128ca4655abc3f3cbf8c" +"checksum lru-cache 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "656fa4dfcb02bcf1063c592ba3ff6a5303ee1f2afe98c8a889e8b1a77c6dfdb7" "checksum matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "15305656809ce5a4805b1ff2946892810992197ce1270ff79baded852187942e" "checksum memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d8b629fb514376c675b98c1421e80b151d3817ac42d7c667717d282761418d20" "checksum mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a74cc2587bf97c49f3f5bab62860d6abf3902ca73b66b51d9b049fbdcd727bd2" @@ -1962,7 +2024,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-dev (git+https://github.com/carllerche/mio?rev=62ec763c9cc34d8a452ed0392c575c50ddd5fc8d)" = "" +"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 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)" = "" @@ -1982,12 +2045,12 @@ dependencies = [ "checksum num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "51fedae97a05f7353612fe017ab705a37e6db8f4d67c5c6fe739a9e70d6eed09" "checksum number_prefix 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "084d05f4bf60621a9ac9bde941a410df548f4de9545f06e5ee9d3aef4b97cd77" "checksum odds 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)" = "b28c06e81b0f789122d415d6394b5fe849bde8067469f4c2980d3cdc10c78ec1" -"checksum parity-dapps 1.4.0 (git+https://github.com/ethcore/parity-ui.git)" = "" -"checksum parity-dapps-home 1.4.0 (git+https://github.com/ethcore/parity-ui.git)" = "" -"checksum parity-dapps-signer 1.4.0 (git+https://github.com/ethcore/parity-ui.git)" = "" -"checksum parity-dapps-status 1.4.0 (git+https://github.com/ethcore/parity-ui.git)" = "" -"checksum parity-dapps-wallet 1.4.0 (git+https://github.com/ethcore/parity-ui.git)" = "" -"checksum parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "e0fd1be2c3cf5fef20a6d18fec252c4f3c87c14fc3039002eb7d4ed91e436826" +"checksum owning_ref 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8d91377085359426407a287ab16884a0111ba473aa6844ff01d4ec20ce3d75e7" +"checksum parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "98378dec0a185da2b7180308752f0bad73aaa949c3e0a3b0528d0e067945f7ab" +"checksum parity-ui-precompiled 1.4.0 (git+https://github.com/ethcore/js-precompiled.git)" = "" +"checksum parking_lot 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "968f685642555d2f7e202c48b8b11de80569e9bfea817f7f12d7c61aac62d4e6" +"checksum parking_lot 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "dbc5847584161f273e69edc63c1a86254a22f570a0b5dd87aa6f9773f6f7d125" +"checksum parking_lot_core 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb1b97670a2ffadce7c397fb80a3d687c4f3060140b885621ef1653d0e5d5068" "checksum phf 0.7.14 (registry+https://github.com/rust-lang/crates.io-index)" = "447d9d45f2e0b4a9b532e808365abf18fc211be6ca217202fcd45236ef12f026" "checksum phf_codegen 0.7.14 (registry+https://github.com/rust-lang/crates.io-index)" = "8af7ae7c3f75a502292b491e5cc0a1f69e3407744abe6e57e2a3b712bb82f01d" "checksum phf_generator 0.7.14 (registry+https://github.com/rust-lang/crates.io-index)" = "db005608fd99800c8c74106a7c894cf582055b689aa14a79462cefdcb7dc1cc3" @@ -2024,9 +2087,11 @@ dependencies = [ "checksum serde_codegen_internals 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f877e2781ed0a323295d1c9f0e26556117b5a11489fc47b1848dfb98b3173d21" "checksum serde_json 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0e10f8a9d94b06cf5d3bef66475f04c8ff90950f1be7004c357ff9472ccbaebc" "checksum sha1 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cc30b1e1e8c40c121ca33b86c23308a090d19974ef001b4bf6e61fd1a0fb095c" +"checksum siphasher 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5c44e42fa187b5a8782489cf7740cc27c3125806be2bf33563cf5e02e9533fcd" "checksum slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d807fd58c4181bbabed77cb3b891ba9748241a552bcc5be698faaebefc54f46e" "checksum slab 0.2.0 (git+https://github.com/carllerche/slab?rev=5476efcafb)" = "" "checksum slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6dbdd334bd28d328dad1c41b0ea662517883d8880d8533895ef96c8003dec9c4" +"checksum slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "17b4fcaed89ab08ef143da37bc52adbcc04d4a69014f4c1208d6b51f0c47bc23" "checksum smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "fcc8d19212aacecf95e4a7a2179b26f7aeb9732a915cf01f05b0d3e044865410" "checksum solicit 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "172382bac9424588d7840732b250faeeef88942e37b6e35317dce98cafdd75b2" "checksum spmc 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "93bdab61c1a413e591c4d17388ffa859eaff2df27f1e13a5ec8b716700605adf" @@ -2064,7 +2129,7 @@ dependencies = [ "checksum webpki 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "813503a5985585e0812d430cd1328ee322f47f66629c8ed4ecab939cf9e92f91" "checksum winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "4dfaaa8fbdaa618fa6914b59b2769d690dd7521920a18d84b42d254678dd5fd4" "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" -"checksum ws 0.5.2 (git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable)" = "" +"checksum ws 0.5.3 (git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable)" = "" "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" "checksum xml-rs 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "65e74b96bd3179209dc70a980da6df843dff09e46eee103a0376c0949257e3ef" "checksum xmltree 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "472a9d37c7c53ab2391161df5b89b1f3bf76dab6ab150d7941ecbdd832282082" diff --git a/Cargo.toml b/Cargo.toml index 38003e7a198bc4c359ccc0661ad771dd240b4517..dc802a0fdd08ff5ec926612360ae23b86b8150e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,11 @@ lazy_static = "0.2" regex = "0.1" isatty = "0.1" toml = "0.2" +serde = "0.8.0" +serde_json = "0.8.0" +hyper = { version = "0.9", default-features = false } ctrlc = { git = "https://github.com/ethcore/rust-ctrlc.git" } +json-ipc-server = { git = "https://github.com/ethcore/json-ipc-server.git" } fdlimit = { path = "util/fdlimit" } ethcore = { path = "ethcore" } ethcore-util = { path = "util" } @@ -40,12 +44,9 @@ ethcore-ipc = { path = "ipc/rpc" } ethcore-ipc-hypervisor = { path = "ipc/hypervisor" } ethcore-logger = { path = "logger" } rlp = { path = "util/rlp" } -json-ipc-server = { git = "https://github.com/ethcore/json-ipc-server.git" } -ethcore-dapps = { path = "dapps", optional = true } -clippy = { version = "0.0.90", optional = true} ethcore-stratum = { path = "stratum" } -serde = "0.8.0" -serde_json = "0.8.0" +ethcore-dapps = { path = "dapps", optional = true } +clippy = { version = "0.0.96", optional = true} [target.'cfg(windows)'.dependencies] winapi = "0.2" @@ -53,19 +54,26 @@ winapi = "0.2" [target.'cfg(not(windows))'.dependencies] daemonize = "0.2" -[dependencies.hyper] -version = "0.9" -default-features = false - [features] -default = ["ui", "use-precompiled-js", "ipc"] -ui = ["dapps", "ethcore-signer/ui"] -use-precompiled-js = ["ethcore-dapps/use-precompiled-js", "ethcore-signer/use-precompiled-js"] +default = ["ui-precompiled"] + +ui = [ + "dapps", + "ethcore-dapps/ui", + "ethcore-signer/ui", +] +ui-precompiled = [ + "dapps", + "ethcore-signer/ui-precompiled", + "ethcore-dapps/ui-precompiled", +] + dapps = ["ethcore-dapps"] ipc = ["ethcore/ipc", "ethsync/ipc"] jit = ["ethcore/jit"] dev = ["clippy", "ethcore/dev", "ethcore-util/dev", "ethsync/dev", "ethcore-rpc/dev", "ethcore-dapps/dev", "ethcore-signer/dev"] json-tests = ["ethcore/json-tests"] +test-heavy = ["ethcore/test-heavy"] stratum = ["ipc"] ethkey-cli = ["ethcore/ethkey-cli"] ethstore-cli = ["ethcore/ethstore-cli"] diff --git a/README.md b/README.md index a6c987a69402d84b41bea7d9633cab459dc9d194..08c04c09702d03588b8aacd51ce361e486badbdc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # [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] [![Coverage Status][coveralls-image]][coveralls-url] [![Join the chat at https://gitter.im/ethcore/parity][gitter-image]][gitter-url] [![GPLv3][license-image]][license-url] [Internal Documentation][doc-url] diff --git a/dapps/Cargo.toml b/dapps/Cargo.toml index 1019e546073c704f135942b171d53dd328298fcb..ddc23c87cdcfead1ef2af7b31fb2e38f132ed0a8 100644 --- a/dapps/Cargo.toml +++ b/dapps/Cargo.toml @@ -11,6 +11,7 @@ build = "build.rs" [dependencies] rand = "0.3.14" log = "0.3" +env_logger = "0.3" jsonrpc-core = "3.0" jsonrpc-http-server = { git = "https://github.com/ethcore/jsonrpc-http-server.git" } hyper = { default-features = false, git = "https://github.com/ethcore/hyper" } @@ -19,33 +20,28 @@ url = "1.0" rustc-serialize = "0.3" serde = "0.8" serde_json = "0.8" -serde_macros = { version = "0.8", optional = true } -zip = { version = "0.1", default-features = false } ethabi = "0.2.2" linked-hash-map = "0.3" +parity-dapps-glue = "1.4" +mime = "0.2" +serde_macros = { version = "0.8", optional = true } +zip = { version = "0.1", default-features = false } ethcore-devtools = { path = "../devtools" } ethcore-rpc = { path = "../rpc" } ethcore-util = { path = "../util" } fetch = { path = "../util/fetch" } -parity-dapps = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4" } -# List of apps -parity-dapps-status = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4" } -parity-dapps-home = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4" } -parity-dapps-wallet = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4", optional = true } +parity-ui = { path = "./ui" } + mime_guess = { version = "1.6.1" } -clippy = { version = "0.0.90", optional = true} +clippy = { version = "0.0.96", optional = true} [build-dependencies] serde_codegen = { version = "0.8", optional = true } [features] -default = ["serde_codegen", "extra-dapps"] -extra-dapps = ["parity-dapps-wallet"] +default = ["serde_codegen"] nightly = ["serde_macros"] dev = ["clippy", "ethcore-rpc/dev", "ethcore-util/dev"] -use-precompiled-js = [ - "parity-dapps-status/use-precompiled-js", - "parity-dapps-home/use-precompiled-js", - "parity-dapps-wallet/use-precompiled-js" -] +ui = ["parity-ui/no-precompiled-js"] +ui-precompiled = ["parity-ui/use-precompiled-js"] diff --git a/dapps/js-glue/Cargo.toml b/dapps/js-glue/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..b85122e90749d6aaf0770a561427ec15e7a17033 --- /dev/null +++ b/dapps/js-glue/Cargo.toml @@ -0,0 +1,31 @@ +[package] +description = "Base Package for all Parity built-in dapps" +name = "parity-dapps-glue" +version = "1.4.0" +license = "GPL-3.0" +authors = ["Ethcore + ``` + + The `inject.js` script will create global `web3` instance with proper provider that should be used by your dapp. + +1. Create `./parity/dapps/myapp/Cargo.toml` with you apps details. See example here: [parity-status Cargo.toml](https://github.com/ethcore/parity-ui/blob/master/status/Cargo.toml). + + ```bash + $ git clone https://github.com/ethcore/parity-ui.git + $ cd ./parity-ui/ + $ cp ./home/Cargo.toml ../parity/dapps/myapp/Cargo.toml + $ cp ./home/build.rs ../parity/dapps/myapp/build.rs + $ cp ./home/src/lib.rs ../parity/dapps/myapp/src/lib.rs + $ cp ./home/src/lib.rs.in ../parity/dapps/myapp/src/lib.rs.in + # And edit the details of your app + $ vim ../parity/dapps/myapp/Cargo.toml # Edit the details + $ vim ./parity/dapps/myapp/src/lib.rs.in # Edit the details + ``` +# How to include your Dapp into `Parity`? +1. Edit `dapps/Cargo.toml` and add dependency to your application (it can be optional) + + ```toml + # Use git repo and version + parity-dapps-myapp = { path="./myapp" } + ``` + +1. Edit `dapps/src/apps.rs` and add your application to `all_pages` (if it's optional you need to specify two functions - see `parity-dapps-wallet` example) + +1. Compile parity. + + ```bash + $ cargo build --release # While inside `parity` + ``` + +1. Commit the results. + + ```bash + $ git add myapp && git commit -am "My first Parity Dapp". + ``` diff --git a/dapps/js-glue/build.rs b/dapps/js-glue/build.rs new file mode 100644 index 0000000000000000000000000000000000000000..82f99018857d72e62c159b1c9bd1baa13db52036 --- /dev/null +++ b/dapps/js-glue/build.rs @@ -0,0 +1,45 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + + +#[cfg(feature = "with-syntex")] +mod inner { + extern crate syntex; + extern crate quasi_codegen; + + use std::env; + use std::path::Path; + + pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + let mut registry = syntex::Registry::new(); + quasi_codegen::register(&mut registry); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + registry.expand("", &src, &dst).unwrap(); + } +} + +#[cfg(not(feature = "with-syntex"))] +mod inner { + pub fn main() {} +} + +fn main() { + inner::main(); +} diff --git a/dapps/js-glue/src/build.rs b/dapps/js-glue/src/build.rs new file mode 100644 index 0000000000000000000000000000000000000000..86c93171b174a2030aed6c38a9f70a2b9b80ec5d --- /dev/null +++ b/dapps/js-glue/src/build.rs @@ -0,0 +1,66 @@ + +#[cfg(feature = "with-syntex")] +pub mod inner { + use syntex; + use codegen; + use syntax::{ast, fold}; + use std::env; + use std::path::Path; + + fn strip_attributes(krate: ast::Crate) -> ast::Crate { + /// Helper folder that strips the serde attributes after the extensions have been expanded. + struct StripAttributeFolder; + + impl fold::Folder for StripAttributeFolder { + fn fold_attribute(&mut self, attr: ast::Attribute) -> Option { + match attr.node.value.node { + ast::MetaItemKind::List(ref n, _) if n == &"webapp" => { return None; } + _ => {} + } + + Some(attr) + } + + fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { + fold::noop_fold_mac(mac, self) + } + } + + fold::Folder::fold_crate(&mut StripAttributeFolder, krate) + } + + pub fn register(reg: &mut syntex::Registry) { + reg.add_attr("feature(custom_derive)"); + reg.add_attr("feature(custom_attribute)"); + + reg.add_decorator("derive_WebAppFiles", codegen::expand_webapp_implementation); + reg.add_post_expansion_pass(strip_attributes); + } + + pub fn generate() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + let mut registry = syntex::Registry::new(); + register(&mut registry); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + registry.expand("", &src, &dst).unwrap(); + } +} + +#[cfg(not(feature = "with-syntex"))] +pub mod inner { + use codegen; + + pub fn register(reg: &mut rustc_plugin::Registry) { + reg.register_syntax_extension( + syntax::parse::token::intern("derive_WebAppFiles"), + syntax::ext::base::MultiDecorator( + Box::new(codegen::expand_webapp_implementation))); + + reg.register_attribute("webapp".to_owned(), AttributeType::Normal); + } + + pub fn generate() {} +} diff --git a/dapps/js-glue/src/codegen.rs b/dapps/js-glue/src/codegen.rs new file mode 100644 index 0000000000000000000000000000000000000000..1a6b6fc7ebd34da2a312ca594808bebabf0c2cd4 --- /dev/null +++ b/dapps/js-glue/src/codegen.rs @@ -0,0 +1,189 @@ +// 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 . + +extern crate aster; +extern crate glob; +extern crate mime_guess; + +use self::mime_guess::guess_mime_type; +use std::path::{self, Path, PathBuf}; +use std::ops::Deref; + +use syntax::ast::{MetaItem, Item}; + +use syntax::ast; +use syntax::attr; +use syntax::codemap::Span; +use syntax::ext::base::{Annotatable, ExtCtxt}; +use syntax::ptr::P; +use syntax::print::pprust::{lit_to_string}; +use syntax::parse::token::{InternedString}; + + +pub fn expand_webapp_implementation( + cx: &mut ExtCtxt, + span: Span, + meta_item: &MetaItem, + annotatable: &Annotatable, + push: &mut FnMut(Annotatable) +) { + let item = match *annotatable { + Annotatable::Item(ref item) => item, + _ => { + cx.span_err(meta_item.span, "`#[derive(WebAppFiles)]` may only be applied to struct implementations"); + return; + }, + }; + let builder = aster::AstBuilder::new().span(span); + implement_webapp(cx, &builder, &item, push); +} + +fn implement_webapp(cx: &ExtCtxt, builder: &aster::AstBuilder, item: &Item, push: &mut FnMut(Annotatable)) { + let static_files_dir = extract_path(cx, item); + + let src = Path::new("src"); + let static_files = { + let mut buf = src.to_path_buf(); + buf.push(static_files_dir.deref()); + buf + }; + + let search_location = { + let mut buf = static_files.to_path_buf(); + buf.push("**"); + buf.push("*"); + buf + }; + + let files = glob::glob(search_location.to_str().expect("Valid UTF8 path")) + .expect("The sources directory is missing.") + .collect::, glob::GlobError>>() + .expect("There should be no error when reading a list of files."); + + let statements = files + .iter() + .filter(|path_buf| path_buf.is_file()) + .map(|path_buf| { + let path = path_buf.as_path(); + let filename = path.file_name().and_then(|s| s.to_str()).expect("Only UTF8 paths."); + let mime_type = guess_mime_type(filename).to_string(); + let file_path = as_uri(path.strip_prefix(&static_files).ok().expect("Prefix is always there, cause it's absolute path;qed")); + let file_path_in_source = path.to_str().expect("Only UTF8 paths."); + + let path_lit = builder.expr().str(file_path.as_str()); + let mime_lit = builder.expr().str(mime_type.as_str()); + let web_path_lit = builder.expr().str(file_path_in_source); + let separator_lit = builder.expr().str(path::MAIN_SEPARATOR.to_string().as_str()); + let concat_id = builder.id("concat!"); + let env_id = builder.id("env!"); + let macro_id = builder.id("include_bytes!"); + + let content = quote_expr!( + cx, + $macro_id($concat_id($env_id("CARGO_MANIFEST_DIR"), $separator_lit, $web_path_lit)) + ); + quote_stmt!( + cx, + files.insert($path_lit, File { path: $path_lit, content_type: $mime_lit, content: $content }); + ).expect("The statement is always ok, because it just uses literals.") + }).collect::>(); + + let type_name = item.ident; + + let files_impl = quote_item!(cx, + impl $type_name { + fn files() -> ::std::collections::HashMap<&'static str, File> { + let mut files = ::std::collections::HashMap::new(); + $statements + files + } + } + ).unwrap(); + + push(Annotatable::Item(files_impl)); +} + +fn extract_path(cx: &ExtCtxt, item: &Item) -> String { + for meta_items in item.attrs().iter().filter_map(webapp_meta_items) { + for meta_item in meta_items { + match meta_item.node { + ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"path" => { + if let Some(s) = get_str_from_lit(cx, name, lit) { + return s.deref().to_owned(); + } + }, + _ => {}, + } + } + } + + // default + "web".to_owned() +} + +fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Option { + match lit.node { + ast::LitKind::Str(ref s, _) => Some(s.clone()), + _ => { + cx.span_err( + lit.span, + &format!("webapp annotation `{}` must be a string, not `{}`", + name, + lit_to_string(lit) + ) + ); + return None; + } + } +} + +fn webapp_meta_items(attr: &ast::Attribute) -> Option<&[P]> { + match attr.node.value.node { + ast::MetaItemKind::List(ref name, ref items) if name == &"webapp" => { + attr::mark_used(&attr); + Some(items) + } + _ => None + } +} + +fn as_uri(path: &Path) -> String { + let mut s = String::new(); + for component in path.iter() { + s.push_str(component.to_str().expect("Only UTF-8 filenames are supported.")); + s.push('/'); + } + s[0..s.len()-1].into() +} + + +#[test] +fn should_convert_path_separators_on_all_platforms() { + // given + let p = { + let mut p = PathBuf::new(); + p.push("web"); + p.push("src"); + p.push("index.html"); + p + }; + + // when + let path = as_uri(&p); + + // then + assert_eq!(path, "web/src/index.html".to_owned()); +} diff --git a/dapps/js-glue/src/js.rs b/dapps/js-glue/src/js.rs new file mode 100644 index 0000000000000000000000000000000000000000..39c33689c81729070c027dc7df9a24aaf26d9de2 --- /dev/null +++ b/dapps/js-glue/src/js.rs @@ -0,0 +1,89 @@ +// 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 . + +#![cfg_attr(feature="use-precompiled-js", allow(dead_code))] +#![cfg_attr(feature="use-precompiled-js", allow(unused_imports))] + +use std::fmt; +use std::process::Command; + +#[cfg(not(windows))] +mod platform { + use std::process::Command; + + pub static NPM_CMD: &'static str = "npm"; + pub fn handle_fd(cmd: &mut Command) -> &mut Command { + cmd + } +} + +#[cfg(windows)] +mod platform { + use std::process::{Command, Stdio}; + + pub static NPM_CMD: &'static str = "npm.cmd"; + // NOTE [ToDr] For some reason on windows + // We cannot have any file descriptors open when running a child process + // during build phase. + pub fn handle_fd(cmd: &mut Command) -> &mut Command { + cmd.stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + } +} + +fn die(s: &'static str, e: T) -> ! { + panic!("Error: {}: {:?}", s, e); +} + +#[cfg(feature = "use-precompiled-js")] +pub fn test(_path: &str) { +} +#[cfg(feature = "use-precompiled-js")] +pub fn build(_path: &str, _dest: &str) { +} + +#[cfg(not(feature = "use-precompiled-js"))] +pub fn build(path: &str, dest: &str) { + let child = platform::handle_fd(&mut Command::new(platform::NPM_CMD)) + .arg("install") + .arg("--no-progress") + .current_dir(path) + .status() + .unwrap_or_else(|e| die("Installing node.js dependencies with npm", e)); + assert!(child.success(), "There was an error installing dependencies."); + + let child = platform::handle_fd(&mut Command::new(platform::NPM_CMD)) + .arg("run") + .arg("build") + .env("NODE_ENV", "production") + .env("BUILD_DEST", dest) + .current_dir(path) + .status() + .unwrap_or_else(|e| die("Building JS code", e)); + assert!(child.success(), "There was an error build JS code."); +} + +#[cfg(not(feature = "use-precompiled-js"))] +pub fn test(path: &str) { + let child = Command::new(platform::NPM_CMD) + .arg("run") + .arg("test") + .current_dir(path) + .status() + .unwrap_or_else(|e| die("Running test command", e)); + assert!(child.success(), "There was an error while running JS tests."); +} diff --git a/dapps/js-glue/src/lib.rs b/dapps/js-glue/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..28ac8d71201a7236edcbe1c4e5565d9a59732499 --- /dev/null +++ b/dapps/js-glue/src/lib.rs @@ -0,0 +1,39 @@ +// 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 . + + +#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))] +#![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))] + +#[cfg(feature = "with-syntex")] +extern crate syntex; + +#[cfg(feature = "with-syntex")] +#[macro_use] +extern crate syntex_syntax as syntax; + +#[cfg(feature = "with-syntex")] +include!(concat!(env!("OUT_DIR"), "/lib.rs")); + +#[cfg(not(feature = "with-syntex"))] +#[macro_use] +extern crate syntax; + +#[cfg(not(feature = "with-syntex"))] +extern crate rustc_plugin; + +#[cfg(not(feature = "with-syntex"))] +include!("lib.rs.in"); diff --git a/dapps/js-glue/src/lib.rs.in b/dapps/js-glue/src/lib.rs.in new file mode 100644 index 0000000000000000000000000000000000000000..07c57705f2d7ff9eccdbe9369d20e4979ec57080 --- /dev/null +++ b/dapps/js-glue/src/lib.rs.in @@ -0,0 +1,46 @@ +// 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 . + +extern crate quasi; + +mod codegen; +mod build; +pub mod js; +pub use build::inner::generate; + +use std::default::Default; + +#[derive(Clone)] +pub struct File { + pub path: &'static str, + pub content: &'static [u8], + // TODO: use strongly-typed MIME. + pub content_type: &'static str, +} + +#[derive(Clone, Debug)] +pub struct Info { + pub name: &'static str, + pub version: &'static str, + pub author: &'static str, + pub description: &'static str, + pub icon_url: &'static str, +} + +pub trait WebApp : Default + Send + Sync { + fn file(&self, path: &str) -> Option<&File>; + fn info(&self) -> Info; +} diff --git a/dapps/src/api/api.rs b/dapps/src/api/api.rs index 80c5e09dee28b9117bbeb6acbecf8962f92a391b..90ab837f52dc4172106983793b740d23b8715bc6 100644 --- a/dapps/src/api/api.rs +++ b/dapps/src/api/api.rs @@ -15,24 +15,31 @@ // along with Parity. If not, see . use std::sync::Arc; +use unicase::UniCase; use hyper::{server, net, Decoder, Encoder, Next, Control}; +use hyper::header; +use hyper::method::Method; +use hyper::header::AccessControlAllowOrigin; + use api::types::{App, ApiError}; -use api::response::{as_json, as_json_error, ping_response}; +use api::response; +use apps::fetcher::ContentFetcher; + use handlers::extract_url; use endpoint::{Endpoint, Endpoints, Handler, EndpointPath}; -use apps::fetcher::ContentFetcher; +use jsonrpc_http_server::cors; #[derive(Clone)] pub struct RestApi { - local_domain: String, + cors_domains: Option>, endpoints: Arc, fetcher: Arc, } impl RestApi { - pub fn new(local_domain: String, endpoints: Arc, fetcher: Arc) -> Box { + pub fn new(cors_domains: Vec, endpoints: Arc, fetcher: Arc) -> Box { Box::new(RestApi { - local_domain: local_domain, + cors_domains: Some(cors_domains.into_iter().map(AccessControlAllowOrigin::Value).collect()), endpoints: endpoints, fetcher: fetcher, }) @@ -53,6 +60,7 @@ impl Endpoint for RestApi { struct RestApiRouter { api: RestApi, + origin: Option, path: Option, control: Option, handler: Box, @@ -62,9 +70,10 @@ impl RestApiRouter { fn new(api: RestApi, path: EndpointPath, control: Control) -> Self { RestApiRouter { path: Some(path), + origin: None, control: Some(control), api: api, - handler: as_json_error(&ApiError { + handler: response::as_json_error(&ApiError { code: "404".into(), title: "Not Found".into(), detail: "Resource you requested has not been found.".into(), @@ -80,11 +89,40 @@ impl RestApiRouter { _ => None } } + + /// Returns basic headers for a response (it may be overwritten by the handler) + fn response_headers(&self) -> header::Headers { + let mut headers = header::Headers::new(); + headers.set(header::AccessControlAllowCredentials); + headers.set(header::AccessControlAllowMethods(vec![ + Method::Options, + Method::Post, + Method::Get, + ])); + headers.set(header::AccessControlAllowHeaders(vec![ + UniCase("origin".to_owned()), + UniCase("content-type".to_owned()), + UniCase("accept".to_owned()), + ])); + + if let Some(cors_header) = cors::get_cors_header(&self.api.cors_domains, &self.origin) { + headers.set(cors_header); + } + + headers + } } impl server::Handler for RestApiRouter { fn on_request(&mut self, request: server::Request) -> Next { + self.origin = cors::read_origin(&request); + + if let Method::Options = *request.method() { + self.handler = response::empty(); + return Next::write(); + } + let url = extract_url(&request); if url.is_none() { // Just return 404 if we can't parse URL @@ -99,11 +137,11 @@ impl server::Handler for RestApiRouter { let hash = url.path.get(2).map(|v| v.as_str()); // at this point path.app_id contains 'api', adjust it to the hash properly, otherwise // we will try and retrieve 'api' as the hash when doing the /api/content route - if let Some(hash) = hash.clone() { path.app_id = hash.to_owned() } + if let Some(ref hash) = hash { path.app_id = hash.clone().to_owned() } let handler = endpoint.and_then(|v| match v { - "apps" => Some(as_json(&self.api.list_apps())), - "ping" => Some(ping_response(&self.api.local_domain)), + "apps" => Some(response::as_json(&self.api.list_apps())), + "ping" => Some(response::ping()), "content" => self.resolve_content(hash, path, control), _ => None }); @@ -121,6 +159,7 @@ impl server::Handler for RestApiRouter { } fn on_response(&mut self, res: &mut server::Response) -> Next { + *res.headers_mut() = self.response_headers(); self.handler.on_response(res) } diff --git a/dapps/src/api/cors.rs b/dapps/src/api/cors.rs new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/dapps/src/api/response.rs b/dapps/src/api/response.rs index ce6eb292199e91b3b2f718071632f5cfdb6279a5..3e8f196ecd28e9260c3b448c107812c8afce2ac7 100644 --- a/dapps/src/api/response.rs +++ b/dapps/src/api/response.rs @@ -19,18 +19,22 @@ use serde_json; use endpoint::Handler; use handlers::{ContentHandler, EchoHandler}; -pub fn as_json(val: &T) -> Box { - Box::new(ContentHandler::ok(serde_json::to_string(val).unwrap(), "application/json".to_owned())) +pub fn empty() -> Box { + Box::new(ContentHandler::ok("".into(), mime!(Text/Plain))) } -pub fn as_json_error(val: &T) -> Box { - Box::new(ContentHandler::not_found(serde_json::to_string(val).unwrap(), "application/json".to_owned())) +pub fn as_json(val: &T) -> Box { + let json = serde_json::to_string(val) + .expect("serialization to string is infallible; qed"); + Box::new(ContentHandler::ok(json, mime!(Application/Json))) } -pub fn ping_response(local_domain: &str) -> Box { - Box::new(EchoHandler::cors(vec![ - format!("http://{}", local_domain), - // Allow CORS calls also for localhost - format!("http://{}", local_domain.replace("127.0.0.1", "localhost")), - ])) +pub fn as_json_error(val: &T) -> Box { + let json = serde_json::to_string(val) + .expect("serialization to string is infallible; qed"); + Box::new(ContentHandler::not_found(json, mime!(Application/Json))) +} + +pub fn ping() -> Box { + Box::new(EchoHandler::default()) } diff --git a/dapps/src/apps/cache.rs b/dapps/src/apps/cache.rs index be9521cf92a64a6740694b24fced17894f81fb54..9d1642fb086c1ba98d15380e979dce89baf55e85 100644 --- a/dapps/src/apps/cache.rs +++ b/dapps/src/apps/cache.rs @@ -47,15 +47,17 @@ impl ContentCache { } pub fn clear_garbage(&mut self, expected_size: usize) -> Vec<(String, ContentStatus)> { - let mut len = self.cache.len(); + let len = self.cache.len(); if len <= expected_size { return Vec::new(); } let mut removed = Vec::with_capacity(len - expected_size); - while len > expected_size { - let entry = self.cache.pop_front().unwrap(); + + while self.cache.len() > expected_size { + let entry = self.cache.pop_front().expect("expected_size bounded at 0, len is greater; qed"); + match entry.1 { ContentStatus::Fetching(ref fetch) => { trace!(target: "dapps", "Aborting {} because of limit.", entry.0); @@ -64,16 +66,15 @@ impl ContentCache { }, ContentStatus::Ready(ref endpoint) => { trace!(target: "dapps", "Removing {} because of limit.", entry.0); - // Remove path - let res = fs::remove_dir_all(&endpoint.path()); + // Remove path (dir or file) + let res = fs::remove_dir_all(&endpoint.path()).or_else(|_| fs::remove_file(&endpoint.path())); if let Err(e) = res { - warn!(target: "dapps", "Unable to remove dapp: {:?}", e); + warn!(target: "dapps", "Unable to remove dapp/content from cache: {:?}", e); } } } removed.push(entry); - len -= 1; } removed } diff --git a/dapps/src/apps/fetcher.rs b/dapps/src/apps/fetcher.rs index 2e1328858301434a8cc91ae92a0fd03982eabbf4..e4ee63fea05e5e859593f4b041a61b17f40678f6 100644 --- a/dapps/src/apps/fetcher.rs +++ b/dapps/src/apps/fetcher.rs @@ -46,6 +46,7 @@ pub struct ContentFetcher { resolver: R, cache: Arc>, sync: Arc, + embeddable_at: Option, } impl Drop for ContentFetcher { @@ -57,7 +58,7 @@ impl Drop for ContentFetcher { impl ContentFetcher { - pub fn new(resolver: R, sync_status: Arc) -> Self { + pub fn new(resolver: R, sync_status: Arc, embeddable_at: Option) -> Self { let mut dapps_path = env::temp_dir(); dapps_path.push(random_filename()); @@ -66,9 +67,19 @@ impl ContentFetcher { resolver: resolver, sync: sync_status, cache: Arc::new(Mutex::new(ContentCache::default())), + embeddable_at: embeddable_at, } } + fn still_syncing() -> 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") + )) + } + #[cfg(test)] fn set_status(&self, content_id: &str, status: ContentStatus) { self.cache.lock().insert(content_id.to_owned(), status); @@ -84,12 +95,10 @@ impl ContentFetcher { } // fallback to resolver if let Ok(content_id) = content_id.from_hex() { - // if app_id is valid, but we are syncing always return true. - if self.sync.is_major_syncing() { - return true; - } // else try to resolve the app_id - self.resolver.resolve(content_id).is_some() + let has_content = self.resolver.resolve(content_id).is_some(); + // if there is content or we are syncing return true + has_content || self.sync.is_major_importing() } else { false } @@ -99,28 +108,19 @@ impl ContentFetcher { let mut cache = self.cache.lock(); let content_id = path.app_id.clone(); - if self.sync.is_major_syncing() { - return 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") - )); - } - let (new_status, handler) = { let status = cache.get(&content_id); match status { - // Just server dapp + // Just serve the content Some(&mut ContentStatus::Ready(ref endpoint)) => { (None, endpoint.to_async_handler(path, control)) }, - // App is already being fetched + // Content is already being fetched Some(&mut ContentStatus::Fetching(ref fetch_control)) => { trace!(target: "dapps", "Content fetching in progress. Waiting..."); (None, fetch_control.to_handler(control)) }, - // We need to start fetching app + // We need to start fetching the content None => { trace!(target: "dapps", "Content unavailable. Fetching... {:?}", content_id); let content_hex = content_id.from_hex().expect("to_handler is called only when `contains` returns true."); @@ -141,6 +141,10 @@ 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()) + }, Some(URLHintResult::Dapp(dapp)) => { let (handler, fetch_control) = ContentFetcherHandler::new( dapp.url(), @@ -150,6 +154,7 @@ impl ContentFetcher { id: content_id.clone(), dapps_path: self.dapps_path.clone(), on_done: Box::new(on_done), + embeddable_at: self.embeddable_at, } ); @@ -170,6 +175,9 @@ impl ContentFetcher { (Some(ContentStatus::Fetching(fetch_control)), Box::new(handler) as Box) }, + None if self.sync.is_major_importing() => { + (None, Self::still_syncing()) + }, None => { // This may happen when sync status changes in between // `contains` and `to_handler` @@ -271,6 +279,7 @@ struct DappInstaller { id: String, dapps_path: PathBuf, on_done: Box) + Send>, + embeddable_at: Option, } impl DappInstaller { @@ -363,7 +372,7 @@ impl ContentValidator for DappInstaller { try!(manifest_file.write_all(manifest_str.as_bytes())); // Create endpoint - let app = LocalPageEndpoint::new(target, manifest.clone().into()); + let app = LocalPageEndpoint::new(target, manifest.clone().into(), self.embeddable_at); // Return modified app manifest Ok((manifest.id.clone(), app)) @@ -396,14 +405,14 @@ mod tests { fn should_true_if_contains_the_app() { // given let path = env::temp_dir(); - let fetcher = ContentFetcher::new(FakeResolver, Arc::new(|| false)); + let fetcher = ContentFetcher::new(FakeResolver, Arc::new(|| false), None); let handler = LocalPageEndpoint::new(path, EndpointInfo { name: "fake".into(), description: "".into(), version: "".into(), author: "".into(), icon_url: "".into(), - }); + }, None); // when fetcher.set_status("test", ContentStatus::Ready(handler)); diff --git a/dapps/src/apps/fs.rs b/dapps/src/apps/fs.rs index 4728757de07f91630908ca6cb9fb811b3c6294c1..e7a11fc8e5f45b544dedf40e911bd21eee8177c3 100644 --- a/dapps/src/apps/fs.rs +++ b/dapps/src/apps/fs.rs @@ -97,12 +97,12 @@ fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo { }) } -pub fn local_endpoints(dapps_path: String) -> Endpoints { +pub fn local_endpoints(dapps_path: String, signer_port: Option) -> Endpoints { let mut pages = Endpoints::new(); for dapp in local_dapps(dapps_path) { pages.insert( dapp.id, - Box::new(LocalPageEndpoint::new(dapp.path, dapp.info)) + Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, signer_port)) ); } pages diff --git a/dapps/src/apps/mod.rs b/dapps/src/apps/mod.rs index 65bee587deabb9ea59a580290d7c61f86a6fe52e..a7b97d37c541afbbe219ec0a366d8389773ff10e 100644 --- a/dapps/src/apps/mod.rs +++ b/dapps/src/apps/mod.rs @@ -25,17 +25,14 @@ pub mod urlhint; pub mod fetcher; pub mod manifest; -extern crate parity_dapps_status; -extern crate parity_dapps_home; +extern crate parity_ui; +pub const HOME_PAGE: &'static str = "home"; pub const DAPPS_DOMAIN : &'static str = ".parity"; pub const RPC_PATH : &'static str = "rpc"; pub const API_PATH : &'static str = "api"; pub const UTILS_PATH : &'static str = "parity-utils"; -pub fn main_page() -> &'static str { - "home" -} pub fn redirection_address(using_dapps_domains: bool, app_id: &str) -> String { if using_dapps_domains { format!("http://{}{}/", app_id, DAPPS_DOMAIN) @@ -45,36 +42,29 @@ pub fn redirection_address(using_dapps_domains: bool, app_id: &str) -> String { } pub fn utils() -> Box { - Box::new(PageEndpoint::with_prefix(parity_dapps_home::App::default(), UTILS_PATH.to_owned())) + Box::new(PageEndpoint::with_prefix(parity_ui::App::default(), UTILS_PATH.to_owned())) } -pub fn all_endpoints(dapps_path: String) -> Endpoints { +pub fn all_endpoints(dapps_path: String, signer_port: Option) -> Endpoints { // fetch fs dapps at first to avoid overwriting builtins - let mut pages = fs::local_endpoints(dapps_path); - // Home page needs to be safe embed - // because we use Cross-Origin LocalStorage. - // TODO [ToDr] Account naming should be moved to parity. - pages.insert("home".into(), Box::new( - PageEndpoint::new_safe_to_embed(parity_dapps_home::App::default()) - )); - pages.insert("proxy".into(), ProxyPac::boxed()); - insert::(&mut pages, "parity"); - insert::(&mut pages, "status"); + let mut pages = fs::local_endpoints(dapps_path, signer_port); - // Optional dapps - wallet_page(&mut pages); + // NOTE [ToDr] Dapps will be currently embeded on 8180 + insert::(&mut pages, "ui", Embeddable::Yes(signer_port)); + pages.insert("proxy".into(), ProxyPac::boxed(signer_port)); pages } -#[cfg(feature = "parity-dapps-wallet")] -fn wallet_page(pages: &mut Endpoints) { - extern crate parity_dapps_wallet; - insert::(pages, "wallet"); +fn insert(pages: &mut Endpoints, id: &str, embed_at: Embeddable) { + pages.insert(id.to_owned(), Box::new(match embed_at { + Embeddable::Yes(port) => PageEndpoint::new_safe_to_embed(T::default(), port), + Embeddable::No => PageEndpoint::new(T::default()), + })); } -#[cfg(not(feature = "parity-dapps-wallet"))] -fn wallet_page(_pages: &mut Endpoints) {} -fn insert(pages: &mut Endpoints, id: &str) { - pages.insert(id.to_owned(), Box::new(PageEndpoint::new(T::default()))); +enum Embeddable { + Yes(Option), + #[allow(dead_code)] + No, } diff --git a/dapps/src/apps/urlhint.rs b/dapps/src/apps/urlhint.rs index 2b86c0777fe9d63fec0b2704c70af30673882e4f..27769d07a81de34a952cfc4f5276268bf4aa63e6 100644 --- a/dapps/src/apps/urlhint.rs +++ b/dapps/src/apps/urlhint.rs @@ -156,9 +156,9 @@ impl URLHintContract { } let mut it = vec.into_iter(); - let account_slash_repo = it.next().unwrap(); - let commit = it.next().unwrap(); - let owner = it.next().unwrap(); + let account_slash_repo = it.next().expect("element 0 of 3-len vector known to exist; qed"); + let commit = it.next().expect("element 1 of 3-len vector known to exist; qed"); + let owner = it.next().expect("element 2 of 3-len vector known to exist qed"); match (account_slash_repo, commit, owner) { (Token::String(account_slash_repo), Token::FixedBytes(commit), Token::Address(owner)) => { diff --git a/dapps/src/handlers/content.rs b/dapps/src/handlers/content.rs index 4dc011475a1fb15e98d6aa7c7c79b7f969ecb57e..6bde9cf841effff34300ee473a21b6f651afd992 100644 --- a/dapps/src/handlers/content.rs +++ b/dapps/src/handlers/content.rs @@ -19,57 +19,60 @@ use std::io::Write; use hyper::{header, server, Decoder, Encoder, Next}; use hyper::net::HttpStream; +use hyper::mime::Mime; use hyper::status::StatusCode; use util::version; +use handlers::add_security_headers; + #[derive(Clone)] pub struct ContentHandler { code: StatusCode, content: String, - mimetype: String, + mimetype: Mime, write_pos: usize, + safe_to_embed_at_port: Option, } impl ContentHandler { - pub fn ok(content: String, mimetype: String) -> Self { - ContentHandler { - code: StatusCode::Ok, - content: content, - mimetype: mimetype, - write_pos: 0 - } + pub fn ok(content: String, mimetype: Mime) -> Self { + Self::new(StatusCode::Ok, content, mimetype) } - pub fn not_found(content: String, mimetype: String) -> Self { - ContentHandler { - code: StatusCode::NotFound, - content: content, - mimetype: mimetype, - write_pos: 0 - } + pub fn not_found(content: String, mimetype: Mime) -> Self { + Self::new(StatusCode::NotFound, content, mimetype) } - pub fn html(code: StatusCode, content: String) -> Self { - Self::new(code, content, "text/html".into()) + pub fn html(code: StatusCode, content: String, embeddable_at: Option) -> Self { + 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 { Self::html(code, format!( include_str!("../error_tpl.html"), title=title, message=message, details=details.unwrap_or_else(|| ""), version=version(), - )) + ), embeddable_at) + } + + pub fn new(code: StatusCode, content: String, mimetype: Mime) -> Self { + Self::new_embeddable(code, content, mimetype, None) } - pub fn new(code: StatusCode, content: String, mimetype: String) -> Self { + pub fn new_embeddable(code: StatusCode, content: String, mimetype: Mime, embeddable_at: Option) -> Self { ContentHandler { code: code, content: content, mimetype: mimetype, write_pos: 0, + safe_to_embed_at_port: embeddable_at, } } } @@ -85,7 +88,8 @@ impl server::Handler for ContentHandler { fn on_response(&mut self, res: &mut server::Response) -> Next { res.set_status(self.code); - res.headers_mut().set(header::ContentType(self.mimetype.parse().unwrap())); + res.headers_mut().set(header::ContentType(self.mimetype.clone())); + add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port.clone()); Next::write() } diff --git a/dapps/src/handlers/echo.rs b/dapps/src/handlers/echo.rs index b2ea8f5807a69d9ebac6c2d57529001d7a2f2caf..165ceb17173c673716a426882219d4f2cd39a390 100644 --- a/dapps/src/handlers/echo.rs +++ b/dapps/src/handlers/echo.rs @@ -17,82 +17,25 @@ //! Echo Handler use std::io::Read; -use hyper::{header, server, Decoder, Encoder, Next}; -use hyper::method::Method; +use hyper::{server, Decoder, Encoder, Next}; use hyper::net::HttpStream; -use unicase::UniCase; use super::ContentHandler; -#[derive(Debug, PartialEq)] -/// Type of Cross-Origin request -enum Cors { - /// Not a Cross-Origin request - no headers needed - No, - /// Cross-Origin request with valid Origin - Allowed(String), - /// Cross-Origin request with invalid Origin - Forbidden, -} - +#[derive(Default)] pub struct EchoHandler { - safe_origins: Vec, content: String, - cors: Cors, handler: Option, } -impl EchoHandler { - - pub fn cors(safe_origins: Vec) -> Self { - EchoHandler { - safe_origins: safe_origins, - content: String::new(), - cors: Cors::Forbidden, - handler: None, - } - } - - fn cors_header(&self, origin: Option) -> Cors { - fn origin_is_allowed(origin: &str, safe_origins: &[String]) -> bool { - for safe in safe_origins { - if origin.starts_with(safe) { - return true; - } - } - false - } - - match origin { - Some(ref origin) if origin_is_allowed(origin, &self.safe_origins) => { - Cors::Allowed(origin.clone()) - }, - None => Cors::No, - _ => Cors::Forbidden, - } - } -} - impl server::Handler for EchoHandler { - fn on_request(&mut self, request: server::Request) -> Next { - let origin = request.headers().get_raw("origin") - .and_then(|list| list.get(0)) - .and_then(|origin| String::from_utf8(origin.clone()).ok()); - - self.cors = self.cors_header(origin); - - // Don't even read the payload if origin is forbidden! - if let Cors::Forbidden = self.cors { - self.handler = Some(ContentHandler::ok(String::new(), "text/plain".into())); - Next::write() - } else { - Next::read() - } + fn on_request(&mut self, _: server::Request) -> Next { + Next::read() } fn on_request_readable(&mut self, decoder: &mut Decoder) -> Next { match decoder.read_to_string(&mut self.content) { Ok(0) => { - self.handler = Some(ContentHandler::ok(self.content.clone(), "application/json".into())); + self.handler = Some(ContentHandler::ok(self.content.clone(), mime!(Application/Json))); Next::write() }, Ok(_) => Next::read(), @@ -104,45 +47,14 @@ impl server::Handler for EchoHandler { } fn on_response(&mut self, res: &mut server::Response) -> Next { - if let Cors::Allowed(ref domain) = self.cors { - let mut headers = res.headers_mut(); - headers.set(header::Allow(vec![Method::Options, Method::Post, Method::Get])); - headers.set(header::AccessControlAllowHeaders(vec![ - UniCase("origin".to_owned()), - UniCase("content-type".to_owned()), - UniCase("accept".to_owned()), - ])); - headers.set(header::AccessControlAllowOrigin::Value(domain.clone())); - } - self.handler.as_mut().unwrap().on_response(res) + self.handler.as_mut() + .expect("handler always set in on_request, which is before now; qed") + .on_response(res) } fn on_response_writable(&mut self, encoder: &mut Encoder) -> Next { - self.handler.as_mut().unwrap().on_response_writable(encoder) + self.handler.as_mut() + .expect("handler always set in on_request, which is before now; qed") + .on_response_writable(encoder) } } - -#[test] -fn should_return_correct_cors_value() { - // given - let safe_origins = vec!["chrome-extension://".to_owned(), "http://localhost:8080".to_owned()]; - let cut = EchoHandler { - safe_origins: safe_origins, - content: String::new(), - cors: Cors::No, - handler: None, - }; - - // when - let res1 = cut.cors_header(Some("http://ethcore.io".into())); - let res2 = cut.cors_header(Some("http://localhost:8080".into())); - let res3 = cut.cors_header(Some("chrome-extension://deadbeefcafe".into())); - let res4 = cut.cors_header(None); - - - // then - assert_eq!(res1, Cors::Forbidden); - assert_eq!(res2, Cors::Allowed("http://localhost:8080".into())); - assert_eq!(res3, Cors::Allowed("chrome-extension://deadbeefcafe".into())); - assert_eq!(res4, Cors::No); -} diff --git a/dapps/src/handlers/mod.rs b/dapps/src/handlers/mod.rs index 54644fe8d6392ecb0f117c852486e024b8881f9c..3d96e8a407b51be2e46f1ad5783710de2a6eb337 100644 --- a/dapps/src/handlers/mod.rs +++ b/dapps/src/handlers/mod.rs @@ -30,7 +30,26 @@ pub use self::fetch::{ContentFetcherHandler, ContentValidator, FetchControl}; use url::Url; use hyper::{server, header, net, uri}; +use signer_address; +/// Adds security-related headers to the Response. +pub fn add_security_headers(headers: &mut header::Headers, embeddable_at: Option) { + headers.set_raw("X-XSS-Protection", vec![b"1; mode=block".to_vec()]); + headers.set_raw("X-Content-Type-Options", vec![b"nosniff".to_vec()]); + + // Embedding header: + if let Some(port) = embeddable_at { + headers.set_raw( + "X-Frame-Options", + vec![format!("ALLOW-FROM http://{}", signer_address(port)).into_bytes()] + ); + } else { + // TODO [ToDr] Should we be more strict here (DENY?)? + headers.set_raw("X-Frame-Options", vec![b"SAMEORIGIN".to_vec()]); + } +} + +/// Extracts URL part from the Request. pub fn extract_url(req: &server::Request) -> Option { match *req.uri() { uri::RequestUri::AbsoluteUri(ref url) => { diff --git a/dapps/src/lib.rs b/dapps/src/lib.rs index cac42f89313722b02db634f5c50f91afea45b4aa..0041dbedf17fdef87517bdc86f30bbc6e9d3a4ad 100644 --- a/dapps/src/lib.rs +++ b/dapps/src/lib.rs @@ -43,10 +43,8 @@ #![warn(missing_docs)] #![cfg_attr(feature="nightly", plugin(clippy))] -#[macro_use] -extern crate log; -extern crate url as url_lib; extern crate hyper; +extern crate url as url_lib; extern crate unicase; extern crate serde; extern crate serde_json; @@ -57,13 +55,21 @@ extern crate jsonrpc_core; extern crate jsonrpc_http_server; extern crate mime_guess; extern crate rustc_serialize; -extern crate parity_dapps; extern crate ethcore_rpc; extern crate ethcore_util as util; extern crate linked_hash_map; extern crate fetch; +extern crate parity_dapps_glue as parity_dapps; +#[macro_use] +extern crate log; +#[macro_use] +extern crate mime; + #[cfg(test)] extern crate ethcore_devtools as devtools; +#[cfg(test)] +extern crate env_logger; + mod endpoint; mod apps; @@ -87,16 +93,16 @@ use jsonrpc_core::{IoHandler, IoDelegate}; use router::auth::{Authorization, NoAuth, HttpBasicAuth}; use ethcore_rpc::Extendable; -static DAPPS_DOMAIN : &'static str = ".parity"; +use self::apps::{HOME_PAGE, DAPPS_DOMAIN}; /// Indicates sync status pub trait SyncStatus: Send + Sync { /// Returns true if there is a major sync happening. - fn is_major_syncing(&self) -> bool; + fn is_major_importing(&self) -> bool; } impl SyncStatus for F where F: Fn() -> bool + Send + Sync { - fn is_major_syncing(&self) -> bool { self() } + fn is_major_importing(&self) -> bool { self() } } /// Webapps HTTP+RPC server build. @@ -105,6 +111,7 @@ pub struct ServerBuilder { handler: Arc, registrar: Arc, sync_status: Arc, + signer_port: Option, } impl Extendable for ServerBuilder { @@ -121,6 +128,7 @@ impl ServerBuilder { handler: Arc::new(IoHandler::new()), registrar: registrar, sync_status: Arc::new(|| false), + signer_port: None, } } @@ -129,6 +137,11 @@ impl ServerBuilder { self.sync_status = status; } + /// Change default signer port. + pub fn with_signer_port(&mut self, signer_port: Option) { + self.signer_port = signer_port; + } + /// Asynchronously start server with no authentication, /// returns result with `Server` handle on success or an error. pub fn start_unsecured_http(&self, addr: &SocketAddr, hosts: Option>) -> Result { @@ -138,6 +151,7 @@ impl ServerBuilder { NoAuth, self.handler.clone(), self.dapps_path.clone(), + self.signer_port.clone(), self.registrar.clone(), self.sync_status.clone(), ) @@ -152,6 +166,7 @@ impl ServerBuilder { HttpBasicAuth::single_user(username, password), self.handler.clone(), self.dapps_path.clone(), + self.signer_port.clone(), self.registrar.clone(), self.sync_status.clone(), ) @@ -180,26 +195,40 @@ impl Server { Some(allowed) } + /// Returns a list of CORS domains for API endpoint. + fn cors_domains(signer_port: Option) -> Vec { + match signer_port { + Some(port) => vec![ + format!("http://{}{}", HOME_PAGE, DAPPS_DOMAIN), + format!("http://{}", signer_address(port)), + ], + None => vec![], + } + } + fn start_http( addr: &SocketAddr, hosts: Option>, authorization: A, handler: Arc, dapps_path: String, + signer_port: Option, registrar: Arc, sync_status: Arc, ) -> Result { let panic_handler = Arc::new(Mutex::new(None)); let authorization = Arc::new(authorization); - let content_fetcher = Arc::new(apps::fetcher::ContentFetcher::new(apps::urlhint::URLHintContract::new(registrar), sync_status)); - let endpoints = Arc::new(apps::all_endpoints(dapps_path)); + let content_fetcher = Arc::new(apps::fetcher::ContentFetcher::new(apps::urlhint::URLHintContract::new(registrar), sync_status, signer_port)); + let endpoints = Arc::new(apps::all_endpoints(dapps_path, signer_port.clone())); + let cors_domains = Self::cors_domains(signer_port); + let special = Arc::new({ let mut special = HashMap::new(); special.insert(router::SpecialEndpoint::Rpc, rpc::rpc(handler, panic_handler.clone())); special.insert(router::SpecialEndpoint::Utils, apps::utils()); special.insert( router::SpecialEndpoint::Api, - api::RestApi::new(format!("{}", addr), endpoints.clone(), content_fetcher.clone()) + api::RestApi::new(cors_domains, endpoints.clone(), content_fetcher.clone()) ); special }); @@ -208,7 +237,7 @@ impl Server { try!(hyper::Server::http(addr)) .handle(move |ctrl| router::Router::new( ctrl, - apps::main_page(), + signer_port.clone(), content_fetcher.clone(), endpoints.clone(), special.clone(), @@ -272,6 +301,10 @@ pub fn random_filename() -> String { rng.gen_ascii_chars().take(12).collect() } +fn signer_address(port: u16) -> String { + format!("127.0.0.1:{}", port) +} + #[cfg(test)] mod util_tests { use super::Server; @@ -291,4 +324,17 @@ mod util_tests { assert_eq!(address, Some(vec!["localhost".into(), "127.0.0.1".into()])); assert_eq!(some, Some(vec!["ethcore.io".into(), "localhost".into(), "127.0.0.1".into()])); } + + #[test] + fn should_return_cors_domains() { + // given + + // when + let none = Server::cors_domains(None); + let some = Server::cors_domains(Some(18180)); + + // then + assert_eq!(none, Vec::::new()); + assert_eq!(some, vec!["http://home.parity".to_owned(), "http://127.0.0.1:18180".into()]); + } } diff --git a/dapps/src/page/builtin.rs b/dapps/src/page/builtin.rs index 3c8d66686245b98f78fc1d671d6c73a3e6803f17..c4f56556e21a064485db4ad1f6a9f14137ffdfc3 100644 --- a/dapps/src/page/builtin.rs +++ b/dapps/src/page/builtin.rs @@ -25,7 +25,7 @@ pub struct PageEndpoint { /// Prefix to strip from the path (when `None` deducted from `app_id`) pub prefix: Option, /// Safe to be loaded in frame by other origin. (use wisely!) - safe_to_embed: bool, + safe_to_embed_at_port: Option, info: EndpointInfo, } @@ -36,7 +36,7 @@ impl PageEndpoint { PageEndpoint { app: Arc::new(app), prefix: None, - safe_to_embed: false, + safe_to_embed_at_port: None, info: EndpointInfo::from(info), } } @@ -49,7 +49,7 @@ impl PageEndpoint { PageEndpoint { app: Arc::new(app), prefix: Some(prefix), - safe_to_embed: false, + safe_to_embed_at_port: None, info: EndpointInfo::from(info), } } @@ -57,12 +57,12 @@ impl PageEndpoint { /// Creates new `PageEndpoint` which can be safely used in iframe /// even from different origin. It might be dangerous (clickjacking). /// Use wisely! - pub fn new_safe_to_embed(app: T) -> Self { + pub fn new_safe_to_embed(app: T, port: Option) -> Self { let info = app.info(); PageEndpoint { app: Arc::new(app), prefix: None, - safe_to_embed: true, + safe_to_embed_at_port: port, info: EndpointInfo::from(info), } } @@ -79,8 +79,8 @@ impl Endpoint for PageEndpoint { app: BuiltinDapp::new(self.app.clone()), prefix: self.prefix.clone(), path: path, - file: Default::default(), - safe_to_embed: self.safe_to_embed, + file: handler::ServedFile::new(self.safe_to_embed_at_port.clone()), + 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 70487443eaf09a1a2c59c2fbc903690e656daa57..0962f22c73885444f1a8b440e72890fcf2bd4687 100644 --- a/dapps/src/page/handler.rs +++ b/dapps/src/page/handler.rs @@ -22,7 +22,7 @@ use hyper::net::HttpStream; use hyper::status::StatusCode; use hyper::{Decoder, Encoder, Next}; use endpoint::EndpointPath; -use handlers::ContentHandler; +use handlers::{ContentHandler, add_security_headers}; /// Represents a file that can be sent to client. /// Implementation should keep track of bytes already sent internally. @@ -57,13 +57,14 @@ pub enum ServedFile { Error(ContentHandler), } -impl Default for ServedFile { - fn default() -> Self { - ServedFile::Error(ContentHandler::error( +impl ServedFile { + pub fn new(embeddable_at: Option) -> Self { + ServedFile::Error(ContentHandler::error_embeddable( StatusCode::NotFound, "404 Not Found", "Requested dapp resource was not found.", - None + None, + embeddable_at, )) } } @@ -81,7 +82,7 @@ pub struct PageHandler { /// Requested path. pub path: EndpointPath, /// Flag indicating if the file can be safely embeded (put in iframe). - pub safe_to_embed: bool, + pub safe_to_embed_at_port: Option, } impl PageHandler { @@ -115,7 +116,7 @@ impl server::Handler for PageHandler { self.app.file(&self.extract_path(url.path())) }, _ => None, - }.map_or_else(|| ServedFile::default(), |f| ServedFile::File(f)); + }.map_or_else(|| ServedFile::new(self.safe_to_embed_at_port.clone()), |f| ServedFile::File(f)); Next::write() } @@ -127,10 +128,14 @@ impl server::Handler for PageHandler { match self.file { ServedFile::File(ref f) => { res.set_status(StatusCode::Ok); - res.headers_mut().set(header::ContentType(f.content_type().parse().unwrap())); - if !self.safe_to_embed { - res.headers_mut().set_raw("X-Frame-Options", vec![b"SAMEORIGIN".to_vec()]); + + 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()), } + + // Security headers: + add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port); Next::write() }, ServedFile::Error(ref mut handler) => { @@ -212,8 +217,8 @@ fn should_extract_path_with_appid() { port: 8080, using_dapps_domains: true, }, - file: Default::default(), - safe_to_embed: true, + file: ServedFile::new(None), + safe_to_embed_at_port: None, }; // when diff --git a/dapps/src/page/local.rs b/dapps/src/page/local.rs index e34cc643459d3471d0b127b5998518da96d8e516..5390f5aac49a7a27c5c644aee21e08cfb54abd38 100644 --- a/dapps/src/page/local.rs +++ b/dapps/src/page/local.rs @@ -26,14 +26,16 @@ pub struct LocalPageEndpoint { path: PathBuf, mime: Option, info: Option, + embeddable_at: Option, } impl LocalPageEndpoint { - pub fn new(path: PathBuf, info: EndpointInfo) -> Self { + pub fn new(path: PathBuf, info: EndpointInfo, embeddable_at: Option) -> Self { LocalPageEndpoint { path: path, mime: None, info: Some(info), + embeddable_at: embeddable_at, } } @@ -42,6 +44,7 @@ impl LocalPageEndpoint { path: path, mime: Some(mime), info: None, + embeddable_at: None, } } @@ -61,16 +64,16 @@ impl Endpoint for LocalPageEndpoint { app: LocalSingleFile { path: self.path.clone(), mime: mime.clone() }, prefix: None, path: path, - file: Default::default(), - safe_to_embed: false, + file: handler::ServedFile::new(None), + safe_to_embed_at_port: self.embeddable_at, }) } else { Box::new(handler::PageHandler { app: LocalDapp { path: self.path.clone() }, prefix: None, path: path, - file: Default::default(), - safe_to_embed: false, + file: handler::ServedFile::new(None), + safe_to_embed_at_port: self.embeddable_at, }) } } diff --git a/dapps/src/proxypac.rs b/dapps/src/proxypac.rs index aaa68dc0c4cc087d5c86cceaa80d99a773f4d18f..2d7c4e3ce04d5fcdb3428205d4e8df352d662be9 100644 --- a/dapps/src/proxypac.rs +++ b/dapps/src/proxypac.rs @@ -18,31 +18,46 @@ use endpoint::{Endpoint, Handler, EndpointPath}; use handlers::ContentHandler; -use apps::DAPPS_DOMAIN; +use apps::{HOME_PAGE, DAPPS_DOMAIN}; +use signer_address; -pub struct ProxyPac; +pub struct ProxyPac { + signer_port: Option, +} impl ProxyPac { - pub fn boxed() -> Box { - Box::new(ProxyPac) + pub fn boxed(signer_port: Option) -> Box { + Box::new(ProxyPac { + signer_port: signer_port + }) } } impl Endpoint for ProxyPac { fn to_handler(&self, path: EndpointPath) -> Box { + let signer = self.signer_port + .map(signer_address) + .unwrap_or_else(|| format!("{}:{}", path.host, path.port)); + let content = format!( r#" function FindProxyForURL(url, host) {{ - if (shExpMatch(host, "*{0}")) + if (shExpMatch(host, "{0}{1}")) + {{ + return "PROXY {4}"; + }} + + if (shExpMatch(host, "*{1}")) {{ - return "PROXY {1}:{2}"; + return "PROXY {2}:{3}"; }} return "DIRECT"; }} "#, - DAPPS_DOMAIN, path.host, path.port); - Box::new(ContentHandler::ok(content, "application/javascript".to_owned())) + HOME_PAGE, DAPPS_DOMAIN, path.host, path.port, signer); + + Box::new(ContentHandler::ok(content, mime!(Application/Javascript))) } } diff --git a/dapps/src/router/host_validation.rs b/dapps/src/router/host_validation.rs index 5be30ef8bc273d92e77013457e0fbdbe6528e5ae..2b7e6c9e48abcb8470cbc371796d6cce878452b5 100644 --- a/dapps/src/router/host_validation.rs +++ b/dapps/src/router/host_validation.rs @@ -15,7 +15,7 @@ // along with Parity. If not, see . -use DAPPS_DOMAIN; +use apps::DAPPS_DOMAIN; use hyper::{server, header, StatusCode}; use hyper::net::HttpStream; diff --git a/dapps/src/router/mod.rs b/dapps/src/router/mod.rs index e3ff6e64f024e28e2f7408ae204a61041d5fc6c1..6ca453d6dda076ac8c00c12fefa0930703a0d21c 100644 --- a/dapps/src/router/mod.rs +++ b/dapps/src/router/mod.rs @@ -20,13 +20,13 @@ pub mod auth; mod host_validation; -use DAPPS_DOMAIN; +use signer_address; use std::sync::Arc; use std::collections::HashMap; use url::{Url, Host}; use hyper::{self, server, Next, Encoder, Decoder, Control, StatusCode}; use hyper::net::HttpStream; -use apps; +use apps::{self, DAPPS_DOMAIN}; use apps::fetcher::ContentFetcher; use endpoint::{Endpoint, Endpoints, EndpointPath}; use handlers::{Redirection, extract_url, ContentHandler}; @@ -43,7 +43,7 @@ pub enum SpecialEndpoint { pub struct Router { control: Option, - main_page: &'static str, + signer_port: Option, endpoints: Arc, fetch: Arc, special: Arc>>, @@ -61,54 +61,85 @@ impl server::Handler for Router { let endpoint = extract_endpoint(&url); let is_utils = endpoint.1 == SpecialEndpoint::Utils; + trace!(target: "dapps", "Routing request to {:?}. Details: {:?}", url, req); + // Validate Host header if let Some(ref hosts) = self.allowed_hosts { + trace!(target: "dapps", "Validating host headers against: {:?}", hosts); let is_valid = is_utils || host_validation::is_valid(&req, hosts, self.endpoints.keys().cloned().collect()); if !is_valid { + debug!(target: "dapps", "Rejecting invalid host header."); self.handler = host_validation::host_invalid_response(); return self.handler.on_request(req); } } + trace!(target: "dapps", "Checking authorization."); // Check authorization let auth = self.authorization.is_authorized(&req); if let Authorized::No(handler) = auth { + debug!(target: "dapps", "Authorization denied."); self.handler = handler; return self.handler.on_request(req); } let control = self.control.take().expect("on_request is called only once; control is always defined at start; qed"); + debug!(target: "dapps", "Handling endpoint request: {:?}", endpoint); self.handler = match endpoint { // First check special endpoints (ref path, ref endpoint) if self.special.contains_key(endpoint) => { - self.special.get(endpoint).unwrap().to_async_handler(path.clone().unwrap_or_default(), control) + trace!(target: "dapps", "Resolving to special endpoint."); + self.special.get(endpoint) + .expect("special known to contain key; qed") + .to_async_handler(path.clone().unwrap_or_default(), control) }, // Then delegate to dapp (Some(ref path), _) if self.endpoints.contains_key(&path.app_id) => { - self.endpoints.get(&path.app_id).unwrap().to_async_handler(path.clone(), control) + trace!(target: "dapps", "Resolving to local/builtin dapp."); + self.endpoints.get(&path.app_id) + .expect("special known to contain key; qed") + .to_async_handler(path.clone(), control) }, // Try to resolve and fetch the dapp (Some(ref path), _) if self.fetch.contains(&path.app_id) => { + trace!(target: "dapps", "Resolving to fetchable content."); self.fetch.to_async_handler(path.clone(), control) }, + // NOTE [todr] /home is redirected to home page since some users may have the redirection cached + // (in the past we used 301 instead of 302) + // It should be safe to remove it in (near) future. + // // 404 for non-existent content - (Some(ref path), _) if *req.method() == hyper::method::Method::Get => { - let address = apps::redirection_address(path.using_dapps_domains, self.main_page); + (Some(ref path), _) if *req.method() == hyper::Method::Get && path.app_id != "home" => { + trace!(target: "dapps", "Resolving to 404."); Box::new(ContentHandler::error( StatusCode::NotFound, "404 Not Found", "Requested content was not found.", - Some(&format!("Go back to the Home Page.", address)) + None, )) }, - // Redirect any GET request to home. - _ if *req.method() == hyper::method::Method::Get => { - let address = apps::redirection_address(false, self.main_page); - Redirection::boxed(address.as_str()) + // Redirect any other GET request to signer. + _ if *req.method() == hyper::Method::Get => { + if let Some(port) = self.signer_port { + trace!(target: "dapps", "Redirecting to signer interface."); + Redirection::boxed(&format!("http://{}", signer_address(port))) + } else { + trace!(target: "dapps", "Signer disabled, returning 404."); + Box::new(ContentHandler::error( + StatusCode::NotFound, + "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."), + )) + } }, // RPC by default _ => { - self.special.get(&SpecialEndpoint::Rpc).unwrap().to_async_handler(EndpointPath::default(), control) + trace!(target: "dapps", "Resolving to RPC call."); + self.special.get(&SpecialEndpoint::Rpc) + .expect("RPC endpoint always stored; qed") + .to_async_handler(EndpointPath::default(), control) } }; @@ -135,7 +166,7 @@ impl server::Handler for Router { impl Router { pub fn new( control: Control, - main_page: &'static str, + signer_port: Option, content_fetcher: Arc, endpoints: Arc, special: Arc>>, @@ -143,10 +174,12 @@ impl Router { allowed_hosts: Option>, ) -> Self { - let handler = special.get(&SpecialEndpoint::Utils).unwrap().to_handler(EndpointPath::default()); + let handler = special.get(&SpecialEndpoint::Utils) + .expect("Utils endpoint always stored; qed") + .to_handler(EndpointPath::default()); Router { control: Some(control), - main_page: main_page, + signer_port: signer_port, endpoints: endpoints, fetch: content_fetcher, special: special, diff --git a/dapps/src/rpc.rs b/dapps/src/rpc.rs index 649d283cee240e1c76e45a1677bc674ddaec8ae6..625bfc269989b78646065e6334193d3f4890c043 100644 --- a/dapps/src/rpc.rs +++ b/dapps/src/rpc.rs @@ -24,7 +24,7 @@ pub fn rpc(handler: Arc, panic_handler: Arc Box::new(RpcEndpoint { handler: handler, panic_handler: panic_handler, - cors_domain: Some(vec![AccessControlAllowOrigin::Null]), + cors_domain: None, // NOTE [ToDr] We don't need to do any hosts validation here. It's already done in router. allowed_hosts: None, }) diff --git a/dapps/src/tests/api.rs b/dapps/src/tests/api.rs index fc255ec207876115b3d9588f64f0db29c0c6495a..ea4c08c60f2a94d7b3a8ee2cbedd8f94bf40c9e3 100644 --- a/dapps/src/tests/api.rs +++ b/dapps/src/tests/api.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, serve_with_registrar, request}; +use tests::helpers::{serve, serve_with_registrar, request, assert_security_headers}; #[test] fn should_return_error() { @@ -34,8 +34,9 @@ fn should_return_error() { // then assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); - assert_eq!(response.headers.get(0).unwrap(), "Content-Type: application/json"); + assert_eq!(response.headers.get(3).unwrap(), "Content-Type: application/json"); assert_eq!(response.body, format!("58\n{}\n0\n\n", r#"{"code":"404","title":"Not Found","detail":"Resource you requested has not been found."}"#)); + assert_security_headers(&response.headers); } #[test] @@ -56,8 +57,9 @@ fn should_serve_apps() { // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert_eq!(response.headers.get(0).unwrap(), "Content-Type: application/json"); - assert!(response.body.contains("Parity Home Screen"), response.body); + assert_eq!(response.headers.get(3).unwrap(), "Content-Type: application/json"); + assert!(response.body.contains("Parity UI"), response.body); + assert_security_headers(&response.headers); } #[test] @@ -78,8 +80,9 @@ fn should_handle_ping() { // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert_eq!(response.headers.get(0).unwrap(), "Content-Type: application/json"); + assert_eq!(response.headers.get(3).unwrap(), "Content-Type: application/json"); assert_eq!(response.body, "0\n\n".to_owned()); + assert_security_headers(&response.headers); } @@ -101,5 +104,57 @@ fn should_try_to_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); } +#[test] +fn should_return_signer_port_cors_headers() { + // given + let server = serve(); + + // when + let response = request(server, + "\ + POST /api/ping HTTP/1.1\r\n\ + Host: localhost:8080\r\n\ + Origin: http://127.0.0.1:18180\r\n\ + Connection: close\r\n\ + \r\n\ + {} + " + ); + + // then + assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); + assert!( + response.headers_raw.contains("Access-Control-Allow-Origin: http://127.0.0.1:18180"), + "CORS header for signer missing: {:?}", + response.headers + ); +} + +#[test] +fn should_return_signer_port_cors_headers_for_home_parity() { + // given + let server = serve(); + + // when + let response = request(server, + "\ + POST /api/ping HTTP/1.1\r\n\ + Host: localhost:8080\r\n\ + Origin: http://home.parity\r\n\ + Connection: close\r\n\ + \r\n\ + {} + " + ); + + // then + assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); + assert!( + response.headers_raw.contains("Access-Control-Allow-Origin: http://home.parity"), + "CORS header for home.parity missing: {:?}", + response.headers + ); +} diff --git a/dapps/src/tests/authorization.rs b/dapps/src/tests/authorization.rs index 9d5a46af47f8f180719b6a4594228e753adcdbd0..86fe4d20720541a64a2887e99c2c2317f3769240 100644 --- a/dapps/src/tests/authorization.rs +++ b/dapps/src/tests/authorization.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_auth, request}; +use tests::helpers::{serve_with_auth, request, assert_security_headers_for_embed}; #[test] fn should_require_authorization() { @@ -66,7 +66,7 @@ fn should_allow_on_valid_auth() { // when let response = request(server, "\ - GET /home/ HTTP/1.1\r\n\ + GET /ui/ HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l\r\n @@ -76,4 +76,5 @@ fn should_allow_on_valid_auth() { // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); + assert_security_headers_for_embed(&response.headers); } diff --git a/dapps/src/tests/fetch.rs b/dapps/src/tests/fetch.rs index 6fd65c00f9b7d046457ccda8b79778444cff7c13..1cabca5cbf1d16b4588a68cf7f83108b1b53c7e8 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, request}; +use tests::helpers::{serve_with_registrar, serve_with_registrar_and_sync, request, assert_security_headers}; #[test] fn should_resolve_dapp() { @@ -34,5 +34,34 @@ 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); } +#[test] +fn should_return_503_when_syncing_but_should_make_the_calls() { + // given + let (server, registrar) = serve_with_registrar_and_sync(); + { + let mut responses = registrar.responses.lock(); + let res1 = responses.get(0).unwrap().clone(); + let res2 = responses.get(1).unwrap().clone(); + // Registrar will be called twice - fill up the responses. + responses.push(res1); + responses.push(res2); + } + + // when + let response = request(server, + "\ + GET / HTTP/1.1\r\n\ + Host: 1472a9e190620cdf6b31f383373e45efcfe869a820c91f9ccd7eb9fb45e4985d.parity\r\n\ + Connection: close\r\n\ + \r\n\ + " + ); + + // 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); +} diff --git a/dapps/src/tests/helpers.rs b/dapps/src/tests/helpers.rs index efbd24a8d82b71474bc347757371b7cb58b83b91..1fa2e777a8279373276c85f424a207849e6f450c 100644 --- a/dapps/src/tests/helpers.rs +++ b/dapps/src/tests/helpers.rs @@ -18,6 +18,7 @@ use std::env; use std::str; use std::sync::Arc; use rustc_serialize::hex::FromHex; +use env_logger::LogBuilder; use ServerBuilder; use Server; @@ -27,6 +28,7 @@ use devtools::http_client; const REGISTRAR: &'static str = "8e4e9b13d4b45cb0befc93c3061b1408f67316b2"; const URLHINT: &'static str = "deadbeefcafe0000000000000000000000000000"; +const SIGNER_PORT: u16 = 18180; pub struct FakeRegistrar { pub calls: Arc>>, @@ -58,11 +60,23 @@ impl ContractClient for FakeRegistrar { } } -pub fn init_server(hosts: Option>) -> (Server, Arc) { +fn init_logger() { + // Initialize logger + if let Ok(log) = env::var("RUST_LOG") { + let mut builder = LogBuilder::new(); + builder.parse(&log); + builder.init().expect("Logger is initialized only once."); + } +} + +pub fn init_server(hosts: Option>, is_syncing: bool) -> (Server, Arc) { + init_logger(); let registrar = Arc::new(FakeRegistrar::new()); let mut dapps_path = env::temp_dir(); dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading"); - let builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar.clone()); + let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar.clone()); + builder.with_sync_status(Arc::new(move || is_syncing)); + builder.with_signer_port(Some(SIGNER_PORT)); ( builder.start_unsecured_http(&"127.0.0.1:0".parse().unwrap(), hosts).unwrap(), registrar, @@ -70,25 +84,38 @@ pub fn init_server(hosts: Option>) -> (Server, Arc) { } pub fn serve_with_auth(user: &str, pass: &str) -> Server { + init_logger(); let registrar = Arc::new(FakeRegistrar::new()); let mut dapps_path = env::temp_dir(); dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading"); - let builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar); + let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar); + builder.with_signer_port(Some(SIGNER_PORT)); builder.start_basic_auth_http(&"127.0.0.1:0".parse().unwrap(), None, user, pass).unwrap() } pub fn serve_hosts(hosts: Option>) -> Server { - init_server(hosts).0 + init_server(hosts, false).0 } pub fn serve_with_registrar() -> (Server, Arc) { - init_server(None) + init_server(None, false) +} + +pub fn serve_with_registrar_and_sync() -> (Server, Arc) { + init_server(None, true) } pub fn serve() -> Server { - init_server(None).0 + init_server(None, false).0 } pub fn request(server: Server, request: &str) -> http_client::Response { http_client::request(server.addr(), request) } + +pub fn assert_security_headers(headers: &[String]) { + http_client::assert_security_headers_present(headers, None) +} +pub fn assert_security_headers_for_embed(headers: &[String]) { + http_client::assert_security_headers_present(headers, Some(SIGNER_PORT)) +} diff --git a/dapps/src/tests/redirection.rs b/dapps/src/tests/redirection.rs index 1a360cd087afa7e5b66f1364ee0deb7d5a4f1584..398d08774e7362c4e694660e4a763f918d12b683 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}; +use tests::helpers::{serve, request, assert_security_headers}; #[test] fn should_redirect_to_home() { @@ -33,7 +33,7 @@ fn should_redirect_to_home() { // then assert_eq!(response.status, "HTTP/1.1 302 Found".to_owned()); - assert_eq!(response.headers.get(0).unwrap(), "Location: /home/"); + assert_eq!(response.headers.get(0).unwrap(), "Location: http://127.0.0.1:18180"); } #[test] @@ -53,7 +53,27 @@ fn should_redirect_to_home_when_trailing_slash_is_missing() { // then assert_eq!(response.status, "HTTP/1.1 302 Found".to_owned()); - assert_eq!(response.headers.get(0).unwrap(), "Location: /home/"); + assert_eq!(response.headers.get(0).unwrap(), "Location: http://127.0.0.1:18180"); +} + +#[test] +fn should_redirect_to_home_for_users_with_cached_redirection() { + // given + let server = serve(); + + // when + let response = request(server, + "\ + GET /home/ HTTP/1.1\r\n\ + Host: 127.0.0.1:8080\r\n\ + Connection: close\r\n\ + \r\n\ + " + ); + + // then + assert_eq!(response.status, "HTTP/1.1 302 Found".to_owned()); + assert_eq!(response.headers.get(0).unwrap(), "Location: http://127.0.0.1:18180"); } #[test] @@ -73,7 +93,7 @@ fn should_display_404_on_invalid_dapp() { // then assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); - assert!(response.body.contains("href=\"/home/")); + assert_security_headers(&response.headers); } #[test] @@ -93,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!(response.body.contains("href=\"http://home.parity/")); + assert_security_headers(&response.headers); } #[test] @@ -159,7 +179,8 @@ fn should_serve_proxy_pac() { // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert_eq!(response.body, "86\n\nfunction FindProxyForURL(url, host) {\n\tif (shExpMatch(host, \"*.parity\"))\n\t{\n\t\treturn \"PROXY 127.0.0.1:8080\";\n\t}\n\n\treturn \"DIRECT\";\n}\n\n0\n\n".to_owned()); + assert_eq!(response.body, "D5\n\nfunction FindProxyForURL(url, host) {\n\tif (shExpMatch(host, \"home.parity\"))\n\t{\n\t\treturn \"PROXY 127.0.0.1:18180\";\n\t}\n\n\tif (shExpMatch(host, \"*.parity\"))\n\t{\n\t\treturn \"PROXY 127.0.0.1:8080\";\n\t}\n\n\treturn \"DIRECT\";\n}\n\n0\n\n".to_owned()); + assert_security_headers(&response.headers); } #[test] @@ -181,5 +202,6 @@ fn should_serve_utils() { // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); assert_eq!(response.body.contains("function(){"), true); + assert_security_headers(&response.headers); } diff --git a/dapps/src/tests/validation.rs b/dapps/src/tests/validation.rs index c39350cce3997dc9210f767919d9eb533f85b841..ae02a6c2ccc2008e80b4421a9ee2fcda97be8ee1 100644 --- a/dapps/src/tests/validation.rs +++ b/dapps/src/tests/validation.rs @@ -45,7 +45,7 @@ fn should_allow_valid_host() { // when let response = request(server, "\ - GET /home/ HTTP/1.1\r\n\ + GET /ui/ HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Connection: close\r\n\ \r\n\ @@ -66,7 +66,7 @@ fn should_serve_dapps_domains() { let response = request(server, "\ GET / HTTP/1.1\r\n\ - Host: home.parity\r\n\ + Host: ui.parity\r\n\ Connection: close\r\n\ \r\n\ {} @@ -98,3 +98,30 @@ fn should_allow_parity_utils_even_on_invalid_domain() { assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } +#[test] +fn should_not_return_cors_headers_for_rpc() { + // given + let server = serve_hosts(Some(vec!["localhost:8080".into()])); + + // when + let response = request(server, + "\ + POST /rpc HTTP/1.1\r\n\ + Host: localhost:8080\r\n\ + Origin: null\r\n\ + Content-Type: application/json\r\n\ + Connection: close\r\n\ + \r\n\ + {} + " + ); + + // then + assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); + assert!( + !response.headers_raw.contains("Access-Control-Allow-Origin"), + "CORS headers were not expected: {:?}", + response.headers + ); +} + diff --git a/dapps/ui/Cargo.toml b/dapps/ui/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..e71782dfaac37fef3986c31c7ed532a40d2621eb --- /dev/null +++ b/dapps/ui/Cargo.toml @@ -0,0 +1,18 @@ +[package] +description = "Ethcore Parity UI" +homepage = "http://ethcore.io" +license = "GPL-3.0" +name = "parity-ui" +version = "1.4.0" +authors = ["Ethcore "] + +[build-dependencies] +rustc_version = "0.1" + +[dependencies] +parity-ui-dev = { path = "../../js", optional = true } +parity-ui-precompiled = { git = "https://github.com/ethcore/js-precompiled.git", optional = true } + +[features] +no-precompiled-js = ["parity-ui-dev"] +use-precompiled-js = ["parity-ui-precompiled"] diff --git a/dapps/ui/src/lib.rs b/dapps/ui/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..6a69a503df2b43b3e0631d405f6212f1962010d5 --- /dev/null +++ b/dapps/ui/src/lib.rs @@ -0,0 +1,33 @@ +// 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 . + + +#[cfg(feature = "parity-ui-dev")] +mod inner { + extern crate parity_ui_dev; + + pub use self::parity_ui_dev::*; +} + +#[cfg(feature = "parity-ui-precompiled")] +mod inner { + extern crate parity_ui_precompiled; + + pub use self::parity_ui_precompiled::*; +} + + +pub use self::inner::*; diff --git a/db/Cargo.toml b/db/Cargo.toml index 15ceb9b3b6dcedb3fa4a66991a5035544fa89650..27eadef4a5834dbb58e6f923c0300c9d7e6627bd 100644 --- a/db/Cargo.toml +++ b/db/Cargo.toml @@ -11,7 +11,7 @@ build = "build.rs" ethcore-ipc-codegen = { path = "../ipc/codegen" } [dependencies] -clippy = { version = "0.0.90", optional = true} +clippy = { version = "0.0.96", optional = true} ethcore-devtools = { path = "../devtools" } ethcore-ipc = { path = "../ipc/rpc" } rocksdb = { git = "https://github.com/ethcore/rust-rocksdb" } diff --git a/devtools/src/http_client.rs b/devtools/src/http_client.rs index f194c4004e3c109c1ea40d731b2c36473d1c7417..acba2989ecde0477da1a658da1fc5e90e1f7fe0b 100644 --- a/devtools/src/http_client.rs +++ b/devtools/src/http_client.rs @@ -64,3 +64,25 @@ pub fn request(address: &SocketAddr, request: &str) -> Response { } } +/// Check if all required security headers are present +pub fn assert_security_headers_present(headers: &[String], port: Option) { + if let Some(port) = port { + assert!( + headers.iter().find(|header| header.as_str() == &format!("X-Frame-Options: ALLOW-FROM http://127.0.0.1:{}", port)).is_some(), + "X-Frame-Options: ALLOW-FROM missing: {:?}", headers + ); + } else { + assert!( + headers.iter().find(|header| header.as_str() == "X-Frame-Options: SAMEORIGIN").is_some(), + "X-Frame-Options: SAMEORIGIN missing: {:?}", headers + ); + } + assert!( + headers.iter().find(|header| header.as_str() == "X-XSS-Protection: 1; mode=block").is_some(), + "X-XSS-Protection missing: {:?}", headers + ); + assert!( + headers.iter().find(|header| header.as_str() == "X-Content-Type-Options: nosniff").is_some(), + "X-Content-Type-Options missing: {:?}", headers + ); +} diff --git a/docker/ubuntu-stable/Dockerfile b/docker/ubuntu-stable/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2a8ee3da8bf799c883c3e23a208f24ad0c395e60 --- /dev/null +++ b/docker/ubuntu-stable/Dockerfile @@ -0,0 +1,39 @@ +FROM ubuntu:14.04 +WORKDIR /build +# install tools and dependencies +RUN apt-get update && \ + apt-get install -y \ + g++ \ + curl \ + git \ + file \ + binutils + +# install rustup +RUN curl https://sh.rustup.rs -sSf | sh -s -- -y + +# rustup directory +ENV PATH /root/.cargo/bin:$PATH + +# show backtraces +ENV RUST_BACKTRACE 1 + +# show tools +RUN rustc -vV && \ +cargo -V && \ +gcc -v &&\ +g++ -v + +# build parity +RUN git clone https://github.com/ethcore/parity && \ + cd parity && \ + git checkout stable && \ + git pull && \ + cargo build --release --verbose && \ + ls /build/parity/target/release/parity && \ + strip /build/parity/target/release/parity + +RUN file /build/parity/target/release/parity + +EXPOSE 8080 8545 8180 +ENTRYPOINT ["/build/parity/target/release/parity"] diff --git a/ethash/Cargo.toml b/ethash/Cargo.toml index bbfe3d6182b0cc46924e788c94eda5cdbde0a2ac..d2fb37d9446648e360b2376a19afdd1bf48f97ba 100644 --- a/ethash/Cargo.toml +++ b/ethash/Cargo.toml @@ -9,4 +9,4 @@ authors = ["arkpar lights.recent.clone(), _ => match lights.prev_epoch.clone() { Some(e) if e == epoch => { - // swap - let t = lights.prev_epoch; - lights.prev_epoch = lights.recent_epoch; - lights.recent_epoch = t; - let t = lights.prev.clone(); - lights.prev = lights.recent.clone(); - lights.recent = t; - lights.recent.clone() + // don't swap if recent is newer. + if lights.recent_epoch > lights.prev_epoch { + None + } else { + // swap + let t = lights.prev_epoch; + lights.prev_epoch = lights.recent_epoch; + lights.recent_epoch = t; + let t = lights.prev.clone(); + lights.prev = lights.recent.clone(); + lights.recent = t; + lights.recent.clone() + } } _ => None, }, diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index 7bda7e567382522e7f2f7bfc0755fc3a1c06d006..1f8413339473f5ff080ed7a6defbe6d6383ef9d7 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -24,8 +24,11 @@ rayon = "0.4.2" semver = "0.2" bit-set = "0.4" time = "0.1" +rand = "0.3" +byteorder = "0.5" +transient-hashmap = "0.1" evmjit = { path = "../evmjit", optional = true } -clippy = { version = "0.0.90", optional = true} +clippy = { version = "0.0.96", optional = true} ethash = { path = "../ethash" } ethcore-util = { path = "../util" } ethcore-io = { path = "../util/io" } @@ -36,10 +39,8 @@ ethstore = { path = "../ethstore" } ethkey = { path = "../ethkey" } ethcore-ipc-nano = { path = "../ipc/nano" } rlp = { path = "../util/rlp" } -rand = "0.3" -lru-cache = "0.0.7" +lru-cache = "0.1.0" ethcore-bloom-journal = { path = "../util/bloom" } -byteorder = "0.5" [dependencies.hyper] git = "https://github.com/ethcore/hyper" diff --git a/ethcore/res/ethereum/classic.json b/ethcore/res/ethereum/classic.json index 8feee79e61ca42f6a413ee8a31fe63bdad7d7f13..5be7b1caf8437da7e09f9bfbf00357b333a23d5d 100644 --- a/ethcore/res/ethereum/classic.json +++ b/ethcore/res/ethereum/classic.json @@ -10,7 +10,8 @@ "durationLimit": "0x0d", "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", - "frontierCompatibilityModeLimit": "0x118c30" + "homesteadTransition": "0x118c30", + "eip150Transition": "0x2625a0" } } }, @@ -38,10 +39,18 @@ "stateRoot": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544" }, "nodes": [ + "enode://08c7ee6a4f861ff0664a49532bcc86de1363acd608999d1b76609bb9bc278649906f069057630fd9493924a368b5d1dc9b8f8bf13ac26df72512f6d1fabd8c95@45.32.7.81:30303", "enode://e809c4a2fec7daed400e5e28564e23693b23b2cc5a019b612505631bbe7b9ccf709c1796d2a3d29ef2b045f210caf51e3c4f5b6d3587d43ad5d6397526fa6179@174.112.32.157:30303", "enode://687be94c3a7beaa3d2fde82fa5046cdeb3e8198354e05b29d6e0d4e276713e3707ac10f784a7904938b06b46c764875c241b0337dd853385a4d8bfcbf8190647@95.183.51.229:30303", "enode://6e538e7c1280f0a31ff08b382db5302480f775480b8e68f8febca0ceff81e4b19153c6f8bf60313b93bef2cc34d34e1df41317de0ce613a201d1660a788a03e2@52.206.67.235:30303", - "enode://217ebe27e89bf4fec8ce06509323ff095b1014378deb75ab2e5f6759a4e8750a3bd8254b8c6833136e4d5e58230d65ee8ab34a5db5abf0640408c4288af3c8a7@188.138.1.237:30303" + "enode://ca5ae4eca09ba6787e29cf6d86f7634d07aae6b9e6317a59aff675851c0bf445068173208cf8ef7f5cd783d8e29b85b2fa3fa358124cf0546823149724f9bde1@138.68.1.16:30303", + "enode://217ebe27e89bf4fec8ce06509323ff095b1014378deb75ab2e5f6759a4e8750a3bd8254b8c6833136e4d5e58230d65ee8ab34a5db5abf0640408c4288af3c8a7@188.138.1.237:30303", + "enode://fa20444ef991596ce99b81652ac4e61de1eddc4ff21d3cd42762abd7ed47e7cf044d3c9ccddaf6035d39725e4eb372806787829ccb9a08ec7cb71883cb8c3abd@50.149.116.182:30303", + "enode://4bd6a4df3612c718333eb5ea7f817923a8cdf1bed89cee70d1710b45a0b6b77b2819846440555e451a9b602ad2efa2d2facd4620650249d8468008946887820a@71.178.232.20:30304", + "enode://921cf8e4c345fe8db913c53964f9cadc667644e7f20195a0b7d877bd689a5934e146ff2c2259f1bae6817b6585153a007ceb67d260b720fa3e6fc4350df25c7f@51.255.49.170:30303", + "enode://ffea3b01c000cdd89e1e9229fea3e80e95b646f9b2aa55071fc865e2f19543c9b06045cc2e69453e6b78100a119e66be1b5ad50b36f2ffd27293caa28efdd1b2@128.199.93.177:3030", + "enode://ee3da491ce6a155eb132708eb0e8d04b0637926ec0ae1b79e63fc97cb9fc3818f49250a0ae0d7f79ed62b66ec677f408c4e01741504dc7a051e274f1e803d454@91.121.65.179:40404", + "enode://48e063a6cf5f335b1ef2ed98126bf522cf254396f850c7d442fe2edbbc23398787e14cd4de7968a00175a82762de9cbe9e1407d8ccbcaeca5004d65f8398d759@159.203.255.59:30303" ], "accounts": { "0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } }, diff --git a/ethcore/res/ethereum/eip150_test.json b/ethcore/res/ethereum/eip150_test.json new file mode 100644 index 0000000000000000000000000000000000000000..39d4b3fe8fdbdf5e232014401c1aa344688f9bc1 --- /dev/null +++ b/ethcore/res/ethereum/eip150_test.json @@ -0,0 +1,43 @@ +{ + "name": "Homestead (Test)", + "engine": { + "Ethash": { + "params": { + "gasLimitBoundDivisor": "0x0400", + "minimumDifficulty": "0x020000", + "difficultyBoundDivisor": "0x0800", + "durationLimit": "0x0d", + "blockReward": "0x4563918244F40000", + "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", + "homesteadTransition": "0x0", + "eip150Transition": "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 9b005096b453465487f89c43ba3c8a9705db5b7b..d2d036487e3de3552be7e61303c0bcdb5b7594c4 100644 --- a/ethcore/res/ethereum/expanse.json +++ b/ethcore/res/ethereum/expanse.json @@ -11,10 +11,11 @@ "durationLimit": "0x3C", "blockReward": "0x6f05b59d3b200000", "registrar" : "0x6c221ca53705f3497ec90ca7b84c59ae7382fc21", - "frontierCompatibilityModeLimit": "0x30d40", + "homesteadTransition": "0x30d40", "difficultyHardforkTransition": "0x59d9", "difficultyHardforkBoundDivisor": "0x0200", - "bombDefuseTransition": "0x30d40" + "bombDefuseTransition": "0x30d40", + "eip150Transition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/frontier.json b/ethcore/res/ethereum/frontier.json index 903e87cc7bacc5b3a0517734a22484d7dbe8e9e8..111dff30e7a3bde8bfb54b0ac3905d7b4ceffa3c 100644 --- a/ethcore/res/ethereum/frontier.json +++ b/ethcore/res/ethereum/frontier.json @@ -8,11 +8,11 @@ "difficultyBoundDivisor": "0x0800", "durationLimit": "0x0d", "blockReward": "0x4563918244F40000", - "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", - "frontierCompatibilityModeLimit": "0x118c30", + "registrar" : "0x3bb2bb5c6c9c9b7f4ef430b47dc7e026310042ea", + "homesteadTransition": "0x118c30", "daoHardforkTransition": "0x1d4c00", "daoHardforkBeneficiary": "0xbf4ed7b27f1d666546e30d74d50d173d20bca754", - "daoHardforkAccounts": [ + "daoHardforkAccounts": [ "0xd4fe7bc31cedb7bfb8a345f31e668033056b2728", "0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425", "0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f", @@ -129,7 +129,8 @@ "0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97", "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" - ] + ], + "eip150Transition": "0x259518" } } }, @@ -157,13 +158,21 @@ "stateRoot": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544" }, "nodes": [ - "enode://cd6611461840543d5b9c56fbf088736154c699c43973b3a1a32390cf27106f87e58a818a606ccb05f3866de95a4fe860786fea71bf891ea95f234480d3022aa3@136.243.154.245:30303", + "enode://efe4f2493f4aff2d641b1db8366b96ddacfe13e7a6e9c8f8f8cf49f9cdba0fdf3258d8c8f8d0c5db529f8123c8f1d95f36d54d590ca1bb366a5818b9a4ba521c@163.172.187.252:30303", + "enode://cd6611461840543d5b9c56fbf088736154c699c43973b3a1a32390cf27106f87e58a818a606ccb05f3866de95a4fe860786fea71bf891ea95f234480d3022aa3@163.172.157.114:30303", "enode://bcc7240543fe2cf86f5e9093d05753dd83343f8fda7bf0e833f65985c73afccf8f981301e13ef49c4804491eab043647374df1c4adf85766af88a624ecc3330e@136.243.154.244:30303", "enode://ed4227681ca8c70beb2277b9e870353a9693f12e7c548c35df6bca6a956934d6f659999c2decb31f75ce217822eefca149ace914f1cbe461ed5a2ebaf9501455@88.212.206.70:30303", + "enode://cadc6e573b6bc2a9128f2f635ac0db3353e360b56deef239e9be7e7fce039502e0ec670b595f6288c0d2116812516ad6b6ff8d5728ff45eba176989e40dead1e@37.128.191.230:30303", + "enode://595a9a06f8b9bc9835c8723b6a82105aea5d55c66b029b6d44f229d6d135ac3ecdd3e9309360a961ea39d7bee7bac5d03564077a4e08823acc723370aace65ec@46.20.235.22:30303", + "enode://029178d6d6f9f8026fc0bc17d5d1401aac76ec9d86633bba2320b5eed7b312980c0a210b74b20c4f9a8b0b2bf884b111fa9ea5c5f916bb9bbc0e0c8640a0f56c@216.158.85.185:30303", + "enode://84f5d5957b4880a8b0545e32e05472318898ad9fc8ebe1d56c90c12334a98e12351eccfdf3a2bf72432ac38b57e9d348400d17caa083879ade3822390f89773f@10.1.52.78:30303", + "enode://f90dc9b9bf7b8db97726b7849e175f1eb2707f3d8f281c929336e398dd89b0409fc6aeceb89e846278e9d3ecc3857cebfbe6758ff352ece6fe5d42921ee761db@10.1.173.87:30303", + "enode://6a868ced2dec399c53f730261173638a93a40214cf299ccf4d42a76e3fa54701db410669e8006347a4b3a74fa090bb35af0320e4bc8d04cf5b7f582b1db285f5@10.3.149.199:30303", + "enode://fdd1b9bb613cfbc200bba17ce199a9490edc752a833f88d4134bf52bb0d858aa5524cb3ec9366c7a4ef4637754b8b15b5dc913e4ed9fdb6022f7512d7b63f181@212.47.247.103:30303", "enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303", "enode://de471bccee3d042261d52e9bff31458daecc406142b401d4cd848f677479f73104b9fdeb090af9583d3391b7f10cb2ba9e26865dd5fca4fcdc0fb1e3b723c786@54.94.239.50:30303", "enode://1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082@52.74.57.123:30303", - "enode://248f12bc8b18d5289358085520ac78cd8076485211e6d96ab0bc93d6cd25442db0ce3a937dc404f64f207b0b9aed50e25e98ce32af5ac7cb321ff285b97de485@zero.parity.io:30303" + "enode://4cd540b2c3292e17cff39922e864094bf8b0741fcc8c5dcea14957e389d7944c70278d872902e3d0345927f621547efa659013c400865485ab4bfa0c6596936f@138.201.144.135:30303" ], "accounts": { "0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } }, diff --git a/ethcore/res/ethereum/frontier_like_test.json b/ethcore/res/ethereum/frontier_like_test.json index aab48e78edac9ec157edeeba2026ed38c1c9d3ca..99a7ad7128f861b8bf6ed081ec0ed472242d2b03 100644 --- a/ethcore/res/ethereum/frontier_like_test.json +++ b/ethcore/res/ethereum/frontier_like_test.json @@ -9,7 +9,7 @@ "durationLimit": "0x0d", "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", - "frontierCompatibilityModeLimit": "0x118c30", + "homesteadTransition": "0x118c30", "daoHardforkTransition": "0x1d4c00", "daoHardforkBeneficiary": "0xbf4ed7b27f1d666546e30d74d50d173d20bca754", "daoHardforkAccounts": [ @@ -129,7 +129,8 @@ "0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97", "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" - ] + ], + "eip150Transition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/frontier_test.json b/ethcore/res/ethereum/frontier_test.json index 3964d33adf0a7eb1c99e885a4cda2089aebfda83..1cb3d8cfc0394933ec143828172c8083a0f4e429 100644 --- a/ethcore/res/ethereum/frontier_test.json +++ b/ethcore/res/ethereum/frontier_test.json @@ -9,7 +9,8 @@ "durationLimit": "0x0d", "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", - "frontierCompatibilityModeLimit": "0xffffffffffffffff" + "homesteadTransition": "0x7fffffffffffffff", + "eip150Transition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/homestead_test.json b/ethcore/res/ethereum/homestead_test.json index 8a362009ff4c0896ab1a2e4ced09d0ae84668f43..ad64ce2d530eece054c76b44d8884a5fc864964f 100644 --- a/ethcore/res/ethereum/homestead_test.json +++ b/ethcore/res/ethereum/homestead_test.json @@ -9,7 +9,8 @@ "durationLimit": "0x0d", "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", - "frontierCompatibilityModeLimit": "0x0" + "homesteadTransition": "0x0", + "eip150Transition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/morden.json b/ethcore/res/ethereum/morden.json index ef18df97d6d92a355048a99b40791d64067d3845..67d9ce0440059162910e7ad43319e2ba989d98b2 100644 --- a/ethcore/res/ethereum/morden.json +++ b/ethcore/res/ethereum/morden.json @@ -9,7 +9,8 @@ "durationLimit": "0x0d", "blockReward": "0x4563918244F40000", "registrar": "0x52dff57a8a1532e6afb3dc07e2af58bb9eb05b3d", - "frontierCompatibilityModeLimit": "0x789b0" + "homesteadTransition": "0x789b0", + "eip150Transition": "0x1b34d8" } } }, @@ -17,7 +18,9 @@ "accountStartNonce": "0x0100000", "maximumExtraDataSize": "0x20", "minGasLimit": "0x1388", - "networkID" : "0x2" + "networkID" : "0x2", + "forkBlock": "0x1b34d8", + "forkCanonHash": "0xf376243aeff1f256d970714c3de9fd78fa4e63cf63e32a51fe1169e375d98145" }, "genesis": { "seal": { diff --git a/ethcore/res/ethereum/olympic.json b/ethcore/res/ethereum/olympic.json index 99686b073651ebcdd7692a25c486a91d85de4411..ebc7abd4ea2564eeb4ccb5b349e174a363246555 100644 --- a/ethcore/res/ethereum/olympic.json +++ b/ethcore/res/ethereum/olympic.json @@ -8,7 +8,9 @@ "difficultyBoundDivisor": "0x0800", "durationLimit": "0x08", "blockReward": "0x14D1120D7B160000", - "registrar": "5e70c0bbcd5636e0f9f9316e9f8633feb64d4050" + "registrar": "5e70c0bbcd5636e0f9f9316e9f8633feb64d4050", + "homesteadTransition": "0x7fffffffffffffff", + "eip150Transition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/tests b/ethcore/res/ethereum/tests index ac5475d676536cb945f98e9ff98384c01abd0599..97066e40ccd061f727deb5cd860e4d9135aa2551 160000 --- a/ethcore/res/ethereum/tests +++ b/ethcore/res/ethereum/tests @@ -1 +1 @@ -Subproject commit ac5475d676536cb945f98e9ff98384c01abd0599 +Subproject commit 97066e40ccd061f727deb5cd860e4d9135aa2551 diff --git a/ethcore/res/ethereum/daohardfork_test.json b/ethcore/res/ethereum/transition_test.json similarity index 98% rename from ethcore/res/ethereum/daohardfork_test.json rename to ethcore/res/ethereum/transition_test.json index 90875f4f604a64832a118c3180b7f5208b41d04b..c004bc2ba3853b34093a694cc9375bba448194ed 100644 --- a/ethcore/res/ethereum/daohardfork_test.json +++ b/ethcore/res/ethereum/transition_test.json @@ -1,5 +1,5 @@ { - "name": "DAO hard-fork consensus test", + "name": "EIP150.1b hard-fork consensus test", "engine": { "Ethash": { "params": { @@ -9,7 +9,7 @@ "durationLimit": "0x0d", "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", - "frontierCompatibilityModeLimit": "0x5", + "homesteadTransition": "0x5", "daoHardforkTransition": "0x8", "daoHardforkBeneficiary": "0xbf4ed7b27f1d666546e30d74d50d173d20bca754", "daoHardforkAccounts": [ @@ -129,7 +129,8 @@ "0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97", "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" - ] + ], + "eip150Transition": "0xa" } } }, diff --git a/ethcore/src/account_db.rs b/ethcore/src/account_db.rs index 2d00f8ed587d27267d0ba028571c9cb88f441542..0761b7fba62ddd3e44c58e29178e6d21ca5a23ab 100644 --- a/ethcore/src/account_db.rs +++ b/ethcore/src/account_db.rs @@ -96,9 +96,9 @@ impl<'db> HashDB for AccountDB<'db>{ unimplemented!() } - fn get(&self, key: &H256) -> Option<&[u8]> { + fn get(&self, key: &H256) -> Option { if key == &SHA3_NULL_RLP { - return Some(&NULL_RLP_STATIC); + return Some(DBValue::from_slice(&NULL_RLP_STATIC)); } self.db.get(&combine_key(&self.address_hash, key)) } @@ -114,7 +114,7 @@ impl<'db> HashDB for AccountDB<'db>{ unimplemented!() } - fn emplace(&mut self, _key: H256, _value: Bytes) { + fn emplace(&mut self, _key: H256, _value: DBValue) { unimplemented!() } @@ -122,7 +122,7 @@ impl<'db> HashDB for AccountDB<'db>{ unimplemented!() } - fn get_aux(&self, hash: &[u8]) -> Option> { + fn get_aux(&self, hash: &[u8]) -> Option { self.db.get_aux(hash) } } @@ -158,9 +158,9 @@ impl<'db> HashDB for AccountDBMut<'db>{ unimplemented!() } - fn get(&self, key: &H256) -> Option<&[u8]> { + fn get(&self, key: &H256) -> Option { if key == &SHA3_NULL_RLP { - return Some(&NULL_RLP_STATIC); + return Some(DBValue::from_slice(&NULL_RLP_STATIC)); } self.db.get(&combine_key(&self.address_hash, key)) } @@ -178,16 +178,16 @@ impl<'db> HashDB for AccountDBMut<'db>{ } let k = value.sha3(); let ak = combine_key(&self.address_hash, &k); - self.db.emplace(ak, value.to_vec()); + self.db.emplace(ak, DBValue::from_slice(value)); k } - fn emplace(&mut self, key: H256, value: Bytes) { + fn emplace(&mut self, key: H256, value: DBValue) { if key == SHA3_NULL_RLP { return; } let key = combine_key(&self.address_hash, &key); - self.db.emplace(key, value.to_vec()) + self.db.emplace(key, value) } fn remove(&mut self, key: &H256) { @@ -202,7 +202,7 @@ impl<'db> HashDB for AccountDBMut<'db>{ self.db.insert_aux(hash, value); } - fn get_aux(&self, hash: &[u8]) -> Option> { + fn get_aux(&self, hash: &[u8]) -> Option { self.db.get_aux(hash) } @@ -218,9 +218,9 @@ impl<'db> HashDB for Wrapping<'db> { unimplemented!() } - fn get(&self, key: &H256) -> Option<&[u8]> { + fn get(&self, key: &H256) -> Option { if key == &SHA3_NULL_RLP { - return Some(&NULL_RLP_STATIC); + return Some(DBValue::from_slice(&NULL_RLP_STATIC)); } self.0.get(key) } @@ -236,7 +236,7 @@ impl<'db> HashDB for Wrapping<'db> { unimplemented!() } - fn emplace(&mut self, _key: H256, _value: Bytes) { + fn emplace(&mut self, _key: H256, _value: DBValue) { unimplemented!() } @@ -252,9 +252,9 @@ impl<'db> HashDB for WrappingMut<'db>{ unimplemented!() } - fn get(&self, key: &H256) -> Option<&[u8]> { + fn get(&self, key: &H256) -> Option { if key == &SHA3_NULL_RLP { - return Some(&NULL_RLP_STATIC); + return Some(DBValue::from_slice(&NULL_RLP_STATIC)); } self.0.get(key) } @@ -273,7 +273,7 @@ impl<'db> HashDB for WrappingMut<'db>{ self.0.insert(value) } - fn emplace(&mut self, key: H256, value: Bytes) { + fn emplace(&mut self, key: H256, value: DBValue) { if key == SHA3_NULL_RLP { return; } @@ -286,4 +286,4 @@ impl<'db> HashDB for WrappingMut<'db>{ } self.0.remove(key) } -} \ No newline at end of file +} diff --git a/ethcore/src/account_provider.rs b/ethcore/src/account_provider.rs index 851d015bac16fd395374d152925fa93e695996b1..064c3e93587ab5de9ec61ded835a258d45c58ede 100644 --- a/ethcore/src/account_provider.rs +++ b/ethcore/src/account_provider.rs @@ -23,7 +23,7 @@ use std::time::{Instant, Duration}; use util::{Mutex, RwLock}; use ethstore::{SecretStore, Error as SSError, SafeAccount, EthStore}; use ethstore::dir::{KeyDirectory}; -use ethstore::ethkey::{Address, Message, Secret, Random, Generator}; +use ethstore::ethkey::{Address, Message, Public, Secret, Random, Generator}; use ethjson::misc::AccountMeta; pub use ethstore::ethkey::Signature; @@ -36,7 +36,7 @@ enum Unlock { /// Use with caution. Perm, /// Account unlocked with a timeout - Timed((Instant, u32)), + Timed(Instant), } /// Data associated with account. @@ -176,15 +176,23 @@ impl AccountProvider { AccountProvider { unlocked: Mutex::new(HashMap::new()), address_book: Mutex::new(AddressBook::new(Default::default())), - sstore: Box::new(EthStore::open(Box::new(NullDir::default())).unwrap()) + sstore: Box::new(EthStore::open(Box::new(NullDir::default())) + .expect("NullDir load always succeeds; qed")) } } /// Creates new random account. pub fn new_account(&self, password: &str) -> Result { - let secret = Random.generate().unwrap().secret().clone(); + self.new_account_and_public(password).map(|d| d.0) + } + + /// Creates new random account and returns address and public key + pub fn new_account_and_public(&self, password: &str) -> Result<(Address, Public), Error> { + let acc = Random.generate().expect("secp context has generation capabilities; qed"); + let public = acc.public().clone(); + let secret = acc.secret().clone(); let address = try!(self.sstore.insert_account(secret, password)); - Ok(address) + Ok((address, public)) } /// Inserts new account into underlying store. @@ -257,6 +265,20 @@ impl AccountProvider { Ok(()) } + /// Returns `true` if the password for `account` is `password`. `false` if not. + pub fn test_password(&self, account: &Address, password: String) -> Result { + match self.sstore.sign(account, &password, &Default::default()) { + Ok(_) => Ok(true), + Err(SSError::InvalidPassword) => Ok(false), + Err(e) => Err(Error::SStore(e)), + } + } + + /// Changes the password of `account` from `password` to `new_password`. Fails if incorrect `password` given. + pub fn change_password(&self, account: &Address, password: String, new_password: String) -> Result<(), Error> { + self.sstore.change_password(account, &password, &new_password).map_err(Error::SStore) + } + /// Helper method used for unlocking accounts. fn unlock_account(&self, account: Address, password: String, unlock: Unlock) -> Result<(), Error> { // verify password by signing dump message @@ -280,6 +302,21 @@ impl AccountProvider { Ok(()) } + fn password(&self, account: &Address) -> Result { + let mut unlocked = self.unlocked.lock(); + let data = try!(unlocked.get(account).ok_or(Error::NotUnlocked)).clone(); + if let Unlock::Temp = data.unlock { + unlocked.remove(account).expect("data exists: so key must exist: qed"); + } + if let Unlock::Timed(ref end) = data.unlock { + if Instant::now() > *end { + unlocked.remove(account).expect("data exists: so key must exist: qed"); + return Err(Error::NotUnlocked); + } + } + Ok(data.password.clone()) + } + /// Unlocks account permanently. pub fn unlock_account_permanently(&self, account: Address, password: String) -> Result<(), Error> { self.unlock_account(account, password, Unlock::Perm) @@ -292,7 +329,7 @@ impl AccountProvider { /// Unlocks account temporarily with a timeout. pub fn unlock_account_timed(&self, account: Address, password: String, duration_ms: u32) -> Result<(), Error> { - self.unlock_account(account, password, Unlock::Timed((Instant::now(), duration_ms))) + self.unlock_account(account, password, Unlock::Timed(Instant::now() + Duration::from_millis(duration_ms as u64))) } /// Checks if given account is unlocked @@ -301,51 +338,16 @@ impl AccountProvider { unlocked.get(&account).is_some() } - /// Signs the message. Account must be unlocked. - pub fn sign(&self, account: Address, message: Message) -> Result { - let data = { - let mut unlocked = self.unlocked.lock(); - let data = try!(unlocked.get(&account).ok_or(Error::NotUnlocked)).clone(); - if let Unlock::Temp = data.unlock { - unlocked.remove(&account).expect("data exists: so key must exist: qed"); - } - if let Unlock::Timed((ref start, ref duration)) = data.unlock { - if start.elapsed() > Duration::from_millis(*duration as u64) { - unlocked.remove(&account).expect("data exists: so key must exist: qed"); - return Err(Error::NotUnlocked); - } - } - data - }; - - let signature = try!(self.sstore.sign(&account, &data.password, &message)); - Ok(signature) - } - - /// Decrypts a message. Account must be unlocked. - pub fn decrypt(&self, account: Address, shared_mac: &[u8], message: &[u8]) -> Result, Error> { - let data = { - let mut unlocked = self.unlocked.lock(); - let data = try!(unlocked.get(&account).ok_or(Error::NotUnlocked)).clone(); - if let Unlock::Temp = data.unlock { - unlocked.remove(&account).expect("data exists: so key must exist: qed"); - } - if let Unlock::Timed((ref start, ref duration)) = data.unlock { - if start.elapsed() > Duration::from_millis(*duration as u64) { - unlocked.remove(&account).expect("data exists: so key must exist: qed"); - return Err(Error::NotUnlocked); - } - } - data - }; - - Ok(try!(self.sstore.decrypt(&account, &data.password, shared_mac, message))) + /// Signs the message. If password is not provided the account must be unlocked. + pub fn sign(&self, account: Address, password: Option, message: Message) -> Result { + let password = try!(password.map(Ok).unwrap_or_else(|| self.password(&account))); + Ok(try!(self.sstore.sign(&account, &password, &message))) } - /// Unlocks an account, signs the message, and locks it again. - pub fn sign_with_password(&self, account: Address, password: String, message: Message) -> Result { - let signature = try!(self.sstore.sign(&account, &password, &message)); - Ok(signature) + /// Decrypts a message. If password is not provided the account must be unlocked. + pub fn decrypt(&self, account: Address, password: Option, shared_mac: &[u8], message: &[u8]) -> Result, Error> { + let password = try!(password.map(Ok).unwrap_or_else(|| self.password(&account))); + Ok(try!(self.sstore.decrypt(&account, &password, shared_mac, message))) } /// Returns the underlying `SecretStore` reference if one exists. @@ -361,11 +363,11 @@ impl AccountProvider { #[cfg(test)] mod tests { - use super::{AccountProvider, AddressBook}; + use super::{AccountProvider, AddressBook, Unlock}; use std::collections::HashMap; + use std::time::Instant; use ethjson::misc::AccountMeta; use ethstore::ethkey::{Generator, Random}; - use std::time::Duration; use devtools::RandomTempPath; #[test] @@ -386,8 +388,8 @@ mod tests { assert!(ap.insert_account(kp.secret().clone(), "test").is_ok()); assert!(ap.unlock_account_temporarily(kp.address(), "test1".into()).is_err()); assert!(ap.unlock_account_temporarily(kp.address(), "test".into()).is_ok()); - assert!(ap.sign(kp.address(), Default::default()).is_ok()); - assert!(ap.sign(kp.address(), Default::default()).is_err()); + assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, Default::default()).is_err()); } #[test] @@ -397,11 +399,11 @@ mod tests { assert!(ap.insert_account(kp.secret().clone(), "test").is_ok()); assert!(ap.unlock_account_permanently(kp.address(), "test1".into()).is_err()); assert!(ap.unlock_account_permanently(kp.address(), "test".into()).is_ok()); - assert!(ap.sign(kp.address(), Default::default()).is_ok()); - assert!(ap.sign(kp.address(), Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); assert!(ap.unlock_account_temporarily(kp.address(), "test".into()).is_ok()); - assert!(ap.sign(kp.address(), Default::default()).is_ok()); - assert!(ap.sign(kp.address(), Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); } #[test] @@ -409,10 +411,10 @@ mod tests { let kp = Random.generate().unwrap(); let ap = AccountProvider::transient_provider(); assert!(ap.insert_account(kp.secret().clone(), "test").is_ok()); - assert!(ap.unlock_account_timed(kp.address(), "test1".into(), 2000).is_err()); - assert!(ap.unlock_account_timed(kp.address(), "test".into(), 2000).is_ok()); - assert!(ap.sign(kp.address(), Default::default()).is_ok()); - ::std::thread::sleep(Duration::from_millis(2000)); - assert!(ap.sign(kp.address(), Default::default()).is_err()); + assert!(ap.unlock_account_timed(kp.address(), "test1".into(), 60000).is_err()); + assert!(ap.unlock_account_timed(kp.address(), "test".into(), 60000).is_ok()); + assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); + ap.unlocked.lock().get_mut(&kp.address()).unwrap().unlock = Unlock::Timed(Instant::now()); + assert!(ap.sign(kp.address(), None, Default::default()).is_err()); } } diff --git a/ethcore/src/action_params.rs b/ethcore/src/action_params.rs index 46c159269be3de44313a2ad29f64ea53c5e9813d..8b863c6256b1af5056ba7359bd3e550d6057f714 100644 --- a/ethcore/src/action_params.rs +++ b/ethcore/src/action_params.rs @@ -15,10 +15,14 @@ // along with Parity. If not, see . //! Evm input params. -use common::*; +use util::{Address, Bytes, Uint, U256}; +use util::hash::{H256, FixedHash}; +use util::sha3::{Hashable, SHA3_EMPTY}; use ethjson; use types::executed::CallType; +use std::sync::Arc; + /// Transaction value #[derive(Clone, Debug)] pub enum ActionValue { diff --git a/ethcore/src/basic_types.rs b/ethcore/src/basic_types.rs index e2a705dd7a9ee72709e6e739bd9a1e79b369b136..5c0100de3b9e2207419dc60d2bf103b9c1bda2b7 100644 --- a/ethcore/src/basic_types.rs +++ b/ethcore/src/basic_types.rs @@ -16,7 +16,7 @@ //! Ethcore basic typenames. -use util::*; +use util::hash::H2048; /// Type for a 2048-bit log-bloom, as used by our blocks. pub type LogBloom = H2048; diff --git a/ethcore/src/block.rs b/ethcore/src/block.rs index 80c35d1d0aa0294f8a2982453f974f89015e074f..54c2a7a02076873b7b909938abda09ee5d5fd500 100644 --- a/ethcore/src/block.rs +++ b/ethcore/src/block.rs @@ -350,7 +350,7 @@ impl<'x> OpenBlock<'x> { let t = outcome.trace; self.block.traces.as_mut().map(|traces| traces.push(t)); self.block.receipts.push(outcome.receipt); - Ok(self.block.receipts.last().unwrap()) + Ok(self.block.receipts.last().expect("receipt just pushed; qed")) } Err(x) => Err(From::from(x)) } @@ -404,6 +404,10 @@ impl<'x> OpenBlock<'x> { uncle_bytes: uncle_bytes, } } + + #[cfg(test)] + /// Return mutable block reference. To be used in tests only. + pub fn block_mut (&mut self) -> &mut ExecutedBlock { &mut self.block } } impl<'x> IsBlock for OpenBlock<'x> { @@ -538,7 +542,7 @@ pub fn enact( Ok(b.close_and_lock()) } -#[inline(always)] +#[inline] #[cfg(not(feature = "slow-blocks"))] fn push_transactions(block: &mut OpenBlock, transactions: &[SignedTransaction]) -> Result<(), Error> { for t in transactions { @@ -583,10 +587,17 @@ pub fn enact_verified( mod tests { use tests::helpers::*; use super::*; - use common::*; use engines::Engine; + use env_info::LastHashes; + use error::Error; + use header::Header; use factory::Factories; use state_db::StateDB; + use views::BlockView; + use util::Address; + use util::hash::FixedHash; + + use std::sync::Arc; /// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header #[cfg_attr(feature="dev", allow(too_many_arguments))] diff --git a/ethcore/src/blockchain/best_block.rs b/ethcore/src/blockchain/best_block.rs index 0cea6190cf06c2a6a8bd1c250a6d69d4ee18ecc2..d5a6c06b2dfe85138da6de13412d65046cc11f87 100644 --- a/ethcore/src/blockchain/best_block.rs +++ b/ethcore/src/blockchain/best_block.rs @@ -29,3 +29,12 @@ pub struct BestBlock { /// Best block uncompressed bytes pub block: Bytes, } + +/// Best ancient block info. If the blockchain has a gap this keeps track of where it starts. +#[derive(Default)] +pub struct BestAncientBlock { + /// Best block hash. + pub hash: H256, + /// Best block number. + pub number: BlockNumber, +} diff --git a/ethcore/src/blockchain/blockchain.rs b/ethcore/src/blockchain/blockchain.rs index d599f957f0e662b7c81e4e97c648aa60ee633d97..8643975b8a461645f3e3c93a8add060640e6e376 100644 --- a/ethcore/src/blockchain/blockchain.rs +++ b/ethcore/src/blockchain/blockchain.rs @@ -27,7 +27,8 @@ use log_entry::{LogEntry, LocalizedLogEntry}; use receipt::Receipt; use blooms::{Bloom, BloomGroup}; use blockchain::block_info::{BlockInfo, BlockLocation, BranchBecomingCanonChainData}; -use blockchain::best_block::BestBlock; +use blockchain::best_block::{BestBlock, BestAncientBlock}; +use types::blockchain_info::BlockChainInfo; use types::tree_route::TreeRoute; use blockchain::update::ExtrasUpdate; use blockchain::{CacheSize, ImportRoute, Config}; @@ -44,16 +45,24 @@ pub trait BlockProvider { /// (though not necessarily a part of the canon chain). fn is_known(&self, hash: &H256) -> bool; - /// Get the first block which this chain holds. + /// Get the first block of the best part of the chain. + /// Return `None` if there is no gap and the first block is the genesis. /// Any queries of blocks which precede this one are not guaranteed to /// succeed. - fn first_block(&self) -> H256; + fn first_block(&self) -> Option; /// Get the number of the first block. - fn first_block_number(&self) -> BlockNumber { - self.block_number(&self.first_block()).expect("First block always stored; qed") + fn first_block_number(&self) -> Option { + self.first_block().map(|b| self.block_number(&b).expect("First block is always set to an existing block or `None`. Existing block always has a number; qed")) } + /// Get the best block of an first block sequence if there is a gap. + fn best_ancient_block(&self) -> Option; + + /// Get the number of the first block. + fn best_ancient_number(&self) -> Option { + self.best_ancient_block().map(|h| self.block_number(&h).expect("Ancient block is always set to an existing block or `None`. Existing block always has a number; qed")) + } /// Get raw block data fn block(&self, hash: &H256) -> Option; @@ -124,7 +133,8 @@ pub trait BlockProvider { /// Returns the header of the genesis block. fn genesis_header(&self) -> Header { - self.block_header(&self.genesis_hash()).unwrap() + self.block_header(&self.genesis_hash()) + .expect("Genesis header always stored; qed") } /// Returns numbers of blocks containing given bloom. @@ -161,9 +171,14 @@ impl bc::group::BloomGroupDatabase for BlockChain { pub struct BlockChain { // All locks must be captured in the order declared here. blooms_config: bc::Config, - first_block: H256, best_block: RwLock, + // Stores best block of the first uninterrupted sequence of blocks. `None` if there are no gaps. + // Only updated with `insert_unordered_block`. + best_ancient_block: RwLock>, + // Stores the last block of the last sequence of blocks. `None` if there are no gaps. + // This is calculated on start and does not get updated. + first_block: Option, // block cache block_headers: RwLock>, @@ -182,6 +197,7 @@ pub struct BlockChain { pending_best_block: RwLock>, pending_block_hashes: RwLock>, + pending_block_details: RwLock>, pending_transaction_addresses: RwLock>>, engine: Arc, @@ -194,8 +210,16 @@ impl BlockProvider for BlockChain { self.db.exists_with_cache(db::COL_EXTRA, &self.block_details, hash) } - fn first_block(&self) -> H256 { - self.first_block + fn first_block(&self) -> Option { + self.first_block.clone() + } + + fn best_ancient_block(&self) -> Option { + self.best_ancient_block.read().as_ref().map(|b| b.hash.clone()) + } + + fn best_ancient_number(&self) -> Option { + self.best_ancient_block.read().as_ref().map(|b| b.number) } /// Get raw block data @@ -335,7 +359,10 @@ impl BlockProvider for BlockChain { .filter_map(|(number, hash)| self.block_receipts(&hash).map(|r| (number, hash, r.receipts))) .filter_map(|(number, hash, receipts)| self.block_body(&hash).map(|ref b| (number, hash, receipts, BodyView::new(b).transaction_hashes()))) .flat_map(|(number, hash, mut receipts, mut hashes)| { - assert_eq!(receipts.len(), hashes.len()); + if receipts.len() != hashes.len() { + warn!("Block {} ({}) has different number of receipts ({}) to transactions ({}). Database corrupt?", number, hash, receipts.len(), hashes.len()); + assert!(false); + } log_index = receipts.iter().fold(0, |sum, receipt| sum + receipt.logs.len()); let receipts_len = receipts.len(); @@ -371,6 +398,8 @@ impl BlockProvider for BlockChain { } } +/// An iterator which walks the blockchain towards the genesis. +#[derive(Clone)] pub struct AncestryIter<'a> { current: H256, chain: &'a BlockChain, @@ -380,11 +409,10 @@ impl<'a> Iterator for AncestryIter<'a> { type Item = H256; fn next(&mut self) -> Option { if self.current.is_zero() { - Option::None + None } else { - let mut n = self.chain.block_details(&self.current).unwrap().parent; - mem::swap(&mut self.current, &mut n); - Some(n) + self.chain.block_details(&self.current) + .map(|details| mem::replace(&mut self.current, details.parent)) } } } @@ -400,8 +428,9 @@ impl BlockChain { levels: LOG_BLOOMS_LEVELS, elements_per_index: LOG_BLOOMS_ELEMENTS_PER_INDEX, }, - first_block: H256::zero(), + first_block: None, best_block: RwLock::new(BestBlock::default()), + best_ancient_block: RwLock::new(None), block_headers: RwLock::new(HashMap::new()), block_bodies: RwLock::new(HashMap::new()), block_details: RwLock::new(HashMap::new()), @@ -413,6 +442,7 @@ impl BlockChain { cache_man: Mutex::new(cache_man), pending_best_block: RwLock::new(None), pending_block_hashes: RwLock::new(HashMap::new()), + pending_block_details: RwLock::new(HashMap::new()), pending_transaction_addresses: RwLock::new(HashMap::new()), engine: engine, }; @@ -444,7 +474,6 @@ impl BlockChain { batch.write(db::COL_EXTRA, &header.number(), &hash); batch.put(db::COL_EXTRA, b"best", &hash); - batch.put(db::COL_EXTRA, b"first", &hash); bc.db.write(batch).expect("Low level database error. Some issue with disk?"); hash } @@ -456,32 +485,45 @@ impl BlockChain { let best_block_total_difficulty = bc.block_details(&best_block_hash).unwrap().total_difficulty; let best_block_rlp = bc.block(&best_block_hash).unwrap(); - let raw_first = bc.db.get(db::COL_EXTRA, b"first").unwrap().map_or(Vec::new(), |v| v.to_vec()); + let raw_first = bc.db.get(db::COL_EXTRA, b"first").unwrap().map(|v| v.to_vec()); + let mut best_ancient = bc.db.get(db::COL_EXTRA, b"ancient").unwrap().map(|h| H256::from_slice(&h)); + let best_ancient_number; + if best_ancient.is_none() && best_block_number > 1 && bc.block_hash(1).is_none() { + best_ancient = Some(bc.genesis_hash()); + best_ancient_number = Some(0); + } else { + best_ancient_number = best_ancient.as_ref().and_then(|h| bc.block_number(h)); + } // binary search for the first block. - if raw_first.is_empty() { - let (mut f, mut hash) = (best_block_number, best_block_hash); - let mut l = 0; + match raw_first { + None => { + let (mut f, mut hash) = (best_block_number, best_block_hash); + let mut l = best_ancient_number.unwrap_or(0); - loop { - if l >= f { break; } + loop { + if l >= f { break; } - let step = (f - l) >> 1; - let m = l + step; + let step = (f - l) >> 1; + let m = l + step; - match bc.block_hash(m) { - Some(h) => { f = m; hash = h }, - None => { l = m + 1 }, + match bc.block_hash(m) { + Some(h) => { f = m; hash = h }, + None => { l = m + 1 }, + } } - } - - let mut batch = db.transaction(); - batch.put(db::COL_EXTRA, b"first", &hash); - db.write(batch).expect("Low level database error."); - bc.first_block = hash; - } else { - bc.first_block = H256::from_slice(&raw_first); + if hash != bc.genesis_hash() { + trace!("First block calculated: {:?}", hash); + let mut batch = db.transaction(); + batch.put(db::COL_EXTRA, b"first", &hash); + db.write(batch).expect("Low level database error."); + bc.first_block = Some(hash); + } + }, + Some(raw_first) => { + bc.first_block = Some(H256::from_slice(&raw_first)); + }, } // and write them @@ -492,6 +534,14 @@ impl BlockChain { hash: best_block_hash, block: best_block_rlp, }; + + if let (Some(hash), Some(number)) = (best_ancient, best_ancient_number) { + let mut best_ancient_block = bc.best_ancient_block.write(); + *best_ancient_block = Some(BestAncientBlock { + hash: hash, + number: number, + }); + } } bc @@ -521,7 +571,7 @@ impl BlockChain { let range = extras.number as bc::Number .. extras.number as bc::Number; let chain = bc::group::BloomGroupChain::new(self.blooms_config, self); let changes = chain.replace(&range, vec![]); - for (k, v) in changes.into_iter() { + for (k, v) in changes { batch.write(db::COL_EXTRA, &LogGroupPosition::from(k), &BloomGroup::from(v)); } batch.put(db::COL_EXTRA, b"best", &hash); @@ -645,11 +695,12 @@ impl BlockChain { /// Inserts a verified, known block from the canonical chain. /// /// Can be performed out-of-order, but care must be taken that the final chain is in a correct state. - /// This is used by snapshot restoration. - /// + /// This is used by snapshot restoration and when downloading missing blocks for the chain gap. + /// `is_best` forces the best block to be updated to this block. + /// `is_ancient` forces the best block of the first block sequence to be updated to this block. /// Supply a dummy parent total difficulty when the parent block may not be in the chain. /// Returns true if the block is disconnected. - pub fn insert_snapshot_block(&self, bytes: &[u8], receipts: Vec, parent_td: Option, is_best: bool) -> bool { + pub fn insert_unordered_block(&self, batch: &mut DBTransaction, bytes: &[u8], receipts: Vec, parent_td: Option, is_best: bool, is_ancient: bool) -> bool { let block = BlockView::new(bytes); let header = block.header_view(); let hash = header.sha3(); @@ -660,8 +711,6 @@ impl BlockChain { assert!(self.pending_best_block.read().is_none()); - let mut batch = self.db.transaction(); - let block_rlp = UntrustedRlp::new(bytes); let compressed_header = block_rlp.at(0).unwrap().compress(RlpType::Blocks); let compressed_body = UntrustedRlp::new(&Self::block_to_body(bytes)).compress(RlpType::Blocks); @@ -675,13 +724,13 @@ impl BlockChain { if let Some(parent_details) = maybe_parent { // parent known to be in chain. let info = BlockInfo { - hash: hash, + hash: hash.clone(), number: header.number(), total_difficulty: parent_details.total_difficulty + header.difficulty(), location: BlockLocation::CanonChain, }; - self.prepare_update(&mut batch, ExtrasUpdate { + self.prepare_update(batch, ExtrasUpdate { block_hashes: self.prepare_block_hashes_update(bytes, &info), block_details: self.prepare_block_details_update(bytes, &info), block_receipts: self.prepare_block_receipts_update(receipts, &info), @@ -690,7 +739,21 @@ impl BlockChain { info: info, block: bytes }, is_best); - self.db.write(batch).unwrap(); + + if is_ancient { + let mut best_ancient_block = self.best_ancient_block.write(); + let ancient_number = best_ancient_block.as_ref().map_or(0, |b| b.number); + if self.block_hash(header.number() + 1).is_some() { + batch.delete(db::COL_EXTRA, b"ancient"); + *best_ancient_block = None; + } else if header.number() > ancient_number { + batch.put(db::COL_EXTRA, b"ancient", &hash); + *best_ancient_block = Some(BestAncientBlock { + hash: hash, + number: header.number(), + }); + } + } false } else { @@ -715,7 +778,7 @@ impl BlockChain { let mut update = HashMap::new(); update.insert(hash, block_details); - self.prepare_update(&mut batch, ExtrasUpdate { + self.prepare_update(batch, ExtrasUpdate { block_hashes: self.prepare_block_hashes_update(bytes, &info), block_details: update, block_receipts: self.prepare_block_receipts_update(receipts, &info), @@ -724,8 +787,6 @@ impl BlockChain { info: info, block: bytes, }, is_best); - self.db.write(batch).unwrap(); - true } } @@ -734,11 +795,10 @@ impl BlockChain { /// the chain and the child's parent is this block. /// /// Used in snapshots to glue the chunks together at the end. - pub fn add_child(&self, block_hash: H256, child_hash: H256) { + pub fn add_child(&self, batch: &mut DBTransaction, block_hash: H256, child_hash: H256) { let mut parent_details = self.block_details(&block_hash) .unwrap_or_else(|| panic!("Invalid block hash: {:?}", block_hash)); - let mut batch = self.db.transaction(); parent_details.children.push(child_hash); let mut update = HashMap::new(); @@ -749,8 +809,6 @@ impl BlockChain { batch.extend_with_cache(db::COL_EXTRA, &mut *write_details, update, CacheUpdatePolicy::Overwrite); self.cache_man.lock().note_used(CacheID::BlockDetails(block_hash)); - - self.db.write(batch).unwrap(); } #[cfg_attr(feature="dev", allow(similar_names))] @@ -838,17 +896,6 @@ impl BlockChain { /// Prepares extras update. fn prepare_update(&self, batch: &mut DBTransaction, update: ExtrasUpdate, is_best: bool) { - { - let block_hashes: Vec<_> = update.block_details.keys().cloned().collect(); - - let mut write_details = self.block_details.write(); - batch.extend_with_cache(db::COL_EXTRA, &mut *write_details, update.block_details, CacheUpdatePolicy::Overwrite); - - let mut cache_man = self.cache_man.lock(); - for hash in block_hashes { - cache_man.note_used(CacheID::BlockDetails(hash)); - } - } { let mut write_receipts = self.block_receipts.write(); @@ -860,7 +907,7 @@ impl BlockChain { batch.extend_with_cache(db::COL_EXTRA, &mut *write_blocks_blooms, update.blocks_blooms, CacheUpdatePolicy::Remove); } - // These cached values must be updated last with all three locks taken to avoid + // These cached values must be updated last with all four locks taken to avoid // cache decoherence { let mut best_block = self.pending_best_block.write(); @@ -878,8 +925,10 @@ impl BlockChain { }, } let mut write_hashes = self.pending_block_hashes.write(); + let mut write_details = self.pending_block_details.write(); let mut write_txs = self.pending_transaction_addresses.write(); + batch.extend_with_cache(db::COL_EXTRA, &mut *write_details, update.block_details, CacheUpdatePolicy::Overwrite); batch.extend_with_cache(db::COL_EXTRA, &mut *write_hashes, update.block_hashes, CacheUpdatePolicy::Overwrite); batch.extend_with_option_cache(db::COL_EXTRA, &mut *write_txs, update.transactions_addresses, CacheUpdatePolicy::Overwrite); } @@ -889,9 +938,11 @@ impl BlockChain { pub fn commit(&self) { let mut pending_best_block = self.pending_best_block.write(); let mut pending_write_hashes = self.pending_block_hashes.write(); + let mut pending_block_details = self.pending_block_details.write(); let mut pending_write_txs = self.pending_transaction_addresses.write(); let mut best_block = self.best_block.write(); + let mut write_block_details = self.block_details.write(); let mut write_hashes = self.block_hashes.write(); let mut write_txs = self.transaction_addresses.write(); // update best block @@ -904,9 +955,11 @@ impl BlockChain { let pending_hashes_keys: Vec<_> = pending_write_hashes.keys().cloned().collect(); let enacted_txs_keys: Vec<_> = enacted_txs.keys().cloned().collect(); + let pending_block_hashes: Vec<_> = pending_block_details.keys().cloned().collect(); write_hashes.extend(mem::replace(&mut *pending_write_hashes, HashMap::new())); write_txs.extend(enacted_txs.into_iter().map(|(k, v)| (k, v.expect("Transactions were partitioned; qed")))); + write_block_details.extend(mem::replace(&mut *pending_block_details, HashMap::new())); for hash in retracted_txs.keys() { write_txs.remove(hash); @@ -920,6 +973,10 @@ impl BlockChain { for hash in enacted_txs_keys { cache_man.note_used(CacheID::TransactionAddresses(hash)); } + + for hash in pending_block_hashes { + cache_man.note_used(CacheID::BlockDetails(hash)); + } } /// Iterator that lists `first` and then all of `first`'s ancestors, by hash. @@ -944,17 +1001,29 @@ impl BlockChain { if !self.is_known(parent) { return None; } let mut excluded = HashSet::new(); - for a in self.ancestry_iter(parent.clone()).unwrap().take(uncle_generations) { - excluded.extend(self.uncle_hashes(&a).unwrap().into_iter()); - excluded.insert(a); + let ancestry = match self.ancestry_iter(parent.clone()) { + Some(iter) => iter, + None => return None, + }; + + for a in ancestry.clone().take(uncle_generations) { + if let Some(uncles) = self.uncle_hashes(&a) { + excluded.extend(uncles); + excluded.insert(a); + } else { + break + } } let mut ret = Vec::new(); - for a in self.ancestry_iter(parent.clone()).unwrap().skip(1).take(uncle_generations) { - ret.extend(self.block_details(&a).unwrap().children.iter() - .filter(|h| !excluded.contains(h)) - ); + for a in ancestry.skip(1).take(uncle_generations) { + if let Some(details) = self.block_details(&a) { + ret.extend(details.children.iter().filter(|h| !excluded.contains(h))) + } else { + break + } } + Some(ret) } @@ -1210,6 +1279,29 @@ impl BlockChain { body.append_raw(block_rlp.at(2).as_raw(), 1); body.out() } + + /// Returns general blockchain information + pub fn chain_info(&self) -> BlockChainInfo { + // ensure data consistencly by locking everything first + let best_block = self.best_block.read(); + let best_ancient_block = self.best_ancient_block.read(); + BlockChainInfo { + total_difficulty: best_block.total_difficulty.clone(), + pending_total_difficulty: best_block.total_difficulty.clone(), + genesis_hash: self.genesis_hash(), + best_block_hash: best_block.hash.clone(), + best_block_number: best_block.number, + first_block_hash: self.first_block(), + first_block_number: From::from(self.first_block_number()), + ancient_block_hash: best_ancient_block.as_ref().map(|b| b.hash.clone()), + ancient_block_number: best_ancient_block.as_ref().map(|b| b.number), + } + } + + #[cfg(test)] + pub fn db(&self) -> &Arc { + &self.db + } } #[cfg(test)] diff --git a/ethcore/src/cache_manager.rs b/ethcore/src/cache_manager.rs index 715f68a5734539c3187b646b011a7d0222f71901..6ad01b453325706feaf8f91c16304245272e1822 100644 --- a/ethcore/src/cache_manager.rs +++ b/ethcore/src/cache_manager.rs @@ -55,18 +55,23 @@ impl CacheManager where T: Eq + Hash { } for _ in 0..COLLECTION_QUEUE_SIZE { - let current_size = notify_unused(self.cache_usage.pop_back().unwrap()); - self.cache_usage.push_front(Default::default()); - if current_size < self.max_cache_size { - break; + if let Some(back) = self.cache_usage.pop_back() { + let current_size = notify_unused(back); + self.cache_usage.push_front(Default::default()); + if current_size < self.max_cache_size { + break + } } } } fn rotate_cache_if_needed(&mut self) { + if self.cache_usage.is_empty() { return } + if self.cache_usage[0].len() * self.bytes_per_cache_entry > self.pref_cache_size / COLLECTION_QUEUE_SIZE { - let cache = self.cache_usage.pop_back().unwrap(); - self.cache_usage.push_front(cache); + if let Some(cache) = self.cache_usage.pop_back() { + self.cache_usage.push_front(cache); + } } } } diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index ba00284f1922f34d566b410a99d31936ba3adb56..f7cf5fecce26c145129fe2008b695a65daf6870c 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -32,7 +32,7 @@ use util::kvdb::*; // other use ethkey::recover; use io::*; -use views::{HeaderView, BodyView}; +use views::{HeaderView, BodyView, BlockView}; use error::{ImportError, ExecutionError, CallError, BlockError, ImportResult, Error as EthcoreError}; use header::BlockNumber; use state::State; @@ -47,8 +47,9 @@ use block::*; use transaction::{LocalizedTransaction, SignedTransaction, Action}; use blockchain::extras::TransactionAddress; use types::filter::Filter; +use types::mode::Mode as IpcMode; use log_entry::LocalizedLogEntry; -use verification::queue::{BlockQueue, QueueInfo as BlockQueueInfo}; +use verification::queue::BlockQueue; use blockchain::{BlockChain, BlockProvider, TreeRoute, ImportRoute}; use client::{ BlockID, TransactionID, UncleID, TraceId, ClientConfig, BlockChainClient, @@ -62,20 +63,23 @@ use receipt::LocalizedReceipt; use trace::{TraceDB, ImportRequest as TraceImportRequest, LocalizedTrace, Database as TraceDatabase}; use trace; use trace::FlatTransactionTraces; -use evm::Factory as EvmFactory; +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 state_db::StateDB; +use rand::OsRng; // re-export pub use types::blockchain_info::BlockChainInfo; pub use types::block_status::BlockStatus; pub use blockchain::CacheSize as BlockChainCacheSize; +pub use verification::queue::QueueInfo as BlockQueueInfo; const MAX_TX_QUEUE_SIZE: usize = 4096; const MAX_QUEUE_SIZE_TO_SLEEP_ON: usize = 2; +const MIN_HISTORY_SIZE: u64 = 8; impl fmt::Display for BlockChainInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -122,7 +126,7 @@ impl SleepState { /// Blockchain database client backed by a persistent database. Owns and manages a blockchain and a block queue. /// Call `import_block()` to import a block asynchronously; `flush_queue()` flushes the queue. pub struct Client { - mode: Mode, + mode: Mutex, chain: RwLock>, tracedb: RwLock>, engine: Arc, @@ -138,17 +142,15 @@ pub struct Client { miner: Arc, sleep_state: Mutex, liveness: AtomicBool, - io_channel: IoChannel, + io_channel: Mutex>, notify: RwLock>>, queue_transactions: AtomicUsize, last_hashes: RwLock>, factories: Factories, + history: u64, + rng: Mutex, } -/// The pruning constant -- how old blocks must be before we -/// assume finality of a given candidate. -pub const HISTORY: u64 = 1200; - impl Client { /// Create a new client with given spec and DB path and custom verifier. pub fn new( @@ -172,27 +174,49 @@ impl Client { }; let journal_db = journaldb::new(db.clone(), config.pruning, ::db::COL_STATE); - let mut state_db = StateDB::new(journal_db); + let mut state_db = StateDB::new(journal_db, config.state_cache_size); if state_db.journal_db().is_empty() && try!(spec.ensure_db_good(&mut state_db)) { let mut batch = DBTransaction::new(&db); - try!(state_db.commit(&mut batch, 0, &spec.genesis_header().hash(), None)); + try!(state_db.journal_under(&mut batch, 0, &spec.genesis_header().hash())); try!(db.write(batch).map_err(ClientError::Database)); } + trace!("Cleanup journal: DB Earliest = {:?}, Latest = {:?}", state_db.journal_db().earliest_era(), state_db.journal_db().latest_era()); + + let history = if config.history < MIN_HISTORY_SIZE { + info!(target: "client", "Ignoring pruning history parameter of {}\ + , falling back to minimum of {}", + config.history, MIN_HISTORY_SIZE); + MIN_HISTORY_SIZE + } else { + config.history + }; + + if let (Some(earliest), Some(latest)) = (state_db.journal_db().earliest_era(), state_db.journal_db().latest_era()) { + if latest > earliest && latest - earliest > history { + for era in earliest..(latest - history + 1) { + trace!("Removing era {}", era); + let mut batch = DBTransaction::new(&db); + try!(state_db.mark_canonical(&mut batch, era, &chain.block_hash(era).expect("Old block not found in the database"))); + try!(db.write(batch).map_err(ClientError::Database)); + } + } + } + if !chain.block_header(&chain.best_block_hash()).map_or(true, |h| state_db.journal_db().contains(h.state_root())) { warn!("State root not found for block #{} ({})", chain.best_block_number(), chain.best_block_hash().hex()); } let engine = spec.engine.clone(); - let block_queue = BlockQueue::new(config.queue.clone(), engine.clone(), message_channel.clone()); + let block_queue = BlockQueue::new(config.queue.clone(), engine.clone(), message_channel.clone(), config.verifier_type.verifying_seal()); let panic_handler = PanicHandler::new_in_arc(); panic_handler.forward_from(&block_queue); let awake = match config.mode { Mode::Dark(..) => false, _ => true }; let factories = Factories { - vm: EvmFactory::new(config.vm_type.clone()), + vm: EvmFactory::new(config.vm_type.clone(), config.jump_table_size), trie: TrieFactory::new(trie_spec), accountdb: Default::default(), }; @@ -200,7 +224,7 @@ impl Client { let client = Client { sleep_state: Mutex::new(SleepState::new(awake)), liveness: AtomicBool::new(awake), - mode: config.mode.clone(), + mode: Mutex::new(config.mode.clone()), chain: RwLock::new(chain), tracedb: tracedb, engine: engine, @@ -214,11 +238,13 @@ impl Client { import_lock: Mutex::new(()), panic_handler: panic_handler, miner: miner, - io_channel: message_channel, + io_channel: Mutex::new(message_channel), notify: RwLock::new(Vec::new()), queue_transactions: AtomicUsize::new(0), last_hashes: RwLock::new(VecDeque::new()), factories: factories, + history: history, + rng: Mutex::new(try!(OsRng::new().map_err(::util::UtilError::StdIo))), }; Ok(Arc::new(client)) } @@ -277,7 +303,7 @@ impl Client { let chain = self.chain.read(); // Check the block isn't so old we won't be able to enact it. let best_block_number = chain.best_block_number(); - if best_block_number >= HISTORY && header.number() <= best_block_number - HISTORY { + if best_block_number >= self.history && header.number() <= best_block_number - self.history { warn!(target: "client", "Block import failed for #{} ({})\nBlock is ancient (current best block: #{}).", header.number(), header.hash(), best_block_number); return Err(()); } @@ -294,7 +320,7 @@ impl Client { if let Some(parent) = chain_has_parent { // Enact Verified Block let last_hashes = self.build_last_hashes(header.parent_hash().clone()); - let db = self.state_db.lock().boxed_clone_canon(&header.parent_hash()); + let db = self.state_db.lock().boxed_clone_canon(header.parent_hash()); let enact_result = enact_verified(block, engine, self.tracedb.read().tracing_enabled(), db, &parent, last_hashes, self.factories.clone()); let locked_block = try!(enact_result.map_err(|e| { @@ -342,16 +368,19 @@ impl Client { /// This is triggered by a message coming from a block queue when the block is ready for insertion pub fn import_verified_blocks(&self) -> usize { - let max_blocks_to_import = 64; - let (imported_blocks, import_results, invalid_blocks, imported, duration) = { + let max_blocks_to_import = 4; + let (imported_blocks, import_results, invalid_blocks, imported, duration, is_empty) = { let mut imported_blocks = Vec::with_capacity(max_blocks_to_import); let mut invalid_blocks = HashSet::new(); let mut import_results = Vec::with_capacity(max_blocks_to_import); let _import_lock = self.import_lock.lock(); + let blocks = self.block_queue.drain(max_blocks_to_import); + if blocks.is_empty() { + return 0; + } let _timer = PerfTimer::new("import_verified_blocks"); let start = precise_time_ns(); - let blocks = self.block_queue.drain(max_blocks_to_import); for block in blocks { let header = &block.header; @@ -375,23 +404,19 @@ impl Client { let imported = imported_blocks.len(); let invalid_blocks = invalid_blocks.into_iter().collect::>(); - { - if !invalid_blocks.is_empty() { - self.block_queue.mark_as_bad(&invalid_blocks); - } - if !imported_blocks.is_empty() { - self.block_queue.mark_as_good(&imported_blocks); - } + if !invalid_blocks.is_empty() { + self.block_queue.mark_as_bad(&invalid_blocks); } + let is_empty = self.block_queue.mark_as_good(&imported_blocks); let duration_ns = precise_time_ns() - start; - (imported_blocks, import_results, invalid_blocks, imported, duration_ns) + (imported_blocks, import_results, invalid_blocks, imported, duration_ns, is_empty) }; { - if !imported_blocks.is_empty() && self.block_queue.queue_info().is_empty() { + if !imported_blocks.is_empty() && is_empty { let (enacted, retracted) = self.calculate_enacted_retracted(&import_results); - if self.queue_info().is_empty() { + if is_empty { self.miner.chain_new_blocks(self, &imported_blocks, &invalid_blocks, &enacted, &retracted); } @@ -412,17 +437,45 @@ impl Client { imported } + /// Import a block with transaction receipts. + /// The block is guaranteed to be the next best blocks in the first block sequence. + /// Does no sealing or transaction validation. + fn import_old_block(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result { + let block = BlockView::new(&block_bytes); + let header = block.header(); + let hash = header.hash(); + let _import_lock = self.import_lock.lock(); + { + let _timer = PerfTimer::new("import_old_block"); + let mut rng = self.rng.lock(); + let chain = self.chain.read(); + + // verify block. + try!(::snapshot::verify_old_block( + &mut *rng, + &header, + &*self.engine, + &*chain, + Some(&block_bytes), + false, + )); + + // Commit results + let receipts = ::rlp::decode(&receipts_bytes); + let mut batch = DBTransaction::new(&self.db.read()); + chain.insert_unordered_block(&mut batch, &block_bytes, receipts, None, false, true); + // Final commit to the DB + self.db.read().write_buffered(batch); + chain.commit(); + } + self.db.read().flush().expect("DB flush failed."); + Ok(hash) + } + fn commit_block(&self, block: B, hash: &H256, block_data: &[u8]) -> ImportRoute where B: IsBlock + Drain { let number = block.header().number(); let parent = block.header().parent_hash().clone(); let chain = self.chain.read(); - // Are we committing an era? - let ancient = if number >= HISTORY { - let n = number - HISTORY; - Some((n, chain.block_hash(n).expect("only verified blocks can be commited; verified block has hash; qed"))) - } else { - None - }; // Commit results let receipts = block.receipts().to_owned(); @@ -438,7 +491,17 @@ impl Client { // already-imported block of the same number. // TODO: Prove it with a test. let mut state = block.drain(); - state.commit(&mut batch, number, hash, ancient).expect("DB commit failed."); + + state.journal_under(&mut batch, number, hash).expect("DB commit failed"); + + if number >= self.history { + let n = number - self.history; + if let Some(ancient_hash) = chain.block_hash(n) { + state.mark_canonical(&mut batch, n, &ancient_hash).expect("DB commit failed"); + } else { + debug!(target: "client", "Missing expected hash for block {}", n); + } + } let route = chain.insert_block(&mut batch, block_data, receipts); self.tracedb.read().import(&mut batch, TraceImportRequest { @@ -448,6 +511,7 @@ impl Client { enacted: route.enacted.clone(), retracted: route.retracted.len() }); + let is_canon = route.enacted.last().map_or(false, |h| h == hash); state.sync_cache(&route.enacted, &route.retracted, is_canon); // Final commit to the DB @@ -497,7 +561,7 @@ impl Client { let db = self.state_db.lock().boxed_clone(); // early exit for pruned blocks - if db.is_pruned() && self.chain.read().best_block_number() >= block_number + HISTORY { + if db.is_pruned() && self.chain.read().best_block_number() >= block_number + self.history { return None; } @@ -553,7 +617,8 @@ impl Client { self.block_queue.collect_garbage(); self.tracedb.read().collect_garbage(); - match self.mode { + let mode = self.mode.lock().clone(); + match mode { Mode::Dark(timeout) => { let mut ss = self.sleep_state.lock(); if let Some(t) = ss.last_activity { @@ -602,20 +667,23 @@ impl Client { let best_block_number = self.chain_info().best_block_number; let block_number = try!(self.block_number(at).ok_or(snapshot::Error::InvalidStartingBlock(at))); - if best_block_number > HISTORY + block_number && db.is_pruned() { + if best_block_number > self.history + block_number && db.is_pruned() { return Err(snapshot::Error::OldBlockPrunedDB.into()); } + let history = ::std::cmp::min(self.history, 1000); + let start_hash = match at { BlockID::Latest => { - let start_num = if best_block_number > 1000 { - best_block_number - 1000 - } else { - 0 + let start_num = match db.earliest_era() { + Some(era) => ::std::cmp::max(era, best_block_number - history), + None => best_block_number - history, }; - self.block_hash(BlockID::Number(start_num)) - .expect("blocks within HISTORY are always stored.") + match self.block_hash(BlockID::Number(start_num)) { + Some(h) => h, + None => return Err(snapshot::Error::InvalidStartingBlock(at).into()), + } } _ => match self.block_hash(at) { Some(hash) => hash, @@ -628,6 +696,11 @@ impl Client { Ok(()) } + /// Ask the client what the history parameter is. + pub fn pruning_history(&self) -> u64 { + self.history + } + fn block_hash(chain: &BlockChain, id: BlockID) -> Option { match id { BlockID::Hash(hash) => Some(hash), @@ -684,7 +757,8 @@ impl snapshot::DatabaseRestore for Client { let db = self.db.write(); try!(db.restore(new_db)); - *state_db = StateDB::new(journaldb::new(db.clone(), self.pruning, ::db::COL_STATE)); + let cache_size = state_db.cache_size(); + *state_db = StateDB::new(journaldb::new(db.clone(), self.pruning, ::db::COL_STATE), cache_size); *chain = Arc::new(BlockChain::new(self.config.blockchain.clone(), &[], db.clone(), self.engine.clone())); *tracedb = TraceDB::new(self.config.tracing.clone(), db.clone(), chain.clone()); Ok(()) @@ -696,7 +770,7 @@ impl BlockChainClient for Client { fn call(&self, t: &SignedTransaction, block: BlockID, analytics: CallAnalytics) -> Result { let header = try!(self.block_header(block).ok_or(CallError::StatePruned)); let view = HeaderView::new(&header); - let last_hashes = self.build_last_hashes(view.hash()); + let last_hashes = self.build_last_hashes(view.parent_hash()); let env_info = EnvInfo { number: view.number(), author: view.author(), @@ -768,12 +842,24 @@ impl BlockChainClient for Client { } fn keep_alive(&self) { - if self.mode != Mode::Active { + let mode = self.mode.lock().clone(); + if mode != Mode::Active { self.wake_up(); (*self.sleep_state.lock()).last_activity = Some(Instant::now()); } } + fn mode(&self) -> IpcMode { self.mode.lock().clone().into() } + + fn set_mode(&self, mode: IpcMode) { + *self.mode.lock() = mode.clone().into(); + match mode { + IpcMode::Active => self.wake_up(), + IpcMode::Off => self.sleep(), + _ => {(*self.sleep_state.lock()).last_activity = Some(Instant::now()); } + } + } + fn best_block_header(&self) -> Bytes { self.chain.read().best_block_header() } @@ -970,6 +1056,20 @@ impl BlockChainClient for Client { Ok(try!(self.block_queue.import(unverified))) } + fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result { + { + // check block order + let header = BlockView::new(&block_bytes).header_view(); + if self.chain.read().is_known(&header.hash()) { + return Err(BlockImportError::Import(ImportError::AlreadyInChain)); + } + if self.block_status(BlockID::Hash(header.parent_hash())) == BlockStatus::Unknown { + return Err(BlockImportError::Block(BlockError::UnknownParent(header.parent_hash()))); + } + } + self.import_old_block(block_bytes, receipts_bytes).map_err(Into::into) + } + fn queue_info(&self) -> BlockQueueInfo { self.block_queue.queue_info() } @@ -979,14 +1079,7 @@ impl BlockChainClient for Client { } fn chain_info(&self) -> BlockChainInfo { - let chain = self.chain.read(); - BlockChainInfo { - total_difficulty: chain.best_block_total_difficulty(), - pending_total_difficulty: chain.best_block_total_difficulty(), - genesis_hash: chain.genesis_hash(), - best_block_hash: chain.best_block_hash(), - best_block_number: From::from(chain.best_block_number()) - } + self.chain.read().chain_info() } fn additional_params(&self) -> BTreeMap { @@ -1062,7 +1155,7 @@ impl BlockChainClient for Client { debug!("Ignoring {} transactions: queue is full", transactions.len()); } else { let len = transactions.len(); - match self.io_channel.send(ClientIoMessage::NewTransactions(transactions)) { + match self.io_channel.lock().send(ClientIoMessage::NewTransactions(transactions)) { Ok(_) => { self.queue_transactions.fetch_add(len, AtomicOrdering::SeqCst); } @@ -1094,6 +1187,23 @@ impl BlockChainClient for Client { } 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) + } + fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { let engine = &*self.engine; let chain = self.chain.read(); @@ -1133,21 +1243,22 @@ impl MiningBlockChainClient for Client { } fn import_sealed_block(&self, block: SealedBlock) -> ImportResult { - let _import_lock = self.import_lock.lock(); - let _timer = PerfTimer::new("import_sealed_block"); - let start = precise_time_ns(); - let h = block.header().hash(); - let number = block.header().number(); - - let block_data = block.rlp_bytes(); - let route = self.commit_block(block, &h, &block_data); - trace!(target: "client", "Imported sealed block #{} ({})", number, h); - self.state_db.lock().sync_cache(&route.enacted, &route.retracted, false); - + let start = precise_time_ns(); + let route = { + // scope for self.import_lock + let _import_lock = self.import_lock.lock(); + let _timer = PerfTimer::new("import_sealed_block"); + + let number = block.header().number(); + let block_data = block.rlp_bytes(); + let route = self.commit_block(block, &h, &block_data); + trace!(target: "client", "Imported sealed block #{} ({})", number, h); + self.state_db.lock().sync_cache(&route.enacted, &route.retracted, false); + route + }; let (enacted, retracted) = self.calculate_enacted_retracted(&[route]); self.miner.chain_new_blocks(self, &[h.clone()], &[], &enacted, &retracted); - self.notify(|notify| { notify.new_blocks( vec![h.clone()], @@ -1168,3 +1279,33 @@ impl MayPanic for Client { self.panic_handler.on_panic(closure); } } + + +#[test] +fn should_not_cache_details_before_commit() { + use tests::helpers::*; + use std::thread; + use std::time::Duration; + use std::sync::atomic::{AtomicBool, Ordering}; + + let client = generate_dummy_client(0); + let genesis = client.chain_info().best_block_hash; + let (new_hash, new_block) = get_good_dummy_block_hash(); + + let go = { + // Separate thread uncommited transaction + let go = Arc::new(AtomicBool::new(false)); + let go_thread = go.clone(); + let another_client = client.reference().clone(); + thread::spawn(move || { + let mut batch = DBTransaction::new(&*another_client.chain.read().db().clone()); + another_client.chain.read().insert_block(&mut batch, &new_block, Vec::new()); + go_thread.store(true, Ordering::SeqCst); + }); + go + }; + + while !go.load(Ordering::SeqCst) { thread::park_timeout(Duration::from_millis(5)); } + + assert!(client.tree_route(&genesis, &new_hash).is_none()); +} diff --git a/ethcore/src/client/config.rs b/ethcore/src/client/config.rs index 8cf54387b1fda8ac510a3ab8b289b39e91f83b84..c4aeba8a4d82f1e03f32672bdf5242cee8c15d1d 100644 --- a/ethcore/src/client/config.rs +++ b/ethcore/src/client/config.rs @@ -15,6 +15,7 @@ // along with Parity. If not, see . use std::str::FromStr; +use std::path::Path; pub use std::time::Duration; pub use blockchain::Config as BlockChainConfig; pub use trace::Config as TraceConfig; @@ -26,23 +27,26 @@ use util::{journaldb, CompactionProfile}; /// Client state db compaction profile #[derive(Debug, PartialEq)] pub enum DatabaseCompactionProfile { - /// Default compaction profile - Default, + /// Try to determine compaction profile automatically + Auto, + /// SSD compaction profile + SSD, /// HDD or other slow storage io compaction profile HDD, } impl Default for DatabaseCompactionProfile { fn default() -> Self { - DatabaseCompactionProfile::Default + DatabaseCompactionProfile::Auto } } impl DatabaseCompactionProfile { /// Returns corresponding compaction profile. - pub fn compaction_profile(&self) -> CompactionProfile { + pub fn compaction_profile(&self, db_path: &Path) -> CompactionProfile { match *self { - DatabaseCompactionProfile::Default => Default::default(), + DatabaseCompactionProfile::Auto => CompactionProfile::auto(db_path), + DatabaseCompactionProfile::SSD => CompactionProfile::ssd(), DatabaseCompactionProfile::HDD => CompactionProfile::hdd(), } } @@ -53,9 +57,10 @@ impl FromStr for DatabaseCompactionProfile { fn from_str(s: &str) -> Result { match s { - "ssd" | "default" => Ok(DatabaseCompactionProfile::Default), + "auto" => Ok(DatabaseCompactionProfile::Auto), + "ssd" => Ok(DatabaseCompactionProfile::SSD), "hdd" => Ok(DatabaseCompactionProfile::HDD), - _ => Err("Invalid compaction profile given. Expected hdd/ssd (default).".into()), + _ => Err("Invalid compaction profile given. Expected default/hdd/ssd.".into()), } } } @@ -71,6 +76,8 @@ pub enum Mode { /// Goes offline after RLP is inactive for some (given) time and /// stays inactive. Dark(Duration), + /// Always off. + Off, } impl Default for Mode { @@ -96,7 +103,7 @@ pub struct ClientConfig { pub pruning: journaldb::Algorithm, /// The name of the client instance. pub name: String, - /// State db cache-size if not default + /// RocksDB state column cache-size if not default pub db_cache_size: Option, /// State db compaction profile pub db_compaction: DatabaseCompactionProfile, @@ -106,6 +113,14 @@ pub struct ClientConfig { pub mode: Mode, /// Type of block verifier used by client. pub verifier_type: VerifierType, + /// State db cache-size. + pub state_cache_size: usize, + /// EVM jump-tables cache size. + pub jump_table_size: usize, + /// State pruning history size. + pub history: u64, + /// Check seal valididity on block import + pub check_seal: bool, } #[cfg(test)] @@ -114,13 +129,13 @@ mod test { #[test] fn test_default_compaction_profile() { - assert_eq!(DatabaseCompactionProfile::default(), DatabaseCompactionProfile::Default); + assert_eq!(DatabaseCompactionProfile::default(), DatabaseCompactionProfile::Auto); } #[test] fn test_parsing_compaction_profile() { - assert_eq!(DatabaseCompactionProfile::Default, "ssd".parse().unwrap()); - assert_eq!(DatabaseCompactionProfile::Default, "default".parse().unwrap()); + assert_eq!(DatabaseCompactionProfile::Auto, "auto".parse().unwrap()); + assert_eq!(DatabaseCompactionProfile::SSD, "ssd".parse().unwrap()); assert_eq!(DatabaseCompactionProfile::HDD, "hdd".parse().unwrap()); } diff --git a/ethcore/src/client/mod.rs b/ethcore/src/client/mod.rs index 1e8aa9d72e9022d7afe0011468db46d3fec5c701..3898ab6cda58a867824bd613f7cad31ace1ce1c9 100644 --- a/ethcore/src/client/mod.rs +++ b/ethcore/src/client/mod.rs @@ -37,6 +37,7 @@ pub use block_import_error::BlockImportError; pub use transaction_import::TransactionImportResult; pub use transaction_import::TransactionImportError; pub use self::traits::{BlockChainClient, MiningBlockChainClient}; +pub use verification::VerifierType; /// IPC interfaces #[cfg(feature="ipc")] diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index 6a53582d3f57b0385379ca6bc875927c051e701f..6dc865decfcbc20c3034b651001f05eed28c7782 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -34,9 +34,10 @@ use log_entry::LocalizedLogEntry; use receipt::{Receipt, LocalizedReceipt}; use blockchain::extras::BlockReceipts; use error::{ImportResult}; -use evm::{Factory as EvmFactory, VMType}; +use evm::{Factory as EvmFactory, VMType, Schedule}; use miner::{Miner, MinerService, TransactionImportResult}; use spec::Spec; +use types::mode::Mode; use verification::queue::QueueInfo; use block::{OpenBlock, SealedBlock}; @@ -83,6 +84,10 @@ pub struct TestBlockChainClient { pub vm_factory: EvmFactory, /// Timestamp assigned to latest sealed block pub latest_block_timestamp: RwLock, + /// Ancient block info. + pub ancient_block: RwLock>, + /// First block info. + pub first_block: RwLock>, } #[derive(Clone)] @@ -130,8 +135,10 @@ impl TestBlockChainClient { queue_size: AtomicUsize::new(0), miner: Arc::new(Miner::with_spec(&spec)), spec: spec, - vm_factory: EvmFactory::new(VMType::Interpreter), + vm_factory: EvmFactory::new(VMType::Interpreter, 1024 * 1024), latest_block_timestamp: RwLock::new(10_000_000), + ancient_block: RwLock::new(None), + first_block: RwLock::new(None), }; client.add_blocks(1, EachBlockWith::Nothing); // add genesis block client.genesis_hash = client.last_hash.read().clone(); @@ -298,7 +305,7 @@ pub fn get_temp_state_db() -> GuardedTempResult { let temp = RandomTempPath::new(); let db = Database::open(&DatabaseConfig::with_columns(NUM_COLUMNS), temp.as_str()).unwrap(); let journal_db = journaldb::new(Arc::new(db), journaldb::Algorithm::EarlyMerge, COL_STATE); - let state_db = StateDB::new(journal_db); + let state_db = StateDB::new(journal_db, 1024 * 1024); GuardedTempResult { _temp: temp, result: Some(state_db) @@ -306,6 +313,10 @@ pub fn get_temp_state_db() -> GuardedTempResult { } impl MiningBlockChainClient for TestBlockChainClient { + fn latest_schedule(&self) -> Schedule { + Schedule::new_homestead_gas_fix() + } + fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { let engine = &*self.spec.engine; let genesis_header = self.spec.genesis_header(); @@ -560,6 +571,10 @@ impl BlockChainClient for TestBlockChainClient { Ok(h) } + fn import_block_with_receipts(&self, b: Bytes, _r: Bytes) -> Result { + self.import_block(b) + } + fn queue_info(&self) -> QueueInfo { QueueInfo { verified_queue_size: self.queue_size.load(AtomicOrder::Relaxed), @@ -585,6 +600,10 @@ impl BlockChainClient for TestBlockChainClient { genesis_hash: self.genesis_hash.clone(), best_block_hash: self.last_hash.read().clone(), best_block_number: self.blocks.read().len() as BlockNumber - 1, + first_block_hash: self.first_block.read().as_ref().map(|x| x.0), + first_block_number: self.first_block.read().as_ref().map(|x| x.1), + ancient_block_hash: self.ancient_block.read().as_ref().map(|x| x.0), + ancient_block_number: self.ancient_block.read().as_ref().map(|x| x.1) } } @@ -617,4 +636,8 @@ impl BlockChainClient for TestBlockChainClient { fn pending_transactions(&self) -> Vec { self.miner.pending_transactions(self.chain_info().best_block_number) } + + 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 f110d6d7b4aee8c7eaddacf234bdc1645345daf2..259068d4500088446c6cbcf04923f933364c696e 100644 --- a/ethcore/src/client/traits.rs +++ b/ethcore/src/client/traits.rs @@ -16,6 +16,7 @@ use std::collections::BTreeMap; use util::{U256, Address, H256, H2048, Bytes, Itertools}; +use util::stats::Histogram; use blockchain::TreeRoute; use verification::queue::QueueInfo as BlockQueueInfo; use block::{OpenBlock, SealedBlock}; @@ -27,7 +28,7 @@ use views::{BlockView}; use error::{ImportResult, CallError}; use receipt::LocalizedReceipt; use trace::LocalizedTrace; -use evm::Factory as EvmFactory; +use evm::{Factory as EvmFactory, Schedule}; use types::ids::*; use types::trace_filter::Filter as TraceFilter; use executive::Executed; @@ -37,6 +38,7 @@ use block_import_error::BlockImportError; use ipc::IpcConfig; use types::blockchain_info::BlockChainInfo; use types::block_status::BlockStatus; +use types::mode::Mode; #[ipc(client_ident="RemoteClient")] /// Blockchain database client. Owns and manages a blockchain and a block queue. @@ -139,6 +141,9 @@ pub trait BlockChainClient : Sync + Send { /// Import a block into the blockchain. fn import_block(&self, bytes: Bytes) -> Result; + /// Import a block with transaction receipts. Does no sealing and transaction validation. + fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result; + /// Get block queue information. fn queue_info(&self) -> BlockQueueInfo; @@ -190,31 +195,44 @@ pub trait BlockChainClient : Sync + Send { /// list all transactions fn pending_transactions(&self) -> Vec; - /// Get the gas price distribution. - fn gas_price_statistics(&self, sample_size: usize, distribution_size: usize) -> Result, ()> { + /// Sorted list of transaction gas prices from at least last sample_size blocks. + fn gas_price_corpus(&self, sample_size: usize) -> Vec { let mut h = self.chain_info().best_block_hash; let mut corpus = Vec::new(); - for _ in 0..sample_size { - let block_bytes = self.block(BlockID::Hash(h)).expect("h is either the best_block_hash or an ancestor; qed"); - let block = BlockView::new(&block_bytes); - let header = block.header_view(); - if header.number() == 0 { - break; + while corpus.is_empty() { + for _ in 0..sample_size { + let block_bytes = self.block(BlockID::Hash(h)).expect("h is either the best_block_hash or an ancestor; qed"); + let block = BlockView::new(&block_bytes); + let header = block.header_view(); + if header.number() == 0 { + return corpus; + } + block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); + h = header.parent_hash().clone(); } - block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); - h = header.parent_hash().clone(); } corpus.sort(); - let n = corpus.len(); - if n > 0 { - Ok((0..(distribution_size + 1)) - .map(|i| corpus[i * (n - 1) / distribution_size]) - .collect::>() - ) - } else { - Err(()) - } + corpus } + + /// 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() + } + + /// Get the gas price distribution based on recent blocks if they have any transactions. + fn gas_price_histogram(&self, sample_size: usize, bucket_number: usize) -> Option { + 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); + Histogram::new(corpus, bucket_number) + } + + fn mode(&self) -> Mode; + + fn set_mode(&self, mode: Mode); } /// Extended client interface used for mining @@ -231,6 +249,9 @@ pub trait MiningBlockChainClient : BlockChainClient { /// Import sealed block. Skips all verifications. fn import_sealed_block(&self, block: SealedBlock) -> ImportResult; + + /// Returns latest schedule. + fn latest_schedule(&self) -> Schedule; } impl IpcConfig for BlockChainClient { } diff --git a/ethcore/src/db.rs b/ethcore/src/db.rs index 10672d7304a07e7948835f5b6fd9038525ec94e0..92c0f1b39919b0dd2329a32ee84db8ea70f8ec8c 100644 --- a/ethcore/src/db.rs +++ b/ethcore/src/db.rs @@ -114,7 +114,7 @@ pub trait Writable { R: Deref { match policy { CacheUpdatePolicy::Overwrite => { - for (key, value) in values.into_iter() { + for (key, value) in values { self.write(col, &key, &value); cache.insert(key, value); } @@ -135,7 +135,7 @@ pub trait Writable { R: Deref { match policy { CacheUpdatePolicy::Overwrite => { - for (key, value) in values.into_iter() { + for (key, value) in values { match value { Some(ref v) => self.write(col, &key, v), None => self.delete(col, &key), @@ -144,7 +144,7 @@ pub trait Writable { } }, CacheUpdatePolicy::Remove => { - for (key, value) in values.into_iter() { + for (key, value) in values { match value { Some(v) => self.write(col, &key, &v), None => self.delete(col, &key), diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index 6e3c2f1dd9990b3a045ec3f4319f9efe534325fa..815d2b43af910602b0cf6579dfc848e25841db85 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -16,14 +16,20 @@ //! A blockchain engine that supports a basic, non-BFT proof-of-authority. -use common::*; use ethkey::{recover, public_to_address}; use account_provider::AccountProvider; use block::*; +use builtin::Builtin; use spec::CommonParams; use engines::Engine; +use env_info::EnvInfo; +use error::{BlockError, Error}; use evm::Schedule; use ethjson; +use header::Header; +use transaction::SignedTransaction; + +use util::*; /// `BasicAuthority` params. #[derive(Debug, PartialEq)] @@ -112,7 +118,7 @@ impl Engine for BasicAuthority { let header = block.header(); let message = header.bare_hash(); // account should be pernamently unlocked, otherwise sealing will fail - if let Ok(signature) = ap.sign(*block.header().author(), message) { + if let Ok(signature) = ap.sign(*block.header().author(), None, message) { return Some(vec![::rlp::encode(&(&*signature as &[u8])).to_vec()]); } else { trace!(target: "basicauthority", "generate_seal: FAIL: accounts secret key unavailable"); @@ -184,10 +190,13 @@ impl Header { #[cfg(test)] mod tests { - use common::*; + use util::*; use block::*; + use env_info::EnvInfo; + use error::{BlockError, Error}; use tests::helpers::*; use account_provider::AccountProvider; + use header::Header; use spec::Spec; /// Create a new test chain spec with `BasicAuthority` consensus engine. diff --git a/ethcore/src/engines/instant_seal.rs b/ethcore/src/engines/instant_seal.rs index 174a80ea803e622872113276b478d4e52edf661c..acead19b4369fffadb2bb77c8f0c93b527d05624 100644 --- a/ethcore/src/engines/instant_seal.rs +++ b/ethcore/src/engines/instant_seal.rs @@ -18,11 +18,11 @@ use std::collections::BTreeMap; use util::Address; use builtin::Builtin; use engines::Engine; +use env_info::EnvInfo; use spec::CommonParams; use evm::Schedule; -use env_info::EnvInfo; use block::ExecutedBlock; -use common::Bytes; +use util::Bytes; use account_provider::AccountProvider; /// An engine which does not provide any consensus mechanism, just seals blocks internally. @@ -67,10 +67,11 @@ impl Engine for InstantSeal { #[cfg(test)] mod tests { - use common::*; + use util::*; use tests::helpers::*; use account_provider::AccountProvider; use spec::Spec; + use header::Header; use block::*; #[test] diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index 0be50738747949645d65c702dd172a0e7fff2360..f03e765a963287b15fd23d357ff63aae5eaf5222 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -30,14 +30,20 @@ pub use self::tendermint::Tendermint; pub use self::signed_vote::SignedVote; pub use self::propose_collect::ProposeCollect; -use common::*; use rlp::UntrustedRlp; +use util::*; use account_provider::AccountProvider; use block::ExecutedBlock; +use builtin::Builtin; +use env_info::EnvInfo; +use error::Error; use spec::CommonParams; use evm::Schedule; +use header::Header; +use transaction::SignedTransaction; use ethereum::ethash; use blockchain::extras::BlockDetails; +use views::HeaderView; /// Voting errors. #[derive(Debug)] @@ -153,10 +159,14 @@ pub trait Engine : Sync + Send { fn is_builtin(&self, a: &Address) -> bool { self.builtins().contains_key(a) } /// Determine the code execution cost of the builtin contract with address `a`. /// Panics if `is_builtin(a)` is not true. - fn cost_of_builtin(&self, a: &Address, input: &[u8]) -> U256 { self.builtins().get(a).unwrap().cost(input.len()) } + fn cost_of_builtin(&self, a: &Address, input: &[u8]) -> U256 { + self.builtins().get(a).expect("queried cost of nonexistent builtin").cost(input.len()) + } /// Execution the builtin contract `a` on `input` and return `output`. /// Panics if `is_builtin(a)` is not true. - fn execute_builtin(&self, a: &Address, input: &[u8], output: &mut BytesRef) { self.builtins().get(a).unwrap().execute(input, output); } + fn execute_builtin(&self, a: &Address, input: &[u8], output: &mut BytesRef) { + self.builtins().get(a).expect("attempted to execute nonexistent builtin").execute(input, output); + } /// Check if new block should be chosen as the one in chain. fn is_new_best_block(&self, best_total_difficulty: U256, _best_header: HeaderView, parent_details: &BlockDetails, new_header: &HeaderView) -> bool { diff --git a/ethcore/src/engines/propose_collect.rs b/ethcore/src/engines/propose_collect.rs index ad245e2cd023142aec3c9f1dbb5f186978ae4bdf..c60457c3af95c7f1b171112088da1d8898c81019 100644 --- a/ethcore/src/engines/propose_collect.rs +++ b/ethcore/src/engines/propose_collect.rs @@ -17,7 +17,7 @@ //! Voting on a hash, where each vote has to come from a set of addresses. use std::sync::atomic::{AtomicBool, Ordering}; -use common::{HashSet, RwLock, H256, Address}; +use util::{HashSet, RwLock, H256, Address}; /// Collect votes on a hash. #[derive(Debug)] @@ -70,9 +70,10 @@ impl ProposeCollect { #[cfg(test)] mod tests { - use common::*; use engines::propose_collect::ProposeCollect; use account_provider::AccountProvider; + use util::*; + use header::Header; #[test] fn simple_propose_collect() { diff --git a/ethcore/src/engines/signed_vote.rs b/ethcore/src/engines/signed_vote.rs index 323972ed42041b6b9b0b01bfcb3e7138b5aea6ac..0cef5c214693e32c70ee780f659b2a6d66aed032 100644 --- a/ethcore/src/engines/signed_vote.rs +++ b/ethcore/src/engines/signed_vote.rs @@ -17,7 +17,8 @@ //! Voting on hashes, where each vote has to come from a set of public keys. use super::EngineError; -use common::{HashSet, HashMap, RwLock, H256, Address, Error, Hashable}; +use util::*; +use error::Error; use ethkey::{Signature, recover}; /// Signed voting on hashes. @@ -82,7 +83,8 @@ impl SignedVote { #[cfg(test)] mod tests { - use common::*; + use util::*; + use header::Header; use engines::signed_vote::SignedVote; use account_provider::AccountProvider; @@ -105,18 +107,18 @@ mod tests { let bare_hash = header.bare_hash(); // Unapproved voter. - let signature = tap.sign(addr3, bare_hash).unwrap(); + let signature = tap.sign(addr3, None, bare_hash).unwrap(); assert!(!vote.vote(bare_hash, signature)); assert!(vote.winner().is_none()); // First good vote. - let signature = tap.sign(addr1, bare_hash).unwrap(); + let signature = tap.sign(addr1, None, bare_hash).unwrap(); assert!(vote.vote(bare_hash, signature)); assert_eq!(vote.winner().unwrap(), bare_hash); // Voting again is ineffective. - let signature = tap.sign(addr1, bare_hash).unwrap(); + let signature = tap.sign(addr1, None, bare_hash).unwrap(); assert!(!vote.vote(bare_hash, signature)); // Second valid vote. - let signature = tap.sign(addr2, bare_hash).unwrap(); + let signature = tap.sign(addr2, None, bare_hash).unwrap(); assert!(vote.vote(bare_hash, signature)); assert_eq!(vote.winner().unwrap(), bare_hash); } diff --git a/ethcore/src/engines/tendermint/mod.rs b/ethcore/src/engines/tendermint/mod.rs index 7826f991ef8b715363dacf5a71a263782bab99df..70ba24a091aa0a7cc79eca921636eae77da03390 100644 --- a/ethcore/src/engines/tendermint/mod.rs +++ b/ethcore/src/engines/tendermint/mod.rs @@ -23,7 +23,12 @@ mod vote; mod vote_collector; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; -use common::*; +use util::*; +use error::{Error, BlockError}; +use header::Header; +use builtin::Builtin; +use env_info::EnvInfo; +use transaction::SignedTransaction; use rlp::{UntrustedRlp, View, encode}; use ethkey::{recover, public_to_address}; use account_provider::AccountProvider; @@ -31,6 +36,7 @@ use block::*; use spec::CommonParams; use engines::{Engine, EngineError, ProposeCollect}; use blockchain::extras::BlockDetails; +use views::HeaderView; use evm::Schedule; use io::IoService; use self::message::ConsensusMessage; @@ -368,11 +374,14 @@ impl Engine for Tendermint { #[cfg(test)] mod tests { - use common::*; use std::thread::sleep; use std::time::{Duration}; + use util::*; use rlp::{UntrustedRlp, RlpStream, Stream, View, encode}; use block::*; + use error::{Error, BlockError}; + use header::Header; + use env_info::EnvInfo; use tests::helpers::*; use account_provider::AccountProvider; use spec::Spec; @@ -406,11 +415,11 @@ mod tests { let mut seal = Vec::new(); let v0 = tap.insert_account("0".sha3(), "0").unwrap(); - let sig0 = tap.sign_with_password(v0, "0".into(), header.bare_hash()).unwrap(); + let sig0 = tap.sign(v0, Some("0".into()), header.bare_hash()).unwrap(); seal.push(encode(&(&*sig0 as &[u8])).to_vec()); let v1 = tap.insert_account("1".sha3(), "1").unwrap(); - let sig1 = tap.sign_with_password(v1, "1".into(), header.bare_hash()).unwrap(); + let sig1 = tap.sign(v1, Some("1".into()), header.bare_hash()).unwrap(); seal.push(encode(&(&*sig1 as &[u8])).to_vec()); seal } @@ -465,7 +474,7 @@ mod tests { let mut seal = Vec::new(); let v1 = tap.insert_account("0".sha3(), "0").unwrap(); - let sig1 = tap.sign_with_password(v1, "0".into(), header.bare_hash()).unwrap(); + let sig1 = tap.sign(v1, Some("0".into()), header.bare_hash()).unwrap(); seal.push(encode(&(&*sig1 as &[u8])).to_vec()); header.set_seal(seal.clone()); @@ -474,7 +483,7 @@ mod tests { assert!(engine.verify_block_basic(&header, None).is_err()); let v2 = tap.insert_account("101".sha3(), "101").unwrap(); - let sig2 = tap.sign_with_password(v2, "101".into(), header.bare_hash()).unwrap(); + let sig2 = tap.sign(v2, Some("101".into()), header.bare_hash()).unwrap(); seal.push(encode(&(&*sig2 as &[u8])).to_vec()); header.set_seal(seal); diff --git a/ethcore/src/engines/tendermint/params.rs b/ethcore/src/engines/tendermint/params.rs index cf7a90931f1d6ab7b795b87b29b362170a24cc9b..904499c046743ae446c032dc3a318126131f0c9c 100644 --- a/ethcore/src/engines/tendermint/params.rs +++ b/ethcore/src/engines/tendermint/params.rs @@ -16,9 +16,9 @@ //! Tendermint specific parameters. -use common::{Address, U256}; use ethjson; use super::timeout::DefaultTimeouts; +use util::{Address, U256}; /// `Tendermint` params. #[derive(Debug, Clone)] diff --git a/ethcore/src/engines/tendermint/vote.rs b/ethcore/src/engines/tendermint/vote.rs index a877d324ecd3d8f00ee3b6bd90ab7fa9188c775d..b01e14460cb837788e90355f967c6d2059a79546 100644 --- a/ethcore/src/engines/tendermint/vote.rs +++ b/ethcore/src/engines/tendermint/vote.rs @@ -16,8 +16,8 @@ //! Tendermint block seal. -use common::{H256, Address, H520, Header}; -use util::Hashable; +use util::*; +use header::Header; use account_provider::AccountProvider; use rlp::{View, DecoderError, Decodable, Decoder, Encodable, RlpStream, Stream}; use basic_types::Seal; @@ -46,7 +46,7 @@ impl Vote { /// Use any unlocked validator account to create a vote. pub fn validate(header: &Header, accounts: &AccountProvider, validator: Address) -> Option { let message = block_hash(&header); - accounts.sign(validator, message) + accounts.sign(validator, None, message) .ok() .map(Into::into) .map(|sig| Self::new(message, sig)) diff --git a/ethcore/src/engines/tendermint/vote_collector.rs b/ethcore/src/engines/tendermint/vote_collector.rs index bcf347053ebafb071efa4b87675d718887ed8534..448a4b209b4136a96da06c1edc5d4d5249280b04 100644 --- a/ethcore/src/engines/tendermint/vote_collector.rs +++ b/ethcore/src/engines/tendermint/vote_collector.rs @@ -17,9 +17,9 @@ //! Collects votes on hashes at each height and round. use super::vote::Vote; -use super::{Height, Round, BlockHash}; -use common::{HashSet, HashMap, RwLock, H256, Address, Error, Hashable}; -use ethkey::{Signature, recover}; +use super::{Height, Round}; +use ethkey::recover; +use util::{RwLock, HashMap, HashSet}; /// Signed voting on hashes. #[derive(Debug)] diff --git a/ethcore/src/error.rs b/ethcore/src/error.rs index d0fa419bb2697fd0a8e3df8431e611713e10df16..3e06f26249f8fd111544389fe57a0fef01f4229b 100644 --- a/ethcore/src/error.rs +++ b/ethcore/src/error.rs @@ -48,6 +48,13 @@ pub enum TransactionError { /// Transaction gas price got: U256, }, + /// Transaction's gas is below currently set minimal gas requirement. + InsufficientGas { + /// Minimal expected gas + minimal: U256, + /// Transaction gas + got: U256, + }, /// Sender doesn't have enough funds to pay for this transaction InsufficientBalance { /// Senders balance @@ -64,6 +71,12 @@ pub enum TransactionError { }, /// Transaction's gas limit (aka gas) is invalid. InvalidGasLimit(OutOfBounds), + /// Transaction sender is banned. + SenderBanned, + /// Transaction receipient is banned. + RecipientBanned, + /// Contract creation code is banned. + CodeBanned, } impl fmt::Display for TransactionError { @@ -76,12 +89,17 @@ impl fmt::Display for TransactionError { LimitReached => "Transaction limit reached".into(), InsufficientGasPrice { minimal, got } => format!("Insufficient gas price. Min={}, Given={}", minimal, got), + InsufficientGas { minimal, got } => + format!("Insufficient gas. Min={}, Given={}", minimal, got), InsufficientBalance { balance, cost } => format!("Insufficient balance for transaction. Balance={}, Cost={}", balance, cost), GasLimitExceeded { limit, got } => format!("Gas limit exceeded. Limit={}, Given={}", limit, got), InvalidGasLimit(ref err) => format!("Invalid gas limit. {}", err), + SenderBanned => "Sender is temporarily banned.".into(), + RecipientBanned => "Recipient is temporarily banned.".into(), + CodeBanned => "Contract code is temporarily banned.".into(), }; f.write_fmt(format_args!("Transaction error ({})", msg)) diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index a1dfd0a40349f554dd1fbd2455f1b3ffd69a340f..a7a6f78345cdb184de54dd4e87a66393639ba15c 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -15,9 +15,15 @@ // along with Parity. If not, see . use ethash::{quick_get_difficulty, slow_get_seedhash, EthashManager, H256 as EH256}; -use common::*; +use util::*; use block::*; +use builtin::Builtin; +use env_info::EnvInfo; +use error::{BlockError, Error}; +use header::Header; +use views::HeaderView; use spec::CommonParams; +use transaction::SignedTransaction; use engines::Engine; use evm::Schedule; use ethjson; @@ -42,7 +48,7 @@ pub struct EthashParams { /// Namereg contract address. pub registrar: Address, /// Homestead transition block number. - pub frontier_compatibility_mode_limit: u64, + pub homestead_transition: u64, /// DAO hard-fork transition block (X). pub dao_hardfork_transition: u64, /// DAO hard-fork refund contract address (C). @@ -55,6 +61,8 @@ 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. + pub eip150_transition: u64, } impl From for EthashParams { @@ -67,13 +75,14 @@ impl From for EthashParams { duration_limit: p.duration_limit.into(), block_reward: p.block_reward.into(), registrar: p.registrar.map_or_else(Address::new, Into::into), - frontier_compatibility_mode_limit: p.frontier_compatibility_mode_limit.map_or(0, Into::into), + homestead_transition: p.homestead_transition.map_or(0, Into::into), dao_hardfork_transition: p.dao_hardfork_transition.map_or(0x7fffffffffffffff, Into::into), dao_hardfork_beneficiary: p.dao_hardfork_beneficiary.map_or_else(Address::new, Into::into), dao_hardfork_accounts: p.dao_hardfork_accounts.unwrap_or_else(Vec::new).into_iter().map(Into::into).collect(), difficulty_hardfork_transition: p.difficulty_hardfork_transition.map_or(0x7fffffffffffffff, Into::into), 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), } } } @@ -118,12 +127,14 @@ impl Engine for Ethash { } fn schedule(&self, env_info: &EnvInfo) -> Schedule { - trace!(target: "client", "Creating schedule. fCML={}", self.ethash_params.frontier_compatibility_mode_limit); + trace!(target: "client", "Creating schedule. fCML={}, bGCML={}", self.ethash_params.homestead_transition, self.ethash_params.eip150_transition); - if env_info.number < self.ethash_params.frontier_compatibility_mode_limit { + if env_info.number < self.ethash_params.homestead_transition { Schedule::new_frontier() - } else { + } else if env_info.number < self.ethash_params.eip150_transition { Schedule::new_homestead() + } else { + Schedule::new_homestead_gas_fix() } } @@ -183,8 +194,8 @@ impl Engine for Ethash { // Commit state so that we can actually figure out the state root. if let Err(e) = fields.state.commit() { - warn!("Encountered error on state commit: {}", e); - } + warn!("Encountered error on state commit: {}", e); + } } fn verify_block_basic(&self, header: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { @@ -265,7 +276,7 @@ impl Engine for Ethash { } fn verify_transaction_basic(&self, t: &SignedTransaction, header: &Header) -> result::Result<(), Error> { - if header.number() >= self.ethash_params.frontier_compatibility_mode_limit { + if header.number() >= self.ethash_params.homestead_transition { try!(t.check_low_s()); } Ok(()) @@ -296,7 +307,7 @@ impl Ethash { false => self.ethash_params.difficulty_bound_divisor, }; let duration_limit = self.ethash_params.duration_limit; - let frontier_limit = self.ethash_params.frontier_compatibility_mode_limit; + let frontier_limit = self.ethash_params.homestead_transition; let mut target = if header.number() < frontier_limit { if header.timestamp() >= parent.timestamp() + duration_limit { @@ -378,9 +389,12 @@ impl Header { #[cfg(test)] mod tests { - use common::*; + use util::*; use block::*; use tests::helpers::*; + use env_info::EnvInfo; + use error::{BlockError, Error}; + use header::Header; use super::super::new_morden; use super::Ethash; use rlp; diff --git a/ethcore/src/ethereum/mod.rs b/ethcore/src/ethereum/mod.rs index 6d4502d2d90576c4946f5835177475d5b57b16a4..d8299324d65ba08d6a96bf359e252ccaa70be8d6 100644 --- a/ethcore/src/ethereum/mod.rs +++ b/ethcore/src/ethereum/mod.rs @@ -51,8 +51,11 @@ pub fn new_frontier_test() -> Spec { load(include_bytes!("../../res/ethereum/fro /// Create a new Homestead chain spec as though it never changed from Frontier. pub fn new_homestead_test() -> Spec { load(include_bytes!("../../res/ethereum/homestead_test.json")) } +/// 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 Frontier/Homestead/DAO chain spec with transition points at #5 and #8. -pub fn new_daohardfork_test() -> Spec { load(include_bytes!("../../res/ethereum/daohardfork_test.json")) } +pub fn new_transition_test() -> Spec { load(include_bytes!("../../res/ethereum/transition_test.json")) } /// Create a new Frontier main net chain spec without genesis accounts. pub fn new_mainnet_like() -> Spec { load(include_bytes!("../../res/ethereum/frontier_like_test.json")) } @@ -62,10 +65,11 @@ pub fn new_morden() -> Spec { load(include_bytes!("../../res/ethereum/morden.jso #[cfg(test)] mod tests { - use common::*; + use util::*; use state::*; use super::*; use tests::helpers::*; + use views::BlockView; #[test] fn ensure_db_good() { diff --git a/ethcore/src/evm/benches/mod.rs b/ethcore/src/evm/benches/mod.rs index 8ef730d88ec766d502ee047099fe3f114c2d5a18..cbed7d8813160be3ae96cfd54601dd317eb4a485 100644 --- a/ethcore/src/evm/benches/mod.rs +++ b/ethcore/src/evm/benches/mod.rs @@ -24,7 +24,8 @@ extern crate test; use self::test::{Bencher, black_box}; -use common::*; +use util::*; +use action_params::ActionParams; use evm::{self, Factory, VMType}; use evm::tests::FakeExt; diff --git a/ethcore/src/evm/factory.rs b/ethcore/src/evm/factory.rs index 629b423da55b50e82f227dbdde9c0995f870243d..a3d94bde83c90cfb78ee31930a3c806967c6cd45 100644 --- a/ethcore/src/evm/factory.rs +++ b/ethcore/src/evm/factory.rs @@ -118,11 +118,12 @@ impl Factory { } } - /// Create new instance of specific `VMType` factory - pub fn new(evm: VMType) -> Self { + /// Create new instance of specific `VMType` factory, with a size in bytes + /// for caching jump destinations. + pub fn new(evm: VMType, cache_size: usize) -> Self { Factory { evm: evm, - evm_cache: Arc::new(SharedCache::default()), + evm_cache: Arc::new(SharedCache::new(cache_size)), } } @@ -164,22 +165,22 @@ macro_rules! evm_test( #[ignore] #[cfg(feature = "jit")] fn $name_jit() { - $name_test(Factory::new(VMType::Jit)); + $name_test(Factory::new(VMType::Jit, 1024 * 32)); } #[test] fn $name_int() { - $name_test(Factory::new(VMType::Interpreter)); + $name_test(Factory::new(VMType::Interpreter, 1024 * 32)); } }; ($name_test: ident: $name_jit: ident, $name_int: ident) => { #[test] #[cfg(feature = "jit")] fn $name_jit() { - $name_test(Factory::new(VMType::Jit)); + $name_test(Factory::new(VMType::Jit, 1024 * 32)); } #[test] fn $name_int() { - $name_test(Factory::new(VMType::Interpreter)); + $name_test(Factory::new(VMType::Interpreter, 1024 * 32)); } } ); @@ -193,13 +194,13 @@ macro_rules! evm_test_ignore( #[cfg(feature = "jit")] #[cfg(feature = "ignored-tests")] fn $name_jit() { - $name_test(Factory::new(VMType::Jit)); + $name_test(Factory::new(VMType::Jit, 1024 * 32)); } #[test] #[ignore] #[cfg(feature = "ignored-tests")] fn $name_int() { - $name_test(Factory::new(VMType::Interpreter)); + $name_test(Factory::new(VMType::Interpreter, 1024 * 32)); } } ); diff --git a/ethcore/src/evm/instructions.rs b/ethcore/src/evm/instructions.rs index 62cfe77d6148c2f1edd2406a636adff9e048815b..e609bf542e5c09c281726b58387a7b6c30422a0f 100644 --- a/ethcore/src/evm/instructions.rs +++ b/ethcore/src/evm/instructions.rs @@ -173,7 +173,7 @@ lazy_static! { arr[SIGNEXTEND as usize] = InstructionInfo::new("SIGNEXTEND", 0, 2, 1, false, GasPriceTier::Low); arr[SHA3 as usize] = InstructionInfo::new("SHA3", 0, 2, 1, false, GasPriceTier::Special); arr[ADDRESS as usize] = InstructionInfo::new("ADDRESS", 0, 0, 1, false, GasPriceTier::Base); - arr[BALANCE as usize] = InstructionInfo::new("BALANCE", 0, 1, 1, false, GasPriceTier::Ext); + arr[BALANCE as usize] = InstructionInfo::new("BALANCE", 0, 1, 1, false, GasPriceTier::Special); arr[ORIGIN as usize] = InstructionInfo::new("ORIGIN", 0, 0, 1, false, GasPriceTier::Base); arr[CALLER as usize] = InstructionInfo::new("CALLER", 0, 0, 1, false, GasPriceTier::Base); arr[CALLVALUE as usize] = InstructionInfo::new("CALLVALUE", 0, 0, 1, false, GasPriceTier::Base); @@ -183,8 +183,8 @@ lazy_static! { arr[CODESIZE as usize] = InstructionInfo::new("CODESIZE", 0, 0, 1, false, GasPriceTier::Base); arr[CODECOPY as usize] = InstructionInfo::new("CODECOPY", 0, 3, 0, true, GasPriceTier::VeryLow); arr[GASPRICE as usize] = InstructionInfo::new("GASPRICE", 0, 0, 1, false, GasPriceTier::Base); - arr[EXTCODESIZE as usize] = InstructionInfo::new("EXTCODESIZE", 0, 1, 1, false, GasPriceTier::Ext); - arr[EXTCODECOPY as usize] = InstructionInfo::new("EXTCODECOPY", 0, 4, 0, true, GasPriceTier::Ext); + arr[EXTCODESIZE as usize] = InstructionInfo::new("EXTCODESIZE", 0, 1, 1, false, GasPriceTier::Special); + arr[EXTCODECOPY as usize] = InstructionInfo::new("EXTCODECOPY", 0, 4, 0, true, GasPriceTier::Special); arr[BLOCKHASH as usize] = InstructionInfo::new("BLOCKHASH", 0, 1, 1, false, GasPriceTier::Ext); arr[COINBASE as usize] = InstructionInfo::new("COINBASE", 0, 0, 1, false, GasPriceTier::Base); arr[TIMESTAMP as usize] = InstructionInfo::new("TIMESTAMP", 0, 0, 1, false, GasPriceTier::Base); @@ -277,7 +277,7 @@ lazy_static! { arr[CALLCODE as usize] = InstructionInfo::new("CALLCODE", 0, 7, 1, true, GasPriceTier::Special); arr[RETURN as usize] = InstructionInfo::new("RETURN", 0, 2, 0, true, GasPriceTier::Zero); arr[DELEGATECALL as usize] = InstructionInfo::new("DELEGATECALL", 0, 6, 1, true, GasPriceTier::Special); - arr[SUICIDE as usize] = InstructionInfo::new("SUICIDE", 0, 1, 0, true, GasPriceTier::Zero); + arr[SUICIDE as usize] = InstructionInfo::new("SUICIDE", 0, 1, 0, true, GasPriceTier::Special); arr }; } diff --git a/ethcore/src/evm/interpreter/gasometer.rs b/ethcore/src/evm/interpreter/gasometer.rs index d7022be7ceb3346aca44d9ec04e196ca5a557d64..a2b9406556c9bf614953658dca735a00fbc7961e 100644 --- a/ethcore/src/evm/interpreter/gasometer.rs +++ b/ethcore/src/evm/interpreter/gasometer.rs @@ -14,11 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use common::*; +use util::*; use super::u256_to_address; use evm::{self, CostType}; use evm::instructions::{self, Instruction, InstructionInfo}; use evm::interpreter::stack::Stack; +use evm::schedule::Schedule; macro_rules! overflowing { ($x: expr) => {{ @@ -29,12 +30,20 @@ macro_rules! overflowing { } #[cfg_attr(feature="dev", allow(enum_variant_names))] -enum InstructionCost { +enum Request { Gas(Cost), GasMem(Cost, Cost), + GasMemProvide(Cost, Cost, Option), GasMemCopy(Cost, Cost, Cost) } +pub struct InstructionRequirements { + pub gas_cost: Cost, + pub provide_gas: Option, + pub memory_total_gas: Cost, + pub memory_required_size: usize, +} + pub struct Gasometer { pub current_gas: Gas, pub current_mem_gas: Gas, @@ -56,22 +65,60 @@ impl Gasometer { } } + /// How much gas is provided to a CALL/CREATE, given that we need to deduct `needed` for this operation + /// and that we `requested` some. + pub fn gas_provided(&self, schedule: &Schedule, needed: Gas, requested: Option) -> evm::Result { + // Try converting requested gas to `Gas` (`U256/u64`) + // but in EIP150 even if we request more we should never fail from OOG + let requested = requested.map(Gas::from_u256); + + match schedule.sub_gas_cap_divisor { + Some(cap_divisor) if self.current_gas >= needed => { + let gas_remaining = self.current_gas - needed; + let max_gas_provided = match cap_divisor { + 64 => gas_remaining - (gas_remaining >> 6), + cap_divisor => gas_remaining - gas_remaining / Gas::from(cap_divisor), + }; + + if let Some(Ok(r)) = requested { + Ok(min(r, max_gas_provided)) + } else { + Ok(max_gas_provided) + } + }, + _ => { + if let Some(r) = requested { + r + } else if self.current_gas >= needed { + Ok(self.current_gas - needed) + } else { + Ok(0.into()) + } + }, + } + } + #[cfg_attr(feature="dev", allow(cyclomatic_complexity))] - pub fn get_gas_cost_mem( + /// Determine how much gas is used by the given instruction, given the machine's state. + /// + /// We guarantee that the final element of the returned tuple (`provided`) will be `Some` + /// iff the `instruction` is one of `CREATE`, or any of the `CALL` variants. In this case, + /// it will be the amount of gas that the current context provides to the child context. + pub fn requirements( &mut self, ext: &evm::Ext, instruction: Instruction, info: &InstructionInfo, stack: &Stack, current_mem_size: usize, - ) -> evm::Result<(Gas, Gas, usize)> { + ) -> evm::Result> { let schedule = ext.schedule(); let tier = instructions::get_tier_idx(info.tier); let default_gas = Gas::from(schedule.tier_step_gas[tier]); let cost = match instruction { instructions::JUMPDEST => { - InstructionCost::Gas(Gas::from(1)) + Request::Gas(Gas::from(1)) }, instructions::SSTORE => { let address = H256::from(stack.peek(0)); @@ -85,31 +132,47 @@ impl Gasometer { // !is_zero(&val) && is_zero(newval) schedule.sstore_reset_gas }; - InstructionCost::Gas(Gas::from(gas)) + Request::Gas(Gas::from(gas)) }, instructions::SLOAD => { - InstructionCost::Gas(Gas::from(schedule.sload_gas)) + Request::Gas(Gas::from(schedule.sload_gas)) + }, + instructions::BALANCE => { + Request::Gas(Gas::from(schedule.balance_gas)) + }, + instructions::EXTCODESIZE => { + Request::Gas(Gas::from(schedule.extcodesize_gas)) + }, + instructions::SUICIDE => { + let mut gas = Gas::from(schedule.suicide_gas); + + let address = u256_to_address(stack.peek(0)); + if !ext.exists(&address) { + gas = overflowing!(gas.overflow_add(schedule.suicide_to_new_account_cost.into())); + } + + Request::Gas(gas) }, instructions::MSTORE | instructions::MLOAD => { - InstructionCost::GasMem(default_gas, try!(mem_needed_const(stack.peek(0), 32))) + Request::GasMem(default_gas, try!(mem_needed_const(stack.peek(0), 32))) }, instructions::MSTORE8 => { - InstructionCost::GasMem(default_gas, try!(mem_needed_const(stack.peek(0), 1))) + Request::GasMem(default_gas, try!(mem_needed_const(stack.peek(0), 1))) }, instructions::RETURN => { - InstructionCost::GasMem(default_gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) + Request::GasMem(default_gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) }, instructions::SHA3 => { let w = overflowing!(add_gas_usize(try!(Gas::from_u256(*stack.peek(1))), 31)); let words = w >> 5; let gas = Gas::from(schedule.sha3_gas) + (Gas::from(schedule.sha3_word_gas) * words); - InstructionCost::GasMem(gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) + Request::GasMem(gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) }, instructions::CALLDATACOPY | instructions::CODECOPY => { - InstructionCost::GasMemCopy(default_gas, try!(mem_needed(stack.peek(0), stack.peek(2))), try!(Gas::from_u256(*stack.peek(2)))) + Request::GasMemCopy(default_gas, try!(mem_needed(stack.peek(0), stack.peek(2))), try!(Gas::from_u256(*stack.peek(2)))) }, instructions::EXTCODECOPY => { - InstructionCost::GasMemCopy(default_gas, try!(mem_needed(stack.peek(1), stack.peek(3))), try!(Gas::from_u256(*stack.peek(3)))) + Request::GasMemCopy(schedule.extcodecopy_base_gas.into(), try!(mem_needed(stack.peek(1), stack.peek(3))), try!(Gas::from_u256(*stack.peek(3)))) }, instructions::LOG0...instructions::LOG4 => { let no_of_topics = instructions::get_log_topics(instruction); @@ -117,10 +180,10 @@ impl Gasometer { let data_gas = overflowing!(try!(Gas::from_u256(*stack.peek(1))).overflow_mul(Gas::from(schedule.log_data_gas))); let gas = overflowing!(data_gas.overflow_add(Gas::from(log_gas))); - InstructionCost::GasMem(gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) + Request::GasMem(gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) }, instructions::CALL | instructions::CALLCODE => { - let mut gas = overflowing!(add_gas_usize(try!(Gas::from_u256(*stack.peek(0))), schedule.call_gas)); + let mut gas = Gas::from(schedule.call_gas); let mem = cmp::max( try!(mem_needed(stack.peek(5), stack.peek(6))), try!(mem_needed(stack.peek(3), stack.peek(4))) @@ -129,55 +192,89 @@ impl Gasometer { let address = u256_to_address(stack.peek(1)); if instruction == instructions::CALL && !ext.exists(&address) { - gas = overflowing!(gas.overflow_add(Gas::from(schedule.call_new_account_gas))); + gas = overflowing!(gas.overflow_add(schedule.call_new_account_gas.into())); }; if !stack.peek(2).is_zero() { - gas = overflowing!(gas.overflow_add(Gas::from(schedule.call_value_transfer_gas))); + gas = overflowing!(gas.overflow_add(schedule.call_value_transfer_gas.into())); }; - InstructionCost::GasMem(gas,mem) + let requested = *stack.peek(0); + + Request::GasMemProvide(gas, mem, Some(requested)) }, instructions::DELEGATECALL => { - let gas = overflowing!(add_gas_usize(try!(Gas::from_u256(*stack.peek(0))), schedule.call_gas)); + let gas = Gas::from(schedule.call_gas); let mem = cmp::max( try!(mem_needed(stack.peek(4), stack.peek(5))), try!(mem_needed(stack.peek(2), stack.peek(3))) ); - InstructionCost::GasMem(gas, mem) + let requested = *stack.peek(0); + + Request::GasMemProvide(gas, mem, Some(requested)) }, instructions::CREATE => { let gas = Gas::from(schedule.create_gas); let mem = try!(mem_needed(stack.peek(1), stack.peek(2))); - InstructionCost::GasMem(gas, mem) + + Request::GasMemProvide(gas, mem, None) }, instructions::EXP => { let expon = stack.peek(1); let bytes = ((expon.bits() + 7) / 8) as usize; let gas = Gas::from(schedule.exp_gas + schedule.exp_byte_gas * bytes); - InstructionCost::Gas(gas) + Request::Gas(gas) }, - _ => InstructionCost::Gas(default_gas) + _ => Request::Gas(default_gas), }; - match cost { - InstructionCost::Gas(gas) => { - Ok((gas, self.current_mem_gas, 0)) + Ok(match cost { + Request::Gas(gas) => { + InstructionRequirements { + gas_cost: gas, + provide_gas: None, + memory_required_size: 0, + memory_total_gas: self.current_mem_gas, + } }, - InstructionCost::GasMem(gas, mem_size) => { + Request::GasMem(gas, mem_size) => { let (mem_gas_cost, new_mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, current_mem_size, &mem_size)); let gas = overflowing!(gas.overflow_add(mem_gas_cost)); - Ok((gas, new_mem_gas, new_mem_size)) + InstructionRequirements { + gas_cost: gas, + provide_gas: None, + memory_required_size: new_mem_size, + memory_total_gas: new_mem_gas, + } }, - InstructionCost::GasMemCopy(gas, mem_size, copy) => { + Request::GasMemProvide(gas, mem_size, requested) => { + let (mem_gas_cost, new_mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, current_mem_size, &mem_size)); + let gas = overflowing!(gas.overflow_add(mem_gas_cost)); + let provided = try!(self.gas_provided(schedule, gas, requested)); + let total_gas = overflowing!(gas.overflow_add(provided)); + + InstructionRequirements { + gas_cost: total_gas, + provide_gas: Some(provided), + memory_required_size: new_mem_size, + memory_total_gas: new_mem_gas, + } + }, + Request::GasMemCopy(gas, mem_size, copy) => { let (mem_gas_cost, new_mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, current_mem_size, &mem_size)); let copy = overflowing!(add_gas_usize(copy, 31)) >> 5; let copy_gas = Gas::from(schedule.copy_gas) * copy; let gas = overflowing!(gas.overflow_add(copy_gas)); let gas = overflowing!(gas.overflow_add(mem_gas_cost)); - Ok((gas, new_mem_gas, new_mem_size)) - } - } + + InstructionRequirements { + gas_cost: gas, + provide_gas: None, + memory_required_size: new_mem_size, + memory_total_gas: new_mem_gas, + } + }, + }) } fn mem_gas_cost(&self, schedule: &evm::Schedule, current_mem_size: usize, mem_size: &Gas) -> evm::Result<(Gas, Gas, usize)> { @@ -187,7 +284,7 @@ impl Gasometer { let a = overflowing!(s.overflow_mul(Gas::from(schedule.memory_gas))); // Calculate s*s/quad_coeff_div - debug_assert_eq!(schedule.quad_coeff_div, 512); + assert_eq!(schedule.quad_coeff_div, 512); let b = overflowing!(s.overflow_mul_shr(s, 9)); Ok(overflowing!(a.overflow_add(b))) }; @@ -259,3 +356,4 @@ fn test_calculate_mem_cost() { assert_eq!(new_mem_gas, 3); assert_eq!(mem_size, 32); } + diff --git a/ethcore/src/evm/interpreter/mod.rs b/ethcore/src/evm/interpreter/mod.rs index 887f37cefd6676801127fd05340f42461b0ef8cb..bb9791abe16695436f17c301724b82f95681d9f4 100644 --- a/ethcore/src/evm/interpreter/mod.rs +++ b/ethcore/src/evm/interpreter/mod.rs @@ -29,12 +29,14 @@ use self::memory::Memory; pub use self::shared_cache::SharedCache; use std::marker::PhantomData; -use common::*; +use action_params::{ActionParams, ActionValue}; use types::executed::CallType; -use super::instructions::{self, Instruction, InstructionInfo}; +use evm::instructions::{self, Instruction, InstructionInfo}; use evm::{self, MessageCallResult, ContractCreateResult, GasLeft, CostType}; use bit_set::BitSet; +use util::*; + type CodePosition = usize; type ProgramCounter = usize; @@ -52,14 +54,14 @@ const TWO_POW_248: U256 = U256([0, 0, 0, 0x100000000000000]); //0x1 00000000 000 /// Abstraction over raw vector of Bytes. Easier state management of PC. struct CodeReader<'a> { position: ProgramCounter, - code: &'a Bytes + code: &'a [u8] } #[cfg_attr(feature="dev", allow(len_without_is_empty))] impl<'a> CodeReader<'a> { /// Create new code reader - starting at position 0. - fn new(code: &'a Bytes) -> Self { + fn new(code: &'a [u8]) -> Self { CodeReader { position: 0, code: code, @@ -81,8 +83,6 @@ impl<'a> CodeReader<'a> { enum InstructionResult { Ok, - UseAllGas, - GasLeft(Gas), UnusedGas(Gas), JumpToPosition(U256), // gas left, init_orf, init_size @@ -104,7 +104,7 @@ impl evm::Evm for Interpreter { let mut informant = informant::EvmInformant::new(ext.depth()); - let code = ¶ms.code.as_ref().unwrap(); + let code = ¶ms.code.as_ref().expect("exec always called with code; qed"); let valid_jump_destinations = self.cache.jump_destinations(¶ms.code_hash, code); let mut gasometer = Gasometer::::new(try!(Cost::from_u256(params.gas))); @@ -120,14 +120,14 @@ impl evm::Evm for Interpreter { try!(self.verify_instruction(ext, instruction, info, &stack)); // Calculate gas cost - let (gas_cost, mem_gas, mem_size) = try!(gasometer.get_gas_cost_mem(ext, instruction, info, &stack, self.mem.size())); + let requirements = try!(gasometer.requirements(ext, instruction, info, &stack, self.mem.size())); // TODO: make compile-time removable if too much of a performance hit. - let trace_executed = ext.trace_prepare_execute(reader.position - 1, instruction, &gas_cost.as_u256()); + let trace_executed = ext.trace_prepare_execute(reader.position - 1, instruction, &requirements.gas_cost.as_u256()); - try!(gasometer.verify_gas(&gas_cost)); - self.mem.expand(mem_size); - gasometer.current_mem_gas = mem_gas; - gasometer.current_gas = gasometer.current_gas - gas_cost; + try!(gasometer.verify_gas(&requirements.gas_cost)); + self.mem.expand(requirements.memory_required_size); + gasometer.current_mem_gas = requirements.memory_total_gas; + gasometer.current_gas = gasometer.current_gas - requirements.gas_cost; evm_debug!({ informant.before_instruction(reader.position, instruction, info, &gasometer.current_gas, &stack) }); @@ -138,27 +138,21 @@ impl evm::Evm for Interpreter { // Execute instruction let result = try!(self.exec_instruction( - gasometer.current_gas, ¶ms, ext, instruction, &mut reader, &mut stack + gasometer.current_gas, ¶ms, ext, instruction, &mut reader, &mut stack, requirements.provide_gas )); evm_debug!({ informant.after_instruction(instruction) }); + if let InstructionResult::UnusedGas(ref gas) = result { + gasometer.current_gas = gasometer.current_gas + *gas; + } + if trace_executed { ext.trace_executed(gasometer.current_gas.as_u256(), stack.peek_top(info.ret), mem_written.map(|(o, s)| (o, &(self.mem[o..(o + s)]))), store_written); } // Advance match result { - InstructionResult::Ok => {}, - InstructionResult::UnusedGas(gas) => { - gasometer.current_gas = gasometer.current_gas + gas; - }, - InstructionResult::UseAllGas => { - gasometer.current_gas = Cost::from(0); - }, - InstructionResult::GasLeft(gas_left) => { - gasometer.current_gas = gas_left; - }, InstructionResult::JumpToPosition(position) => { let pos = try!(self.verify_jump(position, &valid_jump_destinations)); reader.position = pos; @@ -168,6 +162,7 @@ impl evm::Evm for Interpreter { return Ok(GasLeft::NeedsReturn(gas.as_u256(), self.mem.read_slice(off, size))); }, InstructionResult::StopExecution => break, + _ => {}, } } informant.done(); @@ -250,7 +245,8 @@ impl Interpreter { ext: &mut evm::Ext, instruction: Instruction, code: &mut CodeReader, - stack: &mut Stack + stack: &mut Stack, + provided: Option ) -> evm::Result> { match instruction { instructions::JUMP => { @@ -275,31 +271,32 @@ impl Interpreter { let endowment = stack.pop_back(); let init_off = stack.pop_back(); let init_size = stack.pop_back(); + let create_gas = provided.expect("`provided` comes through Self::exec from `Gasometer::get_gas_cost_mem`; `gas_gas_mem_cost` guarantees `Some` when instruction is `CALL`/`CALLCODE`/`DELEGATECALL`/`CREATE`; this is `CREATE`; qed"); let contract_code = self.mem.read_slice(init_off, init_size); let can_create = ext.balance(¶ms.address) >= endowment && ext.depth() < ext.schedule().max_depth; if !can_create { stack.push(U256::zero()); - return Ok(InstructionResult::Ok); + return Ok(InstructionResult::UnusedGas(create_gas)); } - let create_result = ext.create(&gas.as_u256(), &endowment, contract_code); + let create_result = ext.create(&create_gas.as_u256(), &endowment, contract_code); return match create_result { ContractCreateResult::Created(address, gas_left) => { stack.push(address_to_u256(address)); - Ok(InstructionResult::GasLeft(Cost::from_u256(gas_left).expect("Gas left cannot be greater."))) + Ok(InstructionResult::UnusedGas(Cost::from_u256(gas_left).expect("Gas left cannot be greater."))) }, ContractCreateResult::Failed => { stack.push(U256::zero()); - // TODO [todr] Should we just StopExecution here? - Ok(InstructionResult::UseAllGas) + Ok(InstructionResult::Ok) } }; }, instructions::CALL | instructions::CALLCODE | instructions::DELEGATECALL => { assert!(ext.schedule().call_value_transfer_gas > ext.schedule().call_stipend, "overflow possible"); - let call_gas = Cost::from_u256(stack.pop_back()).expect("Gas is already validated."); + stack.pop_back(); + let call_gas = provided.expect("`provided` comes through Self::exec from `Gasometer::get_gas_cost_mem`; `gas_gas_mem_cost` guarantees `Some` when instruction is `CALL`/`CALLCODE`/`DELEGATECALL`/`CREATE`; this is one of `CALL`/`CALLCODE`/`DELEGATECALL`; qed"); let code_address = stack.pop_back(); let code_address = u256_to_address(&code_address); @@ -317,17 +314,17 @@ impl Interpreter { // Add stipend (only CALL|CALLCODE when value > 0) let call_gas = call_gas + value.map_or_else(|| Cost::from(0), |val| match val.is_zero() { false => Cost::from(ext.schedule().call_stipend), - true => Cost::from(0) + true => Cost::from(0), }); // Get sender & receive addresses, check if we have balance let (sender_address, receive_address, has_balance, call_type) = match instruction { instructions::CALL => { - let has_balance = ext.balance(¶ms.address) >= value.unwrap(); + let has_balance = ext.balance(¶ms.address) >= value.expect("value set for all but delegate call; qed"); (¶ms.address, &code_address, has_balance, CallType::Call) }, instructions::CALLCODE => { - let has_balance = ext.balance(¶ms.address) >= value.unwrap(); + let has_balance = ext.balance(¶ms.address) >= value.expect("value set for all but delegate call; qed"); (¶ms.address, ¶ms.address, has_balance, CallType::CallCode) }, instructions::DELEGATECALL => (¶ms.sender, ¶ms.address, true, CallType::DelegateCall), diff --git a/ethcore/src/evm/interpreter/shared_cache.rs b/ethcore/src/evm/interpreter/shared_cache.rs index ce383bae8107ed27531a9bdb598e91b41fa5b3a1..cacc4dde393bd1e66e21baf32f92a60ada2e6a5c 100644 --- a/ethcore/src/evm/interpreter/shared_cache.rs +++ b/ethcore/src/evm/interpreter/shared_cache.rs @@ -15,31 +15,51 @@ // along with Parity. If not, see . use std::sync::Arc; -use lru_cache::LruCache; -use util::{H256, Mutex}; +use util::{H256, HeapSizeOf, Mutex}; use util::sha3::*; +use util::cache::MemoryLruCache; use bit_set::BitSet; use super::super::instructions; -const CACHE_CODE_ITEMS: usize = 65536; +const DEFAULT_CACHE_SIZE: usize = 4 * 1024 * 1024; -/// GLobal cache for EVM interpreter +// stub for a HeapSizeOf implementation. +struct Bits(Arc); + +impl HeapSizeOf for Bits { + fn heap_size_of_children(&self) -> usize { + // dealing in bits here + self.0.capacity() * 8 + } +} + +/// Global cache for EVM interpreter pub struct SharedCache { - jump_destinations: Mutex>> + jump_destinations: Mutex>, } impl SharedCache { - /// Get jump destincations bitmap for a contract. + /// Create a jump destinations cache with a maximum size in bytes + /// to cache. + pub fn new(max_size: usize) -> Self { + SharedCache { + jump_destinations: Mutex::new(MemoryLruCache::new(max_size)), + } + } + + /// Get jump destinations bitmap for a contract. pub fn jump_destinations(&self, code_hash: &H256, code: &[u8]) -> Arc { if code_hash == &SHA3_EMPTY { return Self::find_jump_destinations(code); } + if let Some(d) = self.jump_destinations.lock().get_mut(code_hash) { - return d.clone(); + return d.0.clone(); } let d = Self::find_jump_destinations(code); - self.jump_destinations.lock().insert(code_hash.clone(), d.clone()); + self.jump_destinations.lock().insert(code_hash.clone(), Bits(d.clone())); + d } @@ -57,15 +77,15 @@ impl SharedCache { } position += 1; } + + jump_dests.shrink_to_fit(); Arc::new(jump_dests) } } impl Default for SharedCache { - fn default() -> SharedCache { - SharedCache { - jump_destinations: Mutex::new(LruCache::new(CACHE_CODE_ITEMS)), - } + fn default() -> Self { + SharedCache::new(DEFAULT_CACHE_SIZE) } } diff --git a/ethcore/src/evm/jit.rs b/ethcore/src/evm/jit.rs index 3487d9a593e7f9fadbf5dc89eaf2bb8c709a35af..6fa617396dca13844912beb49bc06fec8652bc5b 100644 --- a/ethcore/src/evm/jit.rs +++ b/ethcore/src/evm/jit.rs @@ -15,7 +15,7 @@ // along with Parity. If not, see . //! Just in time compiler execution environment. -use common::*; +use util::*; use evmjit; use evm::{self, GasLeft}; use types::executed::CallType; @@ -359,7 +359,7 @@ impl evm::Evm for JitEvm { data.timestamp = ext.env_info().timestamp as i64; self.context = Some(unsafe { evmjit::ContextHandle::new(data, schedule, &mut ext_handle) }); - let mut context = self.context.as_mut().unwrap(); + let mut context = self.context.as_mut().expect("context handle set on the prior line; qed"); let res = context.exec(); match res { diff --git a/ethcore/src/evm/schedule.rs b/ethcore/src/evm/schedule.rs index e3e4e3b7bffd0aae1137b666be480c9d50fc6fc4..b8de785b397d6cb496d5c936a0425371418423ea 100644 --- a/ethcore/src/evm/schedule.rs +++ b/ethcore/src/evm/schedule.rs @@ -80,6 +80,19 @@ pub struct Schedule { pub tx_data_non_zero_gas: usize, /// Gas price for copying memory pub copy_gas: usize, + /// Price of EXTCODESIZE + pub extcodesize_gas: usize, + /// Base price of EXTCODECOPY + pub extcodecopy_base_gas: usize, + /// Price of BALANCE + pub balance_gas: usize, + /// Price of SUICIDE + pub suicide_gas: usize, + /// Amount of additional gas to pay when SUICIDE credits a non-existant account + pub suicide_to_new_account_cost: usize, + /// 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, } impl Schedule { @@ -93,6 +106,49 @@ 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{ + 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, + sha3_gas: 30, + sha3_word_gas: 6, + sload_gas: 200, + sstore_set_gas: 20000, + sstore_reset_gas: 5000, + sstore_refund_gas: 15000, + jumpdest_gas: 1, + log_gas: 375, + log_data_gas: 8, + log_topic_gas: 375, + create_gas: 32000, + call_gas: 700, + call_stipend: 2300, + call_value_transfer_gas: 9000, + call_new_account_gas: 25000, + suicide_refund_gas: 24000, + memory_gas: 3, + quad_coeff_div: 512, + create_data_gas: 200, + tx_gas: 21000, + tx_create_gas: 53000, + tx_data_zero_gas: 4, + tx_data_non_zero_gas: 68, + copy_gas: 3, + extcodesize_gas: 700, + extcodecopy_base_gas: 700, + balance_gas: 400, + suicide_gas: 5000, + suicide_to_new_account_cost: 25000, + sub_gas_cap_divisor: Some(64), + } + } + fn new(efcd: bool, hdc: bool, tcg: usize) -> Schedule { Schedule{ exceptional_failed_code_deposit: efcd, @@ -126,6 +182,12 @@ impl Schedule { tx_data_zero_gas: 4, tx_data_non_zero_gas: 68, copy_gas: 3, + extcodesize_gas: 20, + extcodecopy_base_gas: 20, + balance_gas: 20, + suicide_gas: 0, + suicide_to_new_account_cost: 0, + sub_gas_cap_divisor: None, } } } diff --git a/ethcore/src/evm/tests.rs b/ethcore/src/evm/tests.rs index eb7d168cf7beeb7c2e138ac9d8b5a4c26c2777dd..ba002d64970baa91538bc993e40b969a94282d4d 100644 --- a/ethcore/src/evm/tests.rs +++ b/ethcore/src/evm/tests.rs @@ -14,7 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use common::*; +use util::*; +use action_params::{ActionParams, ActionValue}; +use env_info::EnvInfo; use types::executed::CallType; use evm::{self, Ext, Schedule, Factory, GasLeft, VMType, ContractCreateResult, MessageCallResult}; use std::fmt::Debug; @@ -817,7 +819,7 @@ fn test_signextend(factory: super::Factory) { #[test] // JIT just returns out of gas fn test_badinstruction_int() { - let factory = super::Factory::new(VMType::Interpreter); + let factory = super::Factory::new(VMType::Interpreter, 1024 * 32); let code = "af".from_hex().unwrap(); let mut params = ActionParams::default(); diff --git a/ethcore/src/executive.rs b/ethcore/src/executive.rs index f3186d6dd9999d3c64e29545705007b3313c5226..f05cc4fd8d6ee0f8683a24908e726cc77f1d6295 100644 --- a/ethcore/src/executive.rs +++ b/ethcore/src/executive.rs @@ -15,13 +15,17 @@ // along with Parity. If not, see . //! Transaction Execution environment. -use common::*; +use util::*; +use action_params::{ActionParams, ActionValue}; use state::{State, Substate}; use engines::Engine; use types::executed::CallType; +use env_info::EnvInfo; +use error::ExecutionError; use evm::{self, Ext, Factory, Finalize}; use externalities::*; use trace::{FlatTrace, Tracer, NoopTracer, ExecutiveTracer, VMTrace, VMTracer, ExecutiveVMTracer, NoopVMTracer}; +use transaction::{Action, SignedTransaction}; use crossbeam; pub use types::executed::{Executed, ExecutionResult}; @@ -250,7 +254,7 @@ impl<'a> Executive<'a> { vm_tracer: &mut V ) -> evm::Result where T: Tracer, V: VMTracer { // backup used in case of running out of gas - self.state.snapshot(); + self.state.checkpoint(); // at first, transfer value to destination if let ActionValue::Transfer(val) = params.value { @@ -269,7 +273,7 @@ impl<'a> Executive<'a> { let cost = self.engine.cost_of_builtin(¶ms.code_address, data); if cost <= params.gas { self.engine.execute_builtin(¶ms.code_address, data, &mut output); - self.state.discard_snapshot(); + self.state.discard_checkpoint(); // trace only top level calls to builtins to avoid DDoS attacks if self.depth == 0 { @@ -289,7 +293,7 @@ impl<'a> Executive<'a> { Ok(params.gas - cost) } else { // just drain the whole gas - self.state.revert_to_snapshot(); + self.state.revert_to_checkpoint(); tracer.trace_failed_call(trace_info, vec![], evm::Error::OutOfGas.into()); @@ -335,7 +339,7 @@ impl<'a> Executive<'a> { res } else { // otherwise it's just a basic transaction, only do tracing, if necessary. - self.state.discard_snapshot(); + self.state.discard_checkpoint(); tracer.trace_call(trace_info, U256::zero(), trace_output, vec![]); Ok(params.gas) @@ -354,7 +358,7 @@ impl<'a> Executive<'a> { vm_tracer: &mut V ) -> evm::Result where T: Tracer, V: VMTracer { // backup used in case of running out of gas - self.state.snapshot(); + self.state.checkpoint(); // part of substate that may be reverted let mut unconfirmed_substate = Substate::new(); @@ -427,8 +431,16 @@ impl<'a> Executive<'a> { trace!("exec::finalize: t.gas={}, sstore_refunds={}, suicide_refunds={}, refunds_bound={}, gas_left_prerefund={}, refunded={}, gas_left={}, gas_used={}, refund_value={}, fees_value={}\n", t.gas, sstore_refunds, suicide_refunds, refunds_bound, gas_left_prerefund, refunded, gas_left, gas_used, refund_value, fees_value); - trace!("exec::finalize: Refunding refund_value={}, sender={}\n", refund_value, t.sender().unwrap()); - self.state.add_balance(&t.sender().unwrap(), &refund_value); + let sender = match t.sender() { + Ok(sender) => sender, + Err(e) => { + debug!(target: "executive", "attempted to finalize transaction without sender: {}", e); + return Err(ExecutionError::Internal); + } + }; + + trace!("exec::finalize: Refunding refund_value={}, sender={}\n", refund_value, sender); + self.state.add_balance(&sender, &refund_value); trace!("exec::finalize: Compensating author: fees_value={}, author={}\n", fees_value, &self.info.author); self.state.add_balance(&self.info.author, &fees_value); @@ -477,10 +489,10 @@ impl<'a> Executive<'a> { | Err(evm::Error::BadInstruction {.. }) | Err(evm::Error::StackUnderflow {..}) | Err(evm::Error::OutOfStack {..}) => { - self.state.revert_to_snapshot(); + self.state.revert_to_checkpoint(); }, Ok(_) | Err(evm::Error::Internal) => { - self.state.discard_snapshot(); + self.state.discard_checkpoint(); substate.accrue(un_substate); } } @@ -492,13 +504,18 @@ impl<'a> Executive<'a> { mod tests { use ethkey::{Generator, Random}; use super::*; - use common::*; + use util::*; + use action_params::{ActionParams, ActionValue}; + use env_info::EnvInfo; use evm::{Factory, VMType}; + use error::ExecutionError; use state::Substate; use tests::helpers::*; use trace::trace; use trace::{FlatTrace, Tracer, NoopTracer, ExecutiveTracer}; use trace::{VMTrace, VMOperation, VMExecutedOperation, MemoryDiff, StorageDiff, VMTracer, NoopVMTracer, ExecutiveVMTracer}; + use transaction::{Action, Transaction}; + use types::executed::CallType; #[test] @@ -598,7 +615,7 @@ mod tests { #[test] // Tracing is not suported in JIT fn test_call_to_create() { - let factory = Factory::new(VMType::Interpreter); + let factory = Factory::new(VMType::Interpreter, 1024 * 32); // code: // @@ -697,7 +714,7 @@ mod tests { VMOperation { pc: 33, instruction: 96, gas_cost: 3.into(), executed: Some(VMExecutedOperation { gas_used: 99985.into(), stack_push: vec_into![29], mem_diff: None, store_diff: None }) }, VMOperation { pc: 35, instruction: 96, gas_cost: 3.into(), executed: Some(VMExecutedOperation { gas_used: 99982.into(), stack_push: vec_into![3], mem_diff: None, store_diff: None }) }, VMOperation { pc: 37, instruction: 96, gas_cost: 3.into(), executed: Some(VMExecutedOperation { gas_used: 99979.into(), stack_push: vec_into![23], mem_diff: None, store_diff: None }) }, - VMOperation { pc: 39, instruction: 240, gas_cost: 32000.into(), executed: Some(VMExecutedOperation { gas_used: 67979.into(), stack_push: vec_into![U256::from_dec_str("1135198453258042933984631383966629874710669425204").unwrap()], mem_diff: None, store_diff: None }) }, + VMOperation { pc: 39, instruction: 240, gas_cost: 99979.into(), executed: Some(VMExecutedOperation { gas_used: 64755.into(), stack_push: vec_into![U256::from_dec_str("1135198453258042933984631383966629874710669425204").unwrap()], mem_diff: None, store_diff: None }) }, VMOperation { pc: 40, instruction: 96, gas_cost: 3.into(), executed: Some(VMExecutedOperation { gas_used: 64752.into(), stack_push: vec_into![0], mem_diff: None, store_diff: None }) }, VMOperation { pc: 42, instruction: 85, gas_cost: 20000.into(), executed: Some(VMExecutedOperation { gas_used: 44752.into(), stack_push: vec_into![], mem_diff: None, store_diff: Some(StorageDiff { location: 0.into(), value: U256::from_dec_str("1135198453258042933984631383966629874710669425204").unwrap() }) }) } ], @@ -724,7 +741,7 @@ mod tests { #[test] fn test_create_contract() { // Tracing is not supported in JIT - let factory = Factory::new(VMType::Interpreter); + let factory = Factory::new(VMType::Interpreter, 1024 * 32); // code: // // 60 10 - push 16 diff --git a/ethcore/src/externalities.rs b/ethcore/src/externalities.rs index 67c04aefb871613dbeab7109597d99992685ea8a..bbe81a51171cc9de381c85208d03b888492c58e8 100644 --- a/ethcore/src/externalities.rs +++ b/ethcore/src/externalities.rs @@ -15,9 +15,11 @@ // along with Parity. If not, see . //! Transaction Execution environment. -use common::*; +use util::*; +use action_params::{ActionParams, ActionValue}; use state::{State, Substate}; use engines::Engine; +use env_info::EnvInfo; use executive::*; use evm::{self, Schedule, Ext, ContractCreateResult, MessageCallResult, Factory}; use types::executed::CallType; @@ -253,6 +255,8 @@ impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMT } fn log(&mut self, topics: Vec, data: &[u8]) { + use log_entry::LogEntry; + let address = self.origin_info.address.clone(); self.substate.logs.push(LogEntry { address: address, @@ -303,8 +307,9 @@ impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMT #[cfg(test)] mod tests { - use common::*; + use util::*; use engines::Engine; + use env_info::EnvInfo; use evm::Ext; use state::{State, Substate}; use tests::helpers::*; diff --git a/ethcore/src/header.rs b/ethcore/src/header.rs index 794b9230b4d32fb7c7f6e19cd5fc1ce709828452..0aea4efd7ff8c151052c196fdf1dcef959203750 100644 --- a/ethcore/src/header.rs +++ b/ethcore/src/header.rs @@ -17,7 +17,7 @@ //! Block header. use util::*; -use basic_types::*; +use basic_types::{LogBloom, Seal, ZERO_LOGBLOOM}; use time::get_time; use rlp::*; @@ -199,8 +199,9 @@ impl Header { match &mut *hash { &mut Some(ref h) => h.clone(), hash @ &mut None => { - *hash = Some(self.rlp_sha3(Seal::With)); - hash.as_ref().unwrap().clone() + let h = self.rlp_sha3(Seal::With); + *hash = Some(h.clone()); + h } } } @@ -211,8 +212,9 @@ impl Header { match &mut *hash { &mut Some(ref h) => h.clone(), hash @ &mut None => { - *hash = Some(self.rlp_sha3(Seal::Without)); - hash.as_ref().unwrap().clone() + let h = self.rlp_sha3(Seal::Without); + *hash = Some(h.clone()); + h } } } diff --git a/ethcore/src/json_tests/chain.rs b/ethcore/src/json_tests/chain.rs index 93b0cf82cd7c1a2e6cd7b0eff335cdab8d68fcab..bf32db1337fff6c5464feb1cb682743f18fa9e61 100644 --- a/ethcore/src/json_tests/chain.rs +++ b/ethcore/src/json_tests/chain.rs @@ -48,7 +48,8 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { let mut spec = match era { ChainEra::Frontier => ethereum::new_frontier_test(), ChainEra::Homestead => ethereum::new_homestead_test(), - ChainEra::DaoHardfork => ethereum::new_daohardfork_test(), + ChainEra::Eip150 => ethereum::new_eip150_test(), + ChainEra::TransitionTest => ethereum::new_transition_test(), }; spec.set_genesis_state(state); spec.overwrite_genesis_params(genesis); @@ -116,14 +117,38 @@ mod frontier_era_tests { declare_test!{BlockchainTests_RandomTests_bl201507071825GO, "BlockchainTests/RandomTests/bl201507071825GO"} } -mod daohardfork_tests { +mod transition_tests { use tests::helpers::*; use super::json_chain_test; fn do_json_test(json_data: &[u8]) -> Vec { - json_chain_test(json_data, ChainEra::DaoHardfork) + json_chain_test(json_data, ChainEra::TransitionTest) } declare_test!{BlockchainTests_TestNetwork_bcSimpleTransitionTest, "BlockchainTests/TestNetwork/bcSimpleTransitionTest"} declare_test!{BlockchainTests_TestNetwork_bcTheDaoTest, "BlockchainTests/TestNetwork/bcTheDaoTest"} + declare_test!{BlockchainTests_TestNetwork_bcEIP150Test, "BlockchainTests/TestNetwork/bcEIP150Test"} +} + +mod eip150_blockchain_tests { + use tests::helpers::*; + use super::json_chain_test; + + fn do_json_test(json_data: &[u8]) -> Vec { + json_chain_test(json_data, ChainEra::Eip150) + } + + declare_test!{BlockchainTests_EIP150_bcBlockGasLimitTest, "BlockchainTests/EIP150/bcBlockGasLimitTest"} + declare_test!{BlockchainTests_EIP150_bcForkStressTest, "BlockchainTests/EIP150/bcForkStressTest"} + declare_test!{BlockchainTests_EIP150_bcGasPricerTest, "BlockchainTests/EIP150/bcGasPricerTest"} + declare_test!{BlockchainTests_EIP150_bcInvalidHeaderTest, "BlockchainTests/EIP150/bcInvalidHeaderTest"} + declare_test!{BlockchainTests_EIP150_bcInvalidRLPTest, "BlockchainTests/EIP150/bcInvalidRLPTest"} + declare_test!{BlockchainTests_EIP150_bcMultiChainTest, "BlockchainTests/EIP150/bcMultiChainTest"} + declare_test!{BlockchainTests_EIP150_bcRPC_API_Test, "BlockchainTests/EIP150/bcRPC_API_Test"} + declare_test!{BlockchainTests_EIP150_bcStateTest, "BlockchainTests/EIP150/bcStateTest"} + declare_test!{BlockchainTests_EIP150_bcTotalDifficultyTest, "BlockchainTests/EIP150/bcTotalDifficultyTest"} + declare_test!{BlockchainTests_EIP150_bcUncleHeaderValiditiy, "BlockchainTests/EIP150/bcUncleHeaderValiditiy"} + declare_test!{BlockchainTests_EIP150_bcUncleTest, "BlockchainTests/EIP150/bcUncleTest"} + declare_test!{BlockchainTests_EIP150_bcValidBlockTest, "BlockchainTests/EIP150/bcValidBlockTest"} + declare_test!{BlockchainTests_EIP150_bcWalletTest, "BlockchainTests/EIP150/bcWalletTest"} } diff --git a/ethcore/src/json_tests/eip150_state.rs b/ethcore/src/json_tests/eip150_state.rs new file mode 100644 index 0000000000000000000000000000000000000000..9076286eb46bc03de1c4f6d140e51ccbb7085f5e --- /dev/null +++ b/ethcore/src/json_tests/eip150_state.rs @@ -0,0 +1,43 @@ +// 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::Eip150) +} + +declare_test!{StateTests_EIP150_stEIPSpecificTest, "StateTests/EIP150/stEIPSpecificTest"} +declare_test!{StateTests_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP150/stEIPsingleCodeGasPrices"} +declare_test!{StateTests_EIP150_stMemExpandingEIPCalls, "StateTests/EIP150/stMemExpandingEIPCalls"} + +declare_test!{StateTests_EIP150_stCallCodes, "StateTests/EIP150/Homestead/stCallCodes"} +declare_test!{StateTests_EIP150_stCallCreateCallCodeTest, "StateTests/EIP150/Homestead/stCallCreateCallCodeTest"} +declare_test!{StateTests_EIP150_stDelegatecallTest, "StateTests/EIP150/Homestead/stDelegatecallTest"} +declare_test!{StateTests_EIP150_stInitCodeTest, "StateTests/EIP150/Homestead/stInitCodeTest"} +declare_test!{StateTests_EIP150_stLogTests, "StateTests/EIP150/Homestead/stLogTests"} +declare_test!{heavy => StateTests_EIP150_stMemoryStressTest, "StateTests/EIP150/Homestead/stMemoryStressTest"} +declare_test!{heavy => StateTests_EIP150_stMemoryTest, "StateTests/EIP150/Homestead/stMemoryTest"} +declare_test!{StateTests_EIP150_stPreCompiledContracts, "StateTests/EIP150/Homestead/stPreCompiledContracts"} +declare_test!{heavy => StateTests_EIP150_stQuadraticComplexityTest, "StateTests/EIP150/Homestead/stQuadraticComplexityTest"} +declare_test!{StateTests_EIP150_stRecursiveCreate, "StateTests/EIP150/Homestead/stRecursiveCreate"} +declare_test!{StateTests_EIP150_stRefundTest, "StateTests/EIP150/Homestead/stRefundTest"} +declare_test!{StateTests_EIP150_stSpecialTest, "StateTests/EIP150/Homestead/stSpecialTest"} +declare_test!{StateTests_EIP150_stSystemOperationsTest, "StateTests/EIP150/Homestead/stSystemOperationsTest"} +declare_test!{StateTests_EIP150_stTransactionTest, "StateTests/EIP150/Homestead/stTransactionTest"} +declare_test!{StateTests_EIP150_stWalletTest, "StateTests/EIP150/Homestead/stWalletTest"} diff --git a/ethcore/src/json_tests/executive.rs b/ethcore/src/json_tests/executive.rs index 5576f9ad4ed433776aae3cca44042cb6402c811d..1d4faec62dec852314099b705f6ae89632c7b5ad 100644 --- a/ethcore/src/json_tests/executive.rs +++ b/ethcore/src/json_tests/executive.rs @@ -15,9 +15,11 @@ // along with Parity. If not, see . use super::test_common::*; +use action_params::ActionParams; use state::{State, Substate}; use executive::*; use engines::Engine; +use env_info::EnvInfo; use evm; use evm::{Schedule, Ext, Factory, Finalize, VMType, ContractCreateResult, MessageCallResult}; use externalities::*; @@ -191,7 +193,7 @@ fn do_json_test_for(vm_type: &VMType, json_data: &[u8]) -> Vec { state.populate_from(From::from(vm.pre_state.clone())); let info = From::from(vm.env); let engine = TestEngine::new(1); - let vm_factory = Factory::new(vm_type.clone()); + let vm_factory = Factory::new(vm_type.clone(), 1024 * 32); let params = ActionParams::from(vm.transaction); let mut substate = Substate::new(); diff --git a/ethcore/src/json_tests/homestead_chain.rs b/ethcore/src/json_tests/homestead_chain.rs index 8db8ad22466937a2885460881b863c0f8f13ed62..37a9d0a21a1cd3fffce923c5df4c501d084ba8d1 100644 --- a/ethcore/src/json_tests/homestead_chain.rs +++ b/ethcore/src/json_tests/homestead_chain.rs @@ -36,3 +36,6 @@ declare_test!{BlockchainTests_Homestead_bcUncleHeaderValiditiy, "BlockchainTests declare_test!{BlockchainTests_Homestead_bcUncleTest, "BlockchainTests/Homestead/bcUncleTest"} declare_test!{BlockchainTests_Homestead_bcValidBlockTest, "BlockchainTests/Homestead/bcValidBlockTest"} declare_test!{BlockchainTests_Homestead_bcWalletTest, "BlockchainTests/Homestead/bcWalletTest"} +declare_test!{BlockchainTests_Homestead_bcShanghaiLove, "BlockchainTests/Homestead/bcShanghaiLove"} +declare_test!{BlockchainTests_Homestead_bcSuicideIssue, "BlockchainTests/Homestead/bcSuicideIssue"} +declare_test!{BlockchainTests_Homestead_bcExploitTest, "BlockchainTests/Homestead/bcExploitTest"} diff --git a/ethcore/src/json_tests/mod.rs b/ethcore/src/json_tests/mod.rs index 841db229ee6e929bc0a80946e0d7085f38038914..7a5dd30d2490619e065023cbbc75fef9664c2a38 100644 --- a/ethcore/src/json_tests/mod.rs +++ b/ethcore/src/json_tests/mod.rs @@ -23,4 +23,5 @@ mod state; mod chain; mod homestead_state; mod homestead_chain; +mod eip150_state; mod trie; diff --git a/ethcore/src/json_tests/state.rs b/ethcore/src/json_tests/state.rs index 28aaa62ec3263075c93999d2de2bfe6930bad5a4..c3e74af5db7108c4e8751ddfc5798ce965bcb177 100644 --- a/ethcore/src/json_tests/state.rs +++ b/ethcore/src/json_tests/state.rs @@ -17,13 +17,10 @@ use super::test_common::*; use tests::helpers::*; use pod_state::{self, PodState}; +use log_entry::LogEntry; use ethereum; use ethjson; -fn do_json_test(json_data: &[u8]) -> Vec { - json_chain_test(json_data, ChainEra::Frontier) -} - pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { init_log(); let tests = ethjson::state::Test::load(json_data).unwrap(); @@ -31,8 +28,9 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { let engine = match era { ChainEra::Frontier => ethereum::new_mainnet_like().engine, ChainEra::Homestead => ethereum::new_homestead_test().engine, - ChainEra::DaoHardfork => ethereum::new_daohardfork_test().engine, -}; + ChainEra::Eip150 => ethereum::new_eip150_test().engine, + ChainEra::TransitionTest => ethereum::new_transition_test().engine, + }; for (name, test) in tests.into_iter() { let mut fail = false; @@ -93,666 +91,673 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { failed } -declare_test!{StateTests_stBlockHashTest, "StateTests/stBlockHashTest"} -declare_test!{StateTests_stCallCodes, "StateTests/stCallCodes"} -declare_test!{StateTests_stCallCreateCallCodeTest, "StateTests/stCallCreateCallCodeTest"} -declare_test!{StateTests_stDelegatecallTest, "StateTests/stDelegatecallTest"} -declare_test!{StateTests_stExample, "StateTests/stExample"} -declare_test!{StateTests_stInitCodeTest, "StateTests/stInitCodeTest"} -declare_test!{StateTests_stLogTests, "StateTests/stLogTests"} -declare_test!{heavy => StateTests_stMemoryStressTest, "StateTests/stMemoryStressTest"} -declare_test!{heavy => StateTests_stMemoryTest, "StateTests/stMemoryTest"} -declare_test!{StateTests_stPreCompiledContracts, "StateTests/stPreCompiledContracts"} -declare_test!{heavy => StateTests_stQuadraticComplexityTest, "StateTests/stQuadraticComplexityTest"} -declare_test!{StateTests_stRecursiveCreate, "StateTests/stRecursiveCreate"} -declare_test!{StateTests_stRefundTest, "StateTests/stRefundTest"} -declare_test!{StateTests_stSolidityTest, "StateTests/stSolidityTest"} -declare_test!{StateTests_stSpecialTest, "StateTests/stSpecialTest"} -declare_test!{StateTests_stSystemOperationsTest, "StateTests/stSystemOperationsTest"} -declare_test!{StateTests_stTransactionTest, "StateTests/stTransactionTest"} -declare_test!{StateTests_stTransitionTest, "StateTests/stTransitionTest"} -declare_test!{StateTests_stWalletTest, "StateTests/stWalletTest"} +mod frontier_tests { + use super::json_chain_test; + use tests::helpers::ChainEra; + fn do_json_test(json_data: &[u8]) -> Vec { + json_chain_test(json_data, ChainEra::Frontier) + } -declare_test!{StateTests_RandomTests_st201503121803PYTHON, "StateTests/RandomTests/st201503121803PYTHON"} -declare_test!{StateTests_RandomTests_st201503121806PYTHON, "StateTests/RandomTests/st201503121806PYTHON"} -declare_test!{StateTests_RandomTests_st201503121848GO, "StateTests/RandomTests/st201503121848GO"} -declare_test!{StateTests_RandomTests_st201503121849GO, "StateTests/RandomTests/st201503121849GO"} -declare_test!{StateTests_RandomTests_st201503121850GO, "StateTests/RandomTests/st201503121850GO"} -declare_test!{StateTests_RandomTests_st201503121851GO, "StateTests/RandomTests/st201503121851GO"} -declare_test!{StateTests_RandomTests_st201503121953GO, "StateTests/RandomTests/st201503121953GO"} -declare_test!{StateTests_RandomTests_st201503122023GO, "StateTests/RandomTests/st201503122023GO"} -declare_test!{StateTests_RandomTests_st201503122023PYTHON, "StateTests/RandomTests/st201503122023PYTHON"} -declare_test!{StateTests_RandomTests_st201503122027GO, "StateTests/RandomTests/st201503122027GO"} -declare_test!{StateTests_RandomTests_st201503122054GO, "StateTests/RandomTests/st201503122054GO"} -declare_test!{StateTests_RandomTests_st201503122055GO, "StateTests/RandomTests/st201503122055GO"} -declare_test!{StateTests_RandomTests_st201503122115CPPJIT, "StateTests/RandomTests/st201503122115CPPJIT"} -declare_test!{StateTests_RandomTests_st201503122115GO, "StateTests/RandomTests/st201503122115GO"} -declare_test!{StateTests_RandomTests_st201503122123GO, "StateTests/RandomTests/st201503122123GO"} -declare_test!{StateTests_RandomTests_st201503122124GO, "StateTests/RandomTests/st201503122124GO"} -declare_test!{StateTests_RandomTests_st201503122128PYTHON, "StateTests/RandomTests/st201503122128PYTHON"} -declare_test!{StateTests_RandomTests_st201503122140GO, "StateTests/RandomTests/st201503122140GO"} -declare_test!{StateTests_RandomTests_st201503122159GO, "StateTests/RandomTests/st201503122159GO"} -declare_test!{StateTests_RandomTests_st201503122204GO, "StateTests/RandomTests/st201503122204GO"} -declare_test!{StateTests_RandomTests_st201503122212GO, "StateTests/RandomTests/st201503122212GO"} -declare_test!{StateTests_RandomTests_st201503122231GO, "StateTests/RandomTests/st201503122231GO"} -declare_test!{StateTests_RandomTests_st201503122238GO, "StateTests/RandomTests/st201503122238GO"} -declare_test!{StateTests_RandomTests_st201503122252GO, "StateTests/RandomTests/st201503122252GO"} -declare_test!{StateTests_RandomTests_st201503122316GO, "StateTests/RandomTests/st201503122316GO"} -declare_test!{StateTests_RandomTests_st201503122324GO, "StateTests/RandomTests/st201503122324GO"} -declare_test!{StateTests_RandomTests_st201503122358GO, "StateTests/RandomTests/st201503122358GO"} -declare_test!{StateTests_RandomTests_st201503130002GO, "StateTests/RandomTests/st201503130002GO"} -declare_test!{StateTests_RandomTests_st201503130005GO, "StateTests/RandomTests/st201503130005GO"} -declare_test!{StateTests_RandomTests_st201503130007GO, "StateTests/RandomTests/st201503130007GO"} -declare_test!{StateTests_RandomTests_st201503130010GO, "StateTests/RandomTests/st201503130010GO"} -declare_test!{StateTests_RandomTests_st201503130023PYTHON, "StateTests/RandomTests/st201503130023PYTHON"} -declare_test!{StateTests_RandomTests_st201503130059GO, "StateTests/RandomTests/st201503130059GO"} -declare_test!{StateTests_RandomTests_st201503130101GO, "StateTests/RandomTests/st201503130101GO"} -declare_test!{StateTests_RandomTests_st201503130109GO, "StateTests/RandomTests/st201503130109GO"} -declare_test!{StateTests_RandomTests_st201503130117GO, "StateTests/RandomTests/st201503130117GO"} -declare_test!{StateTests_RandomTests_st201503130122GO, "StateTests/RandomTests/st201503130122GO"} -declare_test!{StateTests_RandomTests_st201503130156GO, "StateTests/RandomTests/st201503130156GO"} -declare_test!{StateTests_RandomTests_st201503130156PYTHON, "StateTests/RandomTests/st201503130156PYTHON"} -declare_test!{StateTests_RandomTests_st201503130207GO, "StateTests/RandomTests/st201503130207GO"} -declare_test!{StateTests_RandomTests_st201503130219CPPJIT, "StateTests/RandomTests/st201503130219CPPJIT"} -declare_test!{StateTests_RandomTests_st201503130219GO, "StateTests/RandomTests/st201503130219GO"} -declare_test!{StateTests_RandomTests_st201503130243GO, "StateTests/RandomTests/st201503130243GO"} -declare_test!{StateTests_RandomTests_st201503130246GO, "StateTests/RandomTests/st201503130246GO"} -declare_test!{StateTests_RandomTests_st201503130321GO, "StateTests/RandomTests/st201503130321GO"} -declare_test!{StateTests_RandomTests_st201503130322GO, "StateTests/RandomTests/st201503130322GO"} -declare_test!{StateTests_RandomTests_st201503130332GO, "StateTests/RandomTests/st201503130332GO"} -declare_test!{StateTests_RandomTests_st201503130359GO, "StateTests/RandomTests/st201503130359GO"} -declare_test!{StateTests_RandomTests_st201503130405GO, "StateTests/RandomTests/st201503130405GO"} -declare_test!{StateTests_RandomTests_st201503130408GO, "StateTests/RandomTests/st201503130408GO"} -declare_test!{StateTests_RandomTests_st201503130411GO, "StateTests/RandomTests/st201503130411GO"} -declare_test!{StateTests_RandomTests_st201503130431GO, "StateTests/RandomTests/st201503130431GO"} -declare_test!{StateTests_RandomTests_st201503130437GO, "StateTests/RandomTests/st201503130437GO"} -declare_test!{StateTests_RandomTests_st201503130450GO, "StateTests/RandomTests/st201503130450GO"} -declare_test!{StateTests_RandomTests_st201503130512CPPJIT, "StateTests/RandomTests/st201503130512CPPJIT"} -declare_test!{StateTests_RandomTests_st201503130512GO, "StateTests/RandomTests/st201503130512GO"} -declare_test!{StateTests_RandomTests_st201503130615GO, "StateTests/RandomTests/st201503130615GO"} -declare_test!{StateTests_RandomTests_st201503130705GO, "StateTests/RandomTests/st201503130705GO"} -declare_test!{StateTests_RandomTests_st201503130733CPPJIT, "StateTests/RandomTests/st201503130733CPPJIT"} -declare_test!{StateTests_RandomTests_st201503130733GO, "StateTests/RandomTests/st201503130733GO"} -declare_test!{StateTests_RandomTests_st201503130747GO, "StateTests/RandomTests/st201503130747GO"} -declare_test!{StateTests_RandomTests_st201503130751GO, "StateTests/RandomTests/st201503130751GO"} -declare_test!{StateTests_RandomTests_st201503130752PYTHON, "StateTests/RandomTests/st201503130752PYTHON"} -declare_test!{StateTests_RandomTests_st201503130757PYTHON, "StateTests/RandomTests/st201503130757PYTHON"} -declare_test!{StateTests_RandomTests_st201503131658GO, "StateTests/RandomTests/st201503131658GO"} -declare_test!{StateTests_RandomTests_st201503131739GO, "StateTests/RandomTests/st201503131739GO"} -declare_test!{StateTests_RandomTests_st201503131755CPPJIT, "StateTests/RandomTests/st201503131755CPPJIT"} -declare_test!{StateTests_RandomTests_st201503131755GO, "StateTests/RandomTests/st201503131755GO"} -declare_test!{StateTests_RandomTests_st201503132001CPPJIT, "StateTests/RandomTests/st201503132001CPPJIT"} -declare_test!{StateTests_RandomTests_st201503132127PYTHON, "StateTests/RandomTests/st201503132127PYTHON"} -declare_test!{StateTests_RandomTests_st201503132201CPPJIT, "StateTests/RandomTests/st201503132201CPPJIT"} -declare_test!{StateTests_RandomTests_st201503132201GO, "StateTests/RandomTests/st201503132201GO"} -declare_test!{StateTests_RandomTests_st201503132202PYTHON, "StateTests/RandomTests/st201503132202PYTHON"} -declare_test!{StateTests_RandomTests_st201503140002PYTHON, "StateTests/RandomTests/st201503140002PYTHON"} -declare_test!{StateTests_RandomTests_st201503140240PYTHON, "StateTests/RandomTests/st201503140240PYTHON"} -declare_test!{StateTests_RandomTests_st201503140522PYTHON, "StateTests/RandomTests/st201503140522PYTHON"} -declare_test!{StateTests_RandomTests_st201503140756PYTHON, "StateTests/RandomTests/st201503140756PYTHON"} -declare_test!{StateTests_RandomTests_st201503141144PYTHON, "StateTests/RandomTests/st201503141144PYTHON"} -declare_test!{StateTests_RandomTests_st201503141510PYTHON, "StateTests/RandomTests/st201503141510PYTHON"} -declare_test!{StateTests_RandomTests_st201503150427PYTHON, "StateTests/RandomTests/st201503150427PYTHON"} -declare_test!{StateTests_RandomTests_st201503150716PYTHON, "StateTests/RandomTests/st201503150716PYTHON"} -declare_test!{StateTests_RandomTests_st201503151450PYTHON, "StateTests/RandomTests/st201503151450PYTHON"} -declare_test!{StateTests_RandomTests_st201503151516PYTHON, "StateTests/RandomTests/st201503151516PYTHON"} -declare_test!{StateTests_RandomTests_st201503151753PYTHON, "StateTests/RandomTests/st201503151753PYTHON"} -declare_test!{StateTests_RandomTests_st201503152057PYTHON, "StateTests/RandomTests/st201503152057PYTHON"} -declare_test!{StateTests_RandomTests_st201503152241PYTHON, "StateTests/RandomTests/st201503152241PYTHON"} -declare_test!{StateTests_RandomTests_st201503160014PYTHON, "StateTests/RandomTests/st201503160014PYTHON"} -declare_test!{StateTests_RandomTests_st201503160733PYTHON, "StateTests/RandomTests/st201503160733PYTHON"} -declare_test!{StateTests_RandomTests_st201503170051PYTHON, "StateTests/RandomTests/st201503170051PYTHON"} -declare_test!{StateTests_RandomTests_st201503170433PYTHON, "StateTests/RandomTests/st201503170433PYTHON"} -declare_test!{StateTests_RandomTests_st201503170523PYTHON, "StateTests/RandomTests/st201503170523PYTHON"} -declare_test!{StateTests_RandomTests_st201503171108PYTHON, "StateTests/RandomTests/st201503171108PYTHON"} -declare_test!{StateTests_RandomTests_st201503181223GO, "StateTests/RandomTests/st201503181223GO"} -declare_test!{StateTests_RandomTests_st201503181225GO, "StateTests/RandomTests/st201503181225GO"} -declare_test!{StateTests_RandomTests_st201503181226CPPJIT, "StateTests/RandomTests/st201503181226CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181227CPPJIT, "StateTests/RandomTests/st201503181227CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181227GO, "StateTests/RandomTests/st201503181227GO"} -declare_test!{StateTests_RandomTests_st201503181229GO, "StateTests/RandomTests/st201503181229GO"} -declare_test!{StateTests_RandomTests_st201503181230CPPJIT, "StateTests/RandomTests/st201503181230CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181230GO, "StateTests/RandomTests/st201503181230GO"} -declare_test!{StateTests_RandomTests_st201503181231GO, "StateTests/RandomTests/st201503181231GO"} -declare_test!{StateTests_RandomTests_st201503181232CPPJIT, "StateTests/RandomTests/st201503181232CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181232GO, "StateTests/RandomTests/st201503181232GO"} -declare_test!{StateTests_RandomTests_st201503181233GO, "StateTests/RandomTests/st201503181233GO"} -declare_test!{StateTests_RandomTests_st201503181234CPPJIT, "StateTests/RandomTests/st201503181234CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181234GO, "StateTests/RandomTests/st201503181234GO"} -declare_test!{StateTests_RandomTests_st201503181235CPPJIT, "StateTests/RandomTests/st201503181235CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181235GO, "StateTests/RandomTests/st201503181235GO"} -declare_test!{StateTests_RandomTests_st201503181236GO, "StateTests/RandomTests/st201503181236GO"} -declare_test!{StateTests_RandomTests_st201503181237GO, "StateTests/RandomTests/st201503181237GO"} -declare_test!{StateTests_RandomTests_st201503181239GO, "StateTests/RandomTests/st201503181239GO"} -declare_test!{StateTests_RandomTests_st201503181241CPPJIT, "StateTests/RandomTests/st201503181241CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181241GO, "StateTests/RandomTests/st201503181241GO"} -declare_test!{StateTests_RandomTests_st201503181243GO, "StateTests/RandomTests/st201503181243GO"} -declare_test!{StateTests_RandomTests_st201503181244GO, "StateTests/RandomTests/st201503181244GO"} -declare_test!{StateTests_RandomTests_st201503181245CPPJIT, "StateTests/RandomTests/st201503181245CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181245GO, "StateTests/RandomTests/st201503181245GO"} -declare_test!{StateTests_RandomTests_st201503181246CPPJIT, "StateTests/RandomTests/st201503181246CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181246GO, "StateTests/RandomTests/st201503181246GO"} -declare_test!{StateTests_RandomTests_st201503181247GO, "StateTests/RandomTests/st201503181247GO"} -declare_test!{StateTests_RandomTests_st201503181248GO, "StateTests/RandomTests/st201503181248GO"} -declare_test!{StateTests_RandomTests_st201503181249GO, "StateTests/RandomTests/st201503181249GO"} -declare_test!{StateTests_RandomTests_st201503181250CPPJIT, "StateTests/RandomTests/st201503181250CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181250GO, "StateTests/RandomTests/st201503181250GO"} -declare_test!{StateTests_RandomTests_st201503181251GO, "StateTests/RandomTests/st201503181251GO"} -declare_test!{StateTests_RandomTests_st201503181252CPPJIT, "StateTests/RandomTests/st201503181252CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181253GO, "StateTests/RandomTests/st201503181253GO"} -declare_test!{StateTests_RandomTests_st201503181255CPPJIT, "StateTests/RandomTests/st201503181255CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181255GO, "StateTests/RandomTests/st201503181255GO"} -declare_test!{StateTests_RandomTests_st201503181257GO, "StateTests/RandomTests/st201503181257GO"} -declare_test!{StateTests_RandomTests_st201503181258CPPJIT, "StateTests/RandomTests/st201503181258CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181258GO, "StateTests/RandomTests/st201503181258GO"} -declare_test!{StateTests_RandomTests_st201503181301CPPJIT, "StateTests/RandomTests/st201503181301CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181301GO, "StateTests/RandomTests/st201503181301GO"} -declare_test!{StateTests_RandomTests_st201503181303GO, "StateTests/RandomTests/st201503181303GO"} -declare_test!{StateTests_RandomTests_st201503181304GO, "StateTests/RandomTests/st201503181304GO"} -declare_test!{StateTests_RandomTests_st201503181305GO, "StateTests/RandomTests/st201503181305GO"} -declare_test!{StateTests_RandomTests_st201503181306GO, "StateTests/RandomTests/st201503181306GO"} -declare_test!{StateTests_RandomTests_st201503181307CPPJIT, "StateTests/RandomTests/st201503181307CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181307GO, "StateTests/RandomTests/st201503181307GO"} -declare_test!{StateTests_RandomTests_st201503181308GO, "StateTests/RandomTests/st201503181308GO"} -declare_test!{StateTests_RandomTests_st201503181309GO, "StateTests/RandomTests/st201503181309GO"} -declare_test!{StateTests_RandomTests_st201503181310GO, "StateTests/RandomTests/st201503181310GO"} -declare_test!{StateTests_RandomTests_st201503181311GO, "StateTests/RandomTests/st201503181311GO"} -declare_test!{StateTests_RandomTests_st201503181313GO, "StateTests/RandomTests/st201503181313GO"} -declare_test!{StateTests_RandomTests_st201503181314GO, "StateTests/RandomTests/st201503181314GO"} -declare_test!{StateTests_RandomTests_st201503181315CPPJIT, "StateTests/RandomTests/st201503181315CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181315GO, "StateTests/RandomTests/st201503181315GO"} -declare_test!{StateTests_RandomTests_st201503181316CPPJIT, "StateTests/RandomTests/st201503181316CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181316PYTHON, "StateTests/RandomTests/st201503181316PYTHON"} -declare_test!{StateTests_RandomTests_st201503181317GO, "StateTests/RandomTests/st201503181317GO"} -declare_test!{StateTests_RandomTests_st201503181318CPPJIT, "StateTests/RandomTests/st201503181318CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181318GO, "StateTests/RandomTests/st201503181318GO"} -declare_test!{StateTests_RandomTests_st201503181319GO, "StateTests/RandomTests/st201503181319GO"} -declare_test!{StateTests_RandomTests_st201503181319PYTHON, "StateTests/RandomTests/st201503181319PYTHON"} -declare_test!{StateTests_RandomTests_st201503181322GO, "StateTests/RandomTests/st201503181322GO"} -declare_test!{StateTests_RandomTests_st201503181323CPPJIT, "StateTests/RandomTests/st201503181323CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181323GO, "StateTests/RandomTests/st201503181323GO"} -declare_test!{StateTests_RandomTests_st201503181324GO, "StateTests/RandomTests/st201503181324GO"} -declare_test!{StateTests_RandomTests_st201503181325GO, "StateTests/RandomTests/st201503181325GO"} -declare_test!{StateTests_RandomTests_st201503181326CPPJIT, "StateTests/RandomTests/st201503181326CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181326GO, "StateTests/RandomTests/st201503181326GO"} -declare_test!{StateTests_RandomTests_st201503181327GO, "StateTests/RandomTests/st201503181327GO"} -declare_test!{StateTests_RandomTests_st201503181329CPPJIT, "StateTests/RandomTests/st201503181329CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181329GO, "StateTests/RandomTests/st201503181329GO"} -declare_test!{StateTests_RandomTests_st201503181330GO, "StateTests/RandomTests/st201503181330GO"} -declare_test!{StateTests_RandomTests_st201503181332GO, "StateTests/RandomTests/st201503181332GO"} -declare_test!{StateTests_RandomTests_st201503181333GO, "StateTests/RandomTests/st201503181333GO"} -declare_test!{StateTests_RandomTests_st201503181334GO, "StateTests/RandomTests/st201503181334GO"} -declare_test!{StateTests_RandomTests_st201503181336CPPJIT, "StateTests/RandomTests/st201503181336CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181337GO, "StateTests/RandomTests/st201503181337GO"} -declare_test!{StateTests_RandomTests_st201503181338GO, "StateTests/RandomTests/st201503181338GO"} -declare_test!{StateTests_RandomTests_st201503181339CPPJIT, "StateTests/RandomTests/st201503181339CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181339GO, "StateTests/RandomTests/st201503181339GO"} -declare_test!{StateTests_RandomTests_st201503181340GO, "StateTests/RandomTests/st201503181340GO"} -declare_test!{StateTests_RandomTests_st201503181341CPPJIT, "StateTests/RandomTests/st201503181341CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181342CPPJIT, "StateTests/RandomTests/st201503181342CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181342GO, "StateTests/RandomTests/st201503181342GO"} -declare_test!{StateTests_RandomTests_st201503181345GO, "StateTests/RandomTests/st201503181345GO"} -declare_test!{StateTests_RandomTests_st201503181346GO, "StateTests/RandomTests/st201503181346GO"} -declare_test!{StateTests_RandomTests_st201503181347CPPJIT, "StateTests/RandomTests/st201503181347CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181347GO, "StateTests/RandomTests/st201503181347GO"} -declare_test!{StateTests_RandomTests_st201503181347PYTHON, "StateTests/RandomTests/st201503181347PYTHON"} -declare_test!{StateTests_RandomTests_st201503181350CPPJIT, "StateTests/RandomTests/st201503181350CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181352GO, "StateTests/RandomTests/st201503181352GO"} -declare_test!{StateTests_RandomTests_st201503181353GO, "StateTests/RandomTests/st201503181353GO"} -declare_test!{StateTests_RandomTests_st201503181354CPPJIT, "StateTests/RandomTests/st201503181354CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181354GO, "StateTests/RandomTests/st201503181354GO"} -declare_test!{StateTests_RandomTests_st201503181355GO, "StateTests/RandomTests/st201503181355GO"} -declare_test!{StateTests_RandomTests_st201503181356CPPJIT, "StateTests/RandomTests/st201503181356CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181357CPPJIT, "StateTests/RandomTests/st201503181357CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181358CPPJIT, "StateTests/RandomTests/st201503181358CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181358GO, "StateTests/RandomTests/st201503181358GO"} -declare_test!{StateTests_RandomTests_st201503181359GO, "StateTests/RandomTests/st201503181359GO"} -declare_test!{StateTests_RandomTests_st201503181402CPPJIT, "StateTests/RandomTests/st201503181402CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181403GO, "StateTests/RandomTests/st201503181403GO"} -declare_test!{StateTests_RandomTests_st201503181406CPPJIT, "StateTests/RandomTests/st201503181406CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181406GO, "StateTests/RandomTests/st201503181406GO"} -declare_test!{StateTests_RandomTests_st201503181410GO, "StateTests/RandomTests/st201503181410GO"} -declare_test!{StateTests_RandomTests_st201503181412CPPJIT, "StateTests/RandomTests/st201503181412CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181413GO, "StateTests/RandomTests/st201503181413GO"} -declare_test!{StateTests_RandomTests_st201503181415GO, "StateTests/RandomTests/st201503181415GO"} -declare_test!{StateTests_RandomTests_st201503181416GO, "StateTests/RandomTests/st201503181416GO"} -declare_test!{StateTests_RandomTests_st201503181417CPPJIT, "StateTests/RandomTests/st201503181417CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181417GO, "StateTests/RandomTests/st201503181417GO"} -declare_test!{StateTests_RandomTests_st201503181418CPPJIT, "StateTests/RandomTests/st201503181418CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181422GO, "StateTests/RandomTests/st201503181422GO"} -declare_test!{StateTests_RandomTests_st201503181423CPPJIT, "StateTests/RandomTests/st201503181423CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181424GO, "StateTests/RandomTests/st201503181424GO"} -declare_test!{StateTests_RandomTests_st201503181426CPPJIT, "StateTests/RandomTests/st201503181426CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181426GO, "StateTests/RandomTests/st201503181426GO"} -declare_test!{StateTests_RandomTests_st201503181428GO, "StateTests/RandomTests/st201503181428GO"} -declare_test!{StateTests_RandomTests_st201503181430CPPJIT, "StateTests/RandomTests/st201503181430CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181435GO, "StateTests/RandomTests/st201503181435GO"} -declare_test!{StateTests_RandomTests_st201503181436GO, "StateTests/RandomTests/st201503181436GO"} -declare_test!{StateTests_RandomTests_st201503181437CPPJIT, "StateTests/RandomTests/st201503181437CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181437GO, "StateTests/RandomTests/st201503181437GO"} -declare_test!{StateTests_RandomTests_st201503181438CPPJIT, "StateTests/RandomTests/st201503181438CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181438GO, "StateTests/RandomTests/st201503181438GO"} -declare_test!{StateTests_RandomTests_st201503181439CPPJIT, "StateTests/RandomTests/st201503181439CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181439GO, "StateTests/RandomTests/st201503181439GO"} -declare_test!{StateTests_RandomTests_st201503181439PYTHON, "StateTests/RandomTests/st201503181439PYTHON"} -declare_test!{StateTests_RandomTests_st201503181440GO, "StateTests/RandomTests/st201503181440GO"} -declare_test!{StateTests_RandomTests_st201503181441GO, "StateTests/RandomTests/st201503181441GO"} -declare_test!{StateTests_RandomTests_st201503181442GO, "StateTests/RandomTests/st201503181442GO"} -declare_test!{StateTests_RandomTests_st201503181445CPPJIT, "StateTests/RandomTests/st201503181445CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181446GO, "StateTests/RandomTests/st201503181446GO"} -declare_test!{StateTests_RandomTests_st201503181447GO, "StateTests/RandomTests/st201503181447GO"} -declare_test!{StateTests_RandomTests_st201503181450GO, "StateTests/RandomTests/st201503181450GO"} -declare_test!{StateTests_RandomTests_st201503181451CPPJIT, "StateTests/RandomTests/st201503181451CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181453GO, "StateTests/RandomTests/st201503181453GO"} -declare_test!{StateTests_RandomTests_st201503181455GO, "StateTests/RandomTests/st201503181455GO"} -declare_test!{StateTests_RandomTests_st201503181456CPPJIT, "StateTests/RandomTests/st201503181456CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181457GO, "StateTests/RandomTests/st201503181457GO"} -declare_test!{StateTests_RandomTests_st201503181458GO, "StateTests/RandomTests/st201503181458GO"} -declare_test!{StateTests_RandomTests_st201503181459GO, "StateTests/RandomTests/st201503181459GO"} -declare_test!{StateTests_RandomTests_st201503181500GO, "StateTests/RandomTests/st201503181500GO"} -declare_test!{StateTests_RandomTests_st201503181501GO, "StateTests/RandomTests/st201503181501GO"} -declare_test!{StateTests_RandomTests_st201503181503GO, "StateTests/RandomTests/st201503181503GO"} -declare_test!{StateTests_RandomTests_st201503181504GO, "StateTests/RandomTests/st201503181504GO"} -declare_test!{StateTests_RandomTests_st201503181505GO, "StateTests/RandomTests/st201503181505GO"} -declare_test!{StateTests_RandomTests_st201503181506CPPJIT, "StateTests/RandomTests/st201503181506CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181507GO, "StateTests/RandomTests/st201503181507GO"} -declare_test!{StateTests_RandomTests_st201503181509CPPJIT, "StateTests/RandomTests/st201503181509CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181509GO, "StateTests/RandomTests/st201503181509GO"} -declare_test!{StateTests_RandomTests_st201503181510GO, "StateTests/RandomTests/st201503181510GO"} -declare_test!{StateTests_RandomTests_st201503181511GO, "StateTests/RandomTests/st201503181511GO"} -declare_test!{StateTests_RandomTests_st201503181512GO, "StateTests/RandomTests/st201503181512GO"} -declare_test!{StateTests_RandomTests_st201503181513CPPJIT, "StateTests/RandomTests/st201503181513CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181513GO, "StateTests/RandomTests/st201503181513GO"} -declare_test!{StateTests_RandomTests_st201503181514CPPJIT, "StateTests/RandomTests/st201503181514CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181514GO, "StateTests/RandomTests/st201503181514GO"} -declare_test!{StateTests_RandomTests_st201503181517CPPJIT, "StateTests/RandomTests/st201503181517CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181517GO, "StateTests/RandomTests/st201503181517GO"} -declare_test!{StateTests_RandomTests_st201503181519CPPJIT, "StateTests/RandomTests/st201503181519CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181519GO, "StateTests/RandomTests/st201503181519GO"} -declare_test!{StateTests_RandomTests_st201503181520CPPJIT, "StateTests/RandomTests/st201503181520CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181520GO, "StateTests/RandomTests/st201503181520GO"} -declare_test!{StateTests_RandomTests_st201503181521GO, "StateTests/RandomTests/st201503181521GO"} -declare_test!{StateTests_RandomTests_st201503181522GO, "StateTests/RandomTests/st201503181522GO"} -declare_test!{StateTests_RandomTests_st201503181524CPPJIT, "StateTests/RandomTests/st201503181524CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181524GO, "StateTests/RandomTests/st201503181524GO"} -declare_test!{StateTests_RandomTests_st201503181526GO, "StateTests/RandomTests/st201503181526GO"} -declare_test!{StateTests_RandomTests_st201503181527GO, "StateTests/RandomTests/st201503181527GO"} -declare_test!{StateTests_RandomTests_st201503181528CPPJIT, "StateTests/RandomTests/st201503181528CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181528GO, "StateTests/RandomTests/st201503181528GO"} -declare_test!{StateTests_RandomTests_st201503181528PYTHON, "StateTests/RandomTests/st201503181528PYTHON"} -declare_test!{StateTests_RandomTests_st201503181529GO, "StateTests/RandomTests/st201503181529GO"} -declare_test!{StateTests_RandomTests_st201503181531CPPJIT, "StateTests/RandomTests/st201503181531CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181533GO, "StateTests/RandomTests/st201503181533GO"} -declare_test!{StateTests_RandomTests_st201503181534CPPJIT, "StateTests/RandomTests/st201503181534CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181534GO, "StateTests/RandomTests/st201503181534GO"} -declare_test!{StateTests_RandomTests_st201503181536CPPJIT, "StateTests/RandomTests/st201503181536CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181536GO, "StateTests/RandomTests/st201503181536GO"} -declare_test!{StateTests_RandomTests_st201503181537GO, "StateTests/RandomTests/st201503181537GO"} -declare_test!{StateTests_RandomTests_st201503181538GO, "StateTests/RandomTests/st201503181538GO"} -declare_test!{StateTests_RandomTests_st201503181539GO, "StateTests/RandomTests/st201503181539GO"} -declare_test!{StateTests_RandomTests_st201503181540CPPJIT, "StateTests/RandomTests/st201503181540CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181540PYTHON, "StateTests/RandomTests/st201503181540PYTHON"} -declare_test!{StateTests_RandomTests_st201503181543GO, "StateTests/RandomTests/st201503181543GO"} -declare_test!{StateTests_RandomTests_st201503181544CPPJIT, "StateTests/RandomTests/st201503181544CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181544GO, "StateTests/RandomTests/st201503181544GO"} -declare_test!{StateTests_RandomTests_st201503181547GO, "StateTests/RandomTests/st201503181547GO"} -declare_test!{StateTests_RandomTests_st201503181548CPPJIT, "StateTests/RandomTests/st201503181548CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181548GO, "StateTests/RandomTests/st201503181548GO"} -declare_test!{StateTests_RandomTests_st201503181551GO, "StateTests/RandomTests/st201503181551GO"} -declare_test!{StateTests_RandomTests_st201503181552CPPJIT, "StateTests/RandomTests/st201503181552CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181553GO, "StateTests/RandomTests/st201503181553GO"} -declare_test!{StateTests_RandomTests_st201503181555CPPJIT, "StateTests/RandomTests/st201503181555CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181555GO, "StateTests/RandomTests/st201503181555GO"} -declare_test!{StateTests_RandomTests_st201503181557GO, "StateTests/RandomTests/st201503181557GO"} -declare_test!{StateTests_RandomTests_st201503181559GO, "StateTests/RandomTests/st201503181559GO"} -declare_test!{StateTests_RandomTests_st201503181601CPPJIT, "StateTests/RandomTests/st201503181601CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181601GO, "StateTests/RandomTests/st201503181601GO"} -declare_test!{StateTests_RandomTests_st201503181602GO, "StateTests/RandomTests/st201503181602GO"} -declare_test!{StateTests_RandomTests_st201503181603GO, "StateTests/RandomTests/st201503181603GO"} -declare_test!{StateTests_RandomTests_st201503181604GO, "StateTests/RandomTests/st201503181604GO"} -declare_test!{StateTests_RandomTests_st201503181605GO, "StateTests/RandomTests/st201503181605GO"} -declare_test!{StateTests_RandomTests_st201503181606GO, "StateTests/RandomTests/st201503181606GO"} -declare_test!{StateTests_RandomTests_st201503181607GO, "StateTests/RandomTests/st201503181607GO"} -declare_test!{StateTests_RandomTests_st201503181608CPPJIT, "StateTests/RandomTests/st201503181608CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181608GO, "StateTests/RandomTests/st201503181608GO"} -declare_test!{StateTests_RandomTests_st201503181609GO, "StateTests/RandomTests/st201503181609GO"} -declare_test!{StateTests_RandomTests_st201503181610CPPJIT, "StateTests/RandomTests/st201503181610CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181610GO, "StateTests/RandomTests/st201503181610GO"} -declare_test!{StateTests_RandomTests_st201503181611CPPJIT, "StateTests/RandomTests/st201503181611CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181611GO, "StateTests/RandomTests/st201503181611GO"} -declare_test!{StateTests_RandomTests_st201503181612GO, "StateTests/RandomTests/st201503181612GO"} -declare_test!{StateTests_RandomTests_st201503181614CPPJIT, "StateTests/RandomTests/st201503181614CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181614GO, "StateTests/RandomTests/st201503181614GO"} -declare_test!{StateTests_RandomTests_st201503181616CPPJIT, "StateTests/RandomTests/st201503181616CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181616GO, "StateTests/RandomTests/st201503181616GO"} -declare_test!{StateTests_RandomTests_st201503181617GO, "StateTests/RandomTests/st201503181617GO"} -declare_test!{StateTests_RandomTests_st201503181618GO, "StateTests/RandomTests/st201503181618GO"} -declare_test!{StateTests_RandomTests_st201503181619GO, "StateTests/RandomTests/st201503181619GO"} -declare_test!{StateTests_RandomTests_st201503181620CPPJIT, "StateTests/RandomTests/st201503181620CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181620GO, "StateTests/RandomTests/st201503181620GO"} -declare_test!{StateTests_RandomTests_st201503181621GO, "StateTests/RandomTests/st201503181621GO"} -declare_test!{StateTests_RandomTests_st201503181625GO, "StateTests/RandomTests/st201503181625GO"} -declare_test!{StateTests_RandomTests_st201503181626CPPJIT, "StateTests/RandomTests/st201503181626CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181626GO, "StateTests/RandomTests/st201503181626GO"} -declare_test!{StateTests_RandomTests_st201503181627GO, "StateTests/RandomTests/st201503181627GO"} -declare_test!{StateTests_RandomTests_st201503181628GO, "StateTests/RandomTests/st201503181628GO"} -declare_test!{StateTests_RandomTests_st201503181629GO, "StateTests/RandomTests/st201503181629GO"} -declare_test!{StateTests_RandomTests_st201503181630CPPJIT, "StateTests/RandomTests/st201503181630CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181630GO, "StateTests/RandomTests/st201503181630GO"} -declare_test!{StateTests_RandomTests_st201503181630PYTHON, "StateTests/RandomTests/st201503181630PYTHON"} -declare_test!{StateTests_RandomTests_st201503181632GO, "StateTests/RandomTests/st201503181632GO"} -declare_test!{StateTests_RandomTests_st201503181634CPPJIT, "StateTests/RandomTests/st201503181634CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181635GO, "StateTests/RandomTests/st201503181635GO"} -declare_test!{StateTests_RandomTests_st201503181636GO, "StateTests/RandomTests/st201503181636GO"} -declare_test!{StateTests_RandomTests_st201503181638GO, "StateTests/RandomTests/st201503181638GO"} -declare_test!{StateTests_RandomTests_st201503181639CPPJIT, "StateTests/RandomTests/st201503181639CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181641GO, "StateTests/RandomTests/st201503181641GO"} -declare_test!{StateTests_RandomTests_st201503181645GO, "StateTests/RandomTests/st201503181645GO"} -declare_test!{StateTests_RandomTests_st201503181646GO, "StateTests/RandomTests/st201503181646GO"} -declare_test!{StateTests_RandomTests_st201503181647CPPJIT, "StateTests/RandomTests/st201503181647CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181649CPPJIT, "StateTests/RandomTests/st201503181649CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181650GO, "StateTests/RandomTests/st201503181650GO"} -declare_test!{StateTests_RandomTests_st201503181652CPPJIT, "StateTests/RandomTests/st201503181652CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181653GO, "StateTests/RandomTests/st201503181653GO"} -declare_test!{StateTests_RandomTests_st201503181654GO, "StateTests/RandomTests/st201503181654GO"} -declare_test!{StateTests_RandomTests_st201503181655CPPJIT, "StateTests/RandomTests/st201503181655CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181655GO, "StateTests/RandomTests/st201503181655GO"} -declare_test!{StateTests_RandomTests_st201503181656CPPJIT, "StateTests/RandomTests/st201503181656CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181656GO, "StateTests/RandomTests/st201503181656GO"} -declare_test!{StateTests_RandomTests_st201503181657GO, "StateTests/RandomTests/st201503181657GO"} -declare_test!{StateTests_RandomTests_st201503181658GO, "StateTests/RandomTests/st201503181658GO"} -declare_test!{StateTests_RandomTests_st201503181700GO, "StateTests/RandomTests/st201503181700GO"} -declare_test!{StateTests_RandomTests_st201503181702GO, "StateTests/RandomTests/st201503181702GO"} -declare_test!{StateTests_RandomTests_st201503181703CPPJIT, "StateTests/RandomTests/st201503181703CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181703GO, "StateTests/RandomTests/st201503181703GO"} -declare_test!{StateTests_RandomTests_st201503181704GO, "StateTests/RandomTests/st201503181704GO"} -declare_test!{StateTests_RandomTests_st201503181706GO, "StateTests/RandomTests/st201503181706GO"} -declare_test!{StateTests_RandomTests_st201503181709GO, "StateTests/RandomTests/st201503181709GO"} -declare_test!{StateTests_RandomTests_st201503181711CPPJIT, "StateTests/RandomTests/st201503181711CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181711GO, "StateTests/RandomTests/st201503181711GO"} -declare_test!{StateTests_RandomTests_st201503181713CPPJIT, "StateTests/RandomTests/st201503181713CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181713GO, "StateTests/RandomTests/st201503181713GO"} -declare_test!{StateTests_RandomTests_st201503181714GO, "StateTests/RandomTests/st201503181714GO"} -declare_test!{StateTests_RandomTests_st201503181715CPPJIT, "StateTests/RandomTests/st201503181715CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181715GO, "StateTests/RandomTests/st201503181715GO"} -declare_test!{StateTests_RandomTests_st201503181716GO, "StateTests/RandomTests/st201503181716GO"} -declare_test!{StateTests_RandomTests_st201503181717GO, "StateTests/RandomTests/st201503181717GO"} -declare_test!{StateTests_RandomTests_st201503181720CPPJIT, "StateTests/RandomTests/st201503181720CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181722GO, "StateTests/RandomTests/st201503181722GO"} -declare_test!{StateTests_RandomTests_st201503181723CPPJIT, "StateTests/RandomTests/st201503181723CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181723GO, "StateTests/RandomTests/st201503181723GO"} -declare_test!{StateTests_RandomTests_st201503181724CPPJIT, "StateTests/RandomTests/st201503181724CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181724GO, "StateTests/RandomTests/st201503181724GO"} -declare_test!{StateTests_RandomTests_st201503181725GO, "StateTests/RandomTests/st201503181725GO"} -declare_test!{StateTests_RandomTests_st201503181728GO, "StateTests/RandomTests/st201503181728GO"} -declare_test!{StateTests_RandomTests_st201503181729GO, "StateTests/RandomTests/st201503181729GO"} -declare_test!{StateTests_RandomTests_st201503181730GO, "StateTests/RandomTests/st201503181730GO"} -declare_test!{StateTests_RandomTests_st201503181731CPPJIT, "StateTests/RandomTests/st201503181731CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181732GO, "StateTests/RandomTests/st201503181732GO"} -declare_test!{StateTests_RandomTests_st201503181734CPPJIT, "StateTests/RandomTests/st201503181734CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181734GO, "StateTests/RandomTests/st201503181734GO"} -declare_test!{StateTests_RandomTests_st201503181735GO, "StateTests/RandomTests/st201503181735GO"} -declare_test!{StateTests_RandomTests_st201503181737CPPJIT, "StateTests/RandomTests/st201503181737CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181737GO, "StateTests/RandomTests/st201503181737GO"} -declare_test!{StateTests_RandomTests_st201503181738CPPJIT, "StateTests/RandomTests/st201503181738CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181738GO, "StateTests/RandomTests/st201503181738GO"} -declare_test!{StateTests_RandomTests_st201503181739GO, "StateTests/RandomTests/st201503181739GO"} -declare_test!{StateTests_RandomTests_st201503181740CPPJIT, "StateTests/RandomTests/st201503181740CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181740GO, "StateTests/RandomTests/st201503181740GO"} -declare_test!{StateTests_RandomTests_st201503181742CPPJIT, "StateTests/RandomTests/st201503181742CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181743GO, "StateTests/RandomTests/st201503181743GO"} -declare_test!{StateTests_RandomTests_st201503181744GO, "StateTests/RandomTests/st201503181744GO"} -declare_test!{StateTests_RandomTests_st201503181745CPPJIT, "StateTests/RandomTests/st201503181745CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181746GO, "StateTests/RandomTests/st201503181746GO"} -declare_test!{StateTests_RandomTests_st201503181747GO, "StateTests/RandomTests/st201503181747GO"} -declare_test!{StateTests_RandomTests_st201503181748GO, "StateTests/RandomTests/st201503181748GO"} -declare_test!{StateTests_RandomTests_st201503181749GO, "StateTests/RandomTests/st201503181749GO"} -declare_test!{StateTests_RandomTests_st201503181750CPPJIT, "StateTests/RandomTests/st201503181750CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181750GO, "StateTests/RandomTests/st201503181750GO"} -declare_test!{StateTests_RandomTests_st201503181752GO, "StateTests/RandomTests/st201503181752GO"} -declare_test!{StateTests_RandomTests_st201503181753CPPJIT, "StateTests/RandomTests/st201503181753CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181754CPPJIT, "StateTests/RandomTests/st201503181754CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181754GO, "StateTests/RandomTests/st201503181754GO"} -declare_test!{StateTests_RandomTests_st201503181755CPPJIT, "StateTests/RandomTests/st201503181755CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181755GO, "StateTests/RandomTests/st201503181755GO"} -declare_test!{StateTests_RandomTests_st201503181756GO, "StateTests/RandomTests/st201503181756GO"} -declare_test!{StateTests_RandomTests_st201503181757CPPJIT, "StateTests/RandomTests/st201503181757CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181757GO, "StateTests/RandomTests/st201503181757GO"} -declare_test!{StateTests_RandomTests_st201503181759GO, "StateTests/RandomTests/st201503181759GO"} -declare_test!{StateTests_RandomTests_st201503181800GO, "StateTests/RandomTests/st201503181800GO"} -declare_test!{StateTests_RandomTests_st201503181801GO, "StateTests/RandomTests/st201503181801GO"} -declare_test!{StateTests_RandomTests_st201503181802GO, "StateTests/RandomTests/st201503181802GO"} -declare_test!{StateTests_RandomTests_st201503181803CPPJIT, "StateTests/RandomTests/st201503181803CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181803GO, "StateTests/RandomTests/st201503181803GO"} -declare_test!{StateTests_RandomTests_st201503181804GO, "StateTests/RandomTests/st201503181804GO"} -declare_test!{StateTests_RandomTests_st201503181806GO, "StateTests/RandomTests/st201503181806GO"} -declare_test!{StateTests_RandomTests_st201503181808GO, "StateTests/RandomTests/st201503181808GO"} -declare_test!{StateTests_RandomTests_st201503181809CPPJIT, "StateTests/RandomTests/st201503181809CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181812CPPJIT, "StateTests/RandomTests/st201503181812CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181812GO, "StateTests/RandomTests/st201503181812GO"} -declare_test!{StateTests_RandomTests_st201503181814CPPJIT, "StateTests/RandomTests/st201503181814CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181815GO, "StateTests/RandomTests/st201503181815GO"} -declare_test!{StateTests_RandomTests_st201503181816CPPJIT, "StateTests/RandomTests/st201503181816CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181817CPPJIT, "StateTests/RandomTests/st201503181817CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181819GO, "StateTests/RandomTests/st201503181819GO"} -declare_test!{StateTests_RandomTests_st201503181821GO, "StateTests/RandomTests/st201503181821GO"} -declare_test!{StateTests_RandomTests_st201503181822GO, "StateTests/RandomTests/st201503181822GO"} -declare_test!{StateTests_RandomTests_st201503181823GO, "StateTests/RandomTests/st201503181823GO"} -declare_test!{StateTests_RandomTests_st201503181824GO, "StateTests/RandomTests/st201503181824GO"} -declare_test!{StateTests_RandomTests_st201503181825GO, "StateTests/RandomTests/st201503181825GO"} -declare_test!{StateTests_RandomTests_st201503181829GO, "StateTests/RandomTests/st201503181829GO"} -declare_test!{StateTests_RandomTests_st201503181830CPPJIT, "StateTests/RandomTests/st201503181830CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181833GO, "StateTests/RandomTests/st201503181833GO"} -declare_test!{StateTests_RandomTests_st201503181834CPPJIT, "StateTests/RandomTests/st201503181834CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181834GO, "StateTests/RandomTests/st201503181834GO"} -declare_test!{StateTests_RandomTests_st201503181837GO, "StateTests/RandomTests/st201503181837GO"} -declare_test!{StateTests_RandomTests_st201503181840GO, "StateTests/RandomTests/st201503181840GO"} -declare_test!{StateTests_RandomTests_st201503181842GO, "StateTests/RandomTests/st201503181842GO"} -declare_test!{StateTests_RandomTests_st201503181843GO, "StateTests/RandomTests/st201503181843GO"} -declare_test!{StateTests_RandomTests_st201503181844GO, "StateTests/RandomTests/st201503181844GO"} -declare_test!{StateTests_RandomTests_st201503181845GO, "StateTests/RandomTests/st201503181845GO"} -declare_test!{StateTests_RandomTests_st201503181846GO, "StateTests/RandomTests/st201503181846GO"} -declare_test!{StateTests_RandomTests_st201503181847GO, "StateTests/RandomTests/st201503181847GO"} -declare_test!{StateTests_RandomTests_st201503181848GO, "StateTests/RandomTests/st201503181848GO"} -declare_test!{StateTests_RandomTests_st201503181849GO, "StateTests/RandomTests/st201503181849GO"} -declare_test!{StateTests_RandomTests_st201503181850GO, "StateTests/RandomTests/st201503181850GO"} -declare_test!{StateTests_RandomTests_st201503181851CPPJIT, "StateTests/RandomTests/st201503181851CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181851GO, "StateTests/RandomTests/st201503181851GO"} -declare_test!{StateTests_RandomTests_st201503181852CPPJIT, "StateTests/RandomTests/st201503181852CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181854GO, "StateTests/RandomTests/st201503181854GO"} -declare_test!{StateTests_RandomTests_st201503181855CPPJIT, "StateTests/RandomTests/st201503181855CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181857PYTHON, "StateTests/RandomTests/st201503181857PYTHON"} -declare_test!{StateTests_RandomTests_st201503181859GO, "StateTests/RandomTests/st201503181859GO"} -declare_test!{StateTests_RandomTests_st201503181900GO, "StateTests/RandomTests/st201503181900GO"} -declare_test!{StateTests_RandomTests_st201503181903GO, "StateTests/RandomTests/st201503181903GO"} -declare_test!{StateTests_RandomTests_st201503181904GO, "StateTests/RandomTests/st201503181904GO"} -declare_test!{StateTests_RandomTests_st201503181906GO, "StateTests/RandomTests/st201503181906GO"} -declare_test!{StateTests_RandomTests_st201503181907GO, "StateTests/RandomTests/st201503181907GO"} -declare_test!{StateTests_RandomTests_st201503181910GO, "StateTests/RandomTests/st201503181910GO"} -declare_test!{StateTests_RandomTests_st201503181915GO, "StateTests/RandomTests/st201503181915GO"} -declare_test!{StateTests_RandomTests_st201503181919CPPJIT, "StateTests/RandomTests/st201503181919CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181919PYTHON, "StateTests/RandomTests/st201503181919PYTHON"} -declare_test!{StateTests_RandomTests_st201503181920GO, "StateTests/RandomTests/st201503181920GO"} -declare_test!{StateTests_RandomTests_st201503181922GO, "StateTests/RandomTests/st201503181922GO"} -declare_test!{StateTests_RandomTests_st201503181926GO, "StateTests/RandomTests/st201503181926GO"} -declare_test!{StateTests_RandomTests_st201503181929GO, "StateTests/RandomTests/st201503181929GO"} -declare_test!{StateTests_RandomTests_st201503181931CPPJIT, "StateTests/RandomTests/st201503181931CPPJIT"} -declare_test!{StateTests_RandomTests_st201503181931GO, "StateTests/RandomTests/st201503181931GO"} -declare_test!{StateTests_RandomTests_st201503181931PYTHON, "StateTests/RandomTests/st201503181931PYTHON"} -declare_test!{StateTests_RandomTests_st201503191646GO, "StateTests/RandomTests/st201503191646GO"} -declare_test!{StateTests_RandomTests_st201503200837JS, "StateTests/RandomTests/st201503200837JS"} -declare_test!{StateTests_RandomTests_st201503200838JS, "StateTests/RandomTests/st201503200838JS"} -declare_test!{StateTests_RandomTests_st201503200841JS, "StateTests/RandomTests/st201503200841JS"} -declare_test!{StateTests_RandomTests_st201503200848JS, "StateTests/RandomTests/st201503200848JS"} -declare_test!{StateTests_RandomTests_st201503240609JS, "StateTests/RandomTests/st201503240609JS"} -declare_test!{StateTests_RandomTests_st201503302200JS, "StateTests/RandomTests/st201503302200JS"} -declare_test!{StateTests_RandomTests_st201503302202JS, "StateTests/RandomTests/st201503302202JS"} -declare_test!{StateTests_RandomTests_st201503302206JS, "StateTests/RandomTests/st201503302206JS"} -declare_test!{StateTests_RandomTests_st201503302208JS, "StateTests/RandomTests/st201503302208JS"} -declare_test!{StateTests_RandomTests_st201503302210JS, "StateTests/RandomTests/st201503302210JS"} -declare_test!{StateTests_RandomTests_st201503302211JS, "StateTests/RandomTests/st201503302211JS"} -declare_test!{StateTests_RandomTests_st201504011535GO, "StateTests/RandomTests/st201504011535GO"} -declare_test!{StateTests_RandomTests_st201504011536GO, "StateTests/RandomTests/st201504011536GO"} -declare_test!{StateTests_RandomTests_st201504011547GO, "StateTests/RandomTests/st201504011547GO"} -declare_test!{StateTests_RandomTests_st201504011916JS, "StateTests/RandomTests/st201504011916JS"} -declare_test!{StateTests_RandomTests_st201504012130JS, "StateTests/RandomTests/st201504012130JS"} -declare_test!{StateTests_RandomTests_st201504012259JS, "StateTests/RandomTests/st201504012259JS"} -declare_test!{StateTests_RandomTests_st201504012359JS, "StateTests/RandomTests/st201504012359JS"} -declare_test!{StateTests_RandomTests_st201504020305JS, "StateTests/RandomTests/st201504020305JS"} -declare_test!{StateTests_RandomTests_st201504020400JS, "StateTests/RandomTests/st201504020400JS"} -declare_test!{StateTests_RandomTests_st201504020428JS, "StateTests/RandomTests/st201504020428JS"} -declare_test!{StateTests_RandomTests_st201504020431JS, "StateTests/RandomTests/st201504020431JS"} -declare_test!{StateTests_RandomTests_st201504020444JS, "StateTests/RandomTests/st201504020444JS"} -declare_test!{StateTests_RandomTests_st201504020538JS, "StateTests/RandomTests/st201504020538JS"} -declare_test!{StateTests_RandomTests_st201504020639JS, "StateTests/RandomTests/st201504020639JS"} -declare_test!{StateTests_RandomTests_st201504020836JS, "StateTests/RandomTests/st201504020836JS"} -declare_test!{StateTests_RandomTests_st201504020910JS, "StateTests/RandomTests/st201504020910JS"} -declare_test!{StateTests_RandomTests_st201504021057JS, "StateTests/RandomTests/st201504021057JS"} -declare_test!{StateTests_RandomTests_st201504021104JS, "StateTests/RandomTests/st201504021104JS"} -declare_test!{StateTests_RandomTests_st201504021237CPPJIT, "StateTests/RandomTests/st201504021237CPPJIT"} -declare_test!{StateTests_RandomTests_st201504021237GO, "StateTests/RandomTests/st201504021237GO"} -declare_test!{StateTests_RandomTests_st201504021237JS, "StateTests/RandomTests/st201504021237JS"} -declare_test!{StateTests_RandomTests_st201504021237PYTHON, "StateTests/RandomTests/st201504021237PYTHON"} -declare_test!{StateTests_RandomTests_st201504021949JS, "StateTests/RandomTests/st201504021949JS"} -declare_test!{StateTests_RandomTests_st201504022003CPPJIT, "StateTests/RandomTests/st201504022003CPPJIT"} -declare_test!{StateTests_RandomTests_st201504022124JS, "StateTests/RandomTests/st201504022124JS"} -declare_test!{StateTests_RandomTests_st201504030138JS, "StateTests/RandomTests/st201504030138JS"} -declare_test!{StateTests_RandomTests_st201504030646JS, "StateTests/RandomTests/st201504030646JS"} -declare_test!{StateTests_RandomTests_st201504030709JS, "StateTests/RandomTests/st201504030709JS"} -declare_test!{StateTests_RandomTests_st201504031133JS, "StateTests/RandomTests/st201504031133JS"} -declare_test!{StateTests_RandomTests_st201504031446JS, "StateTests/RandomTests/st201504031446JS"} -declare_test!{StateTests_RandomTests_st201504031841JS, "StateTests/RandomTests/st201504031841JS"} -declare_test!{StateTests_RandomTests_st201504041605JS, "StateTests/RandomTests/st201504041605JS"} -declare_test!{StateTests_RandomTests_st201504042052JS, "StateTests/RandomTests/st201504042052JS"} -declare_test!{StateTests_RandomTests_st201504042226CPPJIT, "StateTests/RandomTests/st201504042226CPPJIT"} -declare_test!{StateTests_RandomTests_st201504042355CPPJIT, "StateTests/RandomTests/st201504042355CPPJIT"} -declare_test!{StateTests_RandomTests_st201504050059JS, "StateTests/RandomTests/st201504050059JS"} -declare_test!{StateTests_RandomTests_st201504050733JS, "StateTests/RandomTests/st201504050733JS"} -declare_test!{StateTests_RandomTests_st201504051540JS, "StateTests/RandomTests/st201504051540JS"} -declare_test!{StateTests_RandomTests_st201504051944CPPJIT, "StateTests/RandomTests/st201504051944CPPJIT"} -declare_test!{StateTests_RandomTests_st201504052008CPPJIT, "StateTests/RandomTests/st201504052008CPPJIT"} -declare_test!{StateTests_RandomTests_st201504052014GO, "StateTests/RandomTests/st201504052014GO"} -declare_test!{StateTests_RandomTests_st201504052031CPPJIT, "StateTests/RandomTests/st201504052031CPPJIT"} -declare_test!{StateTests_RandomTests_st201504060057CPPJIT, "StateTests/RandomTests/st201504060057CPPJIT"} -declare_test!{StateTests_RandomTests_st201504060418CPPJIT, "StateTests/RandomTests/st201504060418CPPJIT"} -declare_test!{StateTests_RandomTests_st201504061106CPPJIT, "StateTests/RandomTests/st201504061106CPPJIT"} -declare_test!{StateTests_RandomTests_st201504061134CPPJIT, "StateTests/RandomTests/st201504061134CPPJIT"} -declare_test!{StateTests_RandomTests_st201504062033CPPJIT, "StateTests/RandomTests/st201504062033CPPJIT"} -declare_test!{StateTests_RandomTests_st201504062046CPPJIT, "StateTests/RandomTests/st201504062046CPPJIT"} -declare_test!{StateTests_RandomTests_st201504062314CPPJIT, "StateTests/RandomTests/st201504062314CPPJIT"} -declare_test!{StateTests_RandomTests_st201504070746JS, "StateTests/RandomTests/st201504070746JS"} -declare_test!{StateTests_RandomTests_st201504070816CPPJIT, "StateTests/RandomTests/st201504070816CPPJIT"} -declare_test!{StateTests_RandomTests_st201504070836CPPJIT, "StateTests/RandomTests/st201504070836CPPJIT"} -declare_test!{StateTests_RandomTests_st201504070839CPPJIT, "StateTests/RandomTests/st201504070839CPPJIT"} -declare_test!{StateTests_RandomTests_st201504071041CPPJIT, "StateTests/RandomTests/st201504071041CPPJIT"} -declare_test!{StateTests_RandomTests_st201504071056CPPJIT, "StateTests/RandomTests/st201504071056CPPJIT"} -declare_test!{StateTests_RandomTests_st201504071621CPPJIT, "StateTests/RandomTests/st201504071621CPPJIT"} -declare_test!{StateTests_RandomTests_st201504071653CPPJIT, "StateTests/RandomTests/st201504071653CPPJIT"} -declare_test!{StateTests_RandomTests_st201504071750CPPJIT, "StateTests/RandomTests/st201504071750CPPJIT"} -declare_test!{StateTests_RandomTests_st201504071905CPPJIT, "StateTests/RandomTests/st201504071905CPPJIT"} -declare_test!{StateTests_RandomTests_st201504080454CPPJIT, "StateTests/RandomTests/st201504080454CPPJIT"} -declare_test!{StateTests_RandomTests_st201504080457CPPJIT, "StateTests/RandomTests/st201504080457CPPJIT"} -declare_test!{StateTests_RandomTests_st201504080650CPPJIT, "StateTests/RandomTests/st201504080650CPPJIT"} -declare_test!{StateTests_RandomTests_st201504080840CPPJIT, "StateTests/RandomTests/st201504080840CPPJIT"} -declare_test!{StateTests_RandomTests_st201504080948CPPJIT, "StateTests/RandomTests/st201504080948CPPJIT"} -declare_test!{StateTests_RandomTests_st201504081100CPPJIT, "StateTests/RandomTests/st201504081100CPPJIT"} -declare_test!{StateTests_RandomTests_st201504081134CPPJIT, "StateTests/RandomTests/st201504081134CPPJIT"} -declare_test!{StateTests_RandomTests_st201504081138CPPJIT, "StateTests/RandomTests/st201504081138CPPJIT"} -declare_test!{StateTests_RandomTests_st201504081611CPPJIT, "StateTests/RandomTests/st201504081611CPPJIT"} -declare_test!{StateTests_RandomTests_st201504081841JAVA, "StateTests/RandomTests/st201504081841JAVA"} -declare_test!{StateTests_RandomTests_st201504081842JAVA, "StateTests/RandomTests/st201504081842JAVA"} -declare_test!{StateTests_RandomTests_st201504081843JAVA, "StateTests/RandomTests/st201504081843JAVA"} -declare_test!{StateTests_RandomTests_st201504081928CPPJIT, "StateTests/RandomTests/st201504081928CPPJIT"} -declare_test!{StateTests_RandomTests_st201504081953JAVA, "StateTests/RandomTests/st201504081953JAVA"} -declare_test!{StateTests_RandomTests_st201504081954JAVA, "StateTests/RandomTests/st201504081954JAVA"} -declare_test!{StateTests_RandomTests_st201504081955JAVA, "StateTests/RandomTests/st201504081955JAVA"} -declare_test!{StateTests_RandomTests_st201504081956JAVA, "StateTests/RandomTests/st201504081956JAVA"} -declare_test!{StateTests_RandomTests_st201504081957JAVA, "StateTests/RandomTests/st201504081957JAVA"} -declare_test!{StateTests_RandomTests_st201504082000JAVA, "StateTests/RandomTests/st201504082000JAVA"} -declare_test!{StateTests_RandomTests_st201504082001JAVA, "StateTests/RandomTests/st201504082001JAVA"} -declare_test!{StateTests_RandomTests_st201504082002JAVA, "StateTests/RandomTests/st201504082002JAVA"} -declare_test!{StateTests_RandomTests_st201504090553CPPJIT, "StateTests/RandomTests/st201504090553CPPJIT"} -declare_test!{StateTests_RandomTests_st201504090657CPPJIT, "StateTests/RandomTests/st201504090657CPPJIT"} -declare_test!{StateTests_RandomTests_st201504091403CPPJIT, "StateTests/RandomTests/st201504091403CPPJIT"} -declare_test!{StateTests_RandomTests_st201504091641CPPJIT, "StateTests/RandomTests/st201504091641CPPJIT"} -declare_test!{StateTests_RandomTests_st201504092303CPPJIT, "StateTests/RandomTests/st201504092303CPPJIT"} -declare_test!{StateTests_RandomTests_st201504100125CPPJIT, "StateTests/RandomTests/st201504100125CPPJIT"} -declare_test!{StateTests_RandomTests_st201504100215CPPJIT, "StateTests/RandomTests/st201504100215CPPJIT"} -declare_test!{StateTests_RandomTests_st201504100226PYTHON, "StateTests/RandomTests/st201504100226PYTHON"} -declare_test!{StateTests_RandomTests_st201504100308CPPJIT, "StateTests/RandomTests/st201504100308CPPJIT"} -declare_test!{StateTests_RandomTests_st201504100337CPPJIT, "StateTests/RandomTests/st201504100337CPPJIT"} -declare_test!{StateTests_RandomTests_st201504100341CPPJIT, "StateTests/RandomTests/st201504100341CPPJIT"} -declare_test!{StateTests_RandomTests_st201504101009CPPJIT, "StateTests/RandomTests/st201504101009CPPJIT"} -declare_test!{StateTests_RandomTests_st201504101150CPPJIT, "StateTests/RandomTests/st201504101150CPPJIT"} -declare_test!{StateTests_RandomTests_st201504101223CPPJIT, "StateTests/RandomTests/st201504101223CPPJIT"} -declare_test!{StateTests_RandomTests_st201504101338CPPJIT, "StateTests/RandomTests/st201504101338CPPJIT"} -declare_test!{StateTests_RandomTests_st201504101754PYTHON, "StateTests/RandomTests/st201504101754PYTHON"} -declare_test!{StateTests_RandomTests_st201504111554CPPJIT, "StateTests/RandomTests/st201504111554CPPJIT"} -declare_test!{StateTests_RandomTests_st201504130653JS, "StateTests/RandomTests/st201504130653JS"} -declare_test!{StateTests_RandomTests_st201504131821CPPJIT, "StateTests/RandomTests/st201504131821CPPJIT"} -declare_test!{StateTests_RandomTests_st201504140229CPPJIT, "StateTests/RandomTests/st201504140229CPPJIT"} -declare_test!{StateTests_RandomTests_st201504140236CPPJIT, "StateTests/RandomTests/st201504140236CPPJIT"} -declare_test!{StateTests_RandomTests_st201504140359CPPJIT, "StateTests/RandomTests/st201504140359CPPJIT"} -declare_test!{StateTests_RandomTests_st201504140750CPPJIT, "StateTests/RandomTests/st201504140750CPPJIT"} -declare_test!{StateTests_RandomTests_st201504140818CPPJIT, "StateTests/RandomTests/st201504140818CPPJIT"} -declare_test!{StateTests_RandomTests_st201504140900CPPJIT, "StateTests/RandomTests/st201504140900CPPJIT"} -declare_test!{StateTests_RandomTests_st201504150854CPPJIT, "StateTests/RandomTests/st201504150854CPPJIT"} -declare_test!{StateTests_RandomTests_st201504151057CPPJIT, "StateTests/RandomTests/st201504151057CPPJIT"} -declare_test!{StateTests_RandomTests_st201504202124CPPJIT, "StateTests/RandomTests/st201504202124CPPJIT"} -declare_test!{StateTests_RandomTests_st201504210245CPPJIT, "StateTests/RandomTests/st201504210245CPPJIT"} -declare_test!{StateTests_RandomTests_st201504210957CPPJIT, "StateTests/RandomTests/st201504210957CPPJIT"} -declare_test!{StateTests_RandomTests_st201504211739CPPJIT, "StateTests/RandomTests/st201504211739CPPJIT"} -declare_test!{StateTests_RandomTests_st201504212038CPPJIT, "StateTests/RandomTests/st201504212038CPPJIT"} -declare_test!{StateTests_RandomTests_st201504230729CPPJIT, "StateTests/RandomTests/st201504230729CPPJIT"} -declare_test!{StateTests_RandomTests_st201504231639CPPJIT, "StateTests/RandomTests/st201504231639CPPJIT"} -declare_test!{StateTests_RandomTests_st201504231710CPPJIT, "StateTests/RandomTests/st201504231710CPPJIT"} -declare_test!{StateTests_RandomTests_st201504231742CPPJIT, "StateTests/RandomTests/st201504231742CPPJIT"} -declare_test!{StateTests_RandomTests_st201504232350CPPJIT, "StateTests/RandomTests/st201504232350CPPJIT"} -declare_test!{StateTests_RandomTests_st201504240140CPPJIT, "StateTests/RandomTests/st201504240140CPPJIT"} -declare_test!{StateTests_RandomTests_st201504240220CPPJIT, "StateTests/RandomTests/st201504240220CPPJIT"} -declare_test!{StateTests_RandomTests_st201504240351CPPJIT, "StateTests/RandomTests/st201504240351CPPJIT"} -declare_test!{StateTests_RandomTests_st201504240817CPPJIT, "StateTests/RandomTests/st201504240817CPPJIT"} -declare_test!{StateTests_RandomTests_st201504241118CPPJIT, "StateTests/RandomTests/st201504241118CPPJIT"} -declare_test!{StateTests_RandomTests_st201505021810CPPJIT, "StateTests/RandomTests/st201505021810CPPJIT"} -declare_test!{StateTests_RandomTests_st201505050557JS, "StateTests/RandomTests/st201505050557JS"} -declare_test!{StateTests_RandomTests_st201505050929GO, "StateTests/RandomTests/st201505050929GO"} -declare_test!{StateTests_RandomTests_st201505050942PYTHON, "StateTests/RandomTests/st201505050942PYTHON"} -declare_test!{StateTests_RandomTests_st201505051004PYTHON, "StateTests/RandomTests/st201505051004PYTHON"} -declare_test!{StateTests_RandomTests_st201505051016PYTHON, "StateTests/RandomTests/st201505051016PYTHON"} -declare_test!{StateTests_RandomTests_st201505051114GO, "StateTests/RandomTests/st201505051114GO"} -declare_test!{StateTests_RandomTests_st201505051238GO, "StateTests/RandomTests/st201505051238GO"} -declare_test!{StateTests_RandomTests_st201505051249GO, "StateTests/RandomTests/st201505051249GO"} -declare_test!{StateTests_RandomTests_st201505051558PYTHON, "StateTests/RandomTests/st201505051558PYTHON"} -declare_test!{StateTests_RandomTests_st201505051611PYTHON, "StateTests/RandomTests/st201505051611PYTHON"} -declare_test!{StateTests_RandomTests_st201505051648JS, "StateTests/RandomTests/st201505051648JS"} -declare_test!{StateTests_RandomTests_st201505051710GO, "StateTests/RandomTests/st201505051710GO"} -declare_test!{StateTests_RandomTests_st201505052013GO, "StateTests/RandomTests/st201505052013GO"} -declare_test!{StateTests_RandomTests_st201505052102JS, "StateTests/RandomTests/st201505052102JS"} -declare_test!{StateTests_RandomTests_st201505052235GO, "StateTests/RandomTests/st201505052235GO"} -declare_test!{StateTests_RandomTests_st201505052238JS, "StateTests/RandomTests/st201505052238JS"} -declare_test!{StateTests_RandomTests_st201505052242PYTHON, "StateTests/RandomTests/st201505052242PYTHON"} -declare_test!{StateTests_RandomTests_st201505052343PYTHON, "StateTests/RandomTests/st201505052343PYTHON"} -declare_test!{StateTests_RandomTests_st201505060120GO, "StateTests/RandomTests/st201505060120GO"} -declare_test!{StateTests_RandomTests_st201505060121GO, "StateTests/RandomTests/st201505060121GO"} -declare_test!{StateTests_RandomTests_st201505060136PYTHON, "StateTests/RandomTests/st201505060136PYTHON"} -declare_test!{StateTests_RandomTests_st201505060646JS, "StateTests/RandomTests/st201505060646JS"} -declare_test!{StateTests_RandomTests_st201505252314CPPJIT, "StateTests/RandomTests/st201505252314CPPJIT"} -declare_test!{StateTests_RandomTests_st201505272131CPPJIT, "StateTests/RandomTests/st201505272131CPPJIT"} -declare_test!{StateTests_RandomTests_st201506040034GO, "StateTests/RandomTests/st201506040034GO"} -declare_test!{StateTests_RandomTests_st201506040157GO, "StateTests/RandomTests/st201506040157GO"} -declare_test!{StateTests_RandomTests_st201506052130GO, "StateTests/RandomTests/st201506052130GO"} -declare_test!{StateTests_RandomTests_st201506060929GO, "StateTests/RandomTests/st201506060929GO"} -declare_test!{StateTests_RandomTests_st201506061255GO, "StateTests/RandomTests/st201506061255GO"} -declare_test!{StateTests_RandomTests_st201506062331GO, "StateTests/RandomTests/st201506062331GO"} -declare_test!{StateTests_RandomTests_st201506070548GO, "StateTests/RandomTests/st201506070548GO"} -declare_test!{StateTests_RandomTests_st201506071050GO, "StateTests/RandomTests/st201506071050GO"} -declare_test!{StateTests_RandomTests_st201506071624GO, "StateTests/RandomTests/st201506071624GO"} -declare_test!{StateTests_RandomTests_st201506071819GO, "StateTests/RandomTests/st201506071819GO"} -declare_test!{StateTests_RandomTests_st201506072007GO, "StateTests/RandomTests/st201506072007GO"} -declare_test!{StateTests_RandomTests_st201506080556GO, "StateTests/RandomTests/st201506080556GO"} -declare_test!{StateTests_RandomTests_st201506080721GO, "StateTests/RandomTests/st201506080721GO"} -declare_test!{StateTests_RandomTests_st201506091836GO, "StateTests/RandomTests/st201506091836GO"} -declare_test!{StateTests_RandomTests_st201506092032GO, "StateTests/RandomTests/st201506092032GO"} -declare_test!{StateTests_RandomTests_st201506101359JS, "StateTests/RandomTests/st201506101359JS"} -declare_test!{StateTests_RandomTests_st201507030359GO, "StateTests/RandomTests/st201507030359GO"} + declare_test!{StateTests_stBlockHashTest, "StateTests/stBlockHashTest"} + declare_test!{StateTests_stCallCodes, "StateTests/stCallCodes"} + declare_test!{StateTests_stCallCreateCallCodeTest, "StateTests/stCallCreateCallCodeTest"} + declare_test!{StateTests_stExample, "StateTests/stExample"} + declare_test!{StateTests_stInitCodeTest, "StateTests/stInitCodeTest"} + declare_test!{StateTests_stLogTests, "StateTests/stLogTests"} + declare_test!{heavy => StateTests_stMemoryStressTest, "StateTests/stMemoryStressTest"} + declare_test!{heavy => StateTests_stMemoryTest, "StateTests/stMemoryTest"} + declare_test!{StateTests_stPreCompiledContracts, "StateTests/stPreCompiledContracts"} + declare_test!{heavy => StateTests_stQuadraticComplexityTest, "StateTests/stQuadraticComplexityTest"} + declare_test!{StateTests_stRecursiveCreate, "StateTests/stRecursiveCreate"} + declare_test!{StateTests_stRefundTest, "StateTests/stRefundTest"} + declare_test!{StateTests_stSolidityTest, "StateTests/stSolidityTest"} + declare_test!{StateTests_stSpecialTest, "StateTests/stSpecialTest"} + declare_test!{StateTests_stSystemOperationsTest, "StateTests/stSystemOperationsTest"} + declare_test!{StateTests_stTransactionTest, "StateTests/stTransactionTest"} + declare_test!{StateTests_stTransitionTest, "StateTests/stTransitionTest"} + declare_test!{StateTests_stWalletTest, "StateTests/stWalletTest"} + + declare_test!{StateTests_RandomTests_st201503121803PYTHON, "StateTests/RandomTests/st201503121803PYTHON"} + declare_test!{StateTests_RandomTests_st201503121806PYTHON, "StateTests/RandomTests/st201503121806PYTHON"} + declare_test!{StateTests_RandomTests_st201503121848GO, "StateTests/RandomTests/st201503121848GO"} + declare_test!{StateTests_RandomTests_st201503121849GO, "StateTests/RandomTests/st201503121849GO"} + declare_test!{StateTests_RandomTests_st201503121850GO, "StateTests/RandomTests/st201503121850GO"} + declare_test!{StateTests_RandomTests_st201503121851GO, "StateTests/RandomTests/st201503121851GO"} + declare_test!{StateTests_RandomTests_st201503121953GO, "StateTests/RandomTests/st201503121953GO"} + declare_test!{StateTests_RandomTests_st201503122023GO, "StateTests/RandomTests/st201503122023GO"} + declare_test!{StateTests_RandomTests_st201503122023PYTHON, "StateTests/RandomTests/st201503122023PYTHON"} + declare_test!{StateTests_RandomTests_st201503122027GO, "StateTests/RandomTests/st201503122027GO"} + declare_test!{StateTests_RandomTests_st201503122054GO, "StateTests/RandomTests/st201503122054GO"} + declare_test!{StateTests_RandomTests_st201503122055GO, "StateTests/RandomTests/st201503122055GO"} + declare_test!{StateTests_RandomTests_st201503122115CPPJIT, "StateTests/RandomTests/st201503122115CPPJIT"} + declare_test!{StateTests_RandomTests_st201503122115GO, "StateTests/RandomTests/st201503122115GO"} + declare_test!{StateTests_RandomTests_st201503122123GO, "StateTests/RandomTests/st201503122123GO"} + declare_test!{StateTests_RandomTests_st201503122124GO, "StateTests/RandomTests/st201503122124GO"} + declare_test!{StateTests_RandomTests_st201503122128PYTHON, "StateTests/RandomTests/st201503122128PYTHON"} + declare_test!{StateTests_RandomTests_st201503122140GO, "StateTests/RandomTests/st201503122140GO"} + declare_test!{StateTests_RandomTests_st201503122159GO, "StateTests/RandomTests/st201503122159GO"} + declare_test!{StateTests_RandomTests_st201503122204GO, "StateTests/RandomTests/st201503122204GO"} + declare_test!{StateTests_RandomTests_st201503122212GO, "StateTests/RandomTests/st201503122212GO"} + declare_test!{StateTests_RandomTests_st201503122231GO, "StateTests/RandomTests/st201503122231GO"} + declare_test!{StateTests_RandomTests_st201503122238GO, "StateTests/RandomTests/st201503122238GO"} + declare_test!{StateTests_RandomTests_st201503122252GO, "StateTests/RandomTests/st201503122252GO"} + declare_test!{StateTests_RandomTests_st201503122316GO, "StateTests/RandomTests/st201503122316GO"} + declare_test!{StateTests_RandomTests_st201503122324GO, "StateTests/RandomTests/st201503122324GO"} + declare_test!{StateTests_RandomTests_st201503122358GO, "StateTests/RandomTests/st201503122358GO"} + declare_test!{StateTests_RandomTests_st201503130002GO, "StateTests/RandomTests/st201503130002GO"} + declare_test!{StateTests_RandomTests_st201503130005GO, "StateTests/RandomTests/st201503130005GO"} + declare_test!{StateTests_RandomTests_st201503130007GO, "StateTests/RandomTests/st201503130007GO"} + declare_test!{StateTests_RandomTests_st201503130010GO, "StateTests/RandomTests/st201503130010GO"} + declare_test!{StateTests_RandomTests_st201503130023PYTHON, "StateTests/RandomTests/st201503130023PYTHON"} + declare_test!{StateTests_RandomTests_st201503130059GO, "StateTests/RandomTests/st201503130059GO"} + declare_test!{StateTests_RandomTests_st201503130101GO, "StateTests/RandomTests/st201503130101GO"} + declare_test!{StateTests_RandomTests_st201503130109GO, "StateTests/RandomTests/st201503130109GO"} + declare_test!{StateTests_RandomTests_st201503130117GO, "StateTests/RandomTests/st201503130117GO"} + declare_test!{StateTests_RandomTests_st201503130122GO, "StateTests/RandomTests/st201503130122GO"} + declare_test!{StateTests_RandomTests_st201503130156GO, "StateTests/RandomTests/st201503130156GO"} + declare_test!{StateTests_RandomTests_st201503130156PYTHON, "StateTests/RandomTests/st201503130156PYTHON"} + declare_test!{StateTests_RandomTests_st201503130207GO, "StateTests/RandomTests/st201503130207GO"} + declare_test!{StateTests_RandomTests_st201503130219CPPJIT, "StateTests/RandomTests/st201503130219CPPJIT"} + declare_test!{StateTests_RandomTests_st201503130219GO, "StateTests/RandomTests/st201503130219GO"} + declare_test!{StateTests_RandomTests_st201503130243GO, "StateTests/RandomTests/st201503130243GO"} + declare_test!{StateTests_RandomTests_st201503130246GO, "StateTests/RandomTests/st201503130246GO"} + declare_test!{StateTests_RandomTests_st201503130321GO, "StateTests/RandomTests/st201503130321GO"} + declare_test!{StateTests_RandomTests_st201503130322GO, "StateTests/RandomTests/st201503130322GO"} + declare_test!{StateTests_RandomTests_st201503130332GO, "StateTests/RandomTests/st201503130332GO"} + declare_test!{StateTests_RandomTests_st201503130359GO, "StateTests/RandomTests/st201503130359GO"} + declare_test!{StateTests_RandomTests_st201503130405GO, "StateTests/RandomTests/st201503130405GO"} + declare_test!{StateTests_RandomTests_st201503130408GO, "StateTests/RandomTests/st201503130408GO"} + declare_test!{StateTests_RandomTests_st201503130411GO, "StateTests/RandomTests/st201503130411GO"} + declare_test!{StateTests_RandomTests_st201503130431GO, "StateTests/RandomTests/st201503130431GO"} + declare_test!{StateTests_RandomTests_st201503130437GO, "StateTests/RandomTests/st201503130437GO"} + declare_test!{StateTests_RandomTests_st201503130450GO, "StateTests/RandomTests/st201503130450GO"} + declare_test!{StateTests_RandomTests_st201503130512CPPJIT, "StateTests/RandomTests/st201503130512CPPJIT"} + declare_test!{StateTests_RandomTests_st201503130512GO, "StateTests/RandomTests/st201503130512GO"} + declare_test!{StateTests_RandomTests_st201503130615GO, "StateTests/RandomTests/st201503130615GO"} + declare_test!{StateTests_RandomTests_st201503130705GO, "StateTests/RandomTests/st201503130705GO"} + declare_test!{StateTests_RandomTests_st201503130733CPPJIT, "StateTests/RandomTests/st201503130733CPPJIT"} + declare_test!{StateTests_RandomTests_st201503130733GO, "StateTests/RandomTests/st201503130733GO"} + declare_test!{StateTests_RandomTests_st201503130747GO, "StateTests/RandomTests/st201503130747GO"} + declare_test!{StateTests_RandomTests_st201503130751GO, "StateTests/RandomTests/st201503130751GO"} + declare_test!{StateTests_RandomTests_st201503130752PYTHON, "StateTests/RandomTests/st201503130752PYTHON"} + declare_test!{StateTests_RandomTests_st201503130757PYTHON, "StateTests/RandomTests/st201503130757PYTHON"} + declare_test!{StateTests_RandomTests_st201503131658GO, "StateTests/RandomTests/st201503131658GO"} + declare_test!{StateTests_RandomTests_st201503131739GO, "StateTests/RandomTests/st201503131739GO"} + declare_test!{StateTests_RandomTests_st201503131755CPPJIT, "StateTests/RandomTests/st201503131755CPPJIT"} + declare_test!{StateTests_RandomTests_st201503131755GO, "StateTests/RandomTests/st201503131755GO"} + declare_test!{StateTests_RandomTests_st201503132001CPPJIT, "StateTests/RandomTests/st201503132001CPPJIT"} + declare_test!{StateTests_RandomTests_st201503132127PYTHON, "StateTests/RandomTests/st201503132127PYTHON"} + declare_test!{StateTests_RandomTests_st201503132201CPPJIT, "StateTests/RandomTests/st201503132201CPPJIT"} + declare_test!{StateTests_RandomTests_st201503132201GO, "StateTests/RandomTests/st201503132201GO"} + declare_test!{StateTests_RandomTests_st201503132202PYTHON, "StateTests/RandomTests/st201503132202PYTHON"} + declare_test!{StateTests_RandomTests_st201503140002PYTHON, "StateTests/RandomTests/st201503140002PYTHON"} + declare_test!{StateTests_RandomTests_st201503140240PYTHON, "StateTests/RandomTests/st201503140240PYTHON"} + declare_test!{StateTests_RandomTests_st201503140522PYTHON, "StateTests/RandomTests/st201503140522PYTHON"} + declare_test!{StateTests_RandomTests_st201503140756PYTHON, "StateTests/RandomTests/st201503140756PYTHON"} + declare_test!{StateTests_RandomTests_st201503141144PYTHON, "StateTests/RandomTests/st201503141144PYTHON"} + declare_test!{StateTests_RandomTests_st201503141510PYTHON, "StateTests/RandomTests/st201503141510PYTHON"} + declare_test!{StateTests_RandomTests_st201503150427PYTHON, "StateTests/RandomTests/st201503150427PYTHON"} + declare_test!{StateTests_RandomTests_st201503150716PYTHON, "StateTests/RandomTests/st201503150716PYTHON"} + declare_test!{StateTests_RandomTests_st201503151450PYTHON, "StateTests/RandomTests/st201503151450PYTHON"} + declare_test!{StateTests_RandomTests_st201503151516PYTHON, "StateTests/RandomTests/st201503151516PYTHON"} + declare_test!{StateTests_RandomTests_st201503151753PYTHON, "StateTests/RandomTests/st201503151753PYTHON"} + declare_test!{StateTests_RandomTests_st201503152057PYTHON, "StateTests/RandomTests/st201503152057PYTHON"} + declare_test!{StateTests_RandomTests_st201503152241PYTHON, "StateTests/RandomTests/st201503152241PYTHON"} + declare_test!{StateTests_RandomTests_st201503160014PYTHON, "StateTests/RandomTests/st201503160014PYTHON"} + declare_test!{StateTests_RandomTests_st201503160733PYTHON, "StateTests/RandomTests/st201503160733PYTHON"} + declare_test!{StateTests_RandomTests_st201503170051PYTHON, "StateTests/RandomTests/st201503170051PYTHON"} + declare_test!{StateTests_RandomTests_st201503170433PYTHON, "StateTests/RandomTests/st201503170433PYTHON"} + declare_test!{StateTests_RandomTests_st201503170523PYTHON, "StateTests/RandomTests/st201503170523PYTHON"} + declare_test!{StateTests_RandomTests_st201503171108PYTHON, "StateTests/RandomTests/st201503171108PYTHON"} + declare_test!{StateTests_RandomTests_st201503181223GO, "StateTests/RandomTests/st201503181223GO"} + declare_test!{StateTests_RandomTests_st201503181225GO, "StateTests/RandomTests/st201503181225GO"} + declare_test!{StateTests_RandomTests_st201503181226CPPJIT, "StateTests/RandomTests/st201503181226CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181227CPPJIT, "StateTests/RandomTests/st201503181227CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181227GO, "StateTests/RandomTests/st201503181227GO"} + declare_test!{StateTests_RandomTests_st201503181229GO, "StateTests/RandomTests/st201503181229GO"} + declare_test!{StateTests_RandomTests_st201503181230CPPJIT, "StateTests/RandomTests/st201503181230CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181230GO, "StateTests/RandomTests/st201503181230GO"} + declare_test!{StateTests_RandomTests_st201503181231GO, "StateTests/RandomTests/st201503181231GO"} + declare_test!{StateTests_RandomTests_st201503181232CPPJIT, "StateTests/RandomTests/st201503181232CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181232GO, "StateTests/RandomTests/st201503181232GO"} + declare_test!{StateTests_RandomTests_st201503181233GO, "StateTests/RandomTests/st201503181233GO"} + declare_test!{StateTests_RandomTests_st201503181234CPPJIT, "StateTests/RandomTests/st201503181234CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181234GO, "StateTests/RandomTests/st201503181234GO"} + declare_test!{StateTests_RandomTests_st201503181235CPPJIT, "StateTests/RandomTests/st201503181235CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181235GO, "StateTests/RandomTests/st201503181235GO"} + declare_test!{StateTests_RandomTests_st201503181236GO, "StateTests/RandomTests/st201503181236GO"} + declare_test!{StateTests_RandomTests_st201503181237GO, "StateTests/RandomTests/st201503181237GO"} + declare_test!{StateTests_RandomTests_st201503181239GO, "StateTests/RandomTests/st201503181239GO"} + declare_test!{StateTests_RandomTests_st201503181241CPPJIT, "StateTests/RandomTests/st201503181241CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181241GO, "StateTests/RandomTests/st201503181241GO"} + declare_test!{StateTests_RandomTests_st201503181243GO, "StateTests/RandomTests/st201503181243GO"} + declare_test!{StateTests_RandomTests_st201503181244GO, "StateTests/RandomTests/st201503181244GO"} + declare_test!{StateTests_RandomTests_st201503181245CPPJIT, "StateTests/RandomTests/st201503181245CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181245GO, "StateTests/RandomTests/st201503181245GO"} + declare_test!{StateTests_RandomTests_st201503181246CPPJIT, "StateTests/RandomTests/st201503181246CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181246GO, "StateTests/RandomTests/st201503181246GO"} + declare_test!{StateTests_RandomTests_st201503181247GO, "StateTests/RandomTests/st201503181247GO"} + declare_test!{StateTests_RandomTests_st201503181248GO, "StateTests/RandomTests/st201503181248GO"} + declare_test!{StateTests_RandomTests_st201503181249GO, "StateTests/RandomTests/st201503181249GO"} + declare_test!{StateTests_RandomTests_st201503181250CPPJIT, "StateTests/RandomTests/st201503181250CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181250GO, "StateTests/RandomTests/st201503181250GO"} + declare_test!{StateTests_RandomTests_st201503181251GO, "StateTests/RandomTests/st201503181251GO"} + declare_test!{StateTests_RandomTests_st201503181252CPPJIT, "StateTests/RandomTests/st201503181252CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181253GO, "StateTests/RandomTests/st201503181253GO"} + declare_test!{StateTests_RandomTests_st201503181255CPPJIT, "StateTests/RandomTests/st201503181255CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181255GO, "StateTests/RandomTests/st201503181255GO"} + declare_test!{StateTests_RandomTests_st201503181257GO, "StateTests/RandomTests/st201503181257GO"} + declare_test!{StateTests_RandomTests_st201503181258CPPJIT, "StateTests/RandomTests/st201503181258CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181258GO, "StateTests/RandomTests/st201503181258GO"} + declare_test!{StateTests_RandomTests_st201503181301CPPJIT, "StateTests/RandomTests/st201503181301CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181301GO, "StateTests/RandomTests/st201503181301GO"} + declare_test!{StateTests_RandomTests_st201503181303GO, "StateTests/RandomTests/st201503181303GO"} + declare_test!{StateTests_RandomTests_st201503181304GO, "StateTests/RandomTests/st201503181304GO"} + declare_test!{StateTests_RandomTests_st201503181305GO, "StateTests/RandomTests/st201503181305GO"} + declare_test!{StateTests_RandomTests_st201503181306GO, "StateTests/RandomTests/st201503181306GO"} + declare_test!{StateTests_RandomTests_st201503181307CPPJIT, "StateTests/RandomTests/st201503181307CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181307GO, "StateTests/RandomTests/st201503181307GO"} + declare_test!{StateTests_RandomTests_st201503181308GO, "StateTests/RandomTests/st201503181308GO"} + declare_test!{StateTests_RandomTests_st201503181309GO, "StateTests/RandomTests/st201503181309GO"} + declare_test!{StateTests_RandomTests_st201503181310GO, "StateTests/RandomTests/st201503181310GO"} + declare_test!{StateTests_RandomTests_st201503181311GO, "StateTests/RandomTests/st201503181311GO"} + declare_test!{StateTests_RandomTests_st201503181313GO, "StateTests/RandomTests/st201503181313GO"} + declare_test!{StateTests_RandomTests_st201503181314GO, "StateTests/RandomTests/st201503181314GO"} + declare_test!{StateTests_RandomTests_st201503181315CPPJIT, "StateTests/RandomTests/st201503181315CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181315GO, "StateTests/RandomTests/st201503181315GO"} + declare_test!{StateTests_RandomTests_st201503181316CPPJIT, "StateTests/RandomTests/st201503181316CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181316PYTHON, "StateTests/RandomTests/st201503181316PYTHON"} + declare_test!{StateTests_RandomTests_st201503181317GO, "StateTests/RandomTests/st201503181317GO"} + declare_test!{StateTests_RandomTests_st201503181318CPPJIT, "StateTests/RandomTests/st201503181318CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181318GO, "StateTests/RandomTests/st201503181318GO"} + declare_test!{StateTests_RandomTests_st201503181319GO, "StateTests/RandomTests/st201503181319GO"} + declare_test!{StateTests_RandomTests_st201503181319PYTHON, "StateTests/RandomTests/st201503181319PYTHON"} + declare_test!{StateTests_RandomTests_st201503181322GO, "StateTests/RandomTests/st201503181322GO"} + declare_test!{StateTests_RandomTests_st201503181323CPPJIT, "StateTests/RandomTests/st201503181323CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181323GO, "StateTests/RandomTests/st201503181323GO"} + declare_test!{StateTests_RandomTests_st201503181324GO, "StateTests/RandomTests/st201503181324GO"} + declare_test!{StateTests_RandomTests_st201503181325GO, "StateTests/RandomTests/st201503181325GO"} + declare_test!{StateTests_RandomTests_st201503181326CPPJIT, "StateTests/RandomTests/st201503181326CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181326GO, "StateTests/RandomTests/st201503181326GO"} + declare_test!{StateTests_RandomTests_st201503181327GO, "StateTests/RandomTests/st201503181327GO"} + declare_test!{StateTests_RandomTests_st201503181329CPPJIT, "StateTests/RandomTests/st201503181329CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181329GO, "StateTests/RandomTests/st201503181329GO"} + declare_test!{StateTests_RandomTests_st201503181330GO, "StateTests/RandomTests/st201503181330GO"} + declare_test!{StateTests_RandomTests_st201503181332GO, "StateTests/RandomTests/st201503181332GO"} + declare_test!{StateTests_RandomTests_st201503181333GO, "StateTests/RandomTests/st201503181333GO"} + declare_test!{StateTests_RandomTests_st201503181334GO, "StateTests/RandomTests/st201503181334GO"} + declare_test!{StateTests_RandomTests_st201503181336CPPJIT, "StateTests/RandomTests/st201503181336CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181337GO, "StateTests/RandomTests/st201503181337GO"} + declare_test!{StateTests_RandomTests_st201503181338GO, "StateTests/RandomTests/st201503181338GO"} + declare_test!{StateTests_RandomTests_st201503181339CPPJIT, "StateTests/RandomTests/st201503181339CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181339GO, "StateTests/RandomTests/st201503181339GO"} + declare_test!{StateTests_RandomTests_st201503181340GO, "StateTests/RandomTests/st201503181340GO"} + declare_test!{StateTests_RandomTests_st201503181341CPPJIT, "StateTests/RandomTests/st201503181341CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181342CPPJIT, "StateTests/RandomTests/st201503181342CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181342GO, "StateTests/RandomTests/st201503181342GO"} + declare_test!{StateTests_RandomTests_st201503181345GO, "StateTests/RandomTests/st201503181345GO"} + declare_test!{StateTests_RandomTests_st201503181346GO, "StateTests/RandomTests/st201503181346GO"} + declare_test!{StateTests_RandomTests_st201503181347CPPJIT, "StateTests/RandomTests/st201503181347CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181347GO, "StateTests/RandomTests/st201503181347GO"} + declare_test!{StateTests_RandomTests_st201503181347PYTHON, "StateTests/RandomTests/st201503181347PYTHON"} + declare_test!{StateTests_RandomTests_st201503181350CPPJIT, "StateTests/RandomTests/st201503181350CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181352GO, "StateTests/RandomTests/st201503181352GO"} + declare_test!{StateTests_RandomTests_st201503181353GO, "StateTests/RandomTests/st201503181353GO"} + declare_test!{StateTests_RandomTests_st201503181354CPPJIT, "StateTests/RandomTests/st201503181354CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181354GO, "StateTests/RandomTests/st201503181354GO"} + declare_test!{StateTests_RandomTests_st201503181355GO, "StateTests/RandomTests/st201503181355GO"} + declare_test!{StateTests_RandomTests_st201503181356CPPJIT, "StateTests/RandomTests/st201503181356CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181357CPPJIT, "StateTests/RandomTests/st201503181357CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181358CPPJIT, "StateTests/RandomTests/st201503181358CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181358GO, "StateTests/RandomTests/st201503181358GO"} + declare_test!{StateTests_RandomTests_st201503181359GO, "StateTests/RandomTests/st201503181359GO"} + declare_test!{StateTests_RandomTests_st201503181402CPPJIT, "StateTests/RandomTests/st201503181402CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181403GO, "StateTests/RandomTests/st201503181403GO"} + declare_test!{StateTests_RandomTests_st201503181406CPPJIT, "StateTests/RandomTests/st201503181406CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181406GO, "StateTests/RandomTests/st201503181406GO"} + declare_test!{StateTests_RandomTests_st201503181410GO, "StateTests/RandomTests/st201503181410GO"} + declare_test!{StateTests_RandomTests_st201503181412CPPJIT, "StateTests/RandomTests/st201503181412CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181413GO, "StateTests/RandomTests/st201503181413GO"} + declare_test!{StateTests_RandomTests_st201503181415GO, "StateTests/RandomTests/st201503181415GO"} + declare_test!{StateTests_RandomTests_st201503181416GO, "StateTests/RandomTests/st201503181416GO"} + declare_test!{StateTests_RandomTests_st201503181417CPPJIT, "StateTests/RandomTests/st201503181417CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181417GO, "StateTests/RandomTests/st201503181417GO"} + declare_test!{StateTests_RandomTests_st201503181418CPPJIT, "StateTests/RandomTests/st201503181418CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181422GO, "StateTests/RandomTests/st201503181422GO"} + declare_test!{StateTests_RandomTests_st201503181423CPPJIT, "StateTests/RandomTests/st201503181423CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181424GO, "StateTests/RandomTests/st201503181424GO"} + declare_test!{StateTests_RandomTests_st201503181426CPPJIT, "StateTests/RandomTests/st201503181426CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181426GO, "StateTests/RandomTests/st201503181426GO"} + declare_test!{StateTests_RandomTests_st201503181428GO, "StateTests/RandomTests/st201503181428GO"} + declare_test!{StateTests_RandomTests_st201503181430CPPJIT, "StateTests/RandomTests/st201503181430CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181435GO, "StateTests/RandomTests/st201503181435GO"} + declare_test!{StateTests_RandomTests_st201503181436GO, "StateTests/RandomTests/st201503181436GO"} + declare_test!{StateTests_RandomTests_st201503181437CPPJIT, "StateTests/RandomTests/st201503181437CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181437GO, "StateTests/RandomTests/st201503181437GO"} + declare_test!{StateTests_RandomTests_st201503181438CPPJIT, "StateTests/RandomTests/st201503181438CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181438GO, "StateTests/RandomTests/st201503181438GO"} + declare_test!{StateTests_RandomTests_st201503181439CPPJIT, "StateTests/RandomTests/st201503181439CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181439GO, "StateTests/RandomTests/st201503181439GO"} + declare_test!{StateTests_RandomTests_st201503181439PYTHON, "StateTests/RandomTests/st201503181439PYTHON"} + declare_test!{StateTests_RandomTests_st201503181440GO, "StateTests/RandomTests/st201503181440GO"} + declare_test!{StateTests_RandomTests_st201503181441GO, "StateTests/RandomTests/st201503181441GO"} + declare_test!{StateTests_RandomTests_st201503181442GO, "StateTests/RandomTests/st201503181442GO"} + declare_test!{StateTests_RandomTests_st201503181445CPPJIT, "StateTests/RandomTests/st201503181445CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181446GO, "StateTests/RandomTests/st201503181446GO"} + declare_test!{StateTests_RandomTests_st201503181447GO, "StateTests/RandomTests/st201503181447GO"} + declare_test!{StateTests_RandomTests_st201503181450GO, "StateTests/RandomTests/st201503181450GO"} + declare_test!{StateTests_RandomTests_st201503181451CPPJIT, "StateTests/RandomTests/st201503181451CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181453GO, "StateTests/RandomTests/st201503181453GO"} + declare_test!{StateTests_RandomTests_st201503181455GO, "StateTests/RandomTests/st201503181455GO"} + declare_test!{StateTests_RandomTests_st201503181456CPPJIT, "StateTests/RandomTests/st201503181456CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181457GO, "StateTests/RandomTests/st201503181457GO"} + declare_test!{StateTests_RandomTests_st201503181458GO, "StateTests/RandomTests/st201503181458GO"} + declare_test!{StateTests_RandomTests_st201503181459GO, "StateTests/RandomTests/st201503181459GO"} + declare_test!{StateTests_RandomTests_st201503181500GO, "StateTests/RandomTests/st201503181500GO"} + declare_test!{StateTests_RandomTests_st201503181501GO, "StateTests/RandomTests/st201503181501GO"} + declare_test!{StateTests_RandomTests_st201503181503GO, "StateTests/RandomTests/st201503181503GO"} + declare_test!{StateTests_RandomTests_st201503181504GO, "StateTests/RandomTests/st201503181504GO"} + declare_test!{StateTests_RandomTests_st201503181505GO, "StateTests/RandomTests/st201503181505GO"} + declare_test!{StateTests_RandomTests_st201503181506CPPJIT, "StateTests/RandomTests/st201503181506CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181507GO, "StateTests/RandomTests/st201503181507GO"} + declare_test!{StateTests_RandomTests_st201503181509CPPJIT, "StateTests/RandomTests/st201503181509CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181509GO, "StateTests/RandomTests/st201503181509GO"} + declare_test!{StateTests_RandomTests_st201503181510GO, "StateTests/RandomTests/st201503181510GO"} + declare_test!{StateTests_RandomTests_st201503181511GO, "StateTests/RandomTests/st201503181511GO"} + declare_test!{StateTests_RandomTests_st201503181512GO, "StateTests/RandomTests/st201503181512GO"} + declare_test!{StateTests_RandomTests_st201503181513CPPJIT, "StateTests/RandomTests/st201503181513CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181513GO, "StateTests/RandomTests/st201503181513GO"} + declare_test!{StateTests_RandomTests_st201503181514CPPJIT, "StateTests/RandomTests/st201503181514CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181514GO, "StateTests/RandomTests/st201503181514GO"} + declare_test!{StateTests_RandomTests_st201503181517CPPJIT, "StateTests/RandomTests/st201503181517CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181517GO, "StateTests/RandomTests/st201503181517GO"} + declare_test!{StateTests_RandomTests_st201503181519CPPJIT, "StateTests/RandomTests/st201503181519CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181519GO, "StateTests/RandomTests/st201503181519GO"} + declare_test!{StateTests_RandomTests_st201503181520CPPJIT, "StateTests/RandomTests/st201503181520CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181520GO, "StateTests/RandomTests/st201503181520GO"} + declare_test!{StateTests_RandomTests_st201503181521GO, "StateTests/RandomTests/st201503181521GO"} + declare_test!{StateTests_RandomTests_st201503181522GO, "StateTests/RandomTests/st201503181522GO"} + declare_test!{StateTests_RandomTests_st201503181524CPPJIT, "StateTests/RandomTests/st201503181524CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181524GO, "StateTests/RandomTests/st201503181524GO"} + declare_test!{StateTests_RandomTests_st201503181526GO, "StateTests/RandomTests/st201503181526GO"} + declare_test!{StateTests_RandomTests_st201503181527GO, "StateTests/RandomTests/st201503181527GO"} + declare_test!{StateTests_RandomTests_st201503181528CPPJIT, "StateTests/RandomTests/st201503181528CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181528GO, "StateTests/RandomTests/st201503181528GO"} + declare_test!{StateTests_RandomTests_st201503181528PYTHON, "StateTests/RandomTests/st201503181528PYTHON"} + declare_test!{StateTests_RandomTests_st201503181529GO, "StateTests/RandomTests/st201503181529GO"} + declare_test!{StateTests_RandomTests_st201503181531CPPJIT, "StateTests/RandomTests/st201503181531CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181533GO, "StateTests/RandomTests/st201503181533GO"} + declare_test!{StateTests_RandomTests_st201503181534CPPJIT, "StateTests/RandomTests/st201503181534CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181534GO, "StateTests/RandomTests/st201503181534GO"} + declare_test!{StateTests_RandomTests_st201503181536CPPJIT, "StateTests/RandomTests/st201503181536CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181536GO, "StateTests/RandomTests/st201503181536GO"} + declare_test!{StateTests_RandomTests_st201503181537GO, "StateTests/RandomTests/st201503181537GO"} + declare_test!{StateTests_RandomTests_st201503181538GO, "StateTests/RandomTests/st201503181538GO"} + declare_test!{StateTests_RandomTests_st201503181539GO, "StateTests/RandomTests/st201503181539GO"} + declare_test!{StateTests_RandomTests_st201503181540CPPJIT, "StateTests/RandomTests/st201503181540CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181540PYTHON, "StateTests/RandomTests/st201503181540PYTHON"} + declare_test!{StateTests_RandomTests_st201503181543GO, "StateTests/RandomTests/st201503181543GO"} + declare_test!{StateTests_RandomTests_st201503181544CPPJIT, "StateTests/RandomTests/st201503181544CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181544GO, "StateTests/RandomTests/st201503181544GO"} + declare_test!{StateTests_RandomTests_st201503181547GO, "StateTests/RandomTests/st201503181547GO"} + declare_test!{StateTests_RandomTests_st201503181548CPPJIT, "StateTests/RandomTests/st201503181548CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181548GO, "StateTests/RandomTests/st201503181548GO"} + declare_test!{StateTests_RandomTests_st201503181551GO, "StateTests/RandomTests/st201503181551GO"} + declare_test!{StateTests_RandomTests_st201503181552CPPJIT, "StateTests/RandomTests/st201503181552CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181553GO, "StateTests/RandomTests/st201503181553GO"} + declare_test!{StateTests_RandomTests_st201503181555CPPJIT, "StateTests/RandomTests/st201503181555CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181555GO, "StateTests/RandomTests/st201503181555GO"} + declare_test!{StateTests_RandomTests_st201503181557GO, "StateTests/RandomTests/st201503181557GO"} + declare_test!{StateTests_RandomTests_st201503181559GO, "StateTests/RandomTests/st201503181559GO"} + declare_test!{StateTests_RandomTests_st201503181601CPPJIT, "StateTests/RandomTests/st201503181601CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181601GO, "StateTests/RandomTests/st201503181601GO"} + declare_test!{StateTests_RandomTests_st201503181602GO, "StateTests/RandomTests/st201503181602GO"} + declare_test!{StateTests_RandomTests_st201503181603GO, "StateTests/RandomTests/st201503181603GO"} + declare_test!{StateTests_RandomTests_st201503181604GO, "StateTests/RandomTests/st201503181604GO"} + declare_test!{StateTests_RandomTests_st201503181605GO, "StateTests/RandomTests/st201503181605GO"} + declare_test!{StateTests_RandomTests_st201503181606GO, "StateTests/RandomTests/st201503181606GO"} + declare_test!{StateTests_RandomTests_st201503181607GO, "StateTests/RandomTests/st201503181607GO"} + declare_test!{StateTests_RandomTests_st201503181608CPPJIT, "StateTests/RandomTests/st201503181608CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181608GO, "StateTests/RandomTests/st201503181608GO"} + declare_test!{StateTests_RandomTests_st201503181609GO, "StateTests/RandomTests/st201503181609GO"} + declare_test!{StateTests_RandomTests_st201503181610CPPJIT, "StateTests/RandomTests/st201503181610CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181610GO, "StateTests/RandomTests/st201503181610GO"} + declare_test!{StateTests_RandomTests_st201503181611CPPJIT, "StateTests/RandomTests/st201503181611CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181611GO, "StateTests/RandomTests/st201503181611GO"} + declare_test!{StateTests_RandomTests_st201503181612GO, "StateTests/RandomTests/st201503181612GO"} + declare_test!{StateTests_RandomTests_st201503181614CPPJIT, "StateTests/RandomTests/st201503181614CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181614GO, "StateTests/RandomTests/st201503181614GO"} + declare_test!{StateTests_RandomTests_st201503181616CPPJIT, "StateTests/RandomTests/st201503181616CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181616GO, "StateTests/RandomTests/st201503181616GO"} + declare_test!{StateTests_RandomTests_st201503181617GO, "StateTests/RandomTests/st201503181617GO"} + declare_test!{StateTests_RandomTests_st201503181618GO, "StateTests/RandomTests/st201503181618GO"} + declare_test!{StateTests_RandomTests_st201503181619GO, "StateTests/RandomTests/st201503181619GO"} + declare_test!{StateTests_RandomTests_st201503181620CPPJIT, "StateTests/RandomTests/st201503181620CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181620GO, "StateTests/RandomTests/st201503181620GO"} + declare_test!{StateTests_RandomTests_st201503181621GO, "StateTests/RandomTests/st201503181621GO"} + declare_test!{StateTests_RandomTests_st201503181625GO, "StateTests/RandomTests/st201503181625GO"} + declare_test!{StateTests_RandomTests_st201503181626CPPJIT, "StateTests/RandomTests/st201503181626CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181626GO, "StateTests/RandomTests/st201503181626GO"} + declare_test!{StateTests_RandomTests_st201503181627GO, "StateTests/RandomTests/st201503181627GO"} + declare_test!{StateTests_RandomTests_st201503181628GO, "StateTests/RandomTests/st201503181628GO"} + declare_test!{StateTests_RandomTests_st201503181629GO, "StateTests/RandomTests/st201503181629GO"} + declare_test!{StateTests_RandomTests_st201503181630CPPJIT, "StateTests/RandomTests/st201503181630CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181630GO, "StateTests/RandomTests/st201503181630GO"} + declare_test!{StateTests_RandomTests_st201503181630PYTHON, "StateTests/RandomTests/st201503181630PYTHON"} + declare_test!{StateTests_RandomTests_st201503181632GO, "StateTests/RandomTests/st201503181632GO"} + declare_test!{StateTests_RandomTests_st201503181634CPPJIT, "StateTests/RandomTests/st201503181634CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181635GO, "StateTests/RandomTests/st201503181635GO"} + declare_test!{StateTests_RandomTests_st201503181636GO, "StateTests/RandomTests/st201503181636GO"} + declare_test!{StateTests_RandomTests_st201503181638GO, "StateTests/RandomTests/st201503181638GO"} + declare_test!{StateTests_RandomTests_st201503181639CPPJIT, "StateTests/RandomTests/st201503181639CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181641GO, "StateTests/RandomTests/st201503181641GO"} + declare_test!{StateTests_RandomTests_st201503181645GO, "StateTests/RandomTests/st201503181645GO"} + declare_test!{StateTests_RandomTests_st201503181646GO, "StateTests/RandomTests/st201503181646GO"} + declare_test!{StateTests_RandomTests_st201503181647CPPJIT, "StateTests/RandomTests/st201503181647CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181649CPPJIT, "StateTests/RandomTests/st201503181649CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181650GO, "StateTests/RandomTests/st201503181650GO"} + declare_test!{StateTests_RandomTests_st201503181652CPPJIT, "StateTests/RandomTests/st201503181652CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181653GO, "StateTests/RandomTests/st201503181653GO"} + declare_test!{StateTests_RandomTests_st201503181654GO, "StateTests/RandomTests/st201503181654GO"} + declare_test!{StateTests_RandomTests_st201503181655CPPJIT, "StateTests/RandomTests/st201503181655CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181655GO, "StateTests/RandomTests/st201503181655GO"} + declare_test!{StateTests_RandomTests_st201503181656CPPJIT, "StateTests/RandomTests/st201503181656CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181656GO, "StateTests/RandomTests/st201503181656GO"} + declare_test!{StateTests_RandomTests_st201503181657GO, "StateTests/RandomTests/st201503181657GO"} + declare_test!{StateTests_RandomTests_st201503181658GO, "StateTests/RandomTests/st201503181658GO"} + declare_test!{StateTests_RandomTests_st201503181700GO, "StateTests/RandomTests/st201503181700GO"} + declare_test!{StateTests_RandomTests_st201503181702GO, "StateTests/RandomTests/st201503181702GO"} + declare_test!{StateTests_RandomTests_st201503181703CPPJIT, "StateTests/RandomTests/st201503181703CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181703GO, "StateTests/RandomTests/st201503181703GO"} + declare_test!{StateTests_RandomTests_st201503181704GO, "StateTests/RandomTests/st201503181704GO"} + declare_test!{StateTests_RandomTests_st201503181706GO, "StateTests/RandomTests/st201503181706GO"} + declare_test!{StateTests_RandomTests_st201503181709GO, "StateTests/RandomTests/st201503181709GO"} + declare_test!{StateTests_RandomTests_st201503181711CPPJIT, "StateTests/RandomTests/st201503181711CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181711GO, "StateTests/RandomTests/st201503181711GO"} + declare_test!{StateTests_RandomTests_st201503181713CPPJIT, "StateTests/RandomTests/st201503181713CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181713GO, "StateTests/RandomTests/st201503181713GO"} + declare_test!{StateTests_RandomTests_st201503181714GO, "StateTests/RandomTests/st201503181714GO"} + declare_test!{StateTests_RandomTests_st201503181715CPPJIT, "StateTests/RandomTests/st201503181715CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181715GO, "StateTests/RandomTests/st201503181715GO"} + declare_test!{StateTests_RandomTests_st201503181716GO, "StateTests/RandomTests/st201503181716GO"} + declare_test!{StateTests_RandomTests_st201503181717GO, "StateTests/RandomTests/st201503181717GO"} + declare_test!{StateTests_RandomTests_st201503181720CPPJIT, "StateTests/RandomTests/st201503181720CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181722GO, "StateTests/RandomTests/st201503181722GO"} + declare_test!{StateTests_RandomTests_st201503181723CPPJIT, "StateTests/RandomTests/st201503181723CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181723GO, "StateTests/RandomTests/st201503181723GO"} + declare_test!{StateTests_RandomTests_st201503181724CPPJIT, "StateTests/RandomTests/st201503181724CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181724GO, "StateTests/RandomTests/st201503181724GO"} + declare_test!{StateTests_RandomTests_st201503181725GO, "StateTests/RandomTests/st201503181725GO"} + declare_test!{StateTests_RandomTests_st201503181728GO, "StateTests/RandomTests/st201503181728GO"} + declare_test!{StateTests_RandomTests_st201503181729GO, "StateTests/RandomTests/st201503181729GO"} + declare_test!{StateTests_RandomTests_st201503181730GO, "StateTests/RandomTests/st201503181730GO"} + declare_test!{StateTests_RandomTests_st201503181731CPPJIT, "StateTests/RandomTests/st201503181731CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181732GO, "StateTests/RandomTests/st201503181732GO"} + declare_test!{StateTests_RandomTests_st201503181734CPPJIT, "StateTests/RandomTests/st201503181734CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181734GO, "StateTests/RandomTests/st201503181734GO"} + declare_test!{StateTests_RandomTests_st201503181735GO, "StateTests/RandomTests/st201503181735GO"} + declare_test!{StateTests_RandomTests_st201503181737CPPJIT, "StateTests/RandomTests/st201503181737CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181737GO, "StateTests/RandomTests/st201503181737GO"} + declare_test!{StateTests_RandomTests_st201503181738CPPJIT, "StateTests/RandomTests/st201503181738CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181738GO, "StateTests/RandomTests/st201503181738GO"} + declare_test!{StateTests_RandomTests_st201503181739GO, "StateTests/RandomTests/st201503181739GO"} + declare_test!{StateTests_RandomTests_st201503181740CPPJIT, "StateTests/RandomTests/st201503181740CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181740GO, "StateTests/RandomTests/st201503181740GO"} + declare_test!{StateTests_RandomTests_st201503181742CPPJIT, "StateTests/RandomTests/st201503181742CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181743GO, "StateTests/RandomTests/st201503181743GO"} + declare_test!{StateTests_RandomTests_st201503181744GO, "StateTests/RandomTests/st201503181744GO"} + declare_test!{StateTests_RandomTests_st201503181745CPPJIT, "StateTests/RandomTests/st201503181745CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181746GO, "StateTests/RandomTests/st201503181746GO"} + declare_test!{StateTests_RandomTests_st201503181747GO, "StateTests/RandomTests/st201503181747GO"} + declare_test!{StateTests_RandomTests_st201503181748GO, "StateTests/RandomTests/st201503181748GO"} + declare_test!{StateTests_RandomTests_st201503181749GO, "StateTests/RandomTests/st201503181749GO"} + declare_test!{StateTests_RandomTests_st201503181750CPPJIT, "StateTests/RandomTests/st201503181750CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181750GO, "StateTests/RandomTests/st201503181750GO"} + declare_test!{StateTests_RandomTests_st201503181752GO, "StateTests/RandomTests/st201503181752GO"} + declare_test!{StateTests_RandomTests_st201503181753CPPJIT, "StateTests/RandomTests/st201503181753CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181754CPPJIT, "StateTests/RandomTests/st201503181754CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181754GO, "StateTests/RandomTests/st201503181754GO"} + declare_test!{StateTests_RandomTests_st201503181755CPPJIT, "StateTests/RandomTests/st201503181755CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181755GO, "StateTests/RandomTests/st201503181755GO"} + declare_test!{StateTests_RandomTests_st201503181756GO, "StateTests/RandomTests/st201503181756GO"} + declare_test!{StateTests_RandomTests_st201503181757CPPJIT, "StateTests/RandomTests/st201503181757CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181757GO, "StateTests/RandomTests/st201503181757GO"} + declare_test!{StateTests_RandomTests_st201503181759GO, "StateTests/RandomTests/st201503181759GO"} + declare_test!{StateTests_RandomTests_st201503181800GO, "StateTests/RandomTests/st201503181800GO"} + declare_test!{StateTests_RandomTests_st201503181801GO, "StateTests/RandomTests/st201503181801GO"} + declare_test!{StateTests_RandomTests_st201503181802GO, "StateTests/RandomTests/st201503181802GO"} + declare_test!{StateTests_RandomTests_st201503181803CPPJIT, "StateTests/RandomTests/st201503181803CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181803GO, "StateTests/RandomTests/st201503181803GO"} + declare_test!{StateTests_RandomTests_st201503181804GO, "StateTests/RandomTests/st201503181804GO"} + declare_test!{StateTests_RandomTests_st201503181806GO, "StateTests/RandomTests/st201503181806GO"} + declare_test!{StateTests_RandomTests_st201503181808GO, "StateTests/RandomTests/st201503181808GO"} + declare_test!{StateTests_RandomTests_st201503181809CPPJIT, "StateTests/RandomTests/st201503181809CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181812CPPJIT, "StateTests/RandomTests/st201503181812CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181812GO, "StateTests/RandomTests/st201503181812GO"} + declare_test!{StateTests_RandomTests_st201503181814CPPJIT, "StateTests/RandomTests/st201503181814CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181815GO, "StateTests/RandomTests/st201503181815GO"} + declare_test!{StateTests_RandomTests_st201503181816CPPJIT, "StateTests/RandomTests/st201503181816CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181817CPPJIT, "StateTests/RandomTests/st201503181817CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181819GO, "StateTests/RandomTests/st201503181819GO"} + declare_test!{StateTests_RandomTests_st201503181821GO, "StateTests/RandomTests/st201503181821GO"} + declare_test!{StateTests_RandomTests_st201503181822GO, "StateTests/RandomTests/st201503181822GO"} + declare_test!{StateTests_RandomTests_st201503181823GO, "StateTests/RandomTests/st201503181823GO"} + declare_test!{StateTests_RandomTests_st201503181824GO, "StateTests/RandomTests/st201503181824GO"} + declare_test!{StateTests_RandomTests_st201503181825GO, "StateTests/RandomTests/st201503181825GO"} + declare_test!{StateTests_RandomTests_st201503181829GO, "StateTests/RandomTests/st201503181829GO"} + declare_test!{StateTests_RandomTests_st201503181830CPPJIT, "StateTests/RandomTests/st201503181830CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181833GO, "StateTests/RandomTests/st201503181833GO"} + declare_test!{StateTests_RandomTests_st201503181834CPPJIT, "StateTests/RandomTests/st201503181834CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181834GO, "StateTests/RandomTests/st201503181834GO"} + declare_test!{StateTests_RandomTests_st201503181837GO, "StateTests/RandomTests/st201503181837GO"} + declare_test!{StateTests_RandomTests_st201503181840GO, "StateTests/RandomTests/st201503181840GO"} + declare_test!{StateTests_RandomTests_st201503181842GO, "StateTests/RandomTests/st201503181842GO"} + declare_test!{StateTests_RandomTests_st201503181843GO, "StateTests/RandomTests/st201503181843GO"} + declare_test!{StateTests_RandomTests_st201503181844GO, "StateTests/RandomTests/st201503181844GO"} + declare_test!{StateTests_RandomTests_st201503181845GO, "StateTests/RandomTests/st201503181845GO"} + declare_test!{StateTests_RandomTests_st201503181846GO, "StateTests/RandomTests/st201503181846GO"} + declare_test!{StateTests_RandomTests_st201503181847GO, "StateTests/RandomTests/st201503181847GO"} + declare_test!{StateTests_RandomTests_st201503181848GO, "StateTests/RandomTests/st201503181848GO"} + declare_test!{StateTests_RandomTests_st201503181849GO, "StateTests/RandomTests/st201503181849GO"} + declare_test!{StateTests_RandomTests_st201503181850GO, "StateTests/RandomTests/st201503181850GO"} + declare_test!{StateTests_RandomTests_st201503181851CPPJIT, "StateTests/RandomTests/st201503181851CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181851GO, "StateTests/RandomTests/st201503181851GO"} + declare_test!{StateTests_RandomTests_st201503181852CPPJIT, "StateTests/RandomTests/st201503181852CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181854GO, "StateTests/RandomTests/st201503181854GO"} + declare_test!{StateTests_RandomTests_st201503181855CPPJIT, "StateTests/RandomTests/st201503181855CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181857PYTHON, "StateTests/RandomTests/st201503181857PYTHON"} + declare_test!{StateTests_RandomTests_st201503181859GO, "StateTests/RandomTests/st201503181859GO"} + declare_test!{StateTests_RandomTests_st201503181900GO, "StateTests/RandomTests/st201503181900GO"} + declare_test!{StateTests_RandomTests_st201503181903GO, "StateTests/RandomTests/st201503181903GO"} + declare_test!{StateTests_RandomTests_st201503181904GO, "StateTests/RandomTests/st201503181904GO"} + declare_test!{StateTests_RandomTests_st201503181906GO, "StateTests/RandomTests/st201503181906GO"} + declare_test!{StateTests_RandomTests_st201503181907GO, "StateTests/RandomTests/st201503181907GO"} + declare_test!{StateTests_RandomTests_st201503181910GO, "StateTests/RandomTests/st201503181910GO"} + declare_test!{StateTests_RandomTests_st201503181915GO, "StateTests/RandomTests/st201503181915GO"} + declare_test!{StateTests_RandomTests_st201503181919CPPJIT, "StateTests/RandomTests/st201503181919CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181919PYTHON, "StateTests/RandomTests/st201503181919PYTHON"} + declare_test!{StateTests_RandomTests_st201503181920GO, "StateTests/RandomTests/st201503181920GO"} + declare_test!{StateTests_RandomTests_st201503181922GO, "StateTests/RandomTests/st201503181922GO"} + declare_test!{StateTests_RandomTests_st201503181926GO, "StateTests/RandomTests/st201503181926GO"} + declare_test!{StateTests_RandomTests_st201503181929GO, "StateTests/RandomTests/st201503181929GO"} + declare_test!{StateTests_RandomTests_st201503181931CPPJIT, "StateTests/RandomTests/st201503181931CPPJIT"} + declare_test!{StateTests_RandomTests_st201503181931GO, "StateTests/RandomTests/st201503181931GO"} + declare_test!{StateTests_RandomTests_st201503181931PYTHON, "StateTests/RandomTests/st201503181931PYTHON"} + declare_test!{StateTests_RandomTests_st201503191646GO, "StateTests/RandomTests/st201503191646GO"} + declare_test!{StateTests_RandomTests_st201503200837JS, "StateTests/RandomTests/st201503200837JS"} + declare_test!{StateTests_RandomTests_st201503200838JS, "StateTests/RandomTests/st201503200838JS"} + declare_test!{StateTests_RandomTests_st201503200841JS, "StateTests/RandomTests/st201503200841JS"} + declare_test!{StateTests_RandomTests_st201503200848JS, "StateTests/RandomTests/st201503200848JS"} + declare_test!{StateTests_RandomTests_st201503240609JS, "StateTests/RandomTests/st201503240609JS"} + declare_test!{StateTests_RandomTests_st201503302200JS, "StateTests/RandomTests/st201503302200JS"} + declare_test!{StateTests_RandomTests_st201503302202JS, "StateTests/RandomTests/st201503302202JS"} + declare_test!{StateTests_RandomTests_st201503302206JS, "StateTests/RandomTests/st201503302206JS"} + declare_test!{StateTests_RandomTests_st201503302208JS, "StateTests/RandomTests/st201503302208JS"} + declare_test!{StateTests_RandomTests_st201503302210JS, "StateTests/RandomTests/st201503302210JS"} + declare_test!{StateTests_RandomTests_st201503302211JS, "StateTests/RandomTests/st201503302211JS"} + declare_test!{StateTests_RandomTests_st201504011535GO, "StateTests/RandomTests/st201504011535GO"} + declare_test!{StateTests_RandomTests_st201504011536GO, "StateTests/RandomTests/st201504011536GO"} + declare_test!{StateTests_RandomTests_st201504011547GO, "StateTests/RandomTests/st201504011547GO"} + declare_test!{StateTests_RandomTests_st201504011916JS, "StateTests/RandomTests/st201504011916JS"} + declare_test!{StateTests_RandomTests_st201504012130JS, "StateTests/RandomTests/st201504012130JS"} + declare_test!{StateTests_RandomTests_st201504012259JS, "StateTests/RandomTests/st201504012259JS"} + declare_test!{StateTests_RandomTests_st201504012359JS, "StateTests/RandomTests/st201504012359JS"} + declare_test!{StateTests_RandomTests_st201504020305JS, "StateTests/RandomTests/st201504020305JS"} + declare_test!{StateTests_RandomTests_st201504020400JS, "StateTests/RandomTests/st201504020400JS"} + declare_test!{StateTests_RandomTests_st201504020428JS, "StateTests/RandomTests/st201504020428JS"} + declare_test!{StateTests_RandomTests_st201504020431JS, "StateTests/RandomTests/st201504020431JS"} + declare_test!{StateTests_RandomTests_st201504020444JS, "StateTests/RandomTests/st201504020444JS"} + declare_test!{StateTests_RandomTests_st201504020538JS, "StateTests/RandomTests/st201504020538JS"} + declare_test!{StateTests_RandomTests_st201504020639JS, "StateTests/RandomTests/st201504020639JS"} + declare_test!{StateTests_RandomTests_st201504020836JS, "StateTests/RandomTests/st201504020836JS"} + declare_test!{StateTests_RandomTests_st201504020910JS, "StateTests/RandomTests/st201504020910JS"} + declare_test!{StateTests_RandomTests_st201504021057JS, "StateTests/RandomTests/st201504021057JS"} + declare_test!{StateTests_RandomTests_st201504021104JS, "StateTests/RandomTests/st201504021104JS"} + declare_test!{StateTests_RandomTests_st201504021237CPPJIT, "StateTests/RandomTests/st201504021237CPPJIT"} + declare_test!{StateTests_RandomTests_st201504021237GO, "StateTests/RandomTests/st201504021237GO"} + declare_test!{StateTests_RandomTests_st201504021237JS, "StateTests/RandomTests/st201504021237JS"} + declare_test!{StateTests_RandomTests_st201504021237PYTHON, "StateTests/RandomTests/st201504021237PYTHON"} + declare_test!{StateTests_RandomTests_st201504021949JS, "StateTests/RandomTests/st201504021949JS"} + declare_test!{StateTests_RandomTests_st201504022003CPPJIT, "StateTests/RandomTests/st201504022003CPPJIT"} + declare_test!{StateTests_RandomTests_st201504022124JS, "StateTests/RandomTests/st201504022124JS"} + declare_test!{StateTests_RandomTests_st201504030138JS, "StateTests/RandomTests/st201504030138JS"} + declare_test!{StateTests_RandomTests_st201504030646JS, "StateTests/RandomTests/st201504030646JS"} + declare_test!{StateTests_RandomTests_st201504030709JS, "StateTests/RandomTests/st201504030709JS"} + declare_test!{StateTests_RandomTests_st201504031133JS, "StateTests/RandomTests/st201504031133JS"} + declare_test!{StateTests_RandomTests_st201504031446JS, "StateTests/RandomTests/st201504031446JS"} + declare_test!{StateTests_RandomTests_st201504031841JS, "StateTests/RandomTests/st201504031841JS"} + declare_test!{StateTests_RandomTests_st201504041605JS, "StateTests/RandomTests/st201504041605JS"} + declare_test!{StateTests_RandomTests_st201504042052JS, "StateTests/RandomTests/st201504042052JS"} + declare_test!{StateTests_RandomTests_st201504042226CPPJIT, "StateTests/RandomTests/st201504042226CPPJIT"} + declare_test!{StateTests_RandomTests_st201504042355CPPJIT, "StateTests/RandomTests/st201504042355CPPJIT"} + declare_test!{StateTests_RandomTests_st201504050059JS, "StateTests/RandomTests/st201504050059JS"} + declare_test!{StateTests_RandomTests_st201504050733JS, "StateTests/RandomTests/st201504050733JS"} + declare_test!{StateTests_RandomTests_st201504051540JS, "StateTests/RandomTests/st201504051540JS"} + declare_test!{StateTests_RandomTests_st201504051944CPPJIT, "StateTests/RandomTests/st201504051944CPPJIT"} + declare_test!{StateTests_RandomTests_st201504052008CPPJIT, "StateTests/RandomTests/st201504052008CPPJIT"} + declare_test!{StateTests_RandomTests_st201504052014GO, "StateTests/RandomTests/st201504052014GO"} + declare_test!{StateTests_RandomTests_st201504052031CPPJIT, "StateTests/RandomTests/st201504052031CPPJIT"} + declare_test!{StateTests_RandomTests_st201504060057CPPJIT, "StateTests/RandomTests/st201504060057CPPJIT"} + declare_test!{StateTests_RandomTests_st201504060418CPPJIT, "StateTests/RandomTests/st201504060418CPPJIT"} + declare_test!{StateTests_RandomTests_st201504061106CPPJIT, "StateTests/RandomTests/st201504061106CPPJIT"} + declare_test!{StateTests_RandomTests_st201504061134CPPJIT, "StateTests/RandomTests/st201504061134CPPJIT"} + declare_test!{StateTests_RandomTests_st201504062033CPPJIT, "StateTests/RandomTests/st201504062033CPPJIT"} + declare_test!{StateTests_RandomTests_st201504062046CPPJIT, "StateTests/RandomTests/st201504062046CPPJIT"} + declare_test!{StateTests_RandomTests_st201504062314CPPJIT, "StateTests/RandomTests/st201504062314CPPJIT"} + declare_test!{StateTests_RandomTests_st201504070746JS, "StateTests/RandomTests/st201504070746JS"} + declare_test!{StateTests_RandomTests_st201504070816CPPJIT, "StateTests/RandomTests/st201504070816CPPJIT"} + declare_test!{StateTests_RandomTests_st201504070836CPPJIT, "StateTests/RandomTests/st201504070836CPPJIT"} + declare_test!{StateTests_RandomTests_st201504070839CPPJIT, "StateTests/RandomTests/st201504070839CPPJIT"} + declare_test!{StateTests_RandomTests_st201504071041CPPJIT, "StateTests/RandomTests/st201504071041CPPJIT"} + declare_test!{StateTests_RandomTests_st201504071056CPPJIT, "StateTests/RandomTests/st201504071056CPPJIT"} + declare_test!{StateTests_RandomTests_st201504071621CPPJIT, "StateTests/RandomTests/st201504071621CPPJIT"} + declare_test!{StateTests_RandomTests_st201504071653CPPJIT, "StateTests/RandomTests/st201504071653CPPJIT"} + declare_test!{StateTests_RandomTests_st201504071750CPPJIT, "StateTests/RandomTests/st201504071750CPPJIT"} + declare_test!{StateTests_RandomTests_st201504071905CPPJIT, "StateTests/RandomTests/st201504071905CPPJIT"} + declare_test!{StateTests_RandomTests_st201504080454CPPJIT, "StateTests/RandomTests/st201504080454CPPJIT"} + declare_test!{StateTests_RandomTests_st201504080457CPPJIT, "StateTests/RandomTests/st201504080457CPPJIT"} + declare_test!{StateTests_RandomTests_st201504080650CPPJIT, "StateTests/RandomTests/st201504080650CPPJIT"} + declare_test!{StateTests_RandomTests_st201504080840CPPJIT, "StateTests/RandomTests/st201504080840CPPJIT"} + declare_test!{StateTests_RandomTests_st201504080948CPPJIT, "StateTests/RandomTests/st201504080948CPPJIT"} + declare_test!{StateTests_RandomTests_st201504081100CPPJIT, "StateTests/RandomTests/st201504081100CPPJIT"} + declare_test!{StateTests_RandomTests_st201504081134CPPJIT, "StateTests/RandomTests/st201504081134CPPJIT"} + declare_test!{StateTests_RandomTests_st201504081138CPPJIT, "StateTests/RandomTests/st201504081138CPPJIT"} + declare_test!{StateTests_RandomTests_st201504081611CPPJIT, "StateTests/RandomTests/st201504081611CPPJIT"} + declare_test!{StateTests_RandomTests_st201504081841JAVA, "StateTests/RandomTests/st201504081841JAVA"} + declare_test!{StateTests_RandomTests_st201504081842JAVA, "StateTests/RandomTests/st201504081842JAVA"} + declare_test!{StateTests_RandomTests_st201504081843JAVA, "StateTests/RandomTests/st201504081843JAVA"} + declare_test!{StateTests_RandomTests_st201504081928CPPJIT, "StateTests/RandomTests/st201504081928CPPJIT"} + declare_test!{StateTests_RandomTests_st201504081953JAVA, "StateTests/RandomTests/st201504081953JAVA"} + declare_test!{StateTests_RandomTests_st201504081954JAVA, "StateTests/RandomTests/st201504081954JAVA"} + declare_test!{StateTests_RandomTests_st201504081955JAVA, "StateTests/RandomTests/st201504081955JAVA"} + declare_test!{StateTests_RandomTests_st201504081956JAVA, "StateTests/RandomTests/st201504081956JAVA"} + declare_test!{StateTests_RandomTests_st201504081957JAVA, "StateTests/RandomTests/st201504081957JAVA"} + declare_test!{StateTests_RandomTests_st201504082000JAVA, "StateTests/RandomTests/st201504082000JAVA"} + declare_test!{StateTests_RandomTests_st201504082001JAVA, "StateTests/RandomTests/st201504082001JAVA"} + declare_test!{StateTests_RandomTests_st201504082002JAVA, "StateTests/RandomTests/st201504082002JAVA"} + declare_test!{StateTests_RandomTests_st201504090553CPPJIT, "StateTests/RandomTests/st201504090553CPPJIT"} + declare_test!{StateTests_RandomTests_st201504090657CPPJIT, "StateTests/RandomTests/st201504090657CPPJIT"} + declare_test!{StateTests_RandomTests_st201504091403CPPJIT, "StateTests/RandomTests/st201504091403CPPJIT"} + declare_test!{StateTests_RandomTests_st201504091641CPPJIT, "StateTests/RandomTests/st201504091641CPPJIT"} + declare_test!{StateTests_RandomTests_st201504092303CPPJIT, "StateTests/RandomTests/st201504092303CPPJIT"} + declare_test!{StateTests_RandomTests_st201504100125CPPJIT, "StateTests/RandomTests/st201504100125CPPJIT"} + declare_test!{StateTests_RandomTests_st201504100215CPPJIT, "StateTests/RandomTests/st201504100215CPPJIT"} + declare_test!{StateTests_RandomTests_st201504100226PYTHON, "StateTests/RandomTests/st201504100226PYTHON"} + declare_test!{StateTests_RandomTests_st201504100308CPPJIT, "StateTests/RandomTests/st201504100308CPPJIT"} + declare_test!{StateTests_RandomTests_st201504100337CPPJIT, "StateTests/RandomTests/st201504100337CPPJIT"} + declare_test!{StateTests_RandomTests_st201504100341CPPJIT, "StateTests/RandomTests/st201504100341CPPJIT"} + declare_test!{StateTests_RandomTests_st201504101009CPPJIT, "StateTests/RandomTests/st201504101009CPPJIT"} + declare_test!{StateTests_RandomTests_st201504101150CPPJIT, "StateTests/RandomTests/st201504101150CPPJIT"} + declare_test!{StateTests_RandomTests_st201504101223CPPJIT, "StateTests/RandomTests/st201504101223CPPJIT"} + declare_test!{StateTests_RandomTests_st201504101338CPPJIT, "StateTests/RandomTests/st201504101338CPPJIT"} + declare_test!{StateTests_RandomTests_st201504101754PYTHON, "StateTests/RandomTests/st201504101754PYTHON"} + declare_test!{StateTests_RandomTests_st201504111554CPPJIT, "StateTests/RandomTests/st201504111554CPPJIT"} + declare_test!{StateTests_RandomTests_st201504130653JS, "StateTests/RandomTests/st201504130653JS"} + declare_test!{StateTests_RandomTests_st201504131821CPPJIT, "StateTests/RandomTests/st201504131821CPPJIT"} + declare_test!{StateTests_RandomTests_st201504140229CPPJIT, "StateTests/RandomTests/st201504140229CPPJIT"} + declare_test!{StateTests_RandomTests_st201504140236CPPJIT, "StateTests/RandomTests/st201504140236CPPJIT"} + declare_test!{StateTests_RandomTests_st201504140359CPPJIT, "StateTests/RandomTests/st201504140359CPPJIT"} + declare_test!{StateTests_RandomTests_st201504140750CPPJIT, "StateTests/RandomTests/st201504140750CPPJIT"} + declare_test!{StateTests_RandomTests_st201504140818CPPJIT, "StateTests/RandomTests/st201504140818CPPJIT"} + declare_test!{StateTests_RandomTests_st201504140900CPPJIT, "StateTests/RandomTests/st201504140900CPPJIT"} + declare_test!{StateTests_RandomTests_st201504150854CPPJIT, "StateTests/RandomTests/st201504150854CPPJIT"} + declare_test!{StateTests_RandomTests_st201504151057CPPJIT, "StateTests/RandomTests/st201504151057CPPJIT"} + declare_test!{StateTests_RandomTests_st201504202124CPPJIT, "StateTests/RandomTests/st201504202124CPPJIT"} + declare_test!{StateTests_RandomTests_st201504210245CPPJIT, "StateTests/RandomTests/st201504210245CPPJIT"} + declare_test!{StateTests_RandomTests_st201504210957CPPJIT, "StateTests/RandomTests/st201504210957CPPJIT"} + declare_test!{StateTests_RandomTests_st201504211739CPPJIT, "StateTests/RandomTests/st201504211739CPPJIT"} + declare_test!{StateTests_RandomTests_st201504212038CPPJIT, "StateTests/RandomTests/st201504212038CPPJIT"} + declare_test!{StateTests_RandomTests_st201504230729CPPJIT, "StateTests/RandomTests/st201504230729CPPJIT"} + declare_test!{StateTests_RandomTests_st201504231639CPPJIT, "StateTests/RandomTests/st201504231639CPPJIT"} + declare_test!{StateTests_RandomTests_st201504231710CPPJIT, "StateTests/RandomTests/st201504231710CPPJIT"} + declare_test!{StateTests_RandomTests_st201504231742CPPJIT, "StateTests/RandomTests/st201504231742CPPJIT"} + declare_test!{StateTests_RandomTests_st201504232350CPPJIT, "StateTests/RandomTests/st201504232350CPPJIT"} + declare_test!{StateTests_RandomTests_st201504240140CPPJIT, "StateTests/RandomTests/st201504240140CPPJIT"} + declare_test!{StateTests_RandomTests_st201504240220CPPJIT, "StateTests/RandomTests/st201504240220CPPJIT"} + declare_test!{StateTests_RandomTests_st201504240351CPPJIT, "StateTests/RandomTests/st201504240351CPPJIT"} + declare_test!{StateTests_RandomTests_st201504240817CPPJIT, "StateTests/RandomTests/st201504240817CPPJIT"} + declare_test!{StateTests_RandomTests_st201504241118CPPJIT, "StateTests/RandomTests/st201504241118CPPJIT"} + declare_test!{StateTests_RandomTests_st201505021810CPPJIT, "StateTests/RandomTests/st201505021810CPPJIT"} + declare_test!{StateTests_RandomTests_st201505050557JS, "StateTests/RandomTests/st201505050557JS"} + declare_test!{StateTests_RandomTests_st201505050929GO, "StateTests/RandomTests/st201505050929GO"} + declare_test!{StateTests_RandomTests_st201505050942PYTHON, "StateTests/RandomTests/st201505050942PYTHON"} + declare_test!{StateTests_RandomTests_st201505051004PYTHON, "StateTests/RandomTests/st201505051004PYTHON"} + declare_test!{StateTests_RandomTests_st201505051016PYTHON, "StateTests/RandomTests/st201505051016PYTHON"} + declare_test!{StateTests_RandomTests_st201505051114GO, "StateTests/RandomTests/st201505051114GO"} + declare_test!{StateTests_RandomTests_st201505051238GO, "StateTests/RandomTests/st201505051238GO"} + declare_test!{StateTests_RandomTests_st201505051249GO, "StateTests/RandomTests/st201505051249GO"} + declare_test!{StateTests_RandomTests_st201505051558PYTHON, "StateTests/RandomTests/st201505051558PYTHON"} + declare_test!{StateTests_RandomTests_st201505051611PYTHON, "StateTests/RandomTests/st201505051611PYTHON"} + declare_test!{StateTests_RandomTests_st201505051648JS, "StateTests/RandomTests/st201505051648JS"} + declare_test!{StateTests_RandomTests_st201505051710GO, "StateTests/RandomTests/st201505051710GO"} + declare_test!{StateTests_RandomTests_st201505052013GO, "StateTests/RandomTests/st201505052013GO"} + declare_test!{StateTests_RandomTests_st201505052102JS, "StateTests/RandomTests/st201505052102JS"} + declare_test!{StateTests_RandomTests_st201505052235GO, "StateTests/RandomTests/st201505052235GO"} + declare_test!{StateTests_RandomTests_st201505052238JS, "StateTests/RandomTests/st201505052238JS"} + declare_test!{StateTests_RandomTests_st201505052242PYTHON, "StateTests/RandomTests/st201505052242PYTHON"} + declare_test!{StateTests_RandomTests_st201505052343PYTHON, "StateTests/RandomTests/st201505052343PYTHON"} + declare_test!{StateTests_RandomTests_st201505060120GO, "StateTests/RandomTests/st201505060120GO"} + declare_test!{StateTests_RandomTests_st201505060121GO, "StateTests/RandomTests/st201505060121GO"} + declare_test!{StateTests_RandomTests_st201505060136PYTHON, "StateTests/RandomTests/st201505060136PYTHON"} + declare_test!{StateTests_RandomTests_st201505060646JS, "StateTests/RandomTests/st201505060646JS"} + declare_test!{StateTests_RandomTests_st201505252314CPPJIT, "StateTests/RandomTests/st201505252314CPPJIT"} + declare_test!{StateTests_RandomTests_st201505272131CPPJIT, "StateTests/RandomTests/st201505272131CPPJIT"} + declare_test!{StateTests_RandomTests_st201506040034GO, "StateTests/RandomTests/st201506040034GO"} + declare_test!{StateTests_RandomTests_st201506040157GO, "StateTests/RandomTests/st201506040157GO"} + declare_test!{StateTests_RandomTests_st201506052130GO, "StateTests/RandomTests/st201506052130GO"} + declare_test!{StateTests_RandomTests_st201506060929GO, "StateTests/RandomTests/st201506060929GO"} + declare_test!{StateTests_RandomTests_st201506061255GO, "StateTests/RandomTests/st201506061255GO"} + declare_test!{StateTests_RandomTests_st201506062331GO, "StateTests/RandomTests/st201506062331GO"} + declare_test!{StateTests_RandomTests_st201506070548GO, "StateTests/RandomTests/st201506070548GO"} + declare_test!{StateTests_RandomTests_st201506071050GO, "StateTests/RandomTests/st201506071050GO"} + declare_test!{StateTests_RandomTests_st201506071624GO, "StateTests/RandomTests/st201506071624GO"} + declare_test!{StateTests_RandomTests_st201506071819GO, "StateTests/RandomTests/st201506071819GO"} + declare_test!{StateTests_RandomTests_st201506072007GO, "StateTests/RandomTests/st201506072007GO"} + declare_test!{StateTests_RandomTests_st201506080556GO, "StateTests/RandomTests/st201506080556GO"} + declare_test!{StateTests_RandomTests_st201506080721GO, "StateTests/RandomTests/st201506080721GO"} + declare_test!{StateTests_RandomTests_st201506091836GO, "StateTests/RandomTests/st201506091836GO"} + declare_test!{StateTests_RandomTests_st201506092032GO, "StateTests/RandomTests/st201506092032GO"} + declare_test!{StateTests_RandomTests_st201506101359JS, "StateTests/RandomTests/st201506101359JS"} + declare_test!{StateTests_RandomTests_st201507030359GO, "StateTests/RandomTests/st201507030359GO"} +} diff --git a/ethcore/src/json_tests/test_common.rs b/ethcore/src/json_tests/test_common.rs index 7f7051bf00f69c271953e54f0698ab5dcb37f661..e77b3df93f255e71519d6bc390dfb703a0ffd5ff 100644 --- a/ethcore/src/json_tests/test_common.rs +++ b/ethcore/src/json_tests/test_common.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -pub use common::*; +pub use util::*; macro_rules! test { ($name: expr) => { diff --git a/ethcore/src/json_tests/transaction.rs b/ethcore/src/json_tests/transaction.rs index a06e3b5dc4f7cdbd57460dc24feb1c5f05157265..50061cbfd68f32af54d0df6ba930c4bcd5318ba4 100644 --- a/ethcore/src/json_tests/transaction.rs +++ b/ethcore/src/json_tests/transaction.rs @@ -18,6 +18,7 @@ use super::test_common::*; use evm; use ethjson; use rlp::{UntrustedRlp, View}; +use transaction::{Action, SignedTransaction}; fn do_json_test(json_data: &[u8]) -> Vec { let tests = ethjson::transaction::Test::load(json_data).unwrap(); diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index c72a977cfbdd364a602267cee4a02172a55aec10..c7f40418cfeca18da18554b63318a3a35a0dad2f 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -101,6 +101,7 @@ extern crate bit_set; extern crate rlp; extern crate ethcore_bloom_journal as bloom_journal; extern crate byteorder; +extern crate transient_hashmap; #[macro_use] extern crate log; @@ -140,7 +141,6 @@ pub mod db; mod cache_manager; mod blooms; -mod common; mod basic_types; mod env_info; mod pod_account; diff --git a/ethcore/src/migrations/state/v7.rs b/ethcore/src/migrations/state/v7.rs index 9af75a8ed3ec7636ceb9534da3e5411d3599634b..49df041eb6425d6bf528418b67abbf6915248871 100644 --- a/ethcore/src/migrations/state/v7.rs +++ b/ethcore/src/migrations/state/v7.rs @@ -154,7 +154,7 @@ impl OverlayRecentV7 { // and commit the altered entries. fn migrate_journal(&self, source: Arc, mut batch: Batch, dest: &mut Database) -> Result<(), Error> { if let Some(val) = try!(source.get(None, V7_LATEST_ERA_KEY).map_err(Error::Custom)) { - try!(batch.insert(V7_LATEST_ERA_KEY.into(), val.to_owned(), dest)); + try!(batch.insert(V7_LATEST_ERA_KEY.into(), val.clone().to_vec(), dest)); let mut era = decode::(&val); loop { diff --git a/ethcore/src/migrations/v10.rs b/ethcore/src/migrations/v10.rs index 88884fb26e71ca653a1042181f2c867bb4a91294..77531eb083052f4e3870f7f995f6b1e12c56f6cf 100644 --- a/ethcore/src/migrations/v10.rs +++ b/ethcore/src/migrations/v10.rs @@ -61,7 +61,7 @@ pub fn generate_bloom(source: Arc, dest: &mut Database) -> Result<(), let account_trie = try!(TrieDB::new(state_db.as_hashdb(), &state_root).map_err(|e| Error::Custom(format!("Cannot open trie: {:?}", e)))); for item in try!(account_trie.iter().map_err(|_| Error::MigrationImpossible)) { let (ref account_key, _) = try!(item.map_err(|_| Error::MigrationImpossible)); - let account_key_hash = H256::from_slice(&account_key); + let account_key_hash = H256::from_slice(account_key); bloom.set(&*account_key_hash); } diff --git a/ethcore/src/miner/banning_queue.rs b/ethcore/src/miner/banning_queue.rs new file mode 100644 index 0000000000000000000000000000000000000000..f127dc7e8e95b5597b0ad0d884fddacc8ec5ed87 --- /dev/null +++ b/ethcore/src/miner/banning_queue.rs @@ -0,0 +1,339 @@ +// 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 . + +//! Banning Queue +//! Transacton Queue wrapper maintaining additional list of banned senders and contract hashes. + +use std::time::Duration; +use std::ops::{Deref, DerefMut}; +use std::cell::Cell; +use transaction::{SignedTransaction, Action}; +use transient_hashmap::TransientHashMap; +use miner::{TransactionQueue, TransactionImportResult, TransactionOrigin, AccountDetails}; +use error::{Error, TransactionError}; +use util::{Uint, U256, H256, Address, Hashable}; + +type Count = u16; + +/// Auto-Banning threshold +pub enum Threshold { + /// Should ban after given number of misbehaves reported. + BanAfter(Count), + /// Should never ban anything + NeverBan +} + +impl Default for Threshold { + fn default() -> Self { + Threshold::NeverBan + } +} + +/// Transaction queue with banlist. +pub struct BanningTransactionQueue { + queue: TransactionQueue, + ban_threshold: Threshold, + senders_bans: TransientHashMap>, + recipients_bans: TransientHashMap>, + codes_bans: TransientHashMap>, +} + +impl BanningTransactionQueue { + /// Creates new banlisting transaction queue + pub fn new(queue: TransactionQueue, ban_threshold: Threshold, ban_lifetime: Duration) -> Self { + let ban_lifetime_sec = ban_lifetime.as_secs(); + assert!(ban_lifetime_sec > 0, "Lifetime has to be specified in seconds."); + BanningTransactionQueue { + queue: queue, + ban_threshold: ban_threshold, + senders_bans: TransientHashMap::new(ban_lifetime_sec), + recipients_bans: TransientHashMap::new(ban_lifetime_sec), + codes_bans: TransientHashMap::new(ban_lifetime_sec), + } + } + + /// Borrows internal queue. + /// NOTE: you can insert transactions to the queue even + /// if they would be rejected because of ban otherwise. + /// But probably you shouldn't. + pub fn queue(&mut self) -> &mut TransactionQueue { + &mut self.queue + } + + /// Add to the queue taking bans into consideration. + /// May reject transaction because of the banlist. + pub fn add_with_banlist( + &mut self, + transaction: SignedTransaction, + account_details: &F, + gas_estimator: &G, + ) -> Result where + F: Fn(&Address) -> AccountDetails, + G: Fn(&SignedTransaction) -> U256, + { + if let Threshold::BanAfter(threshold) = self.ban_threshold { + // NOTE In all checks use direct query to avoid increasing ban timeout. + + // Check sender + if let Ok(sender) = transaction.sender() { + let count = self.senders_bans.direct().get(&sender).map(|v| v.get()).unwrap_or(0); + if count > threshold { + debug!(target: "txqueue", "Ignoring transaction {:?} because sender is banned.", transaction.hash()); + return Err(Error::Transaction(TransactionError::SenderBanned)); + } + } + + // Check recipient + if let Action::Call(recipient) = transaction.action { + let count = self.recipients_bans.direct().get(&recipient).map(|v| v.get()).unwrap_or(0); + if count > threshold { + debug!(target: "txqueue", "Ignoring transaction {:?} because recipient is banned.", transaction.hash()); + return Err(Error::Transaction(TransactionError::RecipientBanned)); + } + } + + // Check code + if let Action::Create = transaction.action { + let code_hash = transaction.data.sha3(); + let count = self.codes_bans.direct().get(&code_hash).map(|v| v.get()).unwrap_or(0); + if count > threshold { + debug!(target: "txqueue", "Ignoring transaction {:?} because code is banned.", transaction.hash()); + return Err(Error::Transaction(TransactionError::CodeBanned)); + } + } + } + self.queue.add(transaction, TransactionOrigin::External, account_details, gas_estimator) + } + + /// Ban transaction with given hash. + /// Transaction has to be in the queue. + /// + /// Bans sender and recipient/code and returns `true` when any ban has reached threshold. + pub fn ban_transaction(&mut self, hash: &H256) -> bool { + let transaction = self.queue.find(hash); + match transaction { + Some(transaction) => { + let sender = transaction.sender().expect("Transaction is in queue, so the sender is already validated; qed"); + // Ban sender + let sender_banned = self.ban_sender(sender); + // Ban recipient and codehash + let recipient_or_code_banned = match transaction.action { + Action::Call(recipient) => { + self.ban_recipient(recipient) + }, + Action::Create => { + self.ban_codehash(transaction.data.sha3()) + }, + }; + sender_banned || recipient_or_code_banned + }, + None => false, + } + } + + /// Ban given sender. + /// If bans threshold is reached all subsequent transactions from this sender will be rejected. + /// Reaching bans threshold also removes all existsing transaction from this sender that are already in the + /// queue. + fn ban_sender(&mut self, address: Address) -> bool { + let count = { + let mut count = self.senders_bans.entry(address).or_insert_with(|| Cell::new(0)); + *count.get_mut() = count.get().saturating_add(1); + count.get() + }; + match self.ban_threshold { + Threshold::BanAfter(threshold) if count > threshold => { + // Banlist the sender. + // Remove all transactions from the queue. + self.remove_all(address, !U256::zero()); + true + }, + _ => false + } + } + + /// Ban given recipient. + /// If bans threshold is reached all subsequent transactions to this address will be rejected. + /// Returns true if bans threshold has been reached. + fn ban_recipient(&mut self, address: Address) -> bool { + let count = { + let mut count = self.recipients_bans.entry(address).or_insert_with(|| Cell::new(0)); + *count.get_mut() = count.get().saturating_add(1); + count.get() + }; + match self.ban_threshold { + // TODO [ToDr] Consider removing other transactions to the same recipient from the queue? + Threshold::BanAfter(threshold) if count > threshold => true, + _ => false + } + } + + + /// Ban given codehash. + /// If bans threshold is reached all subsequent transactions to contracts with this codehash will be rejected. + /// Returns true if bans threshold has been reached. + fn ban_codehash(&mut self, code_hash: H256) -> bool { + let mut count = self.codes_bans.entry(code_hash).or_insert_with(|| Cell::new(0)); + *count.get_mut() = count.get().saturating_add(1); + + match self.ban_threshold { + // TODO [ToDr] Consider removing other transactions with the same code from the queue? + Threshold::BanAfter(threshold) if count.get() > threshold => true, + _ => false, + } + } +} + +impl Deref for BanningTransactionQueue { + type Target = TransactionQueue; + + fn deref(&self) -> &Self::Target { + &self.queue + } +} +impl DerefMut for BanningTransactionQueue { + fn deref_mut(&mut self) -> &mut Self::Target { + self.queue() + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + use super::{BanningTransactionQueue, Threshold}; + use ethkey::{Random, Generator}; + use transaction::{Transaction, SignedTransaction, Action}; + use error::{Error, TransactionError}; + use client::TransactionImportResult; + use miner::{TransactionQueue, TransactionOrigin, AccountDetails}; + use util::{Uint, U256, Address, FromHex, Hashable}; + + fn queue() -> BanningTransactionQueue { + BanningTransactionQueue::new(TransactionQueue::default(), Threshold::BanAfter(1), Duration::from_secs(180)) + } + + fn default_account_details(_address: &Address) -> AccountDetails { + AccountDetails { + nonce: U256::zero(), + balance: !U256::zero(), + } + } + + fn gas_required(_tx: &SignedTransaction) -> U256 { + 0.into() + } + + fn transaction(action: Action) -> SignedTransaction { + let keypair = Random.generate().unwrap(); + Transaction { + action: action, + value: U256::from(100), + data: "3331600055".from_hex().unwrap(), + gas: U256::from(100_000), + gas_price: U256::from(10), + nonce: U256::from(0), + }.sign(keypair.secret()) + } + + fn unwrap_err(res: Result) -> TransactionError { + match res { + Err(Error::Transaction(e)) => e, + Ok(x) => panic!("Expected error, got: Ok({:?})", x), + Err(e) => panic!("Unexpected error type returned by queue: {:?}", e), + } + } + + #[test] + fn should_allow_to_borrow_the_queue() { + // given + let tx = transaction(Action::Create); + let mut txq = queue(); + + // when + txq.queue().add(tx, TransactionOrigin::External, &default_account_details, &gas_required).unwrap(); + + // then + // should also deref to queue + assert_eq!(txq.status().pending, 1); + } + + #[test] + fn should_not_accept_transactions_from_banned_sender() { + // given + let tx = transaction(Action::Create); + let mut txq = queue(); + // Banlist once (threshold not reached) + let banlist1 = txq.ban_sender(tx.sender().unwrap()); + assert!(!banlist1, "Threshold not reached yet."); + // Insert once + let import1 = txq.add_with_banlist(tx.clone(), &default_account_details, &gas_required).unwrap(); + assert_eq!(import1, TransactionImportResult::Current); + + // when + let banlist2 = txq.ban_sender(tx.sender().unwrap()); + let import2 = txq.add_with_banlist(tx.clone(), &default_account_details, &gas_required); + + // then + assert!(banlist2, "Threshold should be reached - banned."); + assert_eq!(unwrap_err(import2), TransactionError::SenderBanned); + // Should also remove transacion from the queue + assert_eq!(txq.find(&tx.hash()), None); + } + + #[test] + fn should_not_accept_transactions_to_banned_recipient() { + // given + let recipient = Address::default(); + let tx = transaction(Action::Call(recipient)); + let mut txq = queue(); + // Banlist once (threshold not reached) + let banlist1 = txq.ban_recipient(recipient); + assert!(!banlist1, "Threshold not reached yet."); + // Insert once + let import1 = txq.add_with_banlist(tx.clone(), &default_account_details, &gas_required).unwrap(); + assert_eq!(import1, TransactionImportResult::Current); + + // when + let banlist2 = txq.ban_recipient(recipient); + let import2 = txq.add_with_banlist(tx.clone(), &default_account_details, &gas_required); + + // then + assert!(banlist2, "Threshold should be reached - banned."); + assert_eq!(unwrap_err(import2), TransactionError::RecipientBanned); + } + + #[test] + fn should_not_accept_transactions_with_banned_code() { + // given + let tx = transaction(Action::Create); + let codehash = tx.data.sha3(); + let mut txq = queue(); + // Banlist once (threshold not reached) + let banlist1 = txq.ban_codehash(codehash); + assert!(!banlist1, "Threshold not reached yet."); + // Insert once + let import1 = txq.add_with_banlist(tx.clone(), &default_account_details, &gas_required).unwrap(); + assert_eq!(import1, TransactionImportResult::Current); + + // when + let banlist2 = txq.ban_codehash(codehash); + let import2 = txq.add_with_banlist(tx.clone(), &default_account_details, &gas_required); + + // then + assert!(banlist2, "Threshold should be reached - banned."); + assert_eq!(unwrap_err(import2), TransactionError::CodeBanned); + } +} diff --git a/ethcore/src/miner/miner.rs b/ethcore/src/miner/miner.rs index a2dab447518dedddf478c04851fd2b0a0b5cee06..d36869a749d9dc6293573b6572b65d4b8ab46ad6 100644 --- a/ethcore/src/miner/miner.rs +++ b/ethcore/src/miner/miner.rs @@ -30,7 +30,8 @@ use transaction::{Action, SignedTransaction}; use receipt::{Receipt, RichReceipt}; use spec::Spec; use engines::Engine; -use miner::{MinerService, MinerStatus, TransactionQueue, AccountDetails, TransactionOrigin}; +use miner::{MinerService, MinerStatus, TransactionQueue, PrioritizationStrategy, AccountDetails, TransactionOrigin}; +use miner::banning_queue::{BanningTransactionQueue, Threshold}; use miner::work_notify::WorkPoster; use client::TransactionImportResult; use miner::price_info::PriceInfo; @@ -59,6 +60,22 @@ pub enum GasLimit { Fixed(U256), } +/// Transaction queue banning settings. +#[derive(Debug, PartialEq, Clone)] +pub enum Banning { + /// Banning in transaction queue is disabled + Disabled, + /// Banning in transaction queue is enabled + Enabled { + /// Upper limit of transaction processing time before banning. + offend_threshold: Duration, + /// Number of similar offending transactions before banning. + min_offends: u16, + /// Number of seconds the offender is banned for. + ban_duration: Duration, + }, +} + /// Configures the behaviour of the miner. #[derive(Debug, PartialEq)] pub struct MinerOptions { @@ -76,6 +93,8 @@ pub struct MinerOptions { pub tx_gas_limit: U256, /// Maximum size of the transaction queue. pub tx_queue_size: usize, + /// Strategy to use for prioritizing transactions in the queue. + pub tx_queue_strategy: PrioritizationStrategy, /// Whether we should fallback to providing all the queue's transactions or just pending. pub pending_set: PendingSet, /// How many historical work packages can we store before running out? @@ -84,6 +103,8 @@ pub struct MinerOptions { pub enable_resubmission: bool, /// Global gas limit for all transaction in the queue except for local and retracted. pub tx_queue_gas_limit: GasLimit, + /// Banning settings + pub tx_queue_banning: Banning, } impl Default for MinerOptions { @@ -94,12 +115,14 @@ impl Default for MinerOptions { reseal_on_external_tx: false, reseal_on_own_tx: true, tx_gas_limit: !U256::zero(), - tx_queue_size: 2048, + tx_queue_size: 1024, + tx_queue_gas_limit: GasLimit::Auto, + tx_queue_strategy: PrioritizationStrategy::GasPriceOnly, pending_set: PendingSet::AlwaysQueue, reseal_min_period: Duration::from_secs(2), work_queue_size: 20, enable_resubmission: true, - tx_queue_gas_limit: GasLimit::Auto, + tx_queue_banning: Banning::Disabled, } } } @@ -133,7 +156,7 @@ impl GasPriceCalibrator { let gas_per_tx: f32 = 21000.0; let wei_per_gas: f32 = wei_per_usd * usd_per_tx / gas_per_tx; info!(target: "miner", "Updated conversion rate to Ξ1 = {} ({} wei/gas)", Colour::White.bold().paint(format!("US${}", usd_per_eth)), Colour::Yellow.bold().paint(format!("{}", wei_per_gas))); - set_price(U256::from_dec_str(&format!("{:.0}", wei_per_gas)).unwrap()); + set_price(U256::from(wei_per_gas as u64)); }) { self.next_calibration = Instant::now() + self.options.recalibration_period; } else { @@ -183,7 +206,7 @@ struct SealingWork { /// Handles preparing work for "work sealing" or seals "internally" if Engine does not require work. pub struct Miner { // NOTE [ToDr] When locking always lock in this order! - transaction_queue: Arc>, + transaction_queue: Arc>, sealing_work: Mutex, next_allowed_reseal: Mutex, sealing_block_last_request: Mutex, @@ -212,9 +235,18 @@ impl Miner { GasLimit::Fixed(ref limit) => *limit, _ => !U256::zero(), }; - let txq = Arc::new(Mutex::new(TransactionQueue::with_limits(options.tx_queue_size, gas_limit, options.tx_gas_limit))); + + let txq = TransactionQueue::with_limits(options.tx_queue_strategy, options.tx_queue_size, gas_limit, options.tx_gas_limit); + let txq = match options.tx_queue_banning { + Banning::Disabled => BanningTransactionQueue::new(txq, Threshold::NeverBan, Duration::from_secs(180)), + Banning::Enabled { ban_duration, min_offends, .. } => BanningTransactionQueue::new( + txq, + Threshold::BanAfter(min_offends), + ban_duration, + ), + }; Miner { - transaction_queue: txq, + transaction_queue: Arc::new(Mutex::new(txq)), next_allowed_reseal: Mutex::new(Instant::now()), sealing_block_last_request: Mutex::new(0), sealing_work: Mutex::new(SealingWork{ @@ -277,6 +309,7 @@ impl Miner { trace!(target: "miner", "prepare_block: done recalibration."); } + let _timer = PerfTimer::new("prepare_block"); let (transactions, mut open_block, original_work_hash) = { let transactions = {self.transaction_queue.lock().top_transactions()}; let mut sealing_work = self.sealing_work.lock(); @@ -312,10 +345,31 @@ impl Miner { let mut invalid_transactions = HashSet::new(); let mut transactions_to_penalize = HashSet::new(); let block_number = open_block.block().fields().header.number(); - // TODO: push new uncles, too. + + // TODO Push new uncles too. for tx in transactions { let hash = tx.hash(); - match open_block.push_transaction(tx, None) { + let start = Instant::now(); + let result = open_block.push_transaction(tx, None); + let took = start.elapsed(); + + // Check for heavy transactions + match self.options.tx_queue_banning { + Banning::Enabled { ref offend_threshold, .. } if &took > offend_threshold => { + match self.transaction_queue.lock().ban_transaction(&hash) { + true => { + warn!(target: "miner", "Detected heavy transaction. Banning the sender and recipient/code."); + }, + false => { + transactions_to_penalize.insert(hash); + debug!(target: "miner", "Detected heavy transaction. Penalizing sender.") + } + } + }, + _ => {}, + } + + match result { Err(Error::Execution(ExecutionError::BlockGasLimitReached { gas_limit, gas_used, gas })) => { debug!(target: "miner", "Skipping adding transaction to block because of gas limit: {:?} (limit: {:?}, used: {:?}, gas: {:?})", hash, gas_limit, gas_used, gas); @@ -356,7 +410,7 @@ impl Miner { { let mut queue = self.transaction_queue.lock(); - for hash in invalid_transactions.into_iter() { + for hash in invalid_transactions { queue.remove_invalid(&hash, &fetch_account); } for hash in transactions_to_penalize { @@ -462,8 +516,8 @@ impl Miner { let mut queue = self.transaction_queue.lock(); queue.set_gas_limit(gas_limit); if let GasLimit::Auto = self.options.tx_queue_gas_limit { - // Set total tx queue gas limit to be 2x the block gas limit. - queue.set_total_gas_limit(gas_limit << 1); + // Set total tx queue gas limit to be 20x the block gas limit. + queue.set_total_gas_limit(gas_limit * 20.into()); } } @@ -500,7 +554,7 @@ impl Miner { prepare_new } - fn add_transactions_to_queue(&self, chain: &MiningBlockChainClient, transactions: Vec, origin: TransactionOrigin, transaction_queue: &mut TransactionQueue) -> + fn add_transactions_to_queue(&self, chain: &MiningBlockChainClient, transactions: Vec, origin: TransactionOrigin, transaction_queue: &mut BanningTransactionQueue) -> Vec> { let fetch_account = |a: &Address| AccountDetails { @@ -508,14 +562,25 @@ impl Miner { balance: chain.latest_balance(a), }; + let schedule = chain.latest_schedule(); + let gas_required = |tx: &SignedTransaction| tx.gas_required(&schedule).into(); transactions.into_iter() - .map(|tx| transaction_queue.add(tx, &fetch_account, origin)) + .map(|tx| match origin { + TransactionOrigin::Local | TransactionOrigin::RetractedBlock => { + transaction_queue.add(tx, origin, &fetch_account, &gas_required) + }, + TransactionOrigin::External => { + transaction_queue.add_with_banlist(tx, &fetch_account, &gas_required) + } + }) .collect() } /// Are we allowed to do a non-mandatory reseal? fn tx_reseal_allowed(&self) -> bool { Instant::now() > *self.next_allowed_reseal.lock() } + #[cfg_attr(feature="dev", allow(wrong_self_convention))] + #[cfg_attr(feature="dev", allow(redundant_closure))] fn from_pending_block(&self, latest_block_number: BlockNumber, from_chain: F, map_block: G) -> H where F: Fn() -> H, G: Fn(&ClosedBlock) -> H { let sealing_work = self.sealing_work.lock(); @@ -741,7 +806,7 @@ impl MinerService for Miner { let mut transaction_queue = self.transaction_queue.lock(); let import = self.add_transactions_to_queue( chain, vec![transaction], TransactionOrigin::Local, &mut transaction_queue - ).pop().unwrap(); + ).pop().expect("one result returned per added transaction; one added => one result; qed"); match import { Ok(ref res) => { @@ -863,7 +928,11 @@ impl MinerService for Miner { gas_used: receipt.gas_used - prev_gas, contract_address: match tx.action { Action::Call(_) => None, - Action::Create => Some(contract_address(&tx.sender().unwrap(), &tx.nonce)), + Action::Create => { + let sender = tx.sender() + .expect("transactions in pending block have already been checked for valid sender; qed"); + Some(contract_address(&sender, &tx.nonce)) + } }, logs: receipt.logs.clone(), } @@ -875,7 +944,7 @@ impl MinerService for Miner { fn pending_receipts(&self, best_block: BlockNumber) -> BTreeMap { self.from_pending_block( best_block, - || BTreeMap::new(), + BTreeMap::new, |pending| { let hashes = pending.transactions() .iter() @@ -1009,7 +1078,7 @@ impl MinerService for Miner { tx.sender().expect("Transaction is in block, so sender has to be defined.") }) .collect::>(); - for sender in to_remove.into_iter() { + for sender in to_remove { transaction_queue.remove_all(sender, chain.latest_nonce(&sender)); } }); @@ -1029,7 +1098,7 @@ impl MinerService for Miner { mod tests { use std::time::Duration; - use super::super::MinerService; + use super::super::{MinerService, PrioritizationStrategy}; use super::*; use util::*; use ethkey::{Generator, Random}; @@ -1083,9 +1152,11 @@ mod tests { tx_gas_limit: !U256::zero(), tx_queue_size: 1024, tx_queue_gas_limit: GasLimit::None, + tx_queue_strategy: PrioritizationStrategy::GasFactorAndGasPrice, pending_set: PendingSet::AlwaysSealing, work_queue_size: 5, enable_resubmission: true, + tx_queue_banning: Banning::Disabled, }, GasPricer::new_fixed(0u64.into()), &Spec::new_test(), diff --git a/ethcore/src/miner/mod.rs b/ethcore/src/miner/mod.rs index 8dfddf483a37da383c8b4e6c70012a63ae2f9ec7..da93dc0b7e34546b18ca31bc25812785aa15ee73 100644 --- a/ethcore/src/miner/mod.rs +++ b/ethcore/src/miner/mod.rs @@ -44,11 +44,12 @@ mod miner; mod external; mod transaction_queue; +mod banning_queue; mod work_notify; mod price_info; -pub use self::transaction_queue::{TransactionQueue, AccountDetails, TransactionOrigin}; -pub use self::miner::{Miner, MinerOptions, PendingSet, GasPricer, GasPriceCalibratorOptions, GasLimit}; +pub use self::transaction_queue::{TransactionQueue, PrioritizationStrategy, AccountDetails, TransactionOrigin}; +pub use self::miner::{Miner, MinerOptions, Banning, PendingSet, GasPricer, GasPriceCalibratorOptions, GasLimit}; pub use self::external::{ExternalMiner, ExternalMinerService}; pub use client::TransactionImportResult; @@ -157,7 +158,7 @@ pub trait MinerService : Send + Sync { fn is_sealing(&self) -> bool; /// Suggested gas price. - fn sensible_gas_price(&self) -> U256 { 20000000000u64.into() } + fn sensible_gas_price(&self) -> U256; /// Suggested gas limit. fn sensible_gas_limit(&self) -> U256 { 21000.into() } diff --git a/ethcore/src/miner/price_info.rs b/ethcore/src/miner/price_info.rs index 268a5dfb49f01312b0f8e41dd189a2b7f5895bb8..77bc1ce0f6e11ee45e1b2c729651074bc1b181a1 100644 --- a/ethcore/src/miner/price_info.rs +++ b/ethcore/src/miner/price_info.rs @@ -52,7 +52,8 @@ impl Handler for SetPriceH .and_then(|json| json.find_path(&["result", "ethusd"]) .and_then(|obj| match *obj { Json::String(ref s) => Some((self.set_price)(PriceInfo { - ethusd: FromStr::from_str(s).unwrap() + ethusd: FromStr::from_str(s) + .expect("Etherscan API will always return properly formatted price; qed") })), _ => None, })); @@ -67,10 +68,14 @@ impl PriceInfo { let client = try!(Client::new().map_err(|_| ())); thread::spawn(move || { let (tx, rx) = mpsc::channel(); - let _ = client.request(FromStr::from_str("http://api.etherscan.io/api?module=stats&action=ethprice").unwrap(), SetPriceHandler { - set_price: set_price, - channel: tx, - }).ok().and_then(|_| rx.recv().ok()); + let url = FromStr::from_str("http://api.etherscan.io/api?module=stats&action=ethprice") + .expect("string known to be a valid URL; qed"); + let _ = client.request( + url, + SetPriceHandler { + set_price: set_price, + channel: tx, + }).ok().and_then(|_| rx.recv().ok()); client.close(); }); Ok(()) diff --git a/ethcore/src/miner/transaction_queue.rs b/ethcore/src/miner/transaction_queue.rs index fdb652780a65f2de668cfd9f01e3f568957f224f..190fc455562e895abe7a94891de2a5e2c61cd5cb 100644 --- a/ethcore/src/miner/transaction_queue.rs +++ b/ethcore/src/miner/transaction_queue.rs @@ -48,10 +48,11 @@ //! nonce: U256::from(10), //! balance: U256::from(1_000_000), //! }; +//! let gas_estimator = |_tx: &SignedTransaction| 2.into(); //! -//! let mut txq = TransactionQueue::new(); -//! txq.add(st2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); -//! txq.add(st1.clone(), &default_account_details, TransactionOrigin::External).unwrap(); +//! let mut txq = TransactionQueue::default(); +//! txq.add(st2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); +//! txq.add(st1.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); //! //! // Check status //! assert_eq!(txq.status().pending, 2); @@ -109,6 +110,7 @@ impl PartialOrd for TransactionOrigin { } impl Ord for TransactionOrigin { + #[cfg_attr(feature="dev", allow(match_same_arms))] fn cmp(&self, other: &TransactionOrigin) -> Ordering { if *other == *self { return Ordering::Equal; @@ -130,11 +132,20 @@ struct TransactionOrder { /// (e.g. Tx(nonce:5), State(nonce:0) -> height: 5) /// High nonce_height = Low priority (processed later) nonce_height: U256, - /// Gas specified in the transaction. - gas: U256, /// Gas Price of the transaction. /// Low gas price = Low priority (processed later) gas_price: U256, + /// Gas usage priority factor. Usage depends on strategy. + /// Represents the linear increment in required gas price for heavy transactions. + /// + /// High gas limit + Low gas price = Low priority + /// High gas limit + High gas price = High priority + gas_factor: U256, + /// Gas (limit) of the transaction. Usage depends on strategy. + /// Low gas limit = High priority (processed earlier) + gas: U256, + /// Transaction ordering strategy + strategy: PrioritizationStrategy, /// Hash to identify associated transaction hash: H256, /// Origin of the transaction @@ -145,11 +156,15 @@ struct TransactionOrder { impl TransactionOrder { - fn for_transaction(tx: &VerifiedTransaction, base_nonce: U256) -> Self { + + fn for_transaction(tx: &VerifiedTransaction, base_nonce: U256, min_gas_price: U256, strategy: PrioritizationStrategy) -> Self { + let factor = (tx.transaction.gas >> 15) * min_gas_price; TransactionOrder { nonce_height: tx.nonce() - base_nonce, - gas: tx.transaction.gas.clone(), gas_price: tx.transaction.gas_price, + gas: tx.transaction.gas, + gas_factor: factor, + strategy: strategy, hash: tx.hash(), origin: tx.origin, penalties: 0, @@ -197,11 +212,28 @@ impl Ord for TransactionOrder { return self.origin.cmp(&b.origin); } + match self.strategy { + PrioritizationStrategy::GasAndGasPrice => { + if self.gas != b.gas { + return self.gas.cmp(&b.gas); + } + }, + PrioritizationStrategy::GasFactorAndGasPrice => { + // avoiding overflows + // (gp1 - g1) > (gp2 - g2) <=> + // (gp1 + g2) > (gp2 + g1) + let f_a = self.gas_price + b.gas_factor; + let f_b = b.gas_price + self.gas_factor; + if f_a != f_b { + return f_b.cmp(&f_a); + } + }, + PrioritizationStrategy::GasPriceOnly => {}, + } + // Then compare gas_prices - let a_gas = self.gas_price; - let b_gas = b.gas_price; - if a_gas != b_gas { - return b_gas.cmp(&a_gas); + if self.gas_price != b.gas_price { + return b.gas_price.cmp(&self.gas_price); } // Compare hashes @@ -326,14 +358,14 @@ impl TransactionSet { let to_drop : Vec<(Address, U256)> = { self.by_priority .iter() - .skip_while(|order| { + .filter(|order| { count = count + 1; let r = gas.overflowing_add(order.gas); if r.1 { return false } gas = r.0; - // Own and retracted transactions are allowed to go above the gas limit, bot not above the count limit. - (gas <= self.gas_limit || order.origin == TransactionOrigin::Local || order.origin == TransactionOrigin::RetractedBlock) && - count <= self.limit + // Own and retracted transactions are allowed to go above all limits. + order.origin != TransactionOrigin::Local && order.origin != TransactionOrigin::RetractedBlock && + (gas > self.gas_limit || count > self.limit) }) .map(|order| by_hash.get(&order.hash) .expect("All transactions in `self.by_priority` and `self.by_address` are kept in sync with `by_hash`.")) @@ -345,6 +377,7 @@ impl TransactionSet { .fold(HashMap::new(), |mut removed, (sender, nonce)| { let order = self.drop(&sender, &nonce) .expect("Transaction has just been found in `by_priority`; so it is in `by_address` also."); + trace!(target: "txqueue", "Dropped out of limit transaction: {:?}", order.hash); by_hash.remove(&order.hash) .expect("hash is in `by_priorty`; all hashes in `by_priority` must be in `by_hash`; qed"); @@ -414,8 +447,33 @@ pub struct AccountDetails { /// Transactions with `gas > (gas_limit + gas_limit * Factor(in percents))` are not imported to the queue. const GAS_LIMIT_HYSTERESIS: usize = 10; // (100/GAS_LIMIT_HYSTERESIS) % +/// Describes the strategy used to prioritize transactions in the queue. +#[cfg_attr(feature="dev", allow(enum_variant_names))] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum PrioritizationStrategy { + /// Use only gas price. Disregards the actual computation cost of the transaction. + /// i.e. Higher gas price = Higher priority + GasPriceOnly, + /// Use gas limit and then gas price. + /// i.e. Higher gas limit = Lower priority + GasAndGasPrice, + /// Calculate and use priority based on gas and gas price. + /// PRIORITY = GAS_PRICE - GAS/2^15 * MIN_GAS_PRICE + /// + /// Rationale: + /// Heavy transactions are paying linear cost (GAS * GAS_PRICE) + /// while the computation might be more expensive. + /// + /// i.e. + /// 1M gas tx with `gas_price=30*min` has the same priority + /// as 32k gas tx with `gas_price=min` + GasFactorAndGasPrice, +} + /// `TransactionQueue` implementation pub struct TransactionQueue { + /// Prioritization strategy for this queue + strategy: PrioritizationStrategy, /// Gas Price threshold for transactions that can be imported to this queue (defaults to 0) minimal_gas_price: U256, /// The maximum amount of gas any individual transaction may use. @@ -434,18 +492,18 @@ pub struct TransactionQueue { impl Default for TransactionQueue { fn default() -> Self { - TransactionQueue::new() + TransactionQueue::new(PrioritizationStrategy::GasPriceOnly) } } impl TransactionQueue { /// Creates new instance of this Queue - pub fn new() -> Self { - Self::with_limits(1024, !U256::zero(), !U256::zero()) + pub fn new(strategy: PrioritizationStrategy) -> Self { + Self::with_limits(strategy, 1024, !U256::zero(), !U256::zero()) } /// Create new instance of this Queue with specified limits - pub fn with_limits(limit: usize, gas_limit: U256, tx_gas_limit: U256) -> Self { + pub fn with_limits(strategy: PrioritizationStrategy, limit: usize, gas_limit: U256, tx_gas_limit: U256) -> Self { let current = TransactionSet { by_priority: BTreeSet::new(), by_address: Table::new(), @@ -463,6 +521,7 @@ impl TransactionQueue { }; TransactionQueue { + strategy: strategy, minimal_gas_price: U256::zero(), tx_gas_limit: tx_gas_limit, gas_limit: !U256::zero(), @@ -536,9 +595,20 @@ impl TransactionQueue { } } - /// Add signed transaction to queue to be verified and imported - pub fn add(&mut self, tx: SignedTransaction, fetch_account: &T, origin: TransactionOrigin) -> Result - where T: Fn(&Address) -> AccountDetails { + /// Add signed transaction to queue to be verified and imported. + /// + /// NOTE fetch_account and gas_estimator should be cheap to compute + /// otherwise it might open up an attack vector. + pub fn add( + &mut self, + tx: SignedTransaction, + origin: TransactionOrigin, + fetch_account: &F, + gas_estimator: &G, + ) -> Result where + F: Fn(&Address) -> AccountDetails, + G: Fn(&SignedTransaction) -> U256, + { if tx.gas_price < self.minimal_gas_price && origin != TransactionOrigin::Local { trace!(target: "txqueue", @@ -569,8 +639,6 @@ impl TransactionQueue { })); } - try!(tx.check_low_s()); - if tx.gas > self.gas_limit || tx.gas > self.tx_gas_limit { trace!(target: "txqueue", "Dropping transaction above gas limit: {:?} ({} > min({}, {}))", @@ -586,6 +654,24 @@ impl TransactionQueue { })); } + let minimal_gas = gas_estimator(&tx); + if tx.gas < minimal_gas { + trace!(target: "txqueue", + "Dropping transaction with insufficient gas: {:?} ({} > {})", + tx.hash(), + tx.gas, + minimal_gas, + ); + + return Err(Error::Transaction(TransactionError::InsufficientGas { + minimal: minimal_gas, + got: tx.gas, + })); + } + + // Verify signature + try!(tx.check_low_s()); + let vtx = try!(VerifiedTransaction::new(tx, origin)); let client_account = fetch_account(&vtx.sender()); @@ -644,7 +730,7 @@ impl TransactionQueue { None => vec![], }; for k in nonces_from_sender { - let order = self.current.drop(&sender, &k).unwrap(); + let order = self.current.drop(&sender, &k).expect("transaction known to be in self.current; qed"); self.current.insert(sender, k, order.penalize()); } // Same thing for future @@ -653,7 +739,7 @@ impl TransactionQueue { None => vec![], }; for k in nonces_from_sender { - let order = self.future.drop(&sender, &k).unwrap(); + let order = self.future.drop(&sender, &k).expect("transaction known to be in self.future; qed"); self.future.insert(sender, k, order.penalize()); } } @@ -678,6 +764,8 @@ impl TransactionQueue { let nonce = transaction.nonce(); let current_nonce = fetch_account(&sender).nonce; + trace!(target: "txqueue", "Removing invalid transaction: {:?}", transaction.hash()); + // Remove from future let order = self.future.drop(&sender, &nonce); if order.is_some() { @@ -841,6 +929,7 @@ impl TransactionQueue { return Err(TransactionError::AlreadyImported); } + let min_gas_price = (self.minimal_gas_price, self.strategy); let address = tx.sender(); let nonce = tx.nonce(); let hash = tx.hash(); @@ -878,7 +967,7 @@ impl TransactionQueue { if nonce > next_nonce { // We have a gap - put to future. // Insert transaction (or replace old one with lower gas price) - try!(check_too_cheap(Self::replace_transaction(tx, state_nonce, &mut self.future, &mut self.by_hash))); + try!(check_too_cheap(Self::replace_transaction(tx, state_nonce, min_gas_price, &mut self.future, &mut self.by_hash))); // Enforce limit in Future let removed = self.future.enforce_limit(&mut self.by_hash); // Return an error if this transaction was not imported because of limit. @@ -894,7 +983,7 @@ impl TransactionQueue { self.move_matching_future_to_current(address, nonce + U256::one(), state_nonce); // Replace transaction if any - try!(check_too_cheap(Self::replace_transaction(tx, state_nonce, &mut self.current, &mut self.by_hash))); + try!(check_too_cheap(Self::replace_transaction(tx, state_nonce, min_gas_price, &mut self.current, &mut self.by_hash))); // Keep track of highest nonce stored in current let new_max = self.last_nonces.get(&address).map_or(nonce, |n| cmp::max(nonce, *n)); self.last_nonces.insert(address, new_max); @@ -931,8 +1020,8 @@ impl TransactionQueue { /// /// Returns `true` if transaction actually got to the queue (`false` if there was already a transaction with higher /// gas_price) - fn replace_transaction(tx: VerifiedTransaction, base_nonce: U256, set: &mut TransactionSet, by_hash: &mut HashMap) -> bool { - let order = TransactionOrder::for_transaction(&tx, base_nonce); + fn replace_transaction(tx: VerifiedTransaction, base_nonce: U256, min_gas_price: (U256, PrioritizationStrategy), set: &mut TransactionSet, by_hash: &mut HashMap) -> bool { + let order = TransactionOrder::for_transaction(&tx, base_nonce, min_gas_price.0, min_gas_price.1); let hash = tx.hash(); let address = tx.sender(); let nonce = tx.nonce(); @@ -953,12 +1042,14 @@ impl TransactionQueue { let old_fee = old.gas_price; let new_fee = order.gas_price; if old_fee.cmp(&new_fee) == Ordering::Greater { + trace!(target: "txqueue", "Didn't insert transaction because gas price was too low: {:?} ({:?} stays in the queue)", order.hash, old.hash); // Put back old transaction since it has greater priority (higher gas_price) set.insert(address, nonce, old); // and remove new one by_hash.remove(&order.hash).expect("The hash has been just inserted and no other line is altering `by_hash`."); false } else { + trace!(target: "txqueue", "Replaced transaction: {:?} with transaction with higher gas price: {:?}", old.hash, order.hash); // Make sure we remove old transaction entirely by_hash.remove(&old.hash).expect("The hash is coming from `future` so it has to be in `by_hash`."); true @@ -1010,12 +1101,12 @@ mod test { fn default_gas_val() -> U256 { 100_000.into() } fn default_gas_price() -> U256 { 1.into() } - fn new_unsigned_tx(nonce: U256, gas_price: U256) -> Transaction { + fn new_unsigned_tx(nonce: U256, gas: U256, gas_price: U256) -> Transaction { Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), - gas: default_gas_val(), + gas: gas, gas_price: gas_price, nonce: nonce } @@ -1023,7 +1114,12 @@ mod test { fn new_tx(nonce: U256, gas_price: U256) -> SignedTransaction { let keypair = Random.generate().unwrap(); - new_unsigned_tx(nonce, gas_price).sign(keypair.secret()) + new_unsigned_tx(nonce, default_gas_val(), gas_price).sign(keypair.secret()) + } + + 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()) } fn new_tx_default() -> SignedTransaction { @@ -1037,9 +1133,13 @@ mod test { } } + fn gas_estimator(_tx: &SignedTransaction) -> U256 { + U256::zero() + } + fn new_tx_pair(nonce: U256, gas_price: U256, nonce_increment: U256, gas_price_increment: U256) -> (SignedTransaction, SignedTransaction) { - let tx1 = new_unsigned_tx(nonce, gas_price); - let tx2 = new_unsigned_tx(nonce + nonce_increment, gas_price + gas_price_increment); + let tx1 = new_unsigned_tx(nonce, default_gas_val(), gas_price); + let tx2 = new_unsigned_tx(nonce + nonce_increment, default_gas_val(), gas_price + gas_price_increment); let keypair = Random.generate().unwrap(); let secret = &keypair.secret(); @@ -1049,8 +1149,8 @@ mod test { /// Returns two consecutive transactions, both with increased gas price fn new_tx_pair_with_gas_price_increment(gas_price_increment: U256) -> (SignedTransaction, SignedTransaction) { let gas = default_gas_price() + gas_price_increment; - let tx1 = new_unsigned_tx(default_nonce(), gas); - let tx2 = new_unsigned_tx(default_nonce() + 1.into(), gas); + let tx1 = new_unsigned_tx(default_nonce(), default_gas_val(), gas); + let tx2 = new_unsigned_tx(default_nonce() + 1.into(), default_gas_val(), gas); let keypair = Random.generate().unwrap(); let secret = &keypair.secret(); @@ -1077,21 +1177,25 @@ mod test { assert_eq!(TransactionOrigin::External.cmp(&TransactionOrigin::RetractedBlock), Ordering::Greater); } + fn transaction_order(tx: &VerifiedTransaction, nonce: U256) -> TransactionOrder { + TransactionOrder::for_transaction(tx, nonce, 0.into(), PrioritizationStrategy::GasPriceOnly) + } + #[test] fn should_return_correct_nonces_when_dropped_because_of_limit() { // given - let mut txq = TransactionQueue::with_limits(2, !U256::zero(), !U256::zero()); + let mut txq = TransactionQueue::with_limits(PrioritizationStrategy::GasPriceOnly, 2, !U256::zero(), !U256::zero()); let (tx1, tx2) = new_tx_pair(123.into(), 1.into(), 1.into(), 0.into()); let sender = tx1.sender().unwrap(); let nonce = tx1.nonce; - txq.add(tx1.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx1.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 2); - assert_eq!(txq.last_nonce(&sender), Some(nonce + U256::one())); + assert_eq!(txq.last_nonce(&sender), Some(nonce + 1.into())); // when let tx = new_tx(123.into(), 1.into()); - let res = txq.add(tx.clone(), &default_account_details, TransactionOrigin::External); + let res = txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator); // then // No longer the case as we don't even consider a transaction that isn't above a full @@ -1133,9 +1237,9 @@ mod test { x }; // Insert both transactions - let order1 = TransactionOrder::for_transaction(&tx1, U256::zero()); + let order1 = transaction_order(&tx1, U256::zero()); set.insert(tx1.sender(), tx1.nonce(), order1.clone()); - let order2 = TransactionOrder::for_transaction(&tx2, U256::zero()); + let order2 = transaction_order(&tx2, U256::zero()); set.insert(tx2.sender(), tx2.nonce(), order2.clone()); assert_eq!(set.by_priority.len(), 2); assert_eq!(set.by_address.len(), 2); @@ -1176,7 +1280,7 @@ mod test { x }; // Insert both transactions - let order1 = TransactionOrder::for_transaction(&tx1, U256::zero()); + let order1 = transaction_order(&tx1, U256::zero()); set.insert(tx1.sender(), tx1.nonce(), order1.clone()); assert_eq!(set.by_priority.len(), 1); assert_eq!(set.by_address.len(), 1); @@ -1184,7 +1288,7 @@ mod test { assert_eq!(*set.by_gas_price.iter().next().unwrap().0, 1.into()); assert_eq!(set.by_gas_price.iter().next().unwrap().1.len(), 1); // Two different orders (imagine nonce changed in the meantime) - let order2 = TransactionOrder::for_transaction(&tx2, U256::one()); + let order2 = transaction_order(&tx2, U256::one()); set.insert(tx2.sender(), tx2.nonce(), order2.clone()); assert_eq!(set.by_priority.len(), 1); assert_eq!(set.by_address.len(), 1); @@ -1213,10 +1317,10 @@ mod test { }; let tx = new_tx_default(); let tx1 = VerifiedTransaction::new(tx.clone(), TransactionOrigin::External).unwrap(); - let order1 = TransactionOrder::for_transaction(&tx1, U256::zero()); + let order1 = TransactionOrder::for_transaction(&tx1, 0.into(), 1.into(), PrioritizationStrategy::GasPriceOnly); assert!(set.insert(tx1.sender(), tx1.nonce(), order1).is_none()); let tx2 = VerifiedTransaction::new(tx, TransactionOrigin::External).unwrap(); - let order2 = TransactionOrder::for_transaction(&tx2, U256::zero()); + let order2 = TransactionOrder::for_transaction(&tx2, 0.into(), 1.into(), PrioritizationStrategy::GasPriceOnly); assert!(set.insert(tx2.sender(), tx2.nonce(), order2).is_some()); } @@ -1233,7 +1337,7 @@ mod test { assert_eq!(set.gas_price_entry_limit(), 0.into()); let tx = new_tx_default(); let tx1 = VerifiedTransaction::new(tx.clone(), TransactionOrigin::External).unwrap(); - let order1 = TransactionOrder::for_transaction(&tx1, U256::zero()); + let order1 = TransactionOrder::for_transaction(&tx1, 0.into(), 1.into(), PrioritizationStrategy::GasPriceOnly); assert!(set.insert(tx1.sender(), tx1.nonce(), order1.clone()).is_none()); assert_eq!(set.gas_price_entry_limit(), 2.into()); } @@ -1241,18 +1345,18 @@ mod test { #[test] fn should_handle_same_transaction_imported_twice_with_different_state_nonces() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_similar_tx_pair(); let prev_nonce = |a: &Address| AccountDetails{ nonce: default_account_details(a).nonce - U256::one(), balance: !U256::zero() }; // First insert one transaction to future - let res = txq.add(tx, &prev_nonce, TransactionOrigin::External); + let res = txq.add(tx, TransactionOrigin::External, &prev_nonce, &gas_estimator); assert_eq!(res.unwrap(), TransactionImportResult::Future); assert_eq!(txq.status().future, 1); // now import second transaction to current - let res = txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External); + let res = txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator); // and then there should be only one transaction in current (the one with higher gas_price) assert_eq!(res.unwrap(), TransactionImportResult::Current); @@ -1266,18 +1370,18 @@ mod test { #[test] fn should_move_all_transactions_from_future() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 1.into()); let prev_nonce = |a: &Address| AccountDetails{ nonce: default_account_details(a).nonce - U256::one(), balance: !U256::zero() }; // First insert one transaction to future - let res = txq.add(tx.clone(), &prev_nonce, TransactionOrigin::External); + let res = txq.add(tx.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator); assert_eq!(res.unwrap(), TransactionImportResult::Future); assert_eq!(txq.status().future, 1); // now import second transaction to current - let res = txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External); + let res = txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator); // then assert_eq!(res.unwrap(), TransactionImportResult::Current); @@ -1292,11 +1396,11 @@ mod test { #[test] fn should_import_tx() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); // when - let res = txq.add(tx, &default_account_details, TransactionOrigin::External); + let res = txq.add(tx, TransactionOrigin::External, &default_account_details, &gas_estimator); // then assert_eq!(res.unwrap(), TransactionImportResult::Current); @@ -1304,10 +1408,77 @@ mod test { assert_eq!(stats.pending, 1); } + #[test] + fn should_order_by_gas() { + // given + let mut txq = TransactionQueue::new(PrioritizationStrategy::GasAndGasPrice); + let tx1 = new_tx_with_gas(50000.into(), 40.into()); + let tx2 = new_tx_with_gas(40000.into(), 30.into()); + let tx3 = new_tx_with_gas(30000.into(), 10.into()); + let tx4 = new_tx_with_gas(50000.into(), 20.into()); + txq.set_minimal_gas_price(15.into()); + + // when + let res1 = txq.add(tx1, TransactionOrigin::External, &default_account_details, &gas_estimator); + let res2 = txq.add(tx2, TransactionOrigin::External, &default_account_details, &gas_estimator); + let res3 = txq.add(tx3, TransactionOrigin::External, &default_account_details, &gas_estimator); + let res4 = txq.add(tx4, TransactionOrigin::External, &default_account_details, &gas_estimator); + + // then + assert_eq!(res1.unwrap(), TransactionImportResult::Current); + assert_eq!(res2.unwrap(), TransactionImportResult::Current); + assert_eq!(unwrap_tx_err(res3), TransactionError::InsufficientGasPrice { + minimal: U256::from(15), + got: U256::from(10), + }); + assert_eq!(res4.unwrap(), TransactionImportResult::Current); + let stats = txq.status(); + assert_eq!(stats.pending, 3); + assert_eq!(txq.top_transactions()[0].gas, 40000.into()); + assert_eq!(txq.top_transactions()[1].gas, 50000.into()); + assert_eq!(txq.top_transactions()[2].gas, 50000.into()); + assert_eq!(txq.top_transactions()[1].gas_price, 40.into()); + assert_eq!(txq.top_transactions()[2].gas_price, 20.into()); + } + + #[test] + fn should_order_by_gas_factor() { + // given + let mut txq = TransactionQueue::new(PrioritizationStrategy::GasFactorAndGasPrice); + + let tx1 = new_tx_with_gas(150_000.into(), 40.into()); + let tx2 = new_tx_with_gas(40_000.into(), 16.into()); + let tx3 = new_tx_with_gas(30_000.into(), 15.into()); + let tx4 = new_tx_with_gas(150_000.into(), 62.into()); + txq.set_minimal_gas_price(15.into()); + + // when + let res1 = txq.add(tx1, TransactionOrigin::External, &default_account_details, &gas_estimator); + let res2 = txq.add(tx2, TransactionOrigin::External, &default_account_details, &gas_estimator); + let res3 = txq.add(tx3, TransactionOrigin::External, &default_account_details, &gas_estimator); + let res4 = txq.add(tx4, TransactionOrigin::External, &default_account_details, &gas_estimator); + + // then + assert_eq!(res1.unwrap(), TransactionImportResult::Current); + assert_eq!(res2.unwrap(), TransactionImportResult::Current); + assert_eq!(res3.unwrap(), TransactionImportResult::Current); + assert_eq!(res4.unwrap(), TransactionImportResult::Current); + let stats = txq.status(); + assert_eq!(stats.pending, 4); + assert_eq!(txq.top_transactions()[0].gas, 30_000.into()); + assert_eq!(txq.top_transactions()[1].gas, 150_000.into()); + assert_eq!(txq.top_transactions()[2].gas, 40_000.into()); + assert_eq!(txq.top_transactions()[3].gas, 150_000.into()); + assert_eq!(txq.top_transactions()[0].gas_price, 15.into()); + assert_eq!(txq.top_transactions()[1].gas_price, 62.into()); + assert_eq!(txq.top_transactions()[2].gas_price, 16.into()); + assert_eq!(txq.top_transactions()[3].gas_price, 40.into()); + } + #[test] fn gas_limit_should_never_overflow() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); txq.set_gas_limit(U256::zero()); assert_eq!(txq.gas_limit, U256::zero()); @@ -1321,14 +1492,14 @@ mod test { #[test] fn should_not_import_transaction_above_gas_limit() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); let gas = tx.gas; let limit = gas / U256::from(2); txq.set_gas_limit(limit); // when - let res = txq.add(tx, &default_account_details, TransactionOrigin::External); + let res = txq.add(tx, TransactionOrigin::External, &default_account_details, &gas_estimator); // then assert_eq!(unwrap_tx_err(res), TransactionError::GasLimitExceeded { @@ -1344,7 +1515,7 @@ mod test { #[test] fn should_drop_transactions_from_senders_without_balance() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); let account = |a: &Address| AccountDetails { nonce: default_account_details(a).nonce, @@ -1352,7 +1523,7 @@ mod test { }; // when - let res = txq.add(tx, &account, TransactionOrigin::External); + let res = txq.add(tx, TransactionOrigin::External, &account, &gas_estimator); // then assert_eq!(unwrap_tx_err(res), TransactionError::InsufficientBalance { @@ -1367,12 +1538,12 @@ mod test { #[test] fn should_not_import_transaction_below_min_gas_price_threshold_if_external() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); txq.set_minimal_gas_price(tx.gas_price + U256::one()); // when - let res = txq.add(tx, &default_account_details, TransactionOrigin::External); + let res = txq.add(tx, TransactionOrigin::External, &default_account_details, &gas_estimator); // then assert_eq!(unwrap_tx_err(res), TransactionError::InsufficientGasPrice { @@ -1387,12 +1558,12 @@ mod test { #[test] fn should_import_transaction_below_min_gas_price_threshold_if_local() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); txq.set_minimal_gas_price(tx.gas_price + U256::one()); // when - let res = txq.add(tx, &default_account_details, TransactionOrigin::Local); + let res = txq.add(tx, TransactionOrigin::Local, &default_account_details, &gas_estimator); // then assert_eq!(res.unwrap(), TransactionImportResult::Current); @@ -1406,8 +1577,8 @@ mod test { use rlp::{self, RlpStream, Stream}; // given - let mut txq = TransactionQueue::new(); - let tx = new_unsigned_tx(123.into(), 1.into()); + let mut txq = TransactionQueue::default(); + let tx = new_unsigned_tx(123.into(), 100.into(), 1.into()); let stx = { let mut s = RlpStream::new_list(9); s.append(&tx.nonce); @@ -1422,7 +1593,7 @@ mod test { rlp::decode(s.as_raw()) }; // when - let res = txq.add(stx, &default_account_details, TransactionOrigin::External); + let res = txq.add(stx, TransactionOrigin::External, &default_account_details, &gas_estimator); // then assert!(res.is_err()); @@ -1431,13 +1602,13 @@ mod test { #[test] fn should_import_txs_from_same_sender() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); // when - txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then let top = txq.top_transactions(); @@ -1449,16 +1620,16 @@ mod test { #[test] fn should_prioritize_local_transactions_within_same_nonce_height() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); // the second one has same nonce but higher `gas_price` let (_, tx2) = new_similar_tx_pair(); // when // first insert the one with higher gas price - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then the one with lower gas price, but local - txq.add(tx.clone(), &default_account_details, TransactionOrigin::Local).unwrap(); + txq.add(tx.clone(), TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); // then let top = txq.top_transactions(); @@ -1470,16 +1641,16 @@ mod test { #[test] fn should_prioritize_reimported_transactions_within_same_nonce_height() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); // the second one has same nonce but higher `gas_price` let (_, tx2) = new_similar_tx_pair(); // when // first insert local one with higher gas price - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::Local).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); // then the one with lower gas price, but from retracted block - txq.add(tx.clone(), &default_account_details, TransactionOrigin::RetractedBlock).unwrap(); + txq.add(tx.clone(), TransactionOrigin::RetractedBlock, &default_account_details, &gas_estimator).unwrap(); // then let top = txq.top_transactions(); @@ -1491,12 +1662,12 @@ mod test { #[test] fn should_not_prioritize_local_transactions_with_different_nonce_height() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); // when - txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::Local).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); // then let top = txq.top_transactions(); @@ -1509,16 +1680,16 @@ mod test { fn should_penalize_transactions_from_sender_in_future() { // given let prev_nonce = |a: &Address| AccountDetails{ nonce: default_account_details(a).nonce - U256::one(), balance: !U256::zero() }; - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); // txa, txb - slightly bigger gas price to have consistent ordering let (txa, txb) = new_tx_pair_default(1.into(), 0.into()); let (tx1, tx2) = new_tx_pair_with_gas_price_increment(3.into()); // insert everything - txq.add(txa.clone(), &prev_nonce, TransactionOrigin::External).unwrap(); - txq.add(txb.clone(), &prev_nonce, TransactionOrigin::External).unwrap(); - txq.add(tx1.clone(), &prev_nonce, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &prev_nonce, TransactionOrigin::External).unwrap(); + txq.add(txa.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(); + txq.add(txb.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(); + txq.add(tx1.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 4); @@ -1538,16 +1709,16 @@ mod test { #[test] fn should_penalize_transactions_from_sender() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); // txa, txb - slightly bigger gas price to have consistent ordering let (txa, txb) = new_tx_pair_default(1.into(), 0.into()); let (tx1, tx2) = new_tx_pair_with_gas_price_increment(3.into()); // insert everything - txq.add(txa.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(txb.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx1.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(txa.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(txb.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx1.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); let top = txq.top_transactions(); assert_eq!(top[0], tx1); @@ -1571,13 +1742,13 @@ mod test { #[test] fn should_return_pending_hashes() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); // when - txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then let top = txq.pending_hashes(); @@ -1589,13 +1760,13 @@ mod test { #[test] fn should_put_transaction_to_futures_if_gap_detected() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(2.into(), 0.into()); // when - let res1 = txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - let res2 = txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + let res1 = txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + let res2 = txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then assert_eq!(res1, TransactionImportResult::Current); @@ -1615,11 +1786,11 @@ mod test { !U256::zero() }; let next2_nonce = default_nonce() + U256::from(3); - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); - txq.add(tx.clone(), &prev_nonce, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &prev_nonce, TransactionOrigin::External).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 2); // when @@ -1634,20 +1805,20 @@ mod test { #[test] fn should_move_transactions_if_gap_filled() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let kp = Random.generate().unwrap(); let secret = kp.secret(); - let tx = new_unsigned_tx(123.into(), 1.into()).sign(secret); - let tx1 = new_unsigned_tx(124.into(), 1.into()).sign(secret); - let tx2 = new_unsigned_tx(125.into(), 1.into()).sign(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); - txq.add(tx, &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 1); - txq.add(tx2, &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx2, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 1); // when - txq.add(tx1, &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx1, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then let stats = txq.status(); @@ -1661,10 +1832,10 @@ mod test { #[test] fn should_remove_transaction() { // given - let mut txq2 = TransactionQueue::new(); + let mut txq2 = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(3.into(), 0.into()); - txq2.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq2.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq2.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq2.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq2.status().pending, 1); assert_eq!(txq2.status().future, 1); @@ -1682,13 +1853,13 @@ mod test { #[test] fn should_move_transactions_to_future_if_gap_introduced() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); let tx3 = new_tx_default(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 1); - txq.add(tx3.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx3.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 3); // when @@ -1703,12 +1874,12 @@ mod test { #[test] fn should_clear_queue() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); // add - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); let stats = txq.status(); assert_eq!(stats.pending, 2); @@ -1723,15 +1894,15 @@ mod test { #[test] fn should_drop_old_transactions_when_hitting_the_limit() { // given - let mut txq = TransactionQueue::with_limits(1, !U256::zero(), !U256::zero()); + let mut txq = TransactionQueue::with_limits(PrioritizationStrategy::GasPriceOnly, 1, !U256::zero(), !U256::zero()); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); let sender = tx.sender().unwrap(); let nonce = tx.nonce; - txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 1); // when - let res = txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External); + let res = txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator); // then let t = txq.top_transactions(); @@ -1744,18 +1915,18 @@ mod test { #[test] fn should_limit_future_transactions() { - let mut txq = TransactionQueue::with_limits(1, !U256::zero(), !U256::zero()); + let mut txq = TransactionQueue::with_limits(PrioritizationStrategy::GasPriceOnly, 1, !U256::zero(), !U256::zero()); txq.current.set_limit(10); let (tx1, tx2) = new_tx_pair_default(4.into(), 1.into()); let (tx3, tx4) = new_tx_pair_default(4.into(), 2.into()); - txq.add(tx1.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx3.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx1.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx3.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 2); // when - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 1); - txq.add(tx4.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx4.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then assert_eq!(txq.status().future, 1); @@ -1763,37 +1934,42 @@ mod test { #[test] fn should_limit_by_gas() { - let mut txq = TransactionQueue::with_limits(100, default_gas_val() * U256::from(2), !U256::zero()); + let mut txq = TransactionQueue::with_limits(PrioritizationStrategy::GasPriceOnly, 100, default_gas_val() * U256::from(2), !U256::zero()); let (tx1, tx2) = new_tx_pair_default(U256::from(1), U256::from(1)); let (tx3, tx4) = new_tx_pair_default(U256::from(1), U256::from(2)); - txq.add(tx1.clone(), &default_account_details, TransactionOrigin::External).ok(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).ok(); - txq.add(tx3.clone(), &default_account_details, TransactionOrigin::External).ok(); - txq.add(tx4.clone(), &default_account_details, TransactionOrigin::External).ok(); + txq.add(tx1.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx3.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + // limited by gas + txq.add(tx4.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap_err(); assert_eq!(txq.status().pending, 2); } #[test] fn should_keep_own_transactions_above_gas_limit() { - let mut txq = TransactionQueue::with_limits(100, default_gas_val() * U256::from(2), !U256::zero()); + let mut txq = TransactionQueue::with_limits(PrioritizationStrategy::GasPriceOnly, 100, default_gas_val() * U256::from(2), !U256::zero()); let (tx1, tx2) = new_tx_pair_default(U256::from(1), U256::from(1)); let (tx3, tx4) = new_tx_pair_default(U256::from(1), U256::from(2)); - txq.add(tx1.clone(), &default_account_details, TransactionOrigin::Local).unwrap(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::Local).unwrap(); - txq.add(tx3.clone(), &default_account_details, TransactionOrigin::Local).unwrap(); - txq.add(tx4.clone(), &default_account_details, TransactionOrigin::Local).unwrap(); + let (tx5, tx6) = new_tx_pair_default(U256::from(1), U256::from(2)); + txq.add(tx1.clone(), TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx5.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + // Not accepted because of limit + txq.add(tx6.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap_err(); + txq.add(tx3.clone(), TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx4.clone(), TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 4); } #[test] fn should_drop_transactions_with_old_nonces() { - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); let last_nonce = tx.nonce + U256::one(); - let fetch_last_nonce = |_a: &Address| AccountDetails{ nonce: last_nonce, balance: !U256::zero() }; + let fetch_last_nonce = |_a: &Address| AccountDetails { nonce: last_nonce, balance: !U256::zero() }; // when - let res = txq.add(tx, &fetch_last_nonce, TransactionOrigin::External); + let res = txq.add(tx, TransactionOrigin::External, &fetch_last_nonce, &gas_estimator); // then assert_eq!(unwrap_tx_err(res), TransactionError::Old); @@ -1807,14 +1983,14 @@ mod test { // given let nonce = |a: &Address| AccountDetails { nonce: default_account_details(a).nonce + U256::one(), balance: !U256::zero() }; - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (_tx1, tx2) = new_tx_pair_default(1.into(), 0.into()); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 1); assert_eq!(txq.status().pending, 0); // when - let res = txq.add(tx2.clone(), &nonce, TransactionOrigin::External); + let res = txq.add(tx2.clone(), TransactionOrigin::External, &nonce, &gas_estimator); // then assert_eq!(unwrap_tx_err(res), TransactionError::AlreadyImported); @@ -1826,17 +2002,17 @@ mod test { #[test] fn should_accept_same_transaction_twice_if_removed() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx1, tx2) = new_tx_pair_default(1.into(), 0.into()); - txq.add(tx1.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx1.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 2); // when txq.remove_invalid(&tx1.hash(), &default_account_details); assert_eq!(txq.status().pending, 0); assert_eq!(txq.status().future, 1); - txq.add(tx1.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx1.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then let stats = txq.status(); @@ -1847,13 +2023,13 @@ mod test { #[test] fn should_not_move_to_future_if_state_nonce_is_higher() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx, tx2) = new_tx_pair_default(1.into(), 0.into()); let tx3 = new_tx_default(); - txq.add(tx2.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx2.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 1); - txq.add(tx3.clone(), &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx.clone(), &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx3.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx.clone(), TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 3); // when @@ -1870,9 +2046,9 @@ mod test { fn should_replace_same_transaction_when_has_higher_fee() { init_log(); // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let keypair = Random.generate().unwrap(); - let tx = new_unsigned_tx(123.into(), 1.into()).sign(keypair.secret()); + let tx = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(keypair.secret()); let tx2 = { let mut tx2 = (*tx).clone(); tx2.gas_price = U256::from(200); @@ -1880,8 +2056,8 @@ mod test { }; // when - txq.add(tx, &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2, &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then let stats = txq.status(); @@ -1893,9 +2069,9 @@ mod test { #[test] fn should_replace_same_transaction_when_importing_to_futures() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let keypair = Random.generate().unwrap(); - let tx0 = new_unsigned_tx(123.into(), 1.into()).sign(keypair.secret()); + let tx0 = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(keypair.secret()); let tx1 = { let mut tx1 = (*tx0).clone(); tx1.nonce = U256::from(124); @@ -1908,10 +2084,10 @@ mod test { }; // when - txq.add(tx1, &default_account_details, TransactionOrigin::External).unwrap(); - txq.add(tx2, &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx1, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 1); - txq.add(tx0, &default_account_details, TransactionOrigin::External).unwrap(); + txq.add(tx0, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); // then let stats = txq.status(); @@ -1927,10 +2103,10 @@ mod test { !U256::zero() }; let next_nonce = |a: &Address| AccountDetails{ nonce: default_account_details(a).nonce + U256::one(), balance: !U256::zero() }; - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx1, tx2) = new_tx_pair_default(1.into(), 0.into()); - txq.add(tx1.clone(), &previous_nonce, TransactionOrigin::External).unwrap(); - txq.add(tx2, &previous_nonce, TransactionOrigin::External).unwrap(); + txq.add(tx1.clone(), TransactionOrigin::External, &previous_nonce, &gas_estimator).unwrap(); + txq.add(tx2, TransactionOrigin::External, &previous_nonce, &gas_estimator).unwrap(); assert_eq!(txq.status().future, 2); // when @@ -1945,7 +2121,7 @@ mod test { #[test] fn should_return_none_when_transaction_from_given_address_does_not_exist() { // given - let txq = TransactionQueue::new(); + let txq = TransactionQueue::default(); // then assert_eq!(txq.last_nonce(&Address::default()), None); @@ -1954,14 +2130,14 @@ mod test { #[test] fn should_return_correct_nonce_when_transactions_from_given_address_exist() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let tx = new_tx_default(); let from = tx.sender().unwrap(); let nonce = tx.nonce; let details = |_a: &Address| AccountDetails { nonce: nonce, balance: !U256::zero() }; // when - txq.add(tx, &details, TransactionOrigin::External).unwrap(); + txq.add(tx, TransactionOrigin::External, &details, &gas_estimator).unwrap(); // then assert_eq!(txq.last_nonce(&from), Some(nonce)); @@ -1970,13 +2146,13 @@ mod test { #[test] fn should_remove_old_transaction_even_if_newer_transaction_was_not_known() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx1, tx2) = new_tx_pair_default(1.into(), 0.into()); let (nonce1, nonce2) = (tx1.nonce, tx2.nonce); let details1 = |_a: &Address| AccountDetails { nonce: nonce1, balance: !U256::zero() }; // Insert first transaction - txq.add(tx1, &details1, TransactionOrigin::External).unwrap(); + txq.add(tx1, TransactionOrigin::External, &details1, &gas_estimator).unwrap(); // when txq.remove_all(tx2.sender().unwrap(), nonce2 + U256::one()); @@ -1988,7 +2164,7 @@ mod test { #[test] fn should_return_valid_last_nonce_after_remove_all() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx1, tx2) = new_tx_pair_default(4.into(), 0.into()); let sender = tx1.sender().unwrap(); let (nonce1, nonce2) = (tx1.nonce, tx2.nonce); @@ -1996,9 +2172,9 @@ mod test { // when // Insert first transaction - assert_eq!(txq.add(tx1, &details1, TransactionOrigin::External).unwrap(), TransactionImportResult::Current); + assert_eq!(txq.add(tx1, TransactionOrigin::External, &details1, &gas_estimator).unwrap(), TransactionImportResult::Current); // Second should go to future - assert_eq!(txq.add(tx2, &details1, TransactionOrigin::External).unwrap(), TransactionImportResult::Future); + assert_eq!(txq.add(tx2, TransactionOrigin::External, &details1, &gas_estimator).unwrap(), TransactionImportResult::Future); // Now block is imported txq.remove_all(sender, nonce2 - U256::from(1)); // tx2 should be not be promoted to current @@ -2012,14 +2188,14 @@ mod test { #[test] fn should_return_true_if_there_is_local_transaction_pending() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx1, tx2) = new_tx_pair_default(1.into(), 0.into()); assert_eq!(txq.has_local_pending_transactions(), false); // when - assert_eq!(txq.add(tx1, &default_account_details, TransactionOrigin::External).unwrap(), TransactionImportResult::Current); + assert_eq!(txq.add(tx1, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(), TransactionImportResult::Current); assert_eq!(txq.has_local_pending_transactions(), false); - assert_eq!(txq.add(tx2, &default_account_details, TransactionOrigin::Local).unwrap(), TransactionImportResult::Current); + assert_eq!(txq.add(tx2, TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(), TransactionImportResult::Current); // then assert_eq!(txq.has_local_pending_transactions(), true); @@ -2028,14 +2204,14 @@ mod test { #[test] fn should_keep_right_order_in_future() { // given - let mut txq = TransactionQueue::with_limits(1, !U256::zero(), !U256::zero()); + let mut txq = TransactionQueue::with_limits(PrioritizationStrategy::GasPriceOnly, 1, !U256::zero(), !U256::zero()); let (tx1, tx2) = new_tx_pair_default(1.into(), 0.into()); let prev_nonce = |a: &Address| AccountDetails { nonce: default_account_details(a).nonce - U256::one(), balance: default_account_details(a).balance }; // when - assert_eq!(txq.add(tx2, &prev_nonce, TransactionOrigin::External).unwrap(), TransactionImportResult::Future); - assert_eq!(txq.add(tx1.clone(), &prev_nonce, TransactionOrigin::External).unwrap(), TransactionImportResult::Future); + assert_eq!(txq.add(tx2, TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(), TransactionImportResult::Future); + assert_eq!(txq.add(tx1.clone(), TransactionOrigin::External, &prev_nonce, &gas_estimator).unwrap(), TransactionImportResult::Future); // then assert_eq!(txq.future.by_priority.len(), 1); @@ -2045,28 +2221,29 @@ mod test { #[test] fn should_return_correct_last_nonce() { // given - let mut txq = TransactionQueue::new(); + let mut txq = TransactionQueue::default(); let (tx1, tx2, tx2_2, tx3) = { let keypair = Random.generate().unwrap(); let secret = &keypair.secret(); let nonce = 123.into(); - let tx = new_unsigned_tx(nonce, 1.into()); - let tx2 = new_unsigned_tx(nonce + 1.into(), 1.into()); - let tx2_2 = new_unsigned_tx(nonce + 1.into(), 5.into()); - let tx3 = new_unsigned_tx(nonce + 2.into(), 1.into()); + let gas = default_gas_val(); + let tx = new_unsigned_tx(nonce, gas, 1.into()); + let tx2 = new_unsigned_tx(nonce + 1.into(), gas, 1.into()); + let tx2_2 = new_unsigned_tx(nonce + 1.into(), gas, 5.into()); + let tx3 = new_unsigned_tx(nonce + 2.into(), gas, 1.into()); (tx.sign(secret), tx2.sign(secret), tx2_2.sign(secret), tx3.sign(secret)) }; let sender = tx1.sender().unwrap(); - txq.add(tx1, &default_account_details, TransactionOrigin::Local).unwrap(); - txq.add(tx2, &default_account_details, TransactionOrigin::Local).unwrap(); - txq.add(tx3, &default_account_details, TransactionOrigin::Local).unwrap(); + txq.add(tx1, TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx2, TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); + txq.add(tx3, TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.future.by_priority.len(), 0); assert_eq!(txq.current.by_priority.len(), 3); // when - let res = txq.add(tx2_2, &default_account_details, TransactionOrigin::Local); + let res = txq.add(tx2_2, TransactionOrigin::Local, &default_account_details, &gas_estimator); // then assert_eq!(txq.last_nonce(&sender).unwrap(), 125.into()); @@ -2074,4 +2251,24 @@ mod test { assert_eq!(txq.current.by_priority.len(), 3); } + #[test] + fn should_reject_transactions_below_bas_gas() { + // given + let mut txq = TransactionQueue::default(); + let (tx1, tx2) = new_tx_pair_default(1.into(), 0.into()); + let high_gas = |_: &SignedTransaction| 100_001.into(); + + // when + let res1 = txq.add(tx1, TransactionOrigin::Local, &default_account_details, &gas_estimator); + let res2 = txq.add(tx2, TransactionOrigin::Local, &default_account_details, &high_gas); + + // then + assert_eq!(res1.unwrap(), TransactionImportResult::Current); + assert_eq!(unwrap_tx_err(res2), TransactionError::InsufficientGas { + minimal: 100_001.into(), + got: 100_000.into(), + }); + + } + } diff --git a/ethcore/src/pod_account.rs b/ethcore/src/pod_account.rs index a92e03ebcad4d1df0707dd7c6f4a1cbd401b3852..afee32f94424defc785b63870e02aa2ac2136a8e 100644 --- a/ethcore/src/pod_account.rs +++ b/ethcore/src/pod_account.rs @@ -163,7 +163,7 @@ pub fn diff_pod(pre: Option<&PodAccount>, post: Option<&PodAccount>) -> Option StateDiff { #[cfg(test)] mod test { - use common::*; + use util::*; use types::state_diff::*; use types::account_diff::*; use pod_account::PodAccount; diff --git a/ethcore/src/service.rs b/ethcore/src/service.rs index b2dd18cd54e8e9b013661105d50fba91a7ac2e41..00ba981b969fd15fa41fece6a7210b704dda3384 100644 --- a/ethcore/src/service.rs +++ b/ethcore/src/service.rs @@ -87,7 +87,7 @@ impl ClientService { db_config.set_cache(::db::COL_STATE, size); } - db_config.compaction = config.db_compaction.compaction_profile(); + db_config.compaction = config.db_compaction.compaction_profile(client_path); db_config.wal = config.db_wal; let pruning = config.pruning; @@ -188,6 +188,8 @@ impl IoHandler for ClientIoHandler { #[cfg_attr(feature="dev", allow(single_match))] fn message(&self, _io: &IoContext, net_message: &ClientIoMessage) { + use std::thread; + match *net_message { ClientIoMessage::BlockVerified => { self.client.import_verified_blocks(); } ClientIoMessage::NewTransactions(ref transactions) => { self.client.import_queued_transactions(transactions); } @@ -199,9 +201,19 @@ impl IoHandler for ClientIoHandler { ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => self.snapshot.feed_state_chunk(*hash, chunk), ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => self.snapshot.feed_block_chunk(*hash, chunk), ClientIoMessage::TakeSnapshot(num) => { - if let Err(e) = self.snapshot.take_snapshot(&*self.client, num) { - warn!("Failed to take snapshot at block #{}: {}", num, e); + let client = self.client.clone(); + let snapshot = self.snapshot.clone(); + + let res = thread::Builder::new().name("Periodic Snapshot".into()).spawn(move || { + if let Err(e) = snapshot.take_snapshot(&*client, num) { + warn!("Failed to take snapshot at block #{}: {}", num, e); + } + }); + + if let Err(e) = res { + debug!(target: "snapshot", "Failed to initialize periodic snapshot thread: {:?}", e); } + } _ => {} // ignore other messages } diff --git a/ethcore/src/snapshot/account.rs b/ethcore/src/snapshot/account.rs index bc1faea3f5bf9fcde9235320346cecf864f186f8..38a4028e140538610bf75f0af4d9864b4b16559d 100644 --- a/ethcore/src/snapshot/account.rs +++ b/ethcore/src/snapshot/account.rs @@ -19,12 +19,20 @@ use account_db::{AccountDB, AccountDBMut}; use snapshot::Error; -use util::{U256, FixedHash, H256, Bytes, HashDB, SHA3_EMPTY}; +use util::{U256, FixedHash, H256, Bytes, HashDB, DBValue, SHA3_EMPTY, SHA3_NULL_RLP}; use util::trie::{TrieDB, Trie}; use rlp::{Rlp, RlpStream, Stream, UntrustedRlp, View}; use std::collections::{HashMap, HashSet}; +// An empty account -- these are replaced with RLP null data for a space optimization. +const ACC_EMPTY: Account = Account { + nonce: U256([0, 0, 0, 0]), + balance: U256([0, 0, 0, 0]), + storage_root: SHA3_NULL_RLP, + code_hash: SHA3_EMPTY, +}; + // whether an encoded account has code and how it is referred to. #[repr(u8)] enum CodeState { @@ -88,6 +96,10 @@ impl Account { // walk the account's storage trie, returning an RLP item containing the // account properties and the storage. pub fn to_fat_rlp(&self, acct_db: &AccountDB, used_code: &mut HashSet) -> Result { + if self == &ACC_EMPTY { + return Ok(::rlp::NULL_RLP.to_vec()); + } + let db = try!(TrieDB::new(acct_db, &self.storage_root)); let mut pairs = Vec::new(); @@ -100,7 +112,7 @@ impl Account { let mut stream = RlpStream::new_list(pairs.len()); for (k, v) in pairs { - stream.begin_list(2).append(&k).append(&v); + stream.begin_list(2).append(&k).append(&&*v); } let pairs_rlp = stream.out(); @@ -118,7 +130,7 @@ impl Account { match acct_db.get(&self.code_hash) { Some(c) => { used_code.insert(self.code_hash.clone()); - account_stream.append(&CodeState::Inline.raw()).append(&c); + account_stream.append(&CodeState::Inline.raw()).append(&&*c); } None => { warn!("code lookup failed during snapshot"); @@ -142,6 +154,11 @@ impl Account { ) -> Result<(Self, Option), Error> { use util::{TrieDBMut, TrieMut}; + // check for special case of empty account. + if rlp.is_empty() { + return Ok((ACC_EMPTY, None)); + } + let nonce = try!(rlp.val_at(0)); let balance = try!(rlp.val_at(1)); let code_state: CodeState = { @@ -161,7 +178,7 @@ impl Account { CodeState::Hash => { let code_hash = try!(rlp.val_at(3)); if let Some(code) = code_map.get(&code_hash) { - acct_db.emplace(code_hash.clone(), code.clone()); + acct_db.emplace(code_hash.clone(), DBValue::from_slice(code)); } (code_hash, None) @@ -209,12 +226,12 @@ mod tests { use snapshot::tests::helpers::fill_storage; use util::sha3::{SHA3_EMPTY, SHA3_NULL_RLP}; - use util::{Address, FixedHash, H256, HashDB}; + use util::{Address, FixedHash, H256, HashDB, DBValue}; use rlp::{UntrustedRlp, View}; use std::collections::{HashSet, HashMap}; - use super::Account; + use super::{ACC_EMPTY, Account}; #[test] fn encoding_basic() { @@ -275,7 +292,7 @@ mod tests { { let mut acct_db = AccountDBMut::new(db.as_hashdb_mut(), &addr2); - acct_db.emplace(code_hash.clone(), b"this is definitely code".to_vec()); + acct_db.emplace(code_hash.clone(), DBValue::from_slice(b"this is definitely code")); } let account1 = Account { @@ -310,4 +327,14 @@ mod tests { assert_eq!(maybe_code, Some(b"this is definitely code".to_vec())); assert_eq!(acc, account1); } + + #[test] + fn encoding_empty_acc() { + let mut db = get_temp_state_db(); + let mut used_code = HashSet::new(); + let code_map = HashMap::new(); + + assert_eq!(ACC_EMPTY.to_fat_rlp(&AccountDB::new(db.as_hashdb(), &Address::default()), &mut used_code).unwrap(), ::rlp::NULL_RLP.to_vec()); + assert_eq!(Account::from_fat_rlp(&mut AccountDBMut::new(db.as_hashdb_mut(), &Address::default()), UntrustedRlp::new(&::rlp::NULL_RLP), &code_map).unwrap(), (ACC_EMPTY, None)); + } } diff --git a/ethcore/src/snapshot/error.rs b/ethcore/src/snapshot/error.rs index acd9409f721bed6edc84c9fbeef867d12e62f452..d634057dc79f37cc1796514066e13f77ce779b77 100644 --- a/ethcore/src/snapshot/error.rs +++ b/ethcore/src/snapshot/error.rs @@ -33,6 +33,12 @@ pub enum Error { BlockNotFound(H256), /// Incomplete chain. IncompleteChain, + /// Best block has wrong state root. + WrongStateRoot(H256, H256), + /// Wrong block hash. + WrongBlockHash(u64, H256, H256), + /// Too many blocks contained within the snapshot. + TooManyBlocks(u64, u64), /// Old starting block in a pruned database. OldBlockPrunedDB, /// Missing code. @@ -52,7 +58,11 @@ impl fmt::Display for Error { match *self { Error::InvalidStartingBlock(ref id) => write!(f, "Invalid starting block: {:?}", id), Error::BlockNotFound(ref hash) => write!(f, "Block not found in chain: {}", hash), - Error::IncompleteChain => write!(f, "Cannot create snapshot due to incomplete chain."), + Error::IncompleteChain => write!(f, "Incomplete blockchain."), + Error::WrongStateRoot(ref expected, ref found) => write!(f, "Final block has wrong state root. Expected {:?}, got {:?}", expected, found), + Error::WrongBlockHash(ref num, ref expected, ref found) => + write!(f, "Block {} had wrong hash. expected {:?}, got {:?}", num, expected, found), + Error::TooManyBlocks(ref expected, ref found) => write!(f, "Snapshot contained too many blocks. Expected {}, got {}", expected, found), Error::OldBlockPrunedDB => write!(f, "Attempted to create a snapshot at an old block while using \ a pruned database. Please re-run with the --pruning archive flag."), Error::MissingCode(ref missing) => write!(f, "Incomplete snapshot: {} contract codes not found.", missing.len()), diff --git a/ethcore/src/snapshot/mod.rs b/ethcore/src/snapshot/mod.rs index a5e6b58bdfed1c1d2fe9dbee23d50a6753b70387..22c44ba3b544058b931fb399c9ace334a4020577 100644 --- a/ethcore/src/snapshot/mod.rs +++ b/ethcore/src/snapshot/mod.rs @@ -26,11 +26,11 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use account_db::{AccountDB, AccountDBMut}; use blockchain::{BlockChain, BlockProvider}; use engines::Engine; +use header::Header; use ids::BlockID; use views::BlockView; -use util::{Bytes, Hashable, HashDB, snappy}; -use util::memorydb::MemoryDB; +use util::{Bytes, Hashable, HashDB, DBValue, snappy, U256, Uint}; use util::Mutex; use util::hash::{FixedHash, H256}; use util::journaldb::{self, Algorithm, JournalDB}; @@ -38,14 +38,16 @@ use util::kvdb::Database; use util::trie::{TrieDB, TrieDBMut, Trie, TrieMut}; use util::sha3::SHA3_NULL_RLP; use rlp::{RlpStream, Stream, UntrustedRlp, View}; +use bloom_journal::Bloom; use self::account::Account; use self::block::AbridgedBlock; use self::io::SnapshotWriter; use super::state_db::StateDB; +use super::state::Account as StateAccount; -use crossbeam::{scope, ScopedJoinHandle}; +use crossbeam::scope; use rand::{Rng, OsRng}; pub use self::error::Error; @@ -135,7 +137,7 @@ pub fn take_snapshot( let writer = Mutex::new(writer); let (state_hashes, block_hashes) = try!(scope(|scope| { - let block_guard = scope.spawn(|| chunk_blocks(chain, (number, block_at), &writer, p)); + let block_guard = scope.spawn(|| chunk_blocks(chain, block_at, &writer, p)); let state_res = chunk_state(state_db, state_root, &writer, p); state_res.and_then(|state_hashes| { @@ -175,10 +177,15 @@ struct BlockChunker<'a> { impl<'a> BlockChunker<'a> { // Repeatedly fill the buffers and writes out chunks, moving backwards from starting block hash. // Loops until we reach the first desired block, and writes out the remainder. - fn chunk_all(&mut self, first_hash: H256) -> Result<(), Error> { + fn chunk_all(&mut self) -> Result<(), Error> { let mut loaded_size = 0; + let mut last = self.current_hash; + + let genesis_hash = self.chain.genesis_hash(); + + for _ in 0..SNAPSHOT_BLOCKS { + if self.current_hash == genesis_hash { break } - while self.current_hash != first_hash { let (block, receipts) = try!(self.chain.block(&self.current_hash) .and_then(|b| self.chain.block_receipts(&self.current_hash).map(|r| (b, r))) .ok_or(Error::BlockNotFound(self.current_hash))); @@ -196,21 +203,21 @@ impl<'a> BlockChunker<'a> { // cut off the chunk if too large. - if new_loaded_size > PREFERRED_CHUNK_SIZE { - try!(self.write_chunk()); + if new_loaded_size > PREFERRED_CHUNK_SIZE && !self.rlps.is_empty() { + try!(self.write_chunk(last)); loaded_size = pair.len(); } else { loaded_size = new_loaded_size; } self.rlps.push_front(pair); + + last = self.current_hash; self.current_hash = view.header_view().parent_hash(); } if loaded_size != 0 { - // we don't store the first block, so once we get to this point, - // the "first" block will be first_number + 1. - try!(self.write_chunk()); + try!(self.write_chunk(last)); } Ok(()) @@ -218,23 +225,24 @@ impl<'a> BlockChunker<'a> { // write out the data in the buffers to a chunk on disk // - // we preface each chunk with the parent of the first block's details. - fn write_chunk(&mut self) -> Result<(), Error> { - // since the block we're inspecting now doesn't go into the - // chunk if it's too large, the current hash is the parent hash - // for the first block in that chunk. - let parent_hash = self.current_hash; - + // we preface each chunk with the parent of the first block's details, + // obtained from the details of the last block written. + fn write_chunk(&mut self, last: H256) -> Result<(), Error> { trace!(target: "snapshot", "prepared block chunk with {} blocks", self.rlps.len()); - let (parent_number, parent_details) = try!(self.chain.block_number(&parent_hash) - .and_then(|n| self.chain.block_details(&parent_hash).map(|d| (n, d))) - .ok_or(Error::BlockNotFound(parent_hash))); - let parent_total_difficulty = parent_details.total_difficulty; + let (last_header, last_details) = try!(self.chain.block_header(&last) + .and_then(|n| self.chain.block_details(&last).map(|d| (n, d))) + .ok_or(Error::BlockNotFound(last))); + + let parent_number = last_header.number() - 1; + let parent_hash = last_header.parent_hash(); + let parent_total_difficulty = last_details.total_difficulty - *last_header.difficulty(); + + trace!(target: "snapshot", "parent last written block: {}", parent_hash); let num_entries = self.rlps.len(); let mut rlp_stream = RlpStream::new_list(3 + num_entries); - rlp_stream.append(&parent_number).append(&parent_hash).append(&parent_total_difficulty); + rlp_stream.append(&parent_number).append(parent_hash).append(&parent_total_difficulty); for pair in self.rlps.drain(..) { rlp_stream.append_raw(&pair, 1); @@ -263,17 +271,7 @@ impl<'a> BlockChunker<'a> { /// The path parameter is the directory to store the block chunks in. /// This function assumes the directory exists already. /// Returns a list of chunk hashes, with the first having the blocks furthest from the genesis. -pub fn chunk_blocks<'a>(chain: &'a BlockChain, start_block_info: (u64, H256), writer: &Mutex, progress: &'a Progress) -> Result, Error> { - let (start_number, start_hash) = start_block_info; - - let first_hash = if start_number < SNAPSHOT_BLOCKS { - // use the genesis hash. - chain.genesis_hash() - } else { - let first_num = start_number - SNAPSHOT_BLOCKS; - try!(chain.block_hash(first_num).ok_or(Error::IncompleteChain)) - }; - +pub fn chunk_blocks<'a>(chain: &'a BlockChain, start_hash: H256, writer: &Mutex, progress: &'a Progress) -> Result, Error> { let mut chunker = BlockChunker { chain: chain, rlps: VecDeque::new(), @@ -284,7 +282,7 @@ pub fn chunk_blocks<'a>(chain: &'a BlockChain, start_block_info: (u64, H256), wr progress: progress, }; - try!(chunker.chunk_all(first_hash)); + try!(chunker.chunk_all()); Ok(chunker.hashes) } @@ -371,7 +369,7 @@ pub fn chunk_state<'a>(db: &HashDB, root: &H256, writer: &Mutex, // maps code hashes to code itself. missing_code: HashMap>, // maps code hashes to lists of accounts missing that code. + bloom: Bloom, } impl StateRebuilder { @@ -403,12 +402,14 @@ impl StateRebuilder { state_root: SHA3_NULL_RLP, code_map: HashMap::new(), missing_code: HashMap::new(), + bloom: StateDB::load_bloom(&*db), } } /// Feed an uncompressed state chunk into the rebuilder. pub fn feed(&mut self, chunk: &[u8]) -> Result<(), ::error::Error> { let rlp = UntrustedRlp::new(chunk); + let empty_rlp = StateAccount::new_basic(U256::zero(), U256::zero()).rlp(); let account_fat_rlps: Vec<_> = rlp.iter().map(|r| r.as_raw()).collect(); let mut pairs = Vec::with_capacity(rlp.item_count()); @@ -420,43 +421,19 @@ impl StateRebuilder { // new code contained within this chunk. let mut chunk_code = HashMap::new(); - // build account tries in parallel. - // Todo [rob] keep a thread pool around so we don't do this per-chunk. - try!(scope(|scope| { - let mut handles = Vec::new(); - for (account_chunk, out_pairs_chunk) in account_fat_rlps.chunks(chunk_size).zip(pairs.chunks_mut(chunk_size)) { - let code_map = &self.code_map; - let handle: ScopedJoinHandle> = scope.spawn(move || { - let mut db = MemoryDB::new(); - let status = try!(rebuild_accounts(&mut db, account_chunk, out_pairs_chunk, code_map)); - - trace!(target: "snapshot", "thread rebuilt {} account tries", account_chunk.len()); - Ok((db, status)) - }); - - handles.push(handle); + for (account_chunk, out_pairs_chunk) in account_fat_rlps.chunks(chunk_size).zip(pairs.chunks_mut(chunk_size)) { + let code_map = &self.code_map; + let status = try!(rebuild_accounts(self.db.as_hashdb_mut(), account_chunk, out_pairs_chunk, code_map)); + chunk_code.extend(status.new_code); + for (addr_hash, code_hash) in status.missing_code { + self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash); } - - // consolidate all edits into the main overlay. - for handle in handles { - let (thread_db, status): (MemoryDB, _) = try!(handle.join()); - self.db.consolidate(thread_db); - - chunk_code.extend(status.new_code); - - for (addr_hash, code_hash) in status.missing_code { - self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash); - } - } - - Ok::<_, ::error::Error>(()) - })); - + } // patch up all missing code. must be done after collecting all new missing code entries. for (code_hash, code) in chunk_code { for addr_hash in self.missing_code.remove(&code_hash).unwrap_or_else(Vec::new) { let mut db = AccountDBMut::from_hash(self.db.as_hashdb_mut(), addr_hash); - db.emplace(code_hash, code.clone()); + db.emplace(code_hash, DBValue::from_slice(&code)); } self.code_map.insert(code_hash, code); @@ -464,9 +441,6 @@ impl StateRebuilder { let backing = self.db.backing().clone(); - // bloom has to be updated - let mut bloom = StateDB::load_bloom(&backing); - // batch trie writes { let mut account_trie = if self.state_root != SHA3_NULL_RLP { @@ -476,16 +450,18 @@ impl StateRebuilder { }; for (hash, thin_rlp) in pairs { - bloom.set(&*hash); + if &thin_rlp[..] != &empty_rlp[..] { + self.bloom.set(&*hash); + } try!(account_trie.insert(&hash, &thin_rlp)); } } - let bloom_journal = bloom.drain_journal(); + let bloom_journal = self.bloom.drain_journal(); let mut batch = backing.transaction(); try!(StateDB::commit_bloom(&mut batch, bloom_journal)); try!(self.db.inject(&mut batch)); - try!(backing.write(batch).map_err(::util::UtilError::SimpleString)); + backing.write_buffered(batch); trace!(target: "snapshot", "current state root: {:?}", self.state_root); Ok(()) } @@ -553,6 +529,20 @@ fn rebuild_accounts( /// Proportion of blocks which we will verify `PoW` for. const POW_VERIFY_RATE: f32 = 0.02; +/// Verify an old block with the given header, engine, blockchain, body. If `always` is set, it will perform +/// the fullest verification possible. If not, it will take a random sample to determine whether it will +/// do heavy or light verification. +pub fn verify_old_block(rng: &mut OsRng, header: &Header, engine: &Engine, chain: &BlockChain, body: Option<&[u8]>, always: bool) -> Result<(), ::error::Error> { + if always || rng.gen::() <= POW_VERIFY_RATE { + match chain.block_header(header.parent_hash()) { + Some(parent) => engine.verify_block_family(&header, &parent, body), + None => engine.verify_block_seal(&header), + } + } else { + engine.verify_block_basic(&header, body) + } +} + /// Rebuilds the blockchain from chunks. /// /// Does basic verification for all blocks, but `PoW` verification for some. @@ -564,19 +554,27 @@ const POW_VERIFY_RATE: f32 = 0.02; /// After all chunks have been submitted, we "glue" the chunks together. pub struct BlockRebuilder { chain: BlockChain, + db: Arc, rng: OsRng, disconnected: Vec<(u64, H256)>, best_number: u64, + best_hash: H256, + best_root: H256, + fed_blocks: u64, } impl BlockRebuilder { /// Create a new BlockRebuilder. - pub fn new(chain: BlockChain, best_number: u64) -> Result { + pub fn new(chain: BlockChain, db: Arc, manifest: &ManifestData) -> Result { Ok(BlockRebuilder { chain: chain, + db: db, rng: try!(OsRng::new()), disconnected: Vec::new(), - best_number: best_number, + best_number: manifest.block_number, + best_hash: manifest.block_hash, + best_root: manifest.state_root, + fed_blocks: 0, }) } @@ -589,8 +587,13 @@ impl BlockRebuilder { let rlp = UntrustedRlp::new(chunk); let item_count = rlp.item_count(); + let num_blocks = (item_count - 3) as u64; + + trace!(target: "snapshot", "restoring block chunk with {} blocks.", item_count - 3); - trace!(target: "snapshot", "restoring block chunk with {} blocks.", item_count - 2); + if self.fed_blocks + num_blocks > SNAPSHOT_BLOCKS { + return Err(Error::TooManyBlocks(SNAPSHOT_BLOCKS, self.fed_blocks).into()) + } // todo: assert here that these values are consistent with chunks being in order. let mut cur_number = try!(rlp.val_at::(0)) + 1; @@ -608,34 +611,53 @@ impl BlockRebuilder { let block = try!(abridged_block.to_block(parent_hash, cur_number, receipts_root)); let block_bytes = block.rlp_bytes(With); + let is_best = cur_number == self.best_number; - if self.rng.gen::() <= POW_VERIFY_RATE { - try!(engine.verify_block_seal(&block.header)) - } else { - try!(engine.verify_block_basic(&block.header, Some(&block_bytes))); + if is_best { + if block.header.hash() != self.best_hash { + return Err(Error::WrongBlockHash(cur_number, self.best_hash, block.header.hash()).into()) + } + + if block.header.state_root() != &self.best_root { + return Err(Error::WrongStateRoot(self.best_root, *block.header.state_root()).into()) + } } - let is_best = cur_number == self.best_number; + try!(verify_old_block( + &mut self.rng, + &block.header, + engine, + &self.chain, + Some(&block_bytes), + is_best + )); + + let mut batch = self.db.transaction(); // special-case the first block in each chunk. if idx == 3 { - if self.chain.insert_snapshot_block(&block_bytes, receipts, Some(parent_total_difficulty), is_best) { + if self.chain.insert_unordered_block(&mut batch, &block_bytes, receipts, Some(parent_total_difficulty), is_best, false) { self.disconnected.push((cur_number, block.header.hash())); } } else { - self.chain.insert_snapshot_block(&block_bytes, receipts, None, is_best); + self.chain.insert_unordered_block(&mut batch, &block_bytes, receipts, None, is_best, false); } + self.db.write_buffered(batch); self.chain.commit(); parent_hash = BlockView::new(&block_bytes).hash(); cur_number += 1; } - Ok(item_count as u64 - 3) + self.fed_blocks += num_blocks; + + Ok(num_blocks) } - /// Glue together any disconnected chunks. To be called at the end. - pub fn glue_chunks(self) { + /// Glue together any disconnected chunks and check that the chain is complete. + pub fn finalize(self, canonical: HashMap) -> Result<(), Error> { + let mut batch = self.db.transaction(); + for (first_num, first_hash) in self.disconnected { let parent_num = first_num - 1; @@ -644,8 +666,23 @@ impl BlockRebuilder { // the first block of the first chunks has nothing to connect to. if let Some(parent_hash) = self.chain.block_hash(parent_num) { // if so, add the child to it. - self.chain.add_child(parent_hash, first_hash); + self.chain.add_child(&mut batch, parent_hash, first_hash); } } + self.db.write_buffered(batch); + + let best_number = self.best_number; + for num in (0..self.fed_blocks).map(|x| best_number - x) { + + let hash = try!(self.chain.block_hash(num).ok_or(Error::IncompleteChain)); + + if let Some(canon_hash) = canonical.get(&num).cloned() { + if canon_hash != hash { + return Err(Error::WrongBlockHash(num, canon_hash, hash)); + } + } + } + + Ok(()) } } diff --git a/ethcore/src/snapshot/service.rs b/ethcore/src/snapshot/service.rs index 30361227305e9c1ba3ee157dbfaa902ffd194cb4..8b9a41cc4265e13390ba9491c9616cc3e7c39d43 100644 --- a/ethcore/src/snapshot/service.rs +++ b/ethcore/src/snapshot/service.rs @@ -16,7 +16,7 @@ //! Snapshot network service implementation. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::io::ErrorKind; use std::fs; use std::path::PathBuf; @@ -75,6 +75,8 @@ struct Restoration { snappy_buffer: Bytes, final_state_root: H256, guard: Guard, + canonical_hashes: HashMap, + db: Arc, } struct RestorationParams<'a> { @@ -99,19 +101,21 @@ impl Restoration { .map_err(UtilError::SimpleString))); let chain = BlockChain::new(Default::default(), params.genesis, raw_db.clone(), Spec::new_null().engine); - let blocks = try!(BlockRebuilder::new(chain, manifest.block_number)); + let blocks = try!(BlockRebuilder::new(chain, raw_db.clone(), &manifest)); let root = manifest.state_root.clone(); Ok(Restoration { manifest: manifest, state_chunks_left: state_chunks, block_chunks_left: block_chunks, - state: StateRebuilder::new(raw_db, params.pruning), + state: StateRebuilder::new(raw_db.clone(), params.pruning), blocks: blocks, writer: params.writer, snappy_buffer: Vec::new(), final_state_root: root, guard: params.guard, + canonical_hashes: HashMap::new(), + db: raw_db, }) } @@ -137,13 +141,18 @@ impl Restoration { try!(self.blocks.feed(&self.snappy_buffer[..len], engine)); if let Some(ref mut writer) = self.writer.as_mut() { - try!(writer.write_block_chunk(hash, chunk)); + try!(writer.write_block_chunk(hash, chunk)); } } Ok(()) } + // note canonical hashes. + fn note_canonical(&mut self, hashes: &[(u64, H256)]) { + self.canonical_hashes.extend(hashes.iter().cloned()); + } + // finish up restoration. fn finalize(self) -> Result<(), Error> { use util::trie::TrieError; @@ -160,8 +169,8 @@ impl Restoration { // check for missing code. try!(self.state.check_missing()); - // connect out-of-order chunks. - self.blocks.glue_chunks(); + // connect out-of-order chunks and verify chain integrity. + try!(self.blocks.finalize(self.canonical_hashes)); if let Some(writer) = self.writer { try!(writer.finish(self.manifest)); @@ -205,7 +214,7 @@ pub struct Service { restoration: Mutex>, snapshot_root: PathBuf, db_config: DatabaseConfig, - io_channel: Channel, + io_channel: Mutex, pruning: Algorithm, status: Mutex, reader: RwLock>, @@ -225,7 +234,7 @@ impl Service { restoration: Mutex::new(None), snapshot_root: params.snapshot_root, db_config: params.db_config, - io_channel: params.channel, + io_channel: Mutex::new(params.channel), pruning: params.pruning, status: Mutex::new(RestorationStatus::Inactive), reader: RwLock::new(None), @@ -347,11 +356,12 @@ impl Service { self.taking_snapshot.store(false, Ordering::SeqCst); if let Err(e) = res { - if client.chain_info().best_block_number >= num + ::client::HISTORY { + if client.chain_info().best_block_number >= num + client.pruning_history() { // "Cancelled" is mincing words a bit -- what really happened // is that the state we were snapshotting got pruned out // before we could finish. - info!("Cancelled prematurely-started periodic snapshot."); + info!("Periodic snapshot failed: block state pruned.\ + Run with a longer `--pruning-history` or with `--no-periodic-snapshot`"); return Ok(()) } else { return Err(e); @@ -416,9 +426,14 @@ impl Service { guard: Guard::new(rest_dir), }; + let state_chunks = params.manifest.state_hashes.len(); + let block_chunks = params.manifest.block_hashes.len(); + *res = Some(try!(Restoration::new(params))); *self.status.lock() = RestorationStatus::Ongoing { + state_chunks: state_chunks as u32, + block_chunks: block_chunks as u32, state_chunks_done: self.state_chunks.load(Ordering::SeqCst) as u32, block_chunks_done: self.block_chunks.load(Ordering::SeqCst) as u32, }; @@ -463,39 +478,47 @@ impl Service { /// Feed a chunk of either kind. no-op if no restoration or status is wrong. fn feed_chunk(&self, hash: H256, chunk: &[u8], is_state: bool) -> Result<(), Error> { // TODO: be able to process block chunks and state chunks at same time? - let mut restoration = self.restoration.lock(); - - match self.status() { - RestorationStatus::Inactive | RestorationStatus::Failed => Ok(()), - RestorationStatus::Ongoing { .. } => { - let res = { - let rest = match *restoration { - Some(ref mut r) => r, - None => return Ok(()), - }; - - match is_state { - true => rest.feed_state(hash, chunk), - false => rest.feed_blocks(hash, chunk, &*self.engine), - }.map(|_| rest.is_done()) - }; - - match res { - Ok(is_done) => { - match is_state { - true => self.state_chunks.fetch_add(1, Ordering::SeqCst), - false => self.block_chunks.fetch_add(1, Ordering::SeqCst), + let (result, db) = { + let mut restoration = self.restoration.lock(); + + match self.status() { + RestorationStatus::Inactive | RestorationStatus::Failed => return Ok(()), + RestorationStatus::Ongoing { .. } => { + let (res, db) = { + let rest = match *restoration { + Some(ref mut r) => r, + None => return Ok(()), }; - match is_done { - true => self.finalize_restoration(&mut *restoration), - false => Ok(()) + (match is_state { + true => rest.feed_state(hash, chunk), + false => rest.feed_blocks(hash, chunk, &*self.engine), + }.map(|_| rest.is_done()), rest.db.clone()) + }; + + let res = match res { + Ok(is_done) => { + match is_state { + true => self.state_chunks.fetch_add(1, Ordering::SeqCst), + false => self.block_chunks.fetch_add(1, Ordering::SeqCst), + }; + + match is_done { + true => { + try!(db.flush().map_err(::util::UtilError::SimpleString)); + drop(db); + return self.finalize_restoration(&mut *restoration); + }, + false => Ok(()) + } } - } - other => other.map(drop), + other => other.map(drop), + }; + (res, db) } } - } + }; + result.and_then(|_| db.flush().map_err(|e| ::util::UtilError::SimpleString(e).into())) } /// Feed a state chunk to be processed synchronously. @@ -536,7 +559,7 @@ impl SnapshotService for Service { fn status(&self) -> RestorationStatus { let mut cur_status = self.status.lock(); - if let RestorationStatus::Ongoing { ref mut state_chunks_done, ref mut block_chunks_done } = *cur_status { + if let RestorationStatus::Ongoing { ref mut state_chunks_done, ref mut block_chunks_done, .. } = *cur_status { *state_chunks_done = self.state_chunks.load(Ordering::SeqCst) as u32; *block_chunks_done = self.block_chunks.load(Ordering::SeqCst) as u32; } @@ -545,8 +568,9 @@ impl SnapshotService for Service { } fn begin_restore(&self, manifest: ManifestData) { - self.io_channel.send(ClientIoMessage::BeginRestoration(manifest)) - .expect("snapshot service and io service are kept alive by client service; qed"); + if let Err(e) = self.io_channel.lock().send(ClientIoMessage::BeginRestoration(manifest)) { + trace!("Error sending snapshot service message: {:?}", e); + } } fn abort_restore(&self) { @@ -555,13 +579,23 @@ impl SnapshotService for Service { } fn restore_state_chunk(&self, hash: H256, chunk: Bytes) { - self.io_channel.send(ClientIoMessage::FeedStateChunk(hash, chunk)) - .expect("snapshot service and io service are kept alive by client service; qed"); + if let Err(e) = self.io_channel.lock().send(ClientIoMessage::FeedStateChunk(hash, chunk)) { + trace!("Error sending snapshot service message: {:?}", e); + } } fn restore_block_chunk(&self, hash: H256, chunk: Bytes) { - self.io_channel.send(ClientIoMessage::FeedBlockChunk(hash, chunk)) - .expect("snapshot service and io service are kept alive by client service; qed"); + if let Err(e) = self.io_channel.lock().send(ClientIoMessage::FeedBlockChunk(hash, chunk)) { + trace!("Error sending snapshot service message: {:?}", e); + } + } + + fn provide_canon_hashes(&self, canonical: &[(u64, H256)]) { + let mut rest = self.restoration.lock(); + + if let Some(ref mut rest) = rest.as_mut() { + rest.note_canonical(canonical); + } } } diff --git a/ethcore/src/snapshot/snapshot_service_trait.rs b/ethcore/src/snapshot/snapshot_service_trait.rs index 65448090fcd899ef8280b103989285dde8a527a7..42223f8784cadd87b8c3fbdb4fee2fcc1a993fbb 100644 --- a/ethcore/src/snapshot/snapshot_service_trait.rs +++ b/ethcore/src/snapshot/snapshot_service_trait.rs @@ -48,6 +48,10 @@ pub trait SnapshotService : Sync + Send { /// Feed a raw block chunk to the service to be processed asynchronously. /// no-op if currently restoring. fn restore_block_chunk(&self, hash: H256, chunk: Bytes); + + /// Give the restoration in-progress some canonical block hashes for + /// extra verification (performed at the end) + fn provide_canon_hashes(&self, canonical: &[(u64, H256)]); } impl IpcConfig for SnapshotService { } diff --git a/ethcore/src/snapshot/tests/blocks.rs b/ethcore/src/snapshot/tests/blocks.rs index 3c8744bcce41f068bacd32327c6d6d27c6596bfb..063ab2e4d59cb5ac5ec5cf60681615c33b8c5578 100644 --- a/ethcore/src/snapshot/tests/blocks.rs +++ b/ethcore/src/snapshot/tests/blocks.rs @@ -26,6 +26,7 @@ use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter}; use util::{Mutex, snappy}; use util::kvdb::{Database, DatabaseConfig}; +use std::collections::HashMap; use std::sync::Arc; use spec::Spec; @@ -61,19 +62,21 @@ fn chunk_and_restore(amount: u64) { // snapshot it. let writer = Mutex::new(PackedWriter::new(&snapshot_path).unwrap()); - let block_hashes = chunk_blocks(&bc, (amount, best_hash), &writer, &Progress::default()).unwrap(); - writer.into_inner().finish(::snapshot::ManifestData { + let block_hashes = chunk_blocks(&bc, best_hash, &writer, &Progress::default()).unwrap(); + let manifest = ::snapshot::ManifestData { state_hashes: Vec::new(), block_hashes: block_hashes, - state_root: Default::default(), + state_root: ::util::sha3::SHA3_NULL_RLP, block_number: amount, block_hash: best_hash, - }).unwrap(); + }; + + writer.into_inner().finish(manifest.clone()).unwrap(); // restore it. - let restored_db = Arc::new(Database::open(&db_cfg, new_path.as_str()).unwrap()); - let restored_chain = new_chain(restored_db.clone()); - let mut rebuilder = BlockRebuilder::new(restored_chain, amount).unwrap(); + let new_db = Arc::new(Database::open(&db_cfg, new_path.as_str()).unwrap()); + let new_chain = BlockChain::new(Default::default(), &genesis, new_db.clone(), Spec::new_null().engine); + let mut rebuilder = BlockRebuilder::new(new_chain, new_db.clone(), &manifest).unwrap(); let reader = PackedReader::new(&snapshot_path).unwrap().unwrap(); let engine = ::engines::NullEngine::new(Default::default(), Default::default()); for chunk_hash in &reader.manifest().block_hashes { @@ -82,11 +85,11 @@ fn chunk_and_restore(amount: u64) { rebuilder.feed(&chunk, &engine).unwrap(); } - rebuilder.glue_chunks(); + rebuilder.finalize(HashMap::new()).unwrap(); // and test it. - let restored_chain = new_chain(restored_db); - assert_eq!(restored_chain.best_block_hash(), best_hash); + let new_chain = BlockChain::new(Default::default(), &genesis, new_db, Spec::new_null().engine); + assert_eq!(new_chain.best_block_hash(), best_hash); } #[test] diff --git a/ethcore/src/snapshot/tests/helpers.rs b/ethcore/src/snapshot/tests/helpers.rs index cb928346e1525a38b0165b27fe057426be1bec9a..c97f138d72f30a3e2a403398c3f51ee58dc64f99 100644 --- a/ethcore/src/snapshot/tests/helpers.rs +++ b/ethcore/src/snapshot/tests/helpers.rs @@ -21,6 +21,7 @@ use account_db::AccountDBMut; use rand::Rng; use snapshot::account::Account; +use util::DBValue; use util::hash::{FixedHash, H256}; use util::hashdb::HashDB; use util::trie::{Alphabet, StandardMap, SecTrieDBMut, TrieMut, ValueMode}; @@ -66,7 +67,7 @@ impl StateProducer { let mut account = Account::from_thin_rlp(&*account_data); let acct_db = AccountDBMut::from_hash(db, *address_hash); fill_storage(acct_db, account.storage_root_mut(), &mut self.storage_seed); - *account_data = account.to_thin_rlp(); + *account_data = DBValue::from_vec(account.to_thin_rlp()); } // sweep again to alter account trie. diff --git a/ethcore/src/snapshot/watcher.rs b/ethcore/src/snapshot/watcher.rs index 65f47efc8e2e530da25ec057e89851f655ec3a4f..43439e437cf9b2d36062f16483ef58bcd771915d 100644 --- a/ethcore/src/snapshot/watcher.rs +++ b/ethcore/src/snapshot/watcher.rs @@ -16,6 +16,7 @@ //! Watcher for snapshot-related chain events. +use util::Mutex; use client::{BlockChainClient, Client, ChainNotify}; use ids::BlockID; use service::ClientIoMessage; @@ -30,7 +31,7 @@ use std::sync::Arc; trait Oracle: Send + Sync { fn to_number(&self, hash: H256) -> Option; - fn is_major_syncing(&self) -> bool; + fn is_major_importing(&self) -> bool; } struct StandardOracle where F: 'static + Send + Sync + Fn() -> bool { @@ -45,10 +46,8 @@ impl Oracle for StandardOracle self.client.block_header(BlockID::Hash(hash)).map(|h| HeaderView::new(&h).number()) } - fn is_major_syncing(&self) -> bool { - let queue_info = self.client.queue_info(); - - (self.sync_status)() || queue_info.unverified_queue_size + queue_info.verified_queue_size > 3 + fn is_major_importing(&self) -> bool { + (self.sync_status)() } } @@ -57,7 +56,7 @@ trait Broadcast: Send + Sync { fn take_at(&self, num: Option); } -impl Broadcast for IoChannel { +impl Broadcast for Mutex> { fn take_at(&self, num: Option) { let num = match num { Some(n) => n, @@ -66,7 +65,7 @@ impl Broadcast for IoChannel { trace!(target: "snapshot_watcher", "broadcast: {}", num); - if let Err(e) = self.send(ClientIoMessage::TakeSnapshot(num)) { + if let Err(e) = self.lock().send(ClientIoMessage::TakeSnapshot(num)) { warn!("Snapshot watcher disconnected from IoService: {}", e); } } @@ -93,7 +92,7 @@ impl Watcher { client: client, sync_status: sync_status, }), - broadcast: Box::new(channel), + broadcast: Box::new(Mutex::new(channel)), period: period, history: history, } @@ -110,7 +109,7 @@ impl ChainNotify for Watcher { _: Vec, _duration: u64) { - if self.oracle.is_major_syncing() { return } + if self.oracle.is_major_importing() { return } trace!(target: "snapshot_watcher", "{} imported", imported.len()); @@ -145,7 +144,7 @@ mod tests { self.0.get(&hash).cloned() } - fn is_major_syncing(&self) -> bool { false } + fn is_major_importing(&self) -> bool { false } } struct TestBroadcast(Option); @@ -200,4 +199,4 @@ mod tests { fn doesnt_fire_before_history() { harness(vec![10, 11], 10, 5, None); } -} \ No newline at end of file +} diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index a76cb7d5ef1affbdd8cb52a1a1edab745830ced4..e6ca8a8c4f80c15c4e133b893ce66f729f7484de 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -16,10 +16,12 @@ //! Parameters for a block chain. -use common::*; +use util::*; +use builtin::Builtin; use engines::{Engine, NullEngine, InstantSeal, BasicAuthority, Tendermint}; use pod_state::*; use account_db::*; +use header::{BlockNumber, Header}; use state_db::StateDB; use super::genesis::Genesis; use super::seal::Generic as GenericSeal; @@ -151,7 +153,8 @@ impl Spec { if self.state_root_memo.read().is_none() { *self.state_root_memo.write() = Some(self.genesis_state.root()); } - self.state_root_memo.read().as_ref().unwrap().clone() + self.state_root_memo.read().as_ref().cloned() + .expect("state root memo ensured to be set at this point; qed") } /// Get the known knodes of the network in enode format. diff --git a/ethcore/src/state/account.rs b/ethcore/src/state/account.rs index 79a9e8ef11251d8226f2d13da46810207549827a..d8d281b176bb24d4681d3bbcbfdf2299aa7f683e 100644 --- a/ethcore/src/state/account.rs +++ b/ethcore/src/state/account.rs @@ -172,7 +172,7 @@ impl Account { using it will not fail."); let item: U256 = match db.get(key){ - Ok(x) => x.map_or_else(U256::zero, decode), + Ok(x) => x.map_or_else(U256::zero, |v| decode(&*v)), Err(e) => panic!("Encountered potential DB corruption: {}", e), }; let value: H256 = item.into(); @@ -247,23 +247,34 @@ impl Account { } /// Provide a database to get `code_hash`. Should not be called if it is a contract without code. - pub fn cache_code(&mut self, db: &HashDB) -> bool { + pub fn cache_code(&mut self, db: &HashDB) -> Option> { // TODO: fill out self.code_cache; trace!("Account::cache_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty()); - self.is_cached() || + + if self.is_cached() { return Some(self.code_cache.clone()) } + match db.get(&self.code_hash) { Some(x) => { - self.code_cache = Arc::new(x.to_vec()); self.code_size = Some(x.len()); - true + self.code_cache = Arc::new(x.to_vec()); + Some(self.code_cache.clone()) }, _ => { warn!("Failed reverse get of {}", self.code_hash); - false + None }, } } + /// Provide code to cache. For correctness, should be the correct code for the + /// account. + pub fn cache_given_code(&mut self, code: Arc) { + trace!("Account::cache_given_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty()); + + self.code_size = Some(code.len()); + self.code_cache = code; + } + /// Provide a database to get `code_size`. Should not be called if it is a contract without code. pub fn cache_code_size(&mut self, db: &HashDB) -> bool { // TODO: fill out self.code_cache; @@ -288,6 +299,15 @@ impl Account { /// Determine whether there are any un-`commit()`-ed storage-setting operations. pub fn storage_is_clean(&self) -> bool { self.storage_changes.is_empty() } + /// Check if account has zero nonce, balance, no code and no storage. + pub fn is_empty(&self) -> bool { + self.storage_changes.is_empty() && + self.balance.is_zero() && + self.nonce.is_zero() && + self.storage_root == SHA3_NULL_RLP && + self.code_hash == SHA3_EMPTY + } + #[cfg(test)] /// return the storage root associated with this account or None if it has been altered via the overlay. pub fn storage_root(&self) -> Option<&H256> { if self.storage_is_clean() {Some(&self.storage_root)} else {None} } @@ -342,7 +362,7 @@ impl Account { self.code_filth = Filth::Clean; }, (true, false) => { - db.emplace(self.code_hash.clone(), (*self.code_cache).clone()); + db.emplace(self.code_hash.clone(), DBValue::from_slice(&*self.code_cache)); self.code_size = Some(self.code_cache.len()); self.code_filth = Filth::Clean; }, @@ -404,7 +424,7 @@ impl Account { self.code_size = other.code_size; self.address_hash = other.address_hash; let mut cache = self.storage_cache.borrow_mut(); - for (k, v) in other.storage_cache.into_inner().into_iter() { + for (k, v) in other.storage_cache.into_inner() { cache.insert(k.clone() , v.clone()); //TODO: cloning should not be required here } self.storage_changes = other.storage_changes; @@ -467,7 +487,7 @@ mod tests { }; let mut a = Account::from_rlp(&rlp); - assert!(a.cache_code(&db.immutable())); + assert!(a.cache_code(&db.immutable()).is_some()); let mut a = Account::from_rlp(&rlp); assert_eq!(a.note_code(vec![0x55, 0x44, 0xffu8]), Ok(())); diff --git a/ethcore/src/state/mod.rs b/ethcore/src/state/mod.rs index 39c8bbc111425f13fc4f0197c97e509f30443ed0..7c0f43d9721583417c6bfec7f873df0b103cc645 100644 --- a/ethcore/src/state/mod.rs +++ b/ethcore/src/state/mod.rs @@ -16,14 +16,18 @@ use std::cell::{RefCell, RefMut}; use std::collections::hash_map::Entry; -use common::*; +use util::*; +use receipt::Receipt; use engines::Engine; +use env_info::EnvInfo; +use error::Error; use executive::{Executive, TransactOptions}; use factory::Factories; use trace::FlatTrace; use pod_account::*; use pod_state::{self, PodState}; use types::state_diff::StateDiff; +use transaction::SignedTransaction; use state_db::StateDB; mod account; @@ -123,11 +127,10 @@ impl AccountEntry { fn overwrite_with(&mut self, other: AccountEntry) { self.state = other.state; match other.account { - Some(acc) => match self.account { - Some(ref mut ours) => { + Some(acc) => { + if let Some(ref mut ours) = self.account { ours.overwrite_with(acc); - }, - None => {}, + } }, None => self.account = None, } @@ -167,24 +170,24 @@ impl AccountEntry { /// Upon destruction all the local cache data propagated into the global cache. /// Propagated items might be rejected if current state is non-canonical. /// -/// State snapshotting. +/// State checkpointing. /// -/// A new snapshot can be created with `snapshot()`. Snapshots can be +/// A new checkpoint can be created with `checkpoint()`. checkpoints can be /// created in a hierarchy. -/// When a snapshot is active all changes are applied directly into -/// `cache` and the original value is copied into an active snapshot. -/// Reverting a snapshot with `revert_to_snapshot` involves copying -/// original values from the latest snapshot back into `cache`. The code +/// When a checkpoint is active all changes are applied directly into +/// `cache` and the original value is copied into an active checkpoint. +/// Reverting a checkpoint with `revert_to_checkpoint` involves copying +/// original values from the latest checkpoint back into `cache`. The code /// takes care not to overwrite cached storage while doing that. -/// Snapshot can be discateded with `discard_snapshot`. All of the orignal -/// backed-up values are moved into a parent snapshot (if any). +/// checkpoint can be discateded with `discard_checkpoint`. All of the orignal +/// backed-up values are moved into a parent checkpoint (if any). /// pub struct State { db: StateDB, root: H256, cache: RefCell>, // The original account is preserved in - snapshots: RefCell>>>, + checkpoints: RefCell>>>, account_start_nonce: U256, factories: Factories, } @@ -213,7 +216,7 @@ impl State { db: db, root: root, cache: RefCell::new(HashMap::new()), - snapshots: RefCell::new(Vec::new()), + checkpoints: RefCell::new(Vec::new()), account_start_nonce: account_start_nonce, factories: factories, } @@ -229,7 +232,7 @@ impl State { db: db, root: root, cache: RefCell::new(HashMap::new()), - snapshots: RefCell::new(Vec::new()), + checkpoints: RefCell::new(Vec::new()), account_start_nonce: account_start_nonce, factories: factories }; @@ -237,21 +240,21 @@ impl State { Ok(state) } - /// Create a recoverable snaphot of this state. - pub fn snapshot(&mut self) { - self.snapshots.borrow_mut().push(HashMap::new()); + /// Create a recoverable checkpoint of this state. + pub fn checkpoint(&mut self) { + self.checkpoints.get_mut().push(HashMap::new()); } - /// Merge last snapshot with previous. - pub fn discard_snapshot(&mut self) { - // merge with previous snapshot - let last = self.snapshots.borrow_mut().pop(); - if let Some(mut snapshot) = last { - if let Some(ref mut prev) = self.snapshots.borrow_mut().last_mut() { + /// Merge last checkpoint with previous. + pub fn discard_checkpoint(&mut self) { + // merge with previous checkpoint + let last = self.checkpoints.get_mut().pop(); + if let Some(mut checkpoint) = last { + if let Some(ref mut prev) = self.checkpoints.get_mut().last_mut() { if prev.is_empty() { - **prev = snapshot; + **prev = checkpoint; } else { - for (k, v) in snapshot.drain() { + for (k, v) in checkpoint.drain() { prev.entry(k).or_insert(v); } } @@ -259,15 +262,15 @@ impl State { } } - /// Revert to the last snapshot and discard it. - pub fn revert_to_snapshot(&mut self) { - if let Some(mut snapshot) = self.snapshots.borrow_mut().pop() { - for (k, v) in snapshot.drain() { + /// Revert to the last checkpoint and discard it. + pub fn revert_to_checkpoint(&mut self) { + if let Some(mut checkpoint) = self.checkpoints.get_mut().pop() { + for (k, v) in checkpoint.drain() { match v { Some(v) => { - match self.cache.borrow_mut().entry(k) { + match self.cache.get_mut().entry(k) { Entry::Occupied(mut e) => { - // Merge snapshotted changes back into the main account + // Merge checkpointed changes back into the main account // storage preserving the cache. e.get_mut().overwrite_with(v); }, @@ -277,13 +280,10 @@ impl State { } }, None => { - match self.cache.borrow_mut().entry(k) { - Entry::Occupied(e) => { - if e.get().is_dirty() { - e.remove(); - } - }, - _ => {} + if let Entry::Occupied(e) = self.cache.get_mut().entry(k) { + if e.get().is_dirty() { + e.remove(); + } } } } @@ -293,14 +293,14 @@ impl State { fn insert_cache(&self, address: &Address, account: AccountEntry) { // Dirty account which is not in the cache means this is a new account. - // It goes directly into the snapshot as there's nothing to rever to. + // It goes directly into the checkpoint as there's nothing to rever to. // // In all other cases account is read as clean first, and after that made - // dirty in and added to the snapshot with `note_cache`. + // dirty in and added to the checkpoint with `note_cache`. if account.is_dirty() { - if let Some(ref mut snapshot) = self.snapshots.borrow_mut().last_mut() { - if !snapshot.contains_key(address) { - snapshot.insert(address.clone(), self.cache.borrow_mut().insert(address.clone(), account)); + if let Some(ref mut checkpoint) = self.checkpoints.borrow_mut().last_mut() { + if !checkpoint.contains_key(address) { + checkpoint.insert(address.clone(), self.cache.borrow_mut().insert(address.clone(), account)); return; } } @@ -309,9 +309,9 @@ impl State { } fn note_cache(&self, address: &Address) { - if let Some(ref mut snapshot) = self.snapshots.borrow_mut().last_mut() { - if !snapshot.contains_key(address) { - snapshot.insert(address.clone(), self.cache.borrow().get(address).map(AccountEntry::clone_dirty)); + if let Some(ref mut checkpoint) = self.checkpoints.borrow_mut().last_mut() { + if !checkpoint.contains_key(address) { + checkpoint.insert(address.clone(), self.cache.borrow().get(address).map(AccountEntry::clone_dirty)); } } } @@ -340,18 +340,20 @@ impl State { /// Determine whether an account exists. pub fn exists(&self, a: &Address) -> bool { - self.ensure_cached(a, RequireCache::None, |a| a.is_some()) + // 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. + self.ensure_cached(a, RequireCache::None, false, |a| a.is_some()) } /// Get the balance of account `a`. pub fn balance(&self, a: &Address) -> U256 { - self.ensure_cached(a, RequireCache::None, + self.ensure_cached(a, RequireCache::None, true, |a| a.as_ref().map_or(U256::zero(), |account| *account.balance())) } /// Get the nonce of account `a`. pub fn nonce(&self, a: &Address) -> U256 { - self.ensure_cached(a, RequireCache::None, + self.ensure_cached(a, RequireCache::None, true, |a| a.as_ref().map_or(self.account_start_nonce, |account| *account.nonce())) } @@ -402,7 +404,7 @@ impl State { // 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); let maybe_acc = match db.get(address) { - Ok(acc) => acc.map(Account::from_rlp), + Ok(acc) => acc.map(|v| Account::from_rlp(&v)), Err(e) => panic!("Potential DB corruption encountered: {}", e), }; let r = maybe_acc.as_ref().map_or(H256::new(), |a| { @@ -415,18 +417,18 @@ impl State { /// Get accounts' code. pub fn code(&self, a: &Address) -> Option> { - self.ensure_cached(a, RequireCache::Code, + self.ensure_cached(a, RequireCache::Code, true, |a| a.as_ref().map_or(None, |a| a.code().clone())) } pub fn code_hash(&self, a: &Address) -> H256 { - self.ensure_cached(a, RequireCache::None, + self.ensure_cached(a, RequireCache::None, true, |a| a.as_ref().map_or(SHA3_EMPTY, |a| a.code_hash())) } /// Get accounts' code size. pub fn code_size(&self, a: &Address) -> Option { - self.ensure_cached(a, RequireCache::CodeSize, + self.ensure_cached(a, RequireCache::CodeSize, true, |a| a.as_ref().and_then(|a| a.code_size())) } @@ -495,6 +497,7 @@ impl State { /// Commit accounts to SecTrieDBMut. This is similar to cpp-ethereum's dev::eth::commit. /// `accounts` is mutable because we may need to commit the code or storage and record that. #[cfg_attr(feature="dev", allow(match_ref_pats))] + #[cfg_attr(feature="dev", allow(needless_borrow))] fn commit_into( factories: &Factories, db: &mut StateDB, @@ -503,20 +506,19 @@ impl State { ) -> Result<(), Error> { // first, commit the sub trees. for (address, ref mut a) in accounts.iter_mut().filter(|&(_, ref a)| a.is_dirty()) { - match a.account { - Some(ref mut account) => { - 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()); + 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 trie = factories.trie.from_existing(db.as_hashdb_mut(), root).unwrap(); + let mut trie = try!(factories.trie.from_existing(db.as_hashdb_mut(), root)); for (address, ref mut a) in accounts.iter_mut().filter(|&(_, ref a)| a.is_dirty()) { a.state = AccountState::Committed; match a.account { @@ -544,7 +546,7 @@ impl State { /// Commits our cached account changes into the trie. pub fn commit(&mut self) -> Result<(), Error> { - assert!(self.snapshots.borrow().is_empty()); + assert!(self.checkpoints.borrow().is_empty()); Self::commit_into(&self.factories, &mut self.db, &mut self.root, &mut *self.cache.borrow_mut()) } @@ -557,16 +559,15 @@ impl State { #[cfg(feature = "json-tests")] /// Populate the state from `accounts`. pub fn populate_from(&mut self, accounts: PodState) { - assert!(self.snapshots.borrow().is_empty()); + assert!(self.checkpoints.borrow().is_empty()); for (add, acc) in accounts.drain().into_iter() { - self.db.note_account_bloom(&add); self.cache.borrow_mut().insert(add, AccountEntry::new_dirty(Some(Account::from_pod(acc)))); } } /// Populate a PodAccount map from this state. pub fn to_pod(&self) -> PodState { - assert!(self.snapshots.borrow().is_empty()); + assert!(self.checkpoints.borrow().is_empty()); // TODO: handle database rather than just the cache. // will need fat db. PodState::from(self.cache.borrow().iter().fold(BTreeMap::new(), |mut m, (add, opt)| { @@ -578,14 +579,14 @@ impl State { } fn query_pod(&mut self, query: &PodState) { - for (address, pod_account) in query.get() { - self.ensure_cached(address, RequireCache::Code, |a| { - if a.is_some() { - for key in pod_account.storage.keys() { - self.storage_at(address, key); - } - } - }); + for (address, pod_account) in query.get().into_iter() + .filter(|&(a, _)| self.ensure_cached(a, RequireCache::Code, true, |a| a.is_some())) + { + // needs to be split into two parts for the refcell code here + // to work. + for key in pod_account.storage.keys() { + self.storage_at(address, key); + } } } @@ -598,14 +599,30 @@ impl State { pod_state::diff_pod(&state_pre.to_pod(), &pod_state_post) } - fn update_account_cache(require: RequireCache, account: &mut Account, db: &HashDB) { - match require { - RequireCache::None => {}, - RequireCache::Code => { - account.cache_code(db); - } - RequireCache::CodeSize => { - account.cache_code_size(db); + // load required account data from the databases. + fn update_account_cache(require: RequireCache, account: &mut Account, state_db: &StateDB, db: &HashDB) { + match (account.is_cached(), require) { + (true, _) | (false, RequireCache::None) => {} + (false, require) => { + // if there's already code in the global cache, always cache it + // locally. + let hash = account.code_hash(); + match state_db.get_cached_code(&hash) { + Some(code) => account.cache_given_code(code), + None => match require { + RequireCache::None => {}, + RequireCache::Code => { + if let Some(code) = account.cache_code(db) { + // propagate code loaded from the database to + // the global code cache. + state_db.cache_code(hash, code) + } + } + RequireCache::CodeSize => { + account.cache_code_size(db); + } + } + } } } } @@ -613,13 +630,13 @@ impl State { /// Check caches for required data /// First searches for account in the local, then the shared cache. /// Populates local cache if nothing found. - fn ensure_cached(&self, a: &Address, require: RequireCache, f: F) -> U + fn ensure_cached(&self, a: &Address, require: RequireCache, check_bloom: bool, f: F) -> U where F: Fn(Option<&Account>) -> U { // check local cache first if let Some(ref mut maybe_acc) = self.cache.borrow_mut().get_mut(a) { if let Some(ref mut account) = maybe_acc.account { let accountdb = self.factories.accountdb.readonly(self.db.as_hashdb(), account.address_hash(a)); - Self::update_account_cache(require, account, accountdb.as_hashdb()); + Self::update_account_cache(require, account, &self.db, accountdb.as_hashdb()); return f(Some(account)); } return f(None); @@ -628,7 +645,7 @@ impl State { let result = self.db.get_cached(a, |mut acc| { if let Some(ref mut account) = acc { let accountdb = self.factories.accountdb.readonly(self.db.as_hashdb(), account.address_hash(a)); - Self::update_account_cache(require, account, accountdb.as_hashdb()); + Self::update_account_cache(require, account, &self.db, accountdb.as_hashdb()); } f(acc.map(|a| &*a)) }); @@ -636,17 +653,17 @@ impl State { Some(r) => r, None => { // first check bloom if it is not in database for sure - if !self.db.check_account_bloom(a) { return f(None); } + if check_bloom && !self.db.check_account_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); let mut maybe_acc = match db.get(a) { - Ok(acc) => acc.map(Account::from_rlp), + Ok(acc) => acc.map(|v| Account::from_rlp(&v)), Err(e) => panic!("Potential DB corruption encountered: {}", e), }; if let Some(ref mut account) = maybe_acc.as_mut() { let accountdb = self.factories.accountdb.readonly(self.db.as_hashdb(), account.address_hash(a)); - Self::update_account_cache(require, account, accountdb.as_hashdb()); + Self::update_account_cache(require, account, &self.db, accountdb.as_hashdb()); } let r = f(maybe_acc.as_ref()); self.insert_cache(a, AccountEntry::new_clean(maybe_acc)); @@ -672,14 +689,12 @@ impl State { None => { let maybe_acc = if self.db.check_account_bloom(a) { let db = self.factories.trie.readonly(self.db.as_hashdb(), &self.root).expect(SEC_TRIE_DB_UNWRAP_STR); - let maybe_acc = match db.get(a) { - Ok(Some(acc)) => AccountEntry::new_clean(Some(Account::from_rlp(acc))), + match db.get(a) { + Ok(Some(acc)) => AccountEntry::new_clean(Some(Account::from_rlp(&acc))), Ok(None) => AccountEntry::new_clean(None), Err(e) => panic!("Potential DB corruption encountered: {}", e), - }; - maybe_acc - } - else { + } + } else { AccountEntry::new_clean(None) }; self.insert_cache(a, maybe_acc); @@ -688,14 +703,15 @@ impl State { } self.note_cache(a); - match &mut self.cache.borrow_mut().get_mut(a).unwrap().account { - &mut Some(ref mut acc) => not_default(acc), - slot => *slot = Some(default()), - } - - // at this point the account is guaranteed to be in the cache. + // at this point the entry is guaranteed to be in the cache. RefMut::map(self.cache.borrow_mut(), |c| { - let mut entry = c.get_mut(a).unwrap(); + let mut entry = c.get_mut(a).expect("entry known to exist in the cache; qed"); + + match &mut entry.account { + &mut Some(ref mut acc) => not_default(acc), + slot => *slot = Some(default()), + } + // set the dirty flag after changing account data. entry.state = AccountState::Dirty; match entry.account { @@ -703,7 +719,7 @@ impl State { if require_code { let addr_hash = account.address_hash(a); let accountdb = self.factories.accountdb.readonly(self.db.as_hashdb(), addr_hash); - account.cache_code(accountdb.as_hashdb()); + Self::update_account_cache(RequireCache::Code, account, &self.db, accountdb.as_hashdb()); } account }, @@ -735,7 +751,7 @@ impl Clone for State { db: self.db.boxed_clone(), root: self.root.clone(), cache: RefCell::new(cache), - snapshots: RefCell::new(Vec::new()), + checkpoints: RefCell::new(Vec::new()), account_start_nonce: self.account_start_nonce.clone(), factories: self.factories.clone(), } @@ -752,7 +768,7 @@ use super::*; use util::{U256, H256, FixedHash, Address, Hashable}; use tests::helpers::*; use devtools::*; -use env_info::*; +use env_info::EnvInfo; use spec::*; use transaction::*; use util::log::init_log; @@ -1667,6 +1683,21 @@ fn remove() { assert_eq!(state.nonce(&a), U256::from(0u64)); } +#[test] +fn empty_account_exists() { + 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.commit().unwrap(); + state.drop() + }; + let state = State::from_existing(db, root, U256::from(0u8), Default::default()).unwrap(); + assert!(state.exists(&a)); +} + #[test] fn remove_from_database() { let a = Address::zero(); @@ -1758,34 +1789,34 @@ fn ensure_cached() { } #[test] -fn snapshot_basic() { +fn checkpoint_basic() { let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); let a = Address::zero(); - state.snapshot(); + state.checkpoint(); state.add_balance(&a, &U256::from(69u64)); assert_eq!(state.balance(&a), U256::from(69u64)); - state.discard_snapshot(); + state.discard_checkpoint(); assert_eq!(state.balance(&a), U256::from(69u64)); - state.snapshot(); + state.checkpoint(); state.add_balance(&a, &U256::from(1u64)); assert_eq!(state.balance(&a), U256::from(70u64)); - state.revert_to_snapshot(); + state.revert_to_checkpoint(); assert_eq!(state.balance(&a), U256::from(69u64)); } #[test] -fn snapshot_nested() { +fn checkpoint_nested() { let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); let a = Address::zero(); - state.snapshot(); - state.snapshot(); + state.checkpoint(); + state.checkpoint(); state.add_balance(&a, &U256::from(69u64)); assert_eq!(state.balance(&a), U256::from(69u64)); - state.discard_snapshot(); + state.discard_checkpoint(); assert_eq!(state.balance(&a), U256::from(69u64)); - state.revert_to_snapshot(); + state.revert_to_checkpoint(); assert_eq!(state.balance(&a), U256::from(0)); } @@ -1797,4 +1828,20 @@ fn create_empty() { assert_eq!(state.root().hex(), "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"); } +#[test] +fn should_not_panic_on_state_diff_with_storage() { + let state = get_temp_state(); + let mut state = state.reference().clone(); + + let a: Address = 0xa.into(); + state.init_code(&a, b"abcdefg".to_vec()); + state.add_balance(&a, &256.into()); + state.set_storage(&a, 0xb.into(), 0xc.into()); + + let mut new_state = state.clone(); + new_state.set_storage(&a, 0xb.into(), 0xd.into()); + + new_state.diff_from(state); +} + } diff --git a/ethcore/src/state_db.rs b/ethcore/src/state_db.rs index 04db274c4249c3c4b15f1b7073fa288e4ffeab77..e60a74614d7da7c205ae50fad470999881b2cf6a 100644 --- a/ethcore/src/state_db.rs +++ b/ethcore/src/state_db.rs @@ -16,6 +16,7 @@ use std::collections::{VecDeque, HashSet}; use lru_cache::LruCache; +use util::cache::MemoryLruCache; use util::journaldb::JournalDB; use util::hash::{H256}; use util::hashdb::HashDB; @@ -26,17 +27,21 @@ use bloom_journal::{Bloom, BloomJournal}; use db::COL_ACCOUNT_BLOOM; use byteorder::{LittleEndian, ByteOrder}; -const STATE_CACHE_ITEMS: usize = 256000; -const STATE_CACHE_BLOCKS: usize = 8; - pub const ACCOUNT_BLOOM_SPACE: usize = 1048576; pub const DEFAULT_ACCOUNT_PRESET: usize = 1000000; pub const ACCOUNT_BLOOM_HASHCOUNT_KEY: &'static [u8] = b"account_hash_count"; +const STATE_CACHE_BLOCKS: usize = 12; + +// The percentage of supplied cache size to go to accounts. +const ACCOUNT_CACHE_RATIO: usize = 90; + /// Shared canonical state cache. struct AccountCache { /// DB Account cache. `None` indicates that account is known to be missing. + // When changing the type of the values here, be sure to update `mem_used` and + // `new`. accounts: LruCache>, /// Information on the modifications in recently committed blocks; specifically which addresses /// changed in which block. Ordered by block number. @@ -88,10 +93,13 @@ pub struct StateDB { db: Box, /// Shared canonical state cache. account_cache: Arc>, + /// DB Code cache. Maps code hashes to shared bytes. + code_cache: Arc>>>>, /// Local dirty cache. local_cache: Vec, /// Shared account bloom. Does not handle chain reorganizations. account_bloom: Arc>, + cache_size: usize, /// Hash of the block on top of which this instance was created or /// `None` if cache is disabled parent_hash: Option, @@ -102,16 +110,44 @@ pub struct StateDB { } impl StateDB { + + /// Create a new instance wrapping `JournalDB` and the maximum allowed size + /// of the LRU cache in bytes. Actual used memory may (read: will) be higher due to bookkeeping. + // TODO: make the cache size actually accurate by moving the account storage cache + // into the `AccountCache` structure as its own `LruCache<(Address, H256), H256>`. + pub fn new(db: Box, cache_size: usize) -> StateDB { + let bloom = Self::load_bloom(db.backing()); + let acc_cache_size = cache_size * ACCOUNT_CACHE_RATIO / 100; + let code_cache_size = cache_size - acc_cache_size; + let cache_items = acc_cache_size / ::std::mem::size_of::>(); + + StateDB { + db: db, + account_cache: Arc::new(Mutex::new(AccountCache { + accounts: LruCache::new(cache_items), + modifications: VecDeque::new(), + })), + code_cache: Arc::new(Mutex::new(MemoryLruCache::new(code_cache_size))), + local_cache: Vec::new(), + account_bloom: Arc::new(Mutex::new(bloom)), + cache_size: cache_size, + parent_hash: None, + commit_hash: None, + commit_number: None, + } + } + /// Loads accounts bloom from the database /// This bloom is used to handle request for the non-existant account fast pub fn load_bloom(db: &Database) -> Bloom { let hash_count_entry = db.get(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY) .expect("Low-level database error"); - if hash_count_entry.is_none() { - return Bloom::new(ACCOUNT_BLOOM_SPACE, DEFAULT_ACCOUNT_PRESET); - } - let hash_count_bytes = hash_count_entry.unwrap(); + let hash_count_bytes = match hash_count_entry { + Some(bytes) => bytes, + None => return Bloom::new(ACCOUNT_BLOOM_SPACE, DEFAULT_ACCOUNT_PRESET), + }; + assert_eq!(hash_count_bytes.len(), 1); let hash_count = hash_count_bytes[0]; @@ -129,23 +165,6 @@ impl StateDB { bloom } - /// Create a new instance wrapping `JournalDB` - pub fn new(db: Box) -> StateDB { - let bloom = Self::load_bloom(db.backing()); - StateDB { - db: db, - account_cache: Arc::new(Mutex::new(AccountCache { - accounts: LruCache::new(STATE_CACHE_ITEMS), - modifications: VecDeque::new(), - })), - local_cache: Vec::new(), - account_bloom: Arc::new(Mutex::new(bloom)), - parent_hash: None, - commit_hash: None, - commit_number: None, - } - } - pub fn check_account_bloom(&self, address: &Address) -> bool { trace!(target: "account_bloom", "Check account bloom: {:?}", address); let bloom = self.account_bloom.lock(); @@ -160,7 +179,7 @@ impl StateDB { pub fn commit_bloom(batch: &mut DBTransaction, journal: BloomJournal) -> Result<(), UtilError> { assert!(journal.hash_functions <= 255); - batch.put(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY, &vec![journal.hash_functions as u8]); + batch.put(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY, &[journal.hash_functions as u8]); let mut key = [0u8; 8]; let mut val = [0u8; 8]; @@ -172,19 +191,24 @@ impl StateDB { Ok(()) } - /// Commit all recent insert operations and canonical historical commits' removals from the - /// old era to the backing database, reverting any non-canonical historical commit's inserts. - pub fn commit(&mut self, batch: &mut DBTransaction, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result { + /// Journal all recent operations under the given era and ID. + pub fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result { { let mut bloom_lock = self.account_bloom.lock(); try!(Self::commit_bloom(batch, bloom_lock.drain_journal())); } - let records = try!(self.db.commit(batch, now, id, end)); + let records = try!(self.db.journal_under(batch, now, id)); self.commit_hash = Some(id.clone()); self.commit_number = Some(now); Ok(records) } + /// Mark a given candidate from an ancient era as canonical, enacting its removals from the + /// backing database and reverting any non-canonical historical commit's insertions. + pub fn mark_canonical(&mut self, batch: &mut DBTransaction, end_era: u64, canon_id: &H256) -> Result { + self.db.mark_canonical(batch, end_era, canon_id) + } + /// Propagate local cache into the global cache and synchonize /// the global cache with the best block state. /// This function updates the global cache by removing entries @@ -201,7 +225,7 @@ impl StateDB { let mut clear = false; for block in enacted.iter().filter(|h| self.commit_hash.as_ref().map_or(true, |p| *h != p)) { clear = clear || { - if let Some(ref mut m) = cache.modifications.iter_mut().find(|ref m| &m.hash == block) { + if let Some(ref mut m) = cache.modifications.iter_mut().find(|m| &m.hash == block) { trace!("Reverting enacted block {:?}", block); m.is_canon = true; for a in &m.accounts { @@ -217,7 +241,7 @@ impl StateDB { for block in retracted { clear = clear || { - if let Some(ref mut m) = cache.modifications.iter_mut().find(|ref m| &m.hash == block) { + if let Some(ref mut m) = cache.modifications.iter_mut().find(|m| &m.hash == block) { trace!("Retracting block {:?}", block); m.is_canon = false; for a in &m.accounts { @@ -271,7 +295,7 @@ impl StateDB { is_canon: is_best, parent: parent.clone(), }; - let insert_at = cache.modifications.iter().enumerate().find(|&(_, ref m)| m.number < *number).map(|(i, _)| i); + let insert_at = cache.modifications.iter().enumerate().find(|&(_, m)| m.number < *number).map(|(i, _)| i); trace!("inserting modifications at {:?}", insert_at); if let Some(insert_at) = insert_at { cache.modifications.insert(insert_at, block_changes); @@ -296,8 +320,10 @@ impl StateDB { StateDB { db: self.db.boxed_clone(), account_cache: self.account_cache.clone(), + code_cache: self.code_cache.clone(), local_cache: Vec::new(), account_bloom: self.account_bloom.clone(), + cache_size: self.cache_size, parent_hash: None, commit_hash: None, commit_number: None, @@ -309,8 +335,10 @@ impl StateDB { StateDB { db: self.db.boxed_clone(), account_cache: self.account_cache.clone(), + code_cache: self.code_cache.clone(), local_cache: Vec::new(), account_bloom: self.account_bloom.clone(), + cache_size: self.cache_size, parent_hash: Some(parent.clone()), commit_hash: None, commit_number: None, @@ -324,7 +352,12 @@ impl StateDB { /// Heap size used. pub fn mem_used(&self) -> usize { - self.db.mem_used() //TODO: + self.account_cache.lock().heap_size_of_children() + // TODO: account for LRU-cache overhead; this is a close approximation. + self.db.mem_used() + { + let accounts = self.account_cache.lock().accounts.len(); + let code_size = self.code_cache.lock().current_size(); + code_size + accounts * ::std::mem::size_of::>() + } } /// Returns underlying `JournalDB`. @@ -344,6 +377,15 @@ impl StateDB { }) } + /// Add a global code cache entry. This doesn't need to worry about canonicality because + /// it simply maps hashes to raw code and will always be correct in the absence of + /// hash collisions. + pub fn cache_code(&self, hash: H256, code: Arc>) { + let mut cache = self.code_cache.lock(); + + cache.insert(hash, code); + } + /// Get basic copy of the cached account. Does not include storage. /// Returns 'None' if cache is disabled or if the account is not cached. pub fn get_cached_account(&self, addr: &Address) -> Option> { @@ -351,7 +393,14 @@ impl StateDB { if !Self::is_allowed(addr, &self.parent_hash, &cache.modifications) { return None; } - cache.accounts.get_mut(&addr).map(|a| a.as_ref().map(|a| a.clone_basic())) + cache.accounts.get_mut(addr).map(|a| a.as_ref().map(|a| a.clone_basic())) + } + + /// Get cached code based on hash. + pub fn get_cached_code(&self, hash: &H256) -> Option>> { + let mut cache = self.code_cache.lock(); + + cache.get_mut(hash).map(|code| code.clone()) } /// Get value from a cached account. @@ -365,6 +414,11 @@ impl StateDB { cache.accounts.get_mut(a).map(|c| f(c.as_mut())) } + /// Query how much memory is set aside for the accounts cache (in bytes). + pub fn cache_size(&self) -> usize { + self.cache_size + } + /// Check if the account can be returned from cache by matching current block parent hash against canonical /// state and filtering out account modified in later blocks. fn is_allowed(addr: &Address, parent_hash: &Option, modifications: &VecDeque) -> bool { @@ -383,8 +437,7 @@ impl StateDB { // We search for our parent in that list first and then for // all its parent until we hit the canonical block, // checking against all the intermediate modifications. - let mut iter = modifications.iter(); - while let Some(ref m) = iter.next() { + for m in modifications { if &m.hash == parent { if m.is_canon { return true; @@ -397,84 +450,82 @@ impl StateDB { } } trace!("Cache lookup skipped for {:?}: parent hash is unknown", addr); - return false; + false } } #[cfg(test)] mod tests { - -use util::{U256, H256, FixedHash, Address, DBTransaction}; -use tests::helpers::*; -use state::Account; -use util::log::init_log; - -#[test] -fn state_db_smoke() { - init_log(); - - let mut state_db_result = get_temp_state_db(); - let state_db = state_db_result.take(); - let root_parent = H256::random(); - let address = Address::random(); - let h0 = H256::random(); - let h1a = H256::random(); - let h1b = H256::random(); - let h2a = H256::random(); - let h2b = H256::random(); - let h3a = H256::random(); - let h3b = H256::random(); - let mut batch = DBTransaction::new(state_db.journal_db().backing()); - - // blocks [ 3a(c) 2a(c) 2b 1b 1a(c) 0 ] - // balance [ 5 5 4 3 2 2 ] - let mut s = state_db.boxed_clone_canon(&root_parent); - s.add_to_account_cache(address, Some(Account::new_basic(2.into(), 0.into())), false); - s.commit(&mut batch, 0, &h0, None).unwrap(); - s.sync_cache(&[], &[], true); - - let mut s = state_db.boxed_clone_canon(&h0); - s.commit(&mut batch, 1, &h1a, None).unwrap(); - s.sync_cache(&[], &[], true); - - let mut s = state_db.boxed_clone_canon(&h0); - s.add_to_account_cache(address, Some(Account::new_basic(3.into(), 0.into())), true); - s.commit(&mut batch, 1, &h1b, None).unwrap(); - s.sync_cache(&[], &[], false); - - let mut s = state_db.boxed_clone_canon(&h1b); - s.add_to_account_cache(address, Some(Account::new_basic(4.into(), 0.into())), true); - s.commit(&mut batch, 2, &h2b, None).unwrap(); - s.sync_cache(&[], &[], false); - - let mut s = state_db.boxed_clone_canon(&h1a); - s.add_to_account_cache(address, Some(Account::new_basic(5.into(), 0.into())), true); - s.commit(&mut batch, 2, &h2a, None).unwrap(); - s.sync_cache(&[], &[], true); - - let mut s = state_db.boxed_clone_canon(&h2a); - s.commit(&mut batch, 3, &h3a, None).unwrap(); - s.sync_cache(&[], &[], true); - - let s = state_db.boxed_clone_canon(&h3a); - assert_eq!(s.get_cached_account(&address).unwrap().unwrap().balance(), &U256::from(5)); - - let s = state_db.boxed_clone_canon(&h1a); - assert!(s.get_cached_account(&address).is_none()); - - let s = state_db.boxed_clone_canon(&h2b); - assert!(s.get_cached_account(&address).is_none()); - - let s = state_db.boxed_clone_canon(&h1b); - assert!(s.get_cached_account(&address).is_none()); - - // reorg to 3b - // blocks [ 3b(c) 3a 2a 2b(c) 1b 1a 0 ] - let mut s = state_db.boxed_clone_canon(&h2b); - s.commit(&mut batch, 3, &h3b, None).unwrap(); - s.sync_cache(&[h1b.clone(), h2b.clone(), h3b.clone()], &[h1a.clone(), h2a.clone(), h3a.clone()], true); - let s = state_db.boxed_clone_canon(&h3a); - assert!(s.get_cached_account(&address).is_none()); -} + use util::{U256, H256, FixedHash, Address, DBTransaction}; + use tests::helpers::*; + use state::Account; + use util::log::init_log; + + #[test] + fn state_db_smoke() { + init_log(); + + let mut state_db_result = get_temp_state_db(); + let state_db = state_db_result.take(); + let root_parent = H256::random(); + let address = Address::random(); + let h0 = H256::random(); + let h1a = H256::random(); + let h1b = H256::random(); + let h2a = H256::random(); + let h2b = H256::random(); + let h3a = H256::random(); + let h3b = H256::random(); + let mut batch = DBTransaction::new(state_db.journal_db().backing()); + + // blocks [ 3a(c) 2a(c) 2b 1b 1a(c) 0 ] + // balance [ 5 5 4 3 2 2 ] + let mut s = state_db.boxed_clone_canon(&root_parent); + s.add_to_account_cache(address, Some(Account::new_basic(2.into(), 0.into())), false); + s.journal_under(&mut batch, 0, &h0).unwrap(); + s.sync_cache(&[], &[], true); + + let mut s = state_db.boxed_clone_canon(&h0); + s.journal_under(&mut batch, 1, &h1a).unwrap(); + s.sync_cache(&[], &[], true); + + let mut s = state_db.boxed_clone_canon(&h0); + s.add_to_account_cache(address, Some(Account::new_basic(3.into(), 0.into())), true); + s.journal_under(&mut batch, 1, &h1b).unwrap(); + s.sync_cache(&[], &[], false); + + let mut s = state_db.boxed_clone_canon(&h1b); + s.add_to_account_cache(address, Some(Account::new_basic(4.into(), 0.into())), true); + s.journal_under(&mut batch, 2, &h2b).unwrap(); + s.sync_cache(&[], &[], false); + + let mut s = state_db.boxed_clone_canon(&h1a); + s.add_to_account_cache(address, Some(Account::new_basic(5.into(), 0.into())), true); + s.journal_under(&mut batch, 2, &h2a).unwrap(); + s.sync_cache(&[], &[], true); + + let mut s = state_db.boxed_clone_canon(&h2a); + s.journal_under(&mut batch, 3, &h3a).unwrap(); + s.sync_cache(&[], &[], true); + + let s = state_db.boxed_clone_canon(&h3a); + assert_eq!(s.get_cached_account(&address).unwrap().unwrap().balance(), &U256::from(5)); + + let s = state_db.boxed_clone_canon(&h1a); + assert!(s.get_cached_account(&address).is_none()); + + let s = state_db.boxed_clone_canon(&h2b); + assert!(s.get_cached_account(&address).is_none()); + + let s = state_db.boxed_clone_canon(&h1b); + assert!(s.get_cached_account(&address).is_none()); + + // reorg to 3b + // blocks [ 3b(c) 3a 2a 2b(c) 1b 1a 0 ] + let mut s = state_db.boxed_clone_canon(&h2b); + s.journal_under(&mut batch, 3, &h3b).unwrap(); + s.sync_cache(&[h1b.clone(), h2b.clone(), h3b.clone()], &[h1a.clone(), h2a.clone(), h3a.clone()], true); + let s = state_db.boxed_clone_canon(&h3a); + assert!(s.get_cached_account(&address).is_none()); + } } - diff --git a/ethcore/src/tests/client.rs b/ethcore/src/tests/client.rs index 067f28d3918f8c48d11fa953dc218a7f9a6f1a01..3a24ccf21e4cebf04004616d267c8b7f6616e3ef 100644 --- a/ethcore/src/tests/client.rs +++ b/ethcore/src/tests/client.rs @@ -20,10 +20,13 @@ use ethereum; use block::IsBlock; use tests::helpers::*; use types::filter::Filter; -use common::*; +use util::*; use devtools::*; use miner::Miner; use rlp::{Rlp, View}; +use spec::Spec; +use views::BlockView; +use util::stats::Histogram; #[test] fn imports_from_empty() { @@ -196,19 +199,37 @@ fn can_collect_garbage() { assert!(client.blockchain_cache_info().blocks < 100 * 1024); } + +#[test] +fn can_generate_gas_price_median() { + let client_result = generate_dummy_client_with_data(3, 1, &vec_into![1, 2, 3]); + let client = client_result.reference(); + assert_eq!(Some(U256::from(2)), client.gas_price_median(3)); + + let client_result = generate_dummy_client_with_data(4, 1, &vec_into![1, 4, 3, 2]); + let client = client_result.reference(); + assert_eq!(Some(U256::from(3)), client.gas_price_median(4)); +} + +#[test] +fn can_generate_gas_price_histogram() { + let client_result = generate_dummy_client_with_data(20, 1, &vec_into![6354,8593,6065,4842,7845,7002,689,4958,4250,6098,5804,4320,643,8895,2296,8589,7145,2000,2512,1408]); + 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] }; + assert_eq!(hist, correct_hist); +} + #[test] -#[cfg_attr(feature="dev", allow(useless_vec))] -fn can_generate_gas_price_statistics() { - let client_result = generate_dummy_client_with_data(16, 1, &vec_into![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); +fn empty_gas_price_histogram() { + let client_result = generate_dummy_client_with_data(20, 0, &vec_into![]); let client = client_result.reference(); - let s = client.gas_price_statistics(8, 8).unwrap(); - assert_eq!(s, vec_into![8, 8, 9, 10, 11, 12, 13, 14, 15]); - let s = client.gas_price_statistics(16, 8).unwrap(); - assert_eq!(s, vec_into![0, 1, 3, 5, 7, 9, 11, 13, 15]); - let s = client.gas_price_statistics(32, 8).unwrap(); - assert_eq!(s, vec_into![0, 1, 3, 5, 7, 9, 11, 13, 15]); + + assert!(client.gas_price_histogram(20, 5).is_none()); } + #[test] fn can_handle_long_fork() { let client_result = generate_dummy_client(1200); @@ -222,7 +243,7 @@ fn can_handle_long_fork() { push_blocks_to_client(client, 49, 1201, 800); push_blocks_to_client(client, 53, 1201, 600); - for _ in 0..40 { + for _ in 0..400 { client.import_verified_blocks(); } assert_eq!(2000, client.chain_info().best_block_number); @@ -238,3 +259,27 @@ fn can_mine() { assert_eq!(*b.block().header().parent_hash(), BlockView::new(&dummy_blocks[0]).header_view().sha3()); } + +#[test] +fn change_history_size() { + let dir = RandomTempPath::new(); + let test_spec = Spec::new_null(); + let mut config = ClientConfig::default(); + let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS); + config.history = 2; + let address = Address::random(); + { + 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.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 + } + } + let mut config = ClientConfig::default(); + config.history = 10; + let client = Client::new(config, &test_spec, dir.as_path(), Arc::new(Miner::with_spec(&test_spec)), IoChannel::disconnected(), &db_config).unwrap(); + assert_eq!(client.state().balance(&address), 100.into()); +} diff --git a/ethcore/src/tests/helpers.rs b/ethcore/src/tests/helpers.rs index 8802019cd8a564faa7d4c6070ded9a155d2ea14c..e3d2f060b2f73b94a6aa1d883d108720eabef4f5 100644 --- a/ethcore/src/tests/helpers.rs +++ b/ethcore/src/tests/helpers.rs @@ -17,37 +17,42 @@ use ethkey::KeyPair; use io::*; use client::{BlockChainClient, Client, ClientConfig}; -use common::*; +use util::*; use spec::*; use state_db::StateDB; use block::{OpenBlock, Drain}; use blockchain::{BlockChain, Config as BlockChainConfig}; +use builtin::Builtin; use state::*; use evm::Schedule; use engines::Engine; +use env_info::EnvInfo; use ethereum; use devtools::*; use miner::Miner; +use header::Header; +use transaction::{Action, SignedTransaction, Transaction}; use rlp::{self, RlpStream, Stream}; -use db::COL_STATE; +use views::BlockView; #[cfg(feature = "json-tests")] pub enum ChainEra { Frontier, Homestead, - DaoHardfork, + Eip150, + TransitionTest, } pub struct TestEngine { engine: Arc, - max_depth: usize + max_depth: usize, } impl TestEngine { pub fn new(max_depth: usize) -> TestEngine { TestEngine { engine: ethereum::new_frontier_test().engine, - max_depth: max_depth + max_depth: max_depth, } } } @@ -345,8 +350,8 @@ pub fn get_temp_state() -> GuardedTempResult { pub fn get_temp_state_db_in(path: &Path) -> StateDB { let db = new_db(path.to_str().expect("Only valid utf8 paths for tests.")); - let journal_db = journaldb::new(db.clone(), journaldb::Algorithm::EarlyMerge, COL_STATE); - StateDB::new(journal_db) + let journal_db = journaldb::new(db.clone(), journaldb::Algorithm::EarlyMerge, ::db::COL_STATE); + StateDB::new(journal_db, 5 * 1024 * 1024) } pub fn get_temp_state_in(path: &Path) -> State { @@ -383,7 +388,7 @@ pub fn get_good_dummy_block_fork_seq(start_number: usize, count: usize, parent_h r } -pub fn get_good_dummy_block() -> Bytes { +pub fn get_good_dummy_block_hash() -> (H256, Bytes) { let mut block_header = Header::new(); let test_spec = get_test_spec(); let test_engine = &test_spec.engine; @@ -394,7 +399,12 @@ pub fn get_good_dummy_block() -> Bytes { block_header.set_parent_hash(test_spec.genesis_header().hash()); block_header.set_state_root(test_spec.genesis_header().state_root().clone()); - create_test_block(&block_header) + (block_header.hash(), create_test_block(&block_header)) +} + +pub fn get_good_dummy_block() -> Bytes { + let (_, bytes) = get_good_dummy_block_hash(); + bytes } pub fn get_bad_state_dummy_block() -> Bytes { diff --git a/ethcore/src/trace/db.rs b/ethcore/src/trace/db.rs index 2cf14828a3b5d43c818f433e5e1bdb8af9676dc1..6a1b55a1b66de431d341ea79e1dfdc7218f1bd86 100644 --- a/ethcore/src/trace/db.rs +++ b/ethcore/src/trace/db.rs @@ -129,7 +129,7 @@ impl TraceDB where T: DatabaseExtras { pub fn new(config: Config, tracesdb: Arc, extras: Arc) -> Self { let mut batch = DBTransaction::new(&tracesdb); batch.put(db::COL_TRACE, b"version", TRACE_DB_VER); - tracesdb.write(batch).unwrap(); + tracesdb.write(batch).expect("failed to update version"); TraceDB { traces: RwLock::new(HashMap::new()), @@ -275,16 +275,6 @@ impl TraceDatabase for TraceDB where T: DatabaseExtras { .map(Into::into) .collect(); - // insert new block traces into the cache and the database - { - let mut traces = self.traces.write(); - // it's important to use overwrite here, - // cause this value might be queried by hash later - batch.write_with_cache(db::COL_TRACE, &mut *traces, request.block_hash, request.traces, CacheUpdatePolicy::Overwrite); - // note_used must be called after locking traces to avoid cache/traces deadlock on garbage collection - self.note_used(CacheID::Trace(request.block_hash.clone())); - } - let chain = BloomGroupChain::new(self.bloom_config, self); let trace_blooms = chain.replace(&replaced_range, enacted_blooms); let blooms_to_insert = trace_blooms.into_iter() @@ -295,10 +285,20 @@ impl TraceDatabase for TraceDB where T: DatabaseExtras { let mut blooms = self.blooms.write(); batch.extend_with_cache(db::COL_TRACE, &mut *blooms, blooms_to_insert, CacheUpdatePolicy::Remove); // note_used must be called after locking blooms to avoid cache/traces deadlock on garbage collection - for key in blooms_keys.into_iter() { + for key in blooms_keys { self.note_used(CacheID::Bloom(key)); } } + + // insert new block traces into the cache and the database + { + let mut traces = self.traces.write(); + // it's important to use overwrite here, + // cause this value might be queried by hash later + batch.write_with_cache(db::COL_TRACE, &mut *traces, request.block_hash, request.traces, CacheUpdatePolicy::Overwrite); + // note_used must be called after locking traces to avoid cache/traces deadlock on garbage collection + self.note_used(CacheID::Trace(request.block_hash.clone())); + } } fn trace(&self, block_number: BlockNumber, tx_position: usize, trace_position: Vec) -> Option { @@ -504,6 +504,28 @@ mod tests { } } + fn create_noncanon_import_request(block_number: BlockNumber, block_hash: H256) -> ImportRequest { + ImportRequest { + traces: FlatBlockTraces::from(vec![FlatTransactionTraces::from(vec![FlatTrace { + trace_address: Default::default(), + subtraces: 0, + action: Action::Call(Call { + from: 1.into(), + to: 2.into(), + value: 3.into(), + gas: 4.into(), + input: vec![], + call_type: CallType::Call, + }), + result: Res::FailedCall(TraceError::OutOfGas), + }])]), + block_hash: block_hash.clone(), + block_number: block_number, + enacted: vec![], + retracted: 0, + } + } + fn create_simple_localized_trace(block_number: BlockNumber, block_hash: H256, tx_hash: H256) -> LocalizedTrace { LocalizedTrace { action: Action::Call(Call { @@ -524,6 +546,34 @@ mod tests { } } + #[test] + fn test_import_non_canon_traces() { + let temp = RandomTempPath::new(); + let db = Arc::new(Database::open(&DatabaseConfig::with_columns(::db::NUM_COLUMNS), temp.as_str()).unwrap()); + let mut config = Config::default(); + config.enabled = true; + let block_0 = H256::from(0xa1); + let block_1 = H256::from(0xa2); + let tx_0 = H256::from(0xff); + let tx_1 = H256::from(0xaf); + + let mut extras = Extras::default(); + extras.block_hashes.insert(0, block_0.clone()); + extras.block_hashes.insert(1, block_1.clone()); + extras.transaction_hashes.insert(0, vec![tx_0.clone()]); + extras.transaction_hashes.insert(1, vec![tx_1.clone()]); + + let tracedb = TraceDB::new(config, db.clone(), Arc::new(extras)); + + // import block 0 + let request = create_noncanon_import_request(0, block_0.clone()); + let mut batch = DBTransaction::new(&db); + tracedb.import(&mut batch, request); + db.write(batch).unwrap(); + + assert!(tracedb.traces(&block_0).is_some(), "Traces should be available even if block is non-canon."); + } + #[test] fn test_import() { diff --git a/ethcore/src/trace/executive_tracer.rs b/ethcore/src/trace/executive_tracer.rs index ca9bc30b51de835ce62fd50c63710124f5671bcf..bb18c61a8425cd0775cc420e4061656418526c08 100644 --- a/ethcore/src/trace/executive_tracer.rs +++ b/ethcore/src/trace/executive_tracer.rs @@ -50,12 +50,12 @@ fn prefix_subtrace_addresses(mut traces: Vec) -> Vec { // [1, 0] let mut current_subtrace_index = 0; let mut first = true; - for trace in traces.iter_mut() { + for trace in &mut traces { match (first, trace.trace_address.is_empty()) { (true, _) => first = false, (_, true) => current_subtrace_index += 1, _ => {} - } + } trace.trace_address.push_front(current_subtrace_index); } traces @@ -78,7 +78,7 @@ fn should_prefix_address_properly() { let t = vec![vec![], vec![0], vec![0, 0], vec![0], vec![], vec![], vec![0], vec![]].into_iter().map(&f).collect(); let t = prefix_subtrace_addresses(t); assert_eq!(t, vec![vec![0], vec![0, 0], vec![0, 0, 0], vec![0, 0], vec![1], vec![2], vec![2, 0], vec![3]].into_iter().map(&f).collect::>()); -} +} impl Tracer for ExecutiveTracer { fn prepare_trace_call(&self, params: &ActionParams) -> Option { diff --git a/ethcore/src/types/blockchain_info.rs b/ethcore/src/types/blockchain_info.rs index ef8924aec0b32fc2e9c842729fba084bac29fd92..ff6aa8ddec3de6727cf36cd93621cbcad290c51e 100644 --- a/ethcore/src/types/blockchain_info.rs +++ b/ethcore/src/types/blockchain_info.rs @@ -31,5 +31,13 @@ pub struct BlockChainInfo { /// Best blockchain block hash. pub best_block_hash: H256, /// Best blockchain block number. - pub best_block_number: BlockNumber + pub best_block_number: BlockNumber, + /// Best ancient block hash. + pub ancient_block_hash: Option, + /// Best ancient block number. + pub ancient_block_number: Option, + /// First block on the best sequence. + pub first_block_hash: Option, + /// Number of the first block on the best sequence. + pub first_block_number: Option, } diff --git a/ethcore/src/types/mod.rs.in b/ethcore/src/types/mod.rs.in index 32c7faabe21d6cc21a8a075aaf37f78d8c4e3909..1d2cdb3c01ac183ed116102321777867cfef088f 100644 --- a/ethcore/src/types/mod.rs.in +++ b/ethcore/src/types/mod.rs.in @@ -33,3 +33,4 @@ pub mod transaction_import; pub mod block_import_error; pub mod restoration_status; pub mod snapshot_manifest; +pub mod mode; \ No newline at end of file diff --git a/ethcore/src/types/mode.rs b/ethcore/src/types/mode.rs new file mode 100644 index 0000000000000000000000000000000000000000..b48a92a8961a20cdba35707b2b88f48d96b84693 --- /dev/null +++ b/ethcore/src/types/mode.rs @@ -0,0 +1,55 @@ +// 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 . + +//! Mode type + +pub use std::time::Duration; +use client::Mode as ClientMode; + +/// IPC-capable shadow-type for client::config::Mode +#[derive(Clone, Binary)] +pub enum Mode { + /// Same as ClientMode::Off. + Off, + /// Same as ClientMode::Dark; values in seconds. + Dark(u64), + /// Same as ClientMode::Passive; values in seconds. + Passive(u64, u64), + /// Same as ClientMode::Active. + Active, +} + +impl From for Mode { + fn from(mode: ClientMode) -> Self { + match mode { + ClientMode::Off => Mode::Off, + ClientMode::Dark(timeout) => Mode::Dark(timeout.as_secs()), + ClientMode::Passive(timeout, alarm) => Mode::Passive(timeout.as_secs(), alarm.as_secs()), + ClientMode::Active => Mode::Active, + } + } +} + +impl From for ClientMode { + fn from(mode: Mode) -> Self { + match mode { + Mode::Off => ClientMode::Off, + Mode::Dark(timeout) => ClientMode::Dark(Duration::from_secs(timeout)), + Mode::Passive(timeout, alarm) => ClientMode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm)), + Mode::Active => ClientMode::Active, + } + } +} \ No newline at end of file diff --git a/ethcore/src/types/restoration_status.rs b/ethcore/src/types/restoration_status.rs index 2840d9416ea3293f9d65c2fef42f07f23dc7767a..ddf4cf1db7c7bd0c95fb34563cf251285aba67e3 100644 --- a/ethcore/src/types/restoration_status.rs +++ b/ethcore/src/types/restoration_status.rs @@ -23,6 +23,10 @@ pub enum RestorationStatus { Inactive, /// Ongoing restoration. Ongoing { + /// Total number of state chunks. + state_chunks: u32, + /// Total number of block chunks. + block_chunks: u32, /// Number of state chunks completed. state_chunks_done: u32, /// Number of block chunks completed. diff --git a/ethcore/src/types/trace_types/filter.rs b/ethcore/src/types/trace_types/filter.rs index 2d35718c0b5e1ec9a9e6e9c59e1f796cc08d49a7..1c1be54e73461405e61750e87461152d8c5c4e53 100644 --- a/ethcore/src/types/trace_types/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -108,7 +108,7 @@ impl Filter { /// Returns true if given trace matches the filter. pub fn matches(&self, trace: &FlatTrace) -> bool { - let action = match trace.action { + match trace.action { Action::Call(ref call) => { let from_matches = self.from_address.matches(&call.from); let to_matches = self.to_address.matches(&call.to); @@ -116,7 +116,12 @@ impl Filter { } Action::Create(ref create) => { let from_matches = self.from_address.matches(&create.from); - let to_matches = self.to_address.matches_all(); + + let to_matches = match trace.result { + Res::Create(ref create_result) => self.to_address.matches(&create_result.address), + _ => false + }; + from_matches && to_matches }, Action::Suicide(ref suicide) => { @@ -124,11 +129,6 @@ impl Filter { let to_matches = self.to_address.matches(&suicide.refund_address); from_matches && to_matches } - }; - - action || match trace.result { - Res::Create(ref create) => self.to_address.matches(&create.address), - _ => false } } } diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index f32a2f4dd0ce9540e6b4a9e7ffda26bca2842199..247a1b3012d8201e65b437b06939d68d4ae600a9 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -21,7 +21,7 @@ use std::cell::*; use rlp::*; use util::sha3::Hashable; use util::{H256, Address, U256, Bytes, HeapSizeOf}; -use ethkey::{Signature, sign, Secret, Public, recover, public_to_address, Error as EthkeyError}; +use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; use evm::Schedule; use header::BlockNumber; @@ -143,7 +143,8 @@ impl Transaction { /// Signs the transaction as coming from `sender`. pub fn sign(self, secret: &Secret) -> SignedTransaction { - let sig = sign(secret, &self.hash()).unwrap(); + let sig = ::ethkey::sign(secret, &self.hash()) + .expect("data is valid and context has signing capabilities; qed"); self.with_signature(sig) } diff --git a/ethcore/src/verification/mod.rs b/ethcore/src/verification/mod.rs index ed9e0ec4c23d3b190675b2b55ec47de6e45b8707..239c8859793272ea692fc2107f46e81766026006 100644 --- a/ethcore/src/verification/mod.rs +++ b/ethcore/src/verification/mod.rs @@ -31,6 +31,8 @@ pub use self::queue::{BlockQueue, Config as QueueConfig, VerificationQueue, Queu pub enum VerifierType { /// Verifies block normally. Canon, + /// Verifies block normallly, but skips seal verification. + CanonNoSeal, /// Does not verify block at all. /// Used in tests. Noop, @@ -44,7 +46,17 @@ impl Default for VerifierType { pub fn new(v: VerifierType) -> Box { match v { - VerifierType::Canon => Box::new(CanonVerifier), + VerifierType::Canon | VerifierType::CanonNoSeal => Box::new(CanonVerifier), VerifierType::Noop => Box::new(NoopVerifier), } } + +impl VerifierType { + /// Check if seal verification is enabled for this verifier type. + pub fn verifying_seal(&self) -> bool { + match *self { + VerifierType::Canon => true, + VerifierType::Noop | VerifierType::CanonNoSeal => false, + } + } +} diff --git a/ethcore/src/verification/queue/kind.rs b/ethcore/src/verification/queue/kind.rs index b6b6c5cf6a5607fdd8747f682ea673da7c904fa9..17b9974903d3dd2a84e75b0e53089e64f27198b2 100644 --- a/ethcore/src/verification/queue/kind.rs +++ b/ethcore/src/verification/queue/kind.rs @@ -57,7 +57,7 @@ pub trait Kind: 'static + Sized + Send + Sync { fn create(input: Self::Input, engine: &Engine) -> Result; /// Attempt to verify the `Unverified` item using the given engine. - fn verify(unverified: Self::Unverified, engine: &Engine) -> Result; + fn verify(unverified: Self::Unverified, engine: &Engine, check_seal: bool) -> Result; } /// The blocks verification module. @@ -89,9 +89,9 @@ pub mod blocks { } } - fn verify(un: Self::Unverified, engine: &Engine) -> Result { + fn verify(un: Self::Unverified, engine: &Engine, check_seal: bool) -> Result { let hash = un.hash(); - match verify_block_unordered(un.header, un.bytes, engine) { + match verify_block_unordered(un.header, un.bytes, engine, check_seal) { Ok(verified) => Ok(verified), Err(e) => { warn!(target: "client", "Stage 2 block verification failed for {}: {:?}", hash, e); @@ -176,8 +176,11 @@ pub mod headers { verify_header_params(&input, engine).map(|_| input) } - fn verify(unverified: Self::Unverified, engine: &Engine) -> Result { - engine.verify_block_unordered(&unverified, None).map(|_| unverified) + fn verify(unverified: Self::Unverified, engine: &Engine, check_seal: bool) -> Result { + match check_seal { + true => engine.verify_block_unordered(&unverified, None).map(|_| unverified), + false => Ok(unverified), + } } } } diff --git a/ethcore/src/verification/queue/mod.rs b/ethcore/src/verification/queue/mod.rs index 3f81d53ce48dbcf719fd765609b417c3a9f8e47b..99e09784da3507a84a5d27036512b1846c64c162 100644 --- a/ethcore/src/verification/queue/mod.rs +++ b/ethcore/src/verification/queue/mod.rs @@ -18,7 +18,7 @@ //! Sorts them ready for blockchain insertion. use std::thread::{JoinHandle, self}; -use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering}; use std::sync::{Condvar as SCondvar, Mutex as SMutex}; use util::*; use io::*; @@ -83,6 +83,13 @@ pub enum Status { Unknown, } +// the internal queue sizes. +struct Sizes { + unverified: AtomicUsize, + verifying: AtomicUsize, + verified: AtomicUsize, +} + /// A queue of items to be verified. Sits between network or other I/O and the `BlockChain`. /// Keeps them in the same order as inserted, minus invalid items. pub struct VerificationQueue { @@ -102,19 +109,35 @@ pub struct VerificationQueue { struct QueueSignal { deleting: Arc, signalled: AtomicBool, - message_channel: IoChannel, + message_channel: Mutex>, } impl QueueSignal { #[cfg_attr(feature="dev", allow(bool_comparison))] - fn set(&self) { + fn set_sync(&self) { + // Do not signal when we are about to close + if self.deleting.load(AtomicOrdering::Relaxed) { + return; + } + + if self.signalled.compare_and_swap(false, true, AtomicOrdering::Relaxed) == false { + let channel = self.message_channel.lock().clone(); + if let Err(e) = channel.send_sync(ClientIoMessage::BlockVerified) { + debug!("Error sending BlockVerified message: {:?}", e); + } + } + } + + #[cfg_attr(feature="dev", allow(bool_comparison))] + fn set_async(&self) { // Do not signal when we are about to close if self.deleting.load(AtomicOrdering::Relaxed) { return; } if self.signalled.compare_and_swap(false, true, AtomicOrdering::Relaxed) == false { - if let Err(e) = self.message_channel.send(ClientIoMessage::BlockVerified) { + let channel = self.message_channel.lock().clone(); + if let Err(e) = channel.send(ClientIoMessage::BlockVerified) { debug!("Error sending BlockVerified message: {:?}", e); } } @@ -128,31 +151,36 @@ impl QueueSignal { struct Verification { // All locks must be captured in the order declared here. unverified: Mutex>, - verified: Mutex>, verifying: Mutex>>, + verified: Mutex>, bad: Mutex>, more_to_verify: SMutex<()>, empty: SMutex<()>, + sizes: Sizes, } impl VerificationQueue { /// Creates a new queue instance. - pub fn new(config: Config, engine: Arc, message_channel: IoChannel) -> Self { + pub fn new(config: Config, engine: Arc, message_channel: IoChannel, check_seal: bool) -> Self { let verification = Arc::new(Verification { unverified: Mutex::new(VecDeque::new()), - verified: Mutex::new(VecDeque::new()), verifying: Mutex::new(VecDeque::new()), + verified: Mutex::new(VecDeque::new()), bad: Mutex::new(HashSet::new()), more_to_verify: SMutex::new(()), empty: SMutex::new(()), - + sizes: Sizes { + unverified: AtomicUsize::new(0), + verifying: AtomicUsize::new(0), + verified: AtomicUsize::new(0), + } }); let more_to_verify = Arc::new(SCondvar::new()); let deleting = Arc::new(AtomicBool::new(false)); let ready_signal = Arc::new(QueueSignal { deleting: deleting.clone(), signalled: AtomicBool::new(false), - message_channel: message_channel + message_channel: Mutex::new(message_channel), }); let empty = Arc::new(SCondvar::new()); let panic_handler = PanicHandler::new_in_arc(); @@ -172,7 +200,7 @@ impl VerificationQueue { .name(format!("Verifier #{}", i)) .spawn(move || { panic_handler.catch_panic(move || { - VerificationQueue::verify(verification, engine, more_to_verify, ready_signal, deleting, empty) + VerificationQueue::verify(verification, engine, more_to_verify, ready_signal, deleting, empty, check_seal) }).unwrap() }) .expect("Error starting block verification thread") @@ -193,7 +221,7 @@ impl VerificationQueue { } } - fn verify(verification: Arc>, engine: Arc, wait: Arc, ready: Arc, deleting: Arc, empty: Arc) { + fn verify(verification: Arc>, engine: Arc, wait: Arc, ready: Arc, deleting: Arc, empty: Arc, check_seal: bool) { while !deleting.load(AtomicOrdering::Acquire) { { let mut more_to_verify = verification.more_to_verify.lock().unwrap(); @@ -221,18 +249,21 @@ impl VerificationQueue { None => continue, }; + verification.sizes.unverified.fetch_sub(item.heap_size_of_children(), AtomicOrdering::SeqCst); verifying.push_back(Verifying { hash: item.hash(), output: None }); item }; let hash = item.hash(); - match K::verify(item, &*engine) { + let is_ready = match K::verify(item, &*engine, check_seal) { Ok(verified) => { let mut verifying = verification.verifying.lock(); let mut idx = None; for (i, e) in verifying.iter_mut().enumerate() { if e.hash == hash { idx = Some(i); + + verification.sizes.verifying.fetch_add(verified.heap_size_of_children(), AtomicOrdering::SeqCst); e.output = Some(verified); break; } @@ -242,8 +273,10 @@ impl VerificationQueue { // we're next! let mut verified = verification.verified.lock(); let mut bad = verification.bad.lock(); - VerificationQueue::drain_verifying(&mut verifying, &mut verified, &mut bad); - ready.set(); + VerificationQueue::drain_verifying(&mut verifying, &mut verified, &mut bad, &verification.sizes); + true + } else { + false } }, Err(_) => { @@ -255,24 +288,38 @@ impl VerificationQueue { verifying.retain(|e| e.hash != hash); if verifying.front().map_or(false, |x| x.output.is_some()) { - VerificationQueue::drain_verifying(&mut verifying, &mut verified, &mut bad); - ready.set(); + VerificationQueue::drain_verifying(&mut verifying, &mut verified, &mut bad, &verification.sizes); + true + } else { + false } } + }; + if is_ready { + // Import the block immediately + ready.set_sync(); } } } - fn drain_verifying(verifying: &mut VecDeque>, verified: &mut VecDeque, bad: &mut HashSet) { + fn drain_verifying(verifying: &mut VecDeque>, verified: &mut VecDeque, bad: &mut HashSet, sizes: &Sizes) { + let mut removed_size = 0; + let mut inserted_size = 0; while let Some(output) = verifying.front_mut().and_then(|x| x.output.take()) { assert!(verifying.pop_front().is_some()); + let size = output.heap_size_of_children(); + removed_size += size; if bad.contains(&output.parent_hash()) { bad.insert(output.hash()); } else { + inserted_size += size; verified.push_back(output); } } + + sizes.verifying.fetch_sub(removed_size, AtomicOrdering::SeqCst); + sizes.verified.fetch_add(inserted_size, AtomicOrdering::SeqCst); } /// Clear the queue and stop verification activity. @@ -283,6 +330,12 @@ impl VerificationQueue { unverified.clear(); verifying.clear(); verified.clear(); + + let sizes = &self.verification.sizes; + sizes.unverified.store(0, AtomicOrdering::Release); + sizes.verifying.store(0, AtomicOrdering::Release); + sizes.verified.store(0, AtomicOrdering::Release); + self.processing.write().clear(); } @@ -326,6 +379,8 @@ impl VerificationQueue { match K::create(input, &*self.engine) { Ok(item) => { + self.verification.sizes.unverified.fetch_add(item.heap_size_of_children(), AtomicOrdering::SeqCst); + self.processing.write().insert(h.clone()); self.verification.unverified.lock().push_back(item); self.more_to_verify.notify_all(); @@ -355,26 +410,32 @@ impl VerificationQueue { } let mut new_verified = VecDeque::new(); + let mut removed_size = 0; for output in verified.drain(..) { if bad.contains(&output.parent_hash()) { + removed_size += output.heap_size_of_children(); bad.insert(output.hash()); processing.remove(&output.hash()); } else { new_verified.push_back(output); } } + + self.verification.sizes.verified.fetch_sub(removed_size, AtomicOrdering::SeqCst); *verified = new_verified; } - /// Mark given item as processed - pub fn mark_as_good(&self, hashes: &[H256]) { + /// Mark given item as processed. + /// Returns true if the queue becomes empty. + pub fn mark_as_good(&self, hashes: &[H256]) -> bool { if hashes.is_empty() { - return; + return self.processing.read().is_empty(); } let mut processing = self.processing.write(); for hash in hashes { processing.remove(hash); } + processing.is_empty() } /// Removes up to `max` verified items from the queue @@ -383,26 +444,35 @@ impl VerificationQueue { let count = min(max, verified.len()); let result = verified.drain(..count).collect::>(); + let drained_size = result.iter().map(HeapSizeOf::heap_size_of_children).fold(0, |a, c| a + c); + self.verification.sizes.verified.fetch_sub(drained_size, AtomicOrdering::SeqCst); + self.ready_signal.reset(); if !verified.is_empty() { - self.ready_signal.set(); + self.ready_signal.set_async(); } result } /// Get queue status. pub fn queue_info(&self) -> QueueInfo { + use std::mem::size_of; + let (unverified_len, unverified_bytes) = { - let v = self.verification.unverified.lock(); - (v.len(), v.heap_size_of_children()) + let len = self.verification.unverified.lock().len(); + let size = self.verification.sizes.unverified.load(AtomicOrdering::Acquire); + + (len, size + len * size_of::()) }; let (verifying_len, verifying_bytes) = { - let v = self.verification.verifying.lock(); - (v.len(), v.heap_size_of_children()) + let len = self.verification.verifying.lock().len(); + let size = self.verification.sizes.verifying.load(AtomicOrdering::Acquire); + (len, size + len * size_of::>()) }; let (verified_len, verified_bytes) = { - let v = self.verification.verified.lock(); - (v.len(), v.heap_size_of_children()) + let len = self.verification.verified.lock().len(); + let size = self.verification.sizes.verified.load(AtomicOrdering::Acquire); + (len, size + len * size_of::()) }; QueueInfo { @@ -411,12 +481,9 @@ impl VerificationQueue { verified_queue_size: verified_len, max_queue_size: self.max_queue_size, max_mem_use: self.max_mem_use, - mem_used: - unverified_bytes - + verifying_bytes - + verified_bytes - // TODO: https://github.com/servo/heapsize/pull/50 - //+ self.processing.read().heap_size_of_children(), + mem_used: unverified_bytes + + verifying_bytes + + verified_bytes } } @@ -464,7 +531,7 @@ mod tests { fn get_test_queue() -> BlockQueue { let spec = get_test_spec(); let engine = spec.engine; - BlockQueue::new(Config::default(), engine, IoChannel::disconnected()) + BlockQueue::new(Config::default(), engine, IoChannel::disconnected(), true) } #[test] @@ -472,7 +539,7 @@ mod tests { // TODO better test let spec = Spec::new_test(); let engine = spec.engine; - let _ = BlockQueue::new(Config::default(), engine, IoChannel::disconnected()); + let _ = BlockQueue::new(Config::default(), engine, IoChannel::disconnected(), true); } #[test] @@ -536,7 +603,7 @@ mod tests { let engine = spec.engine; let mut config = Config::default(); config.max_mem_use = super::MIN_MEM_LIMIT; // empty queue uses about 15000 - let queue = BlockQueue::new(config, engine, IoChannel::disconnected()); + let queue = BlockQueue::new(config, engine, IoChannel::disconnected(), true); assert!(!queue.queue_info().is_full()); let mut blocks = get_good_dummy_block_seq(50); for b in blocks.drain(..) { diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index f89ac7d9af9ed9365298c985b40a1e9ebd9bb9d2..1b8eddfe88436a8168db3702728ceeab008dbcb5 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -21,10 +21,14 @@ /// 2. Signatures verification done in the queue. /// 3. Final verification against the blockchain done before enactment. -use common::*; +use util::*; use engines::Engine; +use error::{BlockError, Error}; use blockchain::*; +use header::{BlockNumber, Header}; use rlp::{UntrustedRlp, View}; +use transaction::SignedTransaction; +use views::BlockView; /// Preprocessed block data gathered in `verify_block_unordered` call pub struct PreverifiedBlock { @@ -66,10 +70,12 @@ pub fn verify_block_basic(header: &Header, bytes: &[u8], engine: &Engine) -> Res /// Phase 2 verification. Perform costly checks such as transaction signatures and block nonce for ethash. /// Still operates on a individual block /// Returns a `PreverifiedBlock` structure populated with transactions -pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine) -> Result { - try!(engine.verify_block_unordered(&header, Some(&bytes))); - for u in try!(UntrustedRlp::new(&bytes).at(2)).iter().map(|rlp| rlp.as_val::
()) { - try!(engine.verify_block_unordered(&try!(u), None)); +pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine, check_seal: bool) -> Result { + if check_seal { + try!(engine.verify_block_unordered(&header, Some(&bytes))); + for u in try!(UntrustedRlp::new(&bytes).at(2)).iter().map(|rlp| rlp.as_val::
()) { + try!(engine.verify_block_unordered(&try!(u), None)); + } } // Verify transactions. let mut transactions = Vec::new(); @@ -108,7 +114,8 @@ pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: & match bc.block_details(&hash) { Some(details) => { excluded.insert(details.parent.clone()); - let b = bc.block(&hash).unwrap(); + let b = bc.block(&hash) + .expect("parent already known to be stored; qed"); excluded.extend(BlockView::new(&b).uncle_hashes()); hash = details.parent; } @@ -296,7 +303,7 @@ mod tests { self.blocks.contains_key(hash) } - fn first_block(&self) -> H256 { + fn first_block(&self) -> Option { unimplemented!() } @@ -313,6 +320,10 @@ mod tests { self.block(hash).map(|b| BlockChain::block_to_body(&b)) } + fn best_ancient_block(&self) -> Option { + None + } + /// Get the familial details concerning a block. fn block_details(&self, hash: &H256) -> Option { self.blocks.get(hash).map(|bytes| { diff --git a/ethcrypto/src/lib.rs b/ethcrypto/src/lib.rs index 7a1aba48ce787bfc0526a3f1a8031c290b30e39d..103e750e687bb42340d11a72134d5d327bfb2f47 100644 --- a/ethcrypto/src/lib.rs +++ b/ethcrypto/src/lib.rs @@ -166,7 +166,9 @@ pub mod ecies { /// Encrypt a message with a public key pub fn encrypt(public: &Public, shared_mac: &[u8], plain: &[u8]) -> Result, Error> { - let r = Random.generate().unwrap(); + let r = Random.generate() + .expect("context known to have key-generation capabilities; qed"); + let z = try!(ecdh::agree(r.secret(), public)); let mut key = [0u8; 32]; let mut mkey = [0u8; 32]; @@ -201,7 +203,9 @@ pub mod ecies { /// Encrypt a message with a public key pub fn encrypt_single_message(public: &Public, plain: &[u8]) -> Result, Error> { - let r = Random.generate().unwrap(); + let r = Random.generate() + .expect("context known to have key-generation capabilities"); + let z = try!(ecdh::agree(r.secret(), public)); let mut key = [0u8; 32]; let mut mkey = [0u8; 32]; diff --git a/ethkey/src/brain.rs b/ethkey/src/brain.rs index f7f9322e0edc3cc1d9e52f4266f9f7fb90e01076..dd8913c66ff2bb7c5b9b9ae5fa2688e86005cbda 100644 --- a/ethkey/src/brain.rs +++ b/ethkey/src/brain.rs @@ -15,7 +15,7 @@ // along with Parity. If not, see . use keccak::Keccak256; -use super::{KeyPair, Error, Generator, Secret}; +use super::{KeyPair, Error, Generator}; /// Simple brainwallet. pub struct Brain(String); @@ -38,9 +38,9 @@ impl Generator for Brain { match i > 16384 { false => i += 1, true => { - let result = KeyPair::from_secret(Secret::from(secret.clone())); - if result.is_ok() { - return result + let result = KeyPair::from_secret(secret.clone().into()); + if result.as_ref().ok().map_or(false, |r| r.address()[0] == 0) { + return result; } }, } diff --git a/ethstore/Cargo.toml b/ethstore/Cargo.toml index 7fa2a6890ec8fd0d7f453e172f5438dc6c221cda..03347cbd753ec586c2058968bcc4f4738d46a43e 100644 --- a/ethstore/Cargo.toml +++ b/ethstore/Cargo.toml @@ -18,6 +18,7 @@ docopt = { version = "0.6", optional = true } time = "0.1.34" lazy_static = "0.2" itertools = "0.4" +parking_lot = "0.3" ethcrypto = { path = "../ethcrypto" } [build-dependencies] diff --git a/ethstore/src/account/safe_account.rs b/ethstore/src/account/safe_account.rs index 315fd283b588c399267da67f01df1f6e1ba8aa3b..5dab3525135852815f9aeaa805f7e6e56c9a69da 100644 --- a/ethstore/src/account/safe_account.rs +++ b/ethstore/src/account/safe_account.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use ethkey::{KeyPair, sign, Address, Secret, Signature, Message}; +use ethkey::{KeyPair, sign, Address, Secret, Signature, Message, Public}; use {json, Error, crypto}; use crypto::Keccak256; use random::Random; @@ -180,6 +180,11 @@ impl SafeAccount { crypto::ecies::decrypt(&secret, shared_mac, message).map_err(From::from) } + pub fn public(&self, password: &str) -> Result { + let secret = try!(self.crypto.secret(password)); + Ok(try!(KeyPair::from_secret(secret)).public().clone()) + } + pub fn change_password(&self, old_password: &str, new_password: &str, iterations: u32) -> Result { let secret = try!(self.crypto.secret(old_password)); let result = SafeAccount { diff --git a/ethstore/src/bin/ethstore.rs b/ethstore/src/bin/ethstore.rs index 94823dc061f3d58925b8ee6094a27d27b6443c34..9d499723b3f36a5ec0f302bbf8d966457b2107e4 100644 --- a/ethstore/src/bin/ethstore.rs +++ b/ethstore/src/bin/ethstore.rs @@ -37,6 +37,7 @@ Usage: ethstore import-wallet [--dir DIR] ethstore remove
[--dir DIR] ethstore sign
[--dir DIR] + ethstore public
ethstore [-h | --help] Options: @@ -56,6 +57,7 @@ Commands: import-wallet Import presale wallet. remove Remove account. sign Sign message. + public Displays public key for an address. "#; #[derive(Debug, RustcDecodable)] @@ -67,6 +69,7 @@ struct Args { cmd_import_wallet: bool, cmd_remove: bool, cmd_sign: bool, + cmd_public: bool, arg_secret: String, arg_password: String, arg_old_pwd: String, @@ -103,7 +106,7 @@ fn key_dir(location: &str) -> Result, Error> { fn format_accounts(accounts: &[Address]) -> String { accounts.iter() .enumerate() - .map(|(i, a)| format!("{:2}: {}", i, a)) + .map(|(i, a)| format!("{:2}: 0x{:?}", i, a)) .collect::>() .join("\n") } @@ -128,7 +131,7 @@ fn execute(command: I) -> Result where I: IntoIterator(command: I) -> Result where I: IntoIterator(command: I) -> Result where I: IntoIterator Result<(), i32> { use std::ffi; use libc; - let cstr = ffi::CString::new(file_path.to_str().unwrap()).unwrap(); + + let cstr = try!(ffi::CString::new(&*file_path.to_string_lossy()) + .map_err(|_| -1)); match unsafe { libc::chmod(cstr.as_ptr(), libc::S_IWUSR | libc::S_IRUSR) } { 0 => Ok(()), x => Err(x), @@ -63,15 +65,15 @@ impl DiskDirectory { let paths = try!(fs::read_dir(&self.path)) .flat_map(Result::ok) .filter(|entry| { - let metadata = entry.metadata(); + let metadata = entry.metadata().ok(); let file_name = entry.file_name(); - let name = file_name.to_str().unwrap(); + let name = file_name.to_string_lossy(); // filter directories - metadata.is_ok() && !metadata.unwrap().is_dir() && + metadata.map_or(false, |m| !m.is_dir()) && // hidden files !name.starts_with(".") && // other ignored files - !IGNORED_FILES.contains(&name) + !IGNORED_FILES.contains(&&*name) }) .map(|entry| entry.path()) .collect::>(); @@ -164,7 +166,8 @@ mod test { #[test] fn should_create_new_account() { // given - let dir = env::temp_dir(); + let mut dir = env::temp_dir(); + dir.push("ethstore_should_create_new_account"); let keypair = Random.generate().unwrap(); let password = "hello world"; let directory = DiskDirectory::create(dir.clone()).unwrap(); diff --git a/ethstore/src/ethstore.rs b/ethstore/src/ethstore.rs index 8de988b9a313e555768e58a4a31dab6786a58058..4360a39f0d0e1930d51ccd9ff8930a3cda08286b 100644 --- a/ethstore/src/ethstore.rs +++ b/ethstore/src/ethstore.rs @@ -15,17 +15,17 @@ // along with Parity. If not, see . use std::collections::BTreeMap; -use std::sync::RwLock; use std::mem; use ethkey::KeyPair; use crypto::KEY_ITERATIONS; use random::Random; -use ethkey::{Signature, Address, Message, Secret}; +use ethkey::{Signature, Address, Message, Secret, Public}; use dir::KeyDirectory; use account::SafeAccount; use {Error, SecretStore}; use json; use json::UUID; +use parking_lot::RwLock; use presale::PresaleWallet; use import; @@ -56,13 +56,13 @@ impl EthStore { let account = try!(self.dir.insert(account.clone())); // update cache - let mut cache = self.cache.write().unwrap(); + let mut cache = self.cache.write(); cache.insert(account.address.clone(), account); Ok(()) } fn reload_accounts(&self) -> Result<(), Error> { - let mut cache = self.cache.write().unwrap(); + let mut cache = self.cache.write(); let accounts = try!(self.dir.load()); let new_accounts: BTreeMap<_, _> = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); mem::replace(&mut *cache, new_accounts); @@ -71,13 +71,13 @@ impl EthStore { fn get(&self, address: &Address) -> Result { { - let cache = self.cache.read().unwrap(); + let cache = self.cache.read(); if let Some(account) = cache.get(address) { return Ok(account.clone()) } } try!(self.reload_accounts()); - let cache = self.cache.read().unwrap(); + let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } } @@ -111,7 +111,7 @@ impl SecretStore for EthStore { fn accounts(&self) -> Result, Error> { try!(self.reload_accounts()); - Ok(self.cache.read().unwrap().keys().cloned().collect()) + Ok(self.cache.read().keys().cloned().collect()) } fn change_password(&self, address: &Address, old_password: &str, new_password: &str) -> Result<(), Error> { @@ -131,7 +131,7 @@ impl SecretStore for EthStore { if can_remove { try!(self.dir.remove(address)); - let mut cache = self.cache.write().unwrap(); + let mut cache = self.cache.write(); cache.remove(address); Ok(()) } else { @@ -149,6 +149,11 @@ impl SecretStore for EthStore { account.decrypt(password, shared_mac, message) } + fn public(&self, account: &Address, password: &str) -> Result { + let account = try!(self.get(account)); + account.public(password) + } + fn uuid(&self, address: &Address) -> Result { let account = try!(self.get(address)); Ok(account.id.into()) diff --git a/ethstore/src/lib.rs b/ethstore/src/lib.rs index 302e165cf2ba448bfa787577e4773174264f4ea4..f8619ff192c97718942cdf966ec4b50071f89ab2 100644 --- a/ethstore/src/lib.rs +++ b/ethstore/src/lib.rs @@ -26,12 +26,15 @@ extern crate serde_json; extern crate rustc_serialize; extern crate crypto as rcrypto; extern crate tiny_keccak; -#[macro_use] -extern crate lazy_static; +extern crate parking_lot; + // reexport it nicely extern crate ethkey as _ethkey; extern crate ethcrypto as crypto; +#[macro_use] +extern crate lazy_static; + pub mod dir; pub mod ethkey; diff --git a/ethstore/src/presale.rs b/ethstore/src/presale.rs index 2904db6efa908dc2aac7a3d343daff23622fdc7e..ff3bde6f4634a9487896a023f669d8d075b1d69c 100644 --- a/ethstore/src/presale.rs +++ b/ethstore/src/presale.rs @@ -33,7 +33,8 @@ impl From for PresaleWallet { impl PresaleWallet { pub fn open

(path: P) -> Result where P: AsRef { let file = try!(fs::File::open(path)); - let presale = json::PresaleWallet::load(file).unwrap(); + let presale = try!(json::PresaleWallet::load(file) + .map_err(|e| Error::InvalidKeyFile(format!("{}", e)))); Ok(PresaleWallet::from(presale)) } diff --git a/ethstore/src/secret_store.rs b/ethstore/src/secret_store.rs index aa79cb8b678aebcb22b2f968491c49cd5c6bc37f..06f38922b3d01ca7886ecc5e4ddd4d9cac14c3af 100644 --- a/ethstore/src/secret_store.rs +++ b/ethstore/src/secret_store.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use ethkey::{Address, Message, Signature, Secret}; +use ethkey::{Address, Message, Signature, Secret, Public}; use Error; use json::UUID; @@ -27,6 +27,7 @@ pub trait SecretStore: Send + Sync { fn sign(&self, account: &Address, password: &str, message: &Message) -> Result; fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result, Error>; + fn public(&self, account: &Address, password: &str) -> Result; fn accounts(&self) -> Result, Error>; fn uuid(&self, account: &Address) -> Result; diff --git a/evmbin/Cargo.lock b/evmbin/Cargo.lock index d97d262f26df5cbb30dfdd8a58b4c2ba25f4a660..fde83d1bffd15d19832ff3e708588995cb145299 100644 --- a/evmbin/Cargo.lock +++ b/evmbin/Cargo.lock @@ -2,15 +2,15 @@ name = "evm" version = "0.1.0" dependencies = [ - "docopt 0.6.81 (registry+https://github.com/rust-lang/crates.io-index)", - "ethcore 1.3.0", - "ethcore-util 1.3.0", + "docopt 0.6.86 (registry+https://github.com/rust-lang/crates.io-index)", + "ethcore 1.4.0", + "ethcore-util 1.4.0", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "aho-corasick" -version = "0.5.1" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -18,16 +18,16 @@ dependencies = [ [[package]] name = "ansi_term" -version = "0.7.2" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "arrayvec" -version = "0.3.16" +version = "0.3.20" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "nodrop 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "odds 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "nodrop 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "odds 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -38,15 +38,6 @@ dependencies = [ "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "bigint" -version = "0.1.0" -dependencies = [ - "heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "bit-set" version = "0.4.0" @@ -60,11 +51,6 @@ name = "bit-vec" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "bitflags" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "bitflags" version = "0.4.0" @@ -77,17 +63,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "bitflags" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "blastfig" -version = "0.3.3" +name = "bloomchain" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "bloomchain" -version = "0.1.0" +name = "byteorder" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -100,27 +86,18 @@ name = "cfg-if" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "chrono" -version = "0.2.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "num 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "cookie" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "crossbeam" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -133,99 +110,139 @@ dependencies = [ [[package]] name = "docopt" -version = "0.6.81" +version = "0.6.86" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "regex 0.1.68 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 0.1.77 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", - "strsim 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "strsim 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "dtoa" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "elastic-array" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "env_logger" -version = "0.3.3" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "regex 0.1.68 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 0.1.77 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "eth-secp256k1" -version = "0.5.4" -source = "git+https://github.com/ethcore/rust-secp256k1#a9a0b1be1f39560ca86e8fc8e55e205a753ff25c" +version = "0.5.6" +source = "git+https://github.com/ethcore/rust-secp256k1#f998f9a8c18227af200f0f7fdadf8a6560d391ff" dependencies = [ - "arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)", - "gcc 0.3.28 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "arrayvec 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)", + "gcc 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (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)", ] [[package]] name = "ethash" -version = "1.3.0" +version = "1.4.0" dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "primal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "sha3 0.1.0", ] [[package]] name = "ethcore" -version = "1.3.0" +version = "1.4.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)", - "crossbeam 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)", - "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "ethash 1.3.0", - "ethcore-devtools 1.3.0", - "ethcore-ipc 1.3.0", - "ethcore-ipc-codegen 1.3.0", - "ethcore-ipc-nano 1.3.0", - "ethcore-util 1.3.0", + "byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", + "env_logger 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", + "ethash 1.4.0", + "ethcore-bloom-journal 0.1.0", + "ethcore-devtools 1.4.0", + "ethcore-io 1.4.0", + "ethcore-ipc 1.4.0", + "ethcore-ipc-codegen 1.4.0", + "ethcore-ipc-nano 1.4.0", + "ethcore-util 1.4.0", "ethjson 0.1.0", + "ethkey 0.2.0", "ethstore 0.1.0", - "heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", + "heapsize 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "hyper 0.9.4 (git+https://github.com/ethcore/hyper)", "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)", - "num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", - "rayon 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "lru-cache 0.1.0 (git+https://github.com/contain-rs/lru-cache)", + "num_cpus 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", + "rayon 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rlp 0.1.0", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "ethcore-bigint" +version = "0.1.1" +dependencies = [ + "heapsize 0.3.7 (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)", + "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ethcore-bloom-journal" +version = "0.1.0" +dependencies = [ + "siphasher 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ethcore-devtools" -version = "1.3.0" +version = "1.4.0" dependencies = [ "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "ethcore-io" +version = "1.4.0" +dependencies = [ + "crossbeam 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)", + "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ethcore-ipc" -version = "1.3.0" +version = "1.4.0" dependencies = [ - "ethcore-devtools 1.3.0", - "ethcore-util 1.3.0", - "nanomsg 0.5.1 (git+https://github.com/ethcore/nanomsg.rs.git)", + "ethcore-devtools 1.4.0", + "ethcore-util 1.4.0", + "nanomsg 0.7.0 (git+https://github.com/ethcore/nanomsg.rs.git)", "semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "ethcore-ipc-codegen" -version = "1.3.0" +version = "1.4.0" dependencies = [ "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "quasi 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -236,95 +253,109 @@ dependencies = [ [[package]] name = "ethcore-ipc-nano" -version = "1.3.0" +version = "1.4.0" dependencies = [ - "ethcore-ipc 1.3.0", - "jsonrpc-core 2.0.7 (registry+https://github.com/rust-lang/crates.io-index)", + "ethcore-ipc 1.4.0", + "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)", - "nanomsg 0.5.1 (git+https://github.com/ethcore/nanomsg.rs.git)", + "nanomsg 0.7.0 (git+https://github.com/ethcore/nanomsg.rs.git)", ] [[package]] name = "ethcore-util" -version = "1.3.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)", - "bigint 0.1.0", - "chrono 0.2.22 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)", - "elastic-array 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "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-devtools 1.3.0", - "heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", - "igd 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "itertools 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)", +version = "1.4.0" +dependencies = [ + "ansi_term 0.7.5 (registry+https://github.com/rust-lang/crates.io-index)", + "arrayvec 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)", + "elastic-array 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "env_logger 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", + "eth-secp256k1 0.5.6 (git+https://github.com/ethcore/rust-secp256k1)", + "ethcore-bigint 0.1.1", + "ethcore-bloom-journal 0.1.0", + "ethcore-devtools 1.4.0", + "heapsize 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", + "itertools 0.4.19 (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.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)", - "nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 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)", + "regex 0.1.77 (registry+https://github.com/rust-lang/crates.io-index)", + "rlp 0.1.0", "rocksdb 0.4.5 (git+https://github.com/ethcore/rust-rocksdb)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "sha3 0.1.0", - "slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "table 0.1.0", "target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "tiny-keccak 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "using_queue 0.1.0", - "vergen 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "vergen 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ethcrypto" +version = "0.1.0" +dependencies = [ + "eth-secp256k1 0.5.6 (git+https://github.com/ethcore/rust-secp256k1)", + "ethcore-bigint 0.1.1", + "ethkey 0.2.0", + "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "ethjson" version = "0.1.0" dependencies = [ - "ethcore-util 1.3.0", + "ethcore-util 1.4.0", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_codegen 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_codegen 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 0.8.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "ethkey" version = "0.2.0" dependencies = [ - "eth-secp256k1 0.5.4 (git+https://github.com/ethcore/rust-secp256k1)", + "eth-secp256k1 0.5.6 (git+https://github.com/ethcore/rust-secp256k1)", + "ethcore-bigint 0.1.1", "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)", - "tiny-keccak 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "ethstore" version = "0.1.0" dependencies = [ + "ethcrypto 0.1.0", "ethkey 0.2.0", - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "itertools 0.4.19 (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.17 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 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)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_codegen 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_codegen 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 0.8.3 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "tiny-keccak 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "gcc" -version = "0.3.28" +version = "0.3.37" source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rayon 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "hamming" @@ -333,55 +364,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "heapsize" -version = "0.3.5" +version = "0.3.7" 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)", ] -[[package]] -name = "hpack" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "httparse" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "hyper" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cookie 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", - "solicit 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "traitobject 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "url 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "hyper" version = "0.9.4" source = "git+https://github.com/ethcore/hyper#9e346c1d4bc30cd4142dea9d8a0b117d30858ca4" dependencies = [ - "cookie 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", "httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "rotor 0.6.3 (git+https://github.com/ethcore/rotor)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "spmc 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -389,7 +392,7 @@ dependencies = [ "traitobject 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "vecio 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -398,45 +401,27 @@ name = "idna" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-normalization 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "igd" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "hyper 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", - "regex 0.1.68 (registry+https://github.com/rust-lang/crates.io-index)", - "xml-rs 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)", - "xmltree 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "itertools" -version = "0.4.13" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "jsonrpc-core" -version = "2.0.7" +name = "itoa" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_codegen 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] name = "kernel32-sys" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -452,7 +437,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libc" -version = "0.2.12" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "linked-hash-map" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -460,9 +450,17 @@ name = "log" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "lru-cache" +version = "0.1.0" +source = "git+https://github.com/contain-rs/lru-cache#3259e3a7200510af55b049f99db407d0c87ed253" +dependencies = [ + "linked-hash-map 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "matches" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -470,12 +468,12 @@ name = "memchr" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "mime" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -487,109 +485,109 @@ 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.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (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.2 (registry+https://github.com/rust-lang/crates.io-index)", - "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", - "nix 0.5.0 (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.26 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "miow" -version = "0.1.2" +version = "0.1.3" 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)", - "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "net2 0.2.26 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "nanomsg" -version = "0.5.1" -source = "git+https://github.com/ethcore/nanomsg.rs.git#c40fe442c9afaea5b38009a3d992ca044dcceb00" +version = "0.7.0" +source = "git+https://github.com/ethcore/nanomsg.rs.git#e93f14e5014ee6e67f4a39a2d7889b020acec4ea" dependencies = [ - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", - "nanomsg-sys 0.5.0 (git+https://github.com/ethcore/nanomsg.rs.git)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", + "nanomsg-sys 0.7.0 (git+https://github.com/ethcore/nanomsg.rs.git)", ] [[package]] name = "nanomsg-sys" -version = "0.5.0" -source = "git+https://github.com/ethcore/nanomsg.rs.git#c40fe442c9afaea5b38009a3d992ca044dcceb00" +version = "0.7.0" +source = "git+https://github.com/ethcore/nanomsg.rs.git#e93f14e5014ee6e67f4a39a2d7889b020acec4ea" dependencies = [ - "gcc 0.3.28 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "gcc 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "net2" -version = "0.2.23" +version = "0.2.26" 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.12 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "nix" -version = "0.5.0" +version = "0.5.1" 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.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "nodrop" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "odds 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "odds 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "nom" -version = "1.2.2" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "num" -version = "0.1.32" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "num-bigint 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "num-complex 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-bigint 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", + "num-complex 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "num-integer 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", "num-iter 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "num-rational 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-rational 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "num-bigint" -version = "0.1.32" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "num-integer 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.1.36 (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)", ] [[package]] name = "num-complex" -version = "0.1.32" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -598,7 +596,7 @@ name = "num-integer" version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -607,47 +605,62 @@ version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "num-integer 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "num-rational" -version = "0.1.32" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "num-bigint 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-bigint 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "num-integer 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "num-traits" -version = "0.1.32" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "num_cpus" -version = "0.2.11" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "odds" -version = "0.2.12" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "owning_ref" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parking_lot" -version = "0.2.6" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "owning_ref 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot_core 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "parking_lot_core" +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.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (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)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -657,7 +670,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "primal-check 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "primal-estimate 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "primal-sieve 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", + "primal-sieve 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -673,7 +686,7 @@ name = "primal-check" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "num 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "num 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -683,7 +696,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "primal-sieve" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "hamming 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -714,57 +727,72 @@ name = "quick-error" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "quote" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "rand" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "rayon" -version = "0.3.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "deque 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", + "num_cpus 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "regex" -version = "0.1.68" +version = "0.1.77" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "aho-corasick 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "aho-corasick 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", - "regex-syntax 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "thread_local 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", + "regex-syntax 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", + "thread_local 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", "utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "regex-syntax" -version = "0.3.1" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "rlp" +version = "0.1.0" +dependencies = [ + "elastic-array 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "ethcore-bigint 0.1.1", + "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)", +] + [[package]] name = "rocksdb" version = "0.4.5" -source = "git+https://github.com/ethcore/rust-rocksdb#eadce7f74cfe92b99ce63a77af425b47857239b8" +source = "git+https://github.com/ethcore/rust-rocksdb#64c63ccbe1f62c2e2b39262486f9ba813793af58" dependencies = [ - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", "rocksdb-sys 0.3.0 (git+https://github.com/ethcore/rust-rocksdb)", ] [[package]] name = "rocksdb-sys" version = "0.3.0" -source = "git+https://github.com/ethcore/rust-rocksdb#eadce7f74cfe92b99ce63a77af425b47857239b8" +source = "git+https://github.com/ethcore/rust-rocksdb#64c63ccbe1f62c2e2b39262486f9ba813793af58" dependencies = [ - "gcc 0.3.28 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "gcc 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -783,8 +811,8 @@ name = "rust-crypto" version = "0.2.36" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "gcc 0.3.28 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "gcc 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (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)", @@ -813,42 +841,57 @@ name = "semver" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "nom 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "nom 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde" -version = "0.7.9" +version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "serde_codegen" -version = "0.7.9" +version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", - "quasi 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "quasi_codegen 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_codegen_internals 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "serde_codegen_internals" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "syn 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde_json" -version = "0.7.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", + "dtoa 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "itoa 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "sha3" version = "0.1.0" dependencies = [ - "gcc 0.3.28 (registry+https://github.com/rust-lang/crates.io-index)", + "gcc 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "siphasher" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "slab" version = "0.1.3" @@ -864,15 +907,6 @@ name = "smallvec" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "solicit" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "hpack 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "spmc" version = "0.2.1" @@ -880,9 +914,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "strsim" -version = "0.3.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "syn" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "quote 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "syntex" version = "0.33.0" @@ -891,19 +934,64 @@ dependencies = [ "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "syntex" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "syntex_errors 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syntex_errors" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.17 (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.45.0 (registry+https://github.com/rust-lang/crates.io-index)", + "term 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syntex_pos" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "syntex_syntax" 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.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (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)", "unicode-xid 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "syntex_syntax" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (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.45.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_pos 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)", + "term 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "table" version = "0.1.0" @@ -919,7 +1007,16 @@ version = "0.2.14" 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)", - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "term" +version = "0.4.4" +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)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -928,12 +1025,12 @@ 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.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "thread_local" -version = "0.2.5" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -945,13 +1042,13 @@ 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.12 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "tiny-keccak" -version = "1.0.5" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -977,7 +1074,7 @@ name = "unicode-bidi" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -992,23 +1089,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "url" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-normalization 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "uuid 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "url" -version = "1.1.1" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "idna 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1020,29 +1105,21 @@ name = "utf8-ranges" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "uuid" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "vecio" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "vergen" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "blastfig 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1053,7 +1130,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi" -version = "0.2.6" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -1066,31 +1143,126 @@ name = "ws2_32-sys" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "xml-rs" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "xml-rs" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "xmltree" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "xml-rs 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - +[metadata] +"checksum aho-corasick 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ca972c2ea5f742bfce5687b9aef75506a764f61d37f8f649047846a9686ddb66" +"checksum ansi_term 0.7.5 (registry+https://github.com/rust-lang/crates.io-index)" = "30275ad0ad84ec1c06dde3b3f7d23c6006b7d76d61a85e7060b426b747eff70d" +"checksum arrayvec 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)" = "d89f1b0e242270b5b797778af0c8d182a1a2ccac5d8d6fadf414223cc0fab096" +"checksum aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)" = "07d344974f0a155f091948aa389fb1b912d3a58414fbdb9c8d446d193ee3496a" +"checksum bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d9bf6104718e80d7b26a68fdbacff3481cfc05df670821affc7e9cbc1884400c" +"checksum bit-vec 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "5b97c2c8e8bbb4251754f559df8af22fb264853c7d009084a576cdf12565089d" +"checksum bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8dead7461c1127cf637931a1e50934eb6eee8bff2f74433ac7909e9afcee04a3" +"checksum bitflags 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4f67931368edf3a9a51d29886d245f1c3db2f1ef0dcc9e35ff70341b78c10d23" +"checksum bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "aad18937a628ec6abcd26d1489012cc0e18c21798210f491af69ded9b881106d" +"checksum bloomchain 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3f421095d2a76fc24cd3fb3f912b90df06be7689912b1bdb423caefae59c258d" +"checksum byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855" +"checksum bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c129aff112dcc562970abb69e2508b40850dd24c274761bb50fb8a0067ba6c27" +"checksum cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de1e760d7b6535af4241fca8bd8adf68e2e7edacc6b29f5d399050c5e48cf88c" +"checksum cookie 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0e3d6405328b6edb412158b3b7710e2634e23f3614b9bb1c412df7952489a626" +"checksum crossbeam 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "0c5ea215664ca264da8a9d9c3be80d2eaf30923c259d03e870388eb927508f97" +"checksum deque 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1614659040e711785ed8ea24219140654da1729f3ec8a47a9719d041112fe7bf" +"checksum docopt 0.6.86 (registry+https://github.com/rust-lang/crates.io-index)" = "4a7ef30445607f6fc8720f0a0a2c7442284b629cf0d049286860fae23e71c4d9" +"checksum dtoa 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0dd841b58510c9618291ffa448da2e4e0f699d984d436122372f446dae62263d" +"checksum elastic-array 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4bc9250a632e7c001b741eb0ec6cee93c9a5b6d5f1879696a4b94d62b012210a" +"checksum env_logger 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "15abd780e45b3ea4f76b4e9a26ff4843258dd8a3eed2775a0e7368c2e7936c2f" +"checksum eth-secp256k1 0.5.6 (git+https://github.com/ethcore/rust-secp256k1)" = "" +"checksum gcc 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)" = "41337e9dc80ebadf36b4f252bf7440f61bcf34f99caa170e50dcd0f9a0cdb5d8" +"checksum hamming 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "65043da274378d68241eb9a8f8f8aa54e349136f7b8e12f63e3ef44043cc30e1" +"checksum heapsize 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "8c80e194758495a9109566134dc06e42ea0423987d6ceca016edaa90381b3549" +"checksum httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46534074dbb80b070d60a5cb8ecadd8963a00a438ae1a95268850a7ef73b67ae" +"checksum hyper 0.9.4 (git+https://github.com/ethcore/hyper)" = "" +"checksum idna 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1053236e00ce4f668aeca4a769a09b3bf5a682d802abd6f3cb39374f6b162c11" +"checksum itertools 0.4.19 (registry+https://github.com/rust-lang/crates.io-index)" = "c4a9b56eb56058f43dc66e58f40a214b2ccbc9f3df51861b63d51dec7b65bc3f" +"checksum itoa 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ae3088ea4baeceb0284ee9eea42f591226e6beaecf65373e41b38d95a1b8e7a1" +"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +"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 libc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)" = "044d1360593a78f5c8e5e710beccdc24ab71d1f01bc19a29bcacdba22e8475d8" +"checksum linked-hash-map 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "bda158e0dabeb97ee8a401f4d17e479d6b891a14de0bba79d5cc2d4d325b5e48" +"checksum log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ab83497bf8bf4ed2a74259c1c802351fcd67a65baa86394b6ba73c36f4838054" +"checksum lru-cache 0.1.0 (git+https://github.com/contain-rs/lru-cache)" = "" +"checksum matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bcc3ad8109fa4b522f9b0cd81440422781f564aaf8c195de6b9d6642177ad0dd" +"checksum memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d8b629fb514376c675b98c1421e80b151d3817ac42d7c667717d282761418d20" +"checksum mime 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b5c93a4bd787ddc6e7833c519b73a50883deb5863d76d9b71eb8216fb7f94e66" +"checksum mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)" = "" +"checksum miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d5bfc6782530ac8ace97af10a540054a37126b63b0702ddaaa243b73b5745b9a" +"checksum nanomsg 0.7.0 (git+https://github.com/ethcore/nanomsg.rs.git)" = "" +"checksum nanomsg-sys 0.7.0 (git+https://github.com/ethcore/nanomsg.rs.git)" = "" +"checksum net2 0.2.26 (registry+https://github.com/rust-lang/crates.io-index)" = "5edf9cb6be97212423aed9413dd4729d62b370b5e1c571750e882cebbbc1e3e2" +"checksum nix 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "bfb3ddedaa14746434a02041940495bf11325c22f6d36125d3bdd56090d50a79" +"checksum nodrop 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "0dbbadd3f4c98dea0bd3d9b4be4c0cdaf1ab57035cb2e41fce3983db5add7cc5" +"checksum nom 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a5b8c256fd9471521bcb84c3cdba98921497f1a331cbc15b8030fc63b82050ce" +"checksum num 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)" = "bde7c03b09e7c6a301ee81f6ddf66d7a28ec305699e3d3b056d2fc56470e3120" +"checksum num-bigint 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)" = "88b14378471f7c2adc5262f05b4701ef53e8da376453a8d8fee48e51db745e49" +"checksum num-complex 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)" = "f0c78e054dd19c3fd03419ade63fa661e9c49bb890ce3beb4eee5b7baf93f92f" +"checksum num-integer 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "fb24d9bfb3f222010df27995441ded1e954f8f69cd35021f6bef02ca9552fb92" +"checksum num-iter 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "287a1c9969a847055e1122ec0ea7a5c5d6f72aad97934e131c83d5c08ab4e45c" +"checksum num-rational 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)" = "54ff603b8334a72fbb27fe66948aac0abaaa40231b3cecd189e76162f6f38aaf" +"checksum num-traits 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)" = "a16a42856a256b39c6d3484f097f6713e14feacd9bfb02290917904fae46c81c" +"checksum num_cpus 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)" = "cee7e88156f3f9e19bdd598f8d6c9db7bf4078f99f8381f43a55b09648d1a6e3" +"checksum odds 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)" = "e04630a62b3f1cc8c58b4d8f2555a40136f02b420e158242936ef286a72d33a0" +"checksum owning_ref 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8d91377085359426407a287ab16884a0111ba473aa6844ff01d4ec20ce3d75e7" +"checksum parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "e1435e7a2a00dfebededd6c6bdbd54008001e94b4a2aadd6aef0dc4c56317621" +"checksum parking_lot_core 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb1b97670a2ffadce7c397fb80a3d687c4f3060140b885621ef1653d0e5d5068" +"checksum primal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0e31b86efadeaeb1235452171a66689682783149a6249ff334a2c5d8218d00a4" +"checksum primal-bit 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "464a91febc06166783d4f5ba3577b5ed8dda8e421012df80bfe48a971ed7be8f" +"checksum primal-check 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "647c81b67bb9551a7b88d0bcd785ac35b7d0bf4b2f358683d7c2375d04daec51" +"checksum primal-estimate 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "56ea4531dde757b56906493c8604641da14607bf9cdaa80fb9c9cabd2429f8d5" +"checksum primal-sieve 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "943788ecb9a362697c46acf6b58164c3fb4e13af576f036af1bbd15b2174151a" +"checksum quasi 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b26543b563704e7d87f3ec7cfafb713010a905c5f1b155a8ab66863af43ca578" +"checksum quasi_codegen 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0881d9a45d5f9ebe4a7e77742f8c604f3658c212baf8dd711a692dd000bc648c" +"checksum quick-error 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0aad603e8d7fb67da22dbdf1f4b826ce8829e406124109e73cf1b2454b93a71c" +"checksum quote 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0b22ffb272d214bfc8b6c89ff856d0acb52f0cd6b85162243460c9291b93c56e" +"checksum rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "2791d88c6defac799c3f20d74f094ca33b9332612d9aef9078519c82e4fe04a5" +"checksum rayon 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "655df67c314c30fa3055a365eae276eb88aa4f3413a352a1ab32c1320eda41ea" +"checksum regex 0.1.77 (registry+https://github.com/rust-lang/crates.io-index)" = "64b03446c466d35b42f2a8b203c8e03ed8b91c0f17b56e1f84f7210a257aa665" +"checksum regex-syntax 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "48f0573bcee95a48da786f8823465b5f2a1fae288a55407aca991e5b3e0eae11" +"checksum rocksdb 0.4.5 (git+https://github.com/ethcore/rust-rocksdb)" = "" +"checksum rocksdb-sys 0.3.0 (git+https://github.com/ethcore/rust-rocksdb)" = "" +"checksum rotor 0.6.3 (git+https://github.com/ethcore/rotor)" = "" +"checksum rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)" = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" +"checksum rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)" = "6159e4e6e559c81bd706afe9c8fd68f547d3e851ce12e76b1de7914bab61691b" +"checksum rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "c5f5376ea5e30ce23c03eb77cbe4962b988deead10910c372b226388b594c084" +"checksum semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)" = "d4f410fedcf71af0345d7607d246e7ad15faaadd49d240ee3b24e5dc21a820ac" +"checksum semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2d5b7638a1f03815d94e88cb3b3c08e87f0db4d683ef499d1836aaf70a45623f" +"checksum serde 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)" = "14db385091b1ef02cc209ba2236b2f97666a778674cdbad46b1b0cb2c88cb0ed" +"checksum serde_codegen 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)" = "e575e583f7d162e163af117fb9791fbd2bd203c31023b3219617e12c5997a738" +"checksum serde_codegen_internals 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "318f7e77aa5187391d74aaf4553d2189f56b0ce25e963414c951b97877ffdcec" +"checksum serde_json 0.8.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1cb6b19e74d9f65b9d03343730b643d729a446b29376785cd65efdff4675e2fc" +"checksum siphasher 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5c44e42fa187b5a8782489cf7740cc27c3125806be2bf33563cf5e02e9533fcd" +"checksum slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d807fd58c4181bbabed77cb3b891ba9748241a552bcc5be698faaebefc54f46e" +"checksum slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6dbdd334bd28d328dad1c41b0ea662517883d8880d8533895ef96c8003dec9c4" +"checksum smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "fcc8d19212aacecf95e4a7a2179b26f7aeb9732a915cf01f05b0d3e044865410" +"checksum spmc 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "93bdab61c1a413e591c4d17388ffa859eaff2df27f1e13a5ec8b716700605adf" +"checksum strsim 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "50c069df92e4b01425a8bf3576d5d417943a6a7272fbabaf5bd80b1aaa76442e" +"checksum syn 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "96fed4e825d615b0ffd74dabb1dc4c5a078ab44e2c8004798f01510edf6cf515" +"checksum syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "393b6dd0889df2b064beeea954cfda6bc2571604ac460deeae0fed55a53988af" +"checksum syntex 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)" = "871acb190170a9eb8bd85943aee9f9edd66f4c3bbe8f1856f9c0656fc6debf33" +"checksum syntex_errors 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2fb4a792e49d439a271688827ddcd330c0dd45f5830575bed9ad36e732c28694" +"checksum syntex_pos 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)" = "24a047946021b25c127b86d7217007e63429b11eaca2bb55151c57ee1bc98dbd" +"checksum syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "44bded3cabafc65c90b663b1071bd2d198a9ab7515e6ce729e4570aaf53c407e" +"checksum syntex_syntax 0.45.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0b90281e9f8adf9171d7570638970ffd9f1d858f791c69196ec9a4e22c04242c" +"checksum target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c63f48baada5c52e65a29eef93ab4f8982681b67f9e8d29c7b05abcfec2b9ffe" +"checksum term 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "f2077e54d38055cf1ca0fd7933a2e00cd3ec8f6fed352b2a377f06dcdaaf3281" +"checksum term 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "3deff8a2b3b6607d6d7cc32ac25c0b33709453ca9cceac006caac51e963cf94a" +"checksum thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" +"checksum thread_local 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "8576dbbfcaef9641452d5cf0df9b0e7eeab7694956dd33bb61515fb8f18cfdd5" +"checksum time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)" = "3c7ec6d62a20df54e07ab3b78b9a3932972f4b7981de295563686849eb3989af" +"checksum tiny-keccak 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8ac274ea206f5352fe553c7b5d8f5658eea51238e747e12968c48705b791b644" +"checksum traitobject 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "07eaeb7689bb7fca7ce15628319635758eda769fed481ecfe6686ddef2600616" +"checksum typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1410f6f91f21d1612654e7cc69193b0334f909dcf2c790c4826254fbb86f8887" +"checksum unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "13a5906ca2b98c799f4b1ab4557b76367ebd6ae5ef14930ec841c74aed5f3764" +"checksum unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c1f7ceb96afdfeedee42bade65a0d585a6a0106f681b6749c8ff4daa8df30b3f" +"checksum unicode-normalization 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "26643a2f83bac55f1976fb716c10234485f9202dcd65cfbdf9da49867b271172" +"checksum unicode-xid 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "36dff09cafb4ec7c8cf0023eb0b686cb6ce65499116a12201c9e11840ca01beb" +"checksum url 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8527c62d9869a08325c38272b3f85668df22a65890c61a639d233dc0ed0b23a2" +"checksum utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a1ca13c08c41c9c3e04224ed9ff80461d97e121589ff27c753a16cb10830ae0f" +"checksum vecio 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0795a11576d29ae80525a3fda315bf7b534f8feb9d34101e5fe63fb95bb2fd24" +"checksum vergen 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c3365f36c57e5df714a34be40902b27a992eeddb9996eca52d0584611cf885d" +"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" +"checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" +"checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" diff --git a/evmbin/Cargo.toml b/evmbin/Cargo.toml index 8ec687687591be8e0aa9c2f4ae33b03116b42d01..479e7e7ecb9ef42d20607e16335a9bd9abde4d1a 100644 --- a/evmbin/Cargo.toml +++ b/evmbin/Cargo.toml @@ -17,3 +17,6 @@ rustc-serialize = "0.3" docopt = { version = "0.6" } ethcore = { path = "../ethcore" } ethcore-util = { path = "../util" } + +[features] +evm-debug = ["ethcore/evm-debug-tests"] diff --git a/evmbin/src/ext.rs b/evmbin/src/ext.rs index d9a6932bac7fc5356ce00e9dc11844ef614cdaa8..11fb3a8763a625927d67649c1b3b78f5b8dbcf33 100644 --- a/evmbin/src/ext.rs +++ b/evmbin/src/ext.rs @@ -16,6 +16,7 @@ //! Externalities implementation. +use std::sync::Arc; use std::collections::HashMap; use util::{U256, H256, Address, Bytes, FixedHash}; use ethcore::client::EnvInfo; @@ -24,13 +25,15 @@ use ethcore::evm::{self, Ext, ContractCreateResult, MessageCallResult, Schedule, pub struct FakeExt { schedule: Schedule, store: HashMap, + depth: usize, } impl Default for FakeExt { fn default() -> Self { FakeExt { - schedule: Schedule::new_homestead(), + schedule: Schedule::new_homestead_gas_fix(), store: HashMap::new(), + depth: 1, } } } @@ -72,7 +75,11 @@ impl Ext for FakeExt { unimplemented!(); } - fn extcode(&self, _address: &Address) -> Bytes { + fn extcode(&self, _address: &Address) -> Arc { + unimplemented!(); + } + + fn extcodesize(&self, _address: &Address) -> usize { unimplemented!(); } @@ -97,8 +104,7 @@ impl Ext for FakeExt { } fn depth(&self) -> usize { - unimplemented!(); - // self.depth + self.depth } fn inc_sstore_clears(&mut self) { diff --git a/evmbin/src/main.rs b/evmbin/src/main.rs index bc24afa1e743abb939335b742f21aee81354b9ba..aa9faa1dac58f4be015b9c7363249c0aef98b1df 100644 --- a/evmbin/src/main.rs +++ b/evmbin/src/main.rs @@ -26,11 +26,13 @@ extern crate ethcore_util as util; mod ext; +use std::sync::Arc; use std::time::{Instant, Duration}; +use std::fmt; use std::str::FromStr; use docopt::Docopt; use util::{U256, FromHex, Uint, Bytes}; -use ethcore::evm::{Factory, VMType, Finalize}; +use ethcore::evm::{self, Factory, VMType, Finalize}; use ethcore::action_params::ActionParams; const USAGE: &'static str = r#" @@ -42,9 +44,9 @@ Usage: evmbin [-h | --help] Transaction options: - --code CODE Contract code. - --input DATA Input data. - --gas GAS Supplied gas. + --code CODE Contract code as hex (without 0x) + --input DATA Input data as hex (without 0x) + --gas GAS Supplied gas as hex (without 0x) General options: -h, --help Display this message and exit. @@ -56,41 +58,72 @@ fn main() { let mut params = ActionParams::default(); params.gas = args.gas(); - params.code = Some(args.code()); + params.code = Some(Arc::new(args.code())); params.data = args.data(); let result = run_vm(params); - println!("Gas used: {:?}", result.gas_used); - println!("Output: {:?}", result.output); - println!("Time: {}.{:.9}s", result.time.as_secs(), result.time.subsec_nanos()); + match result { + Ok(success) => println!("{}", success), + Err(failure) => println!("{}", failure), + } } /// Execute VM with given `ActionParams` -pub fn run_vm(params: ActionParams) -> ExecutionResults { +pub fn run_vm(params: ActionParams) -> Result { let initial_gas = params.gas; - let factory = Factory::new(VMType::Interpreter); + let factory = Factory::new(VMType::Interpreter, 1024); let mut vm = factory.create(params.gas); let mut ext = ext::FakeExt::default(); let start = Instant::now(); - let gas_left = vm.exec(params, &mut ext).finalize(ext).expect("OK"); + let gas_left = vm.exec(params, &mut ext).finalize(ext); let duration = start.elapsed(); - ExecutionResults { - gas_used: initial_gas - gas_left, - output: Vec::new(), - time: duration, + match gas_left { + Ok(gas_left) => Ok(Success { + gas_used: initial_gas - gas_left, + // TODO [ToDr] get output from ext + output: Vec::new(), + time: duration, + }), + Err(e) => Err(Failure { + error: e, + time: duration, + }), } } -/// VM execution results -pub struct ExecutionResults { +/// Execution finished correctly +pub struct Success { /// Used gas - pub gas_used: U256, + gas_used: U256, /// Output as bytes - pub output: Vec, + output: Vec, /// Time Taken - pub time: Duration, + time: Duration, +} +impl fmt::Display for Success { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + try!(writeln!(f, "Gas used: {:?}", self.gas_used)); + try!(writeln!(f, "Output: {:?}", self.output)); + try!(writeln!(f, "Time: {}.{:.9}s", self.time.as_secs(), self.time.subsec_nanos())); + Ok(()) + } +} + +/// Execution failed +pub struct Failure { + /// Internal error + error: evm::Error, + /// Duration + time: Duration, +} +impl fmt::Display for Failure { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + try!(writeln!(f, "Error: {:?}", self.error)); + try!(writeln!(f, "Time: {}.{:.9}s", self.time.as_secs(), self.time.subsec_nanos())); + Ok(()) + } } #[derive(Debug, RustcDecodable)] diff --git a/js/.babelrc b/js/.babelrc new file mode 100644 index 0000000000000000000000000000000000000000..27c697885555c69529c885a9655e845b573d5ab4 --- /dev/null +++ b/js/.babelrc @@ -0,0 +1,15 @@ +{ + "presets": ["es2017", "es2016", "es2015", "stage-0", "react"], + "plugins": [ + "transform-runtime", + "transform-decorators-legacy", + "transform-class-properties", + "lodash" + ], + "retainLines": true, + "env": { + "production": { + "plugins": ["transform-react-remove-prop-types"] + } + } +} diff --git a/js/.codeclimate.yml b/js/.codeclimate.yml new file mode 100644 index 0000000000000000000000000000000000000000..ca6414f5883de71b270a7f6de829837da85a2e4d --- /dev/null +++ b/js/.codeclimate.yml @@ -0,0 +1,8 @@ +engines: + eslint: + enabled: true + channel: "eslint-2" + +ratings: + paths: + - "**.js" diff --git a/js/.editorconfig b/js/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..3c229b5dc188afe95adfd59e57d14cc599ead1eb --- /dev/null +++ b/js/.editorconfig @@ -0,0 +1,10 @@ +root = true +[*] +indent_style=space +indent_size=2 +tab_width=2 +end_of_line=lf +charset=utf-8 +trim_trailing_whitespace=true +max_line_length=120 +insert_final_newline=true diff --git a/js/.eslintrc.json b/js/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..b649a1beaf83d30bc12236bb0ef74ef230c3eca0 --- /dev/null +++ b/js/.eslintrc.json @@ -0,0 +1,20 @@ +{ + "extends": ["semistandard", "standard-react"], + "parser": "babel-eslint", + "env": { + "browser": true, + "mocha": true, + "node": true + }, + "globals": { + "expect": true, + "FileReader": true + }, + "rules": { + "object-curly-spacing": ["error", "always"], + "no-debugger": "error", + "no-alert": "error", + "jsx-quotes": ["error", "prefer-single"], + "react/jsx-curly-spacing": ["error", "always"] + } +} diff --git a/js/.gitignore b/js/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..acb73a82ad12d1eda83a9f7408bbfad9a7add1dc --- /dev/null +++ b/js/.gitignore @@ -0,0 +1,8 @@ +node_modules +npm-debug.log +build +.build +.coverage +.dist +.happypack +.npmjs diff --git a/js/.istanbul.yml b/js/.istanbul.yml new file mode 100644 index 0000000000000000000000000000000000000000..4535167dbff60cc20d1452fde48a0e4aac5c841b --- /dev/null +++ b/js/.istanbul.yml @@ -0,0 +1,6 @@ +instrumentation: + root: src + extensions: + - .js +reporting: + dir: ./.coverage diff --git a/js/.npmignore b/js/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..5093a29b859a5e7a79413a37ad397761ec16415a --- /dev/null +++ b/js/.npmignore @@ -0,0 +1 @@ +scripts/ diff --git a/js/Cargo.precompiled.toml b/js/Cargo.precompiled.toml new file mode 100644 index 0000000000000000000000000000000000000000..b8175e4f7a38a5b8b8481d4b9917c546da98c4bc --- /dev/null +++ b/js/Cargo.precompiled.toml @@ -0,0 +1,19 @@ +[package] +description = "Parity built-in dapps." +name = "parity-ui-precompiled" +version = "1.4.0" +license = "GPL-3.0" +authors = ["Ethcore "] +build = "build.rs" + +[features] +default = ["with-syntex", "use-precompiled-js"] +use-precompiled-js = ["parity-dapps-glue/use-precompiled-js"] +with-syntex = ["parity-dapps-glue/with-syntex"] + +[build-dependencies] +parity-dapps-glue = "1.4" + +[dependencies] +parity-dapps-glue = "1.4" + diff --git a/js/Cargo.toml b/js/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..e52bfec9e25eddcc44e9abeb06de9393898717e0 --- /dev/null +++ b/js/Cargo.toml @@ -0,0 +1,18 @@ +[package] +description = "Parity built-in dapps." +name = "parity-ui-dev" +version = "1.4.0" +license = "GPL-3.0" +authors = ["Ethcore "] +build = "build.rs" + +[features] +default = ["with-syntex"] +with-syntex = ["parity-dapps-glue/with-syntex"] + +[build-dependencies] +parity-dapps-glue = "1.4" + +[dependencies] +parity-dapps-glue = "1.4" + diff --git a/js/LICENSE b/js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9cecc1d4669ee8af2ca727a5d8cde10cd8b2d7cc --- /dev/null +++ b/js/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program 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. + + This program 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 this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/js/README.md b/js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..41252bc916f88127723f035ce6f4154fcdacc9a4 --- /dev/null +++ b/js/README.md @@ -0,0 +1,12 @@ +# parity.js + +JavaScript APIs and UIs for Parity. + +## development + +0. Install [Node](https://nodejs.org/) if not already available +0. Change to the `js` directory inside `parity/` +0. Install the npm modules via `npm install` +0. Parity should be run with `parity --signer-no-validation [...options]` (where `options` can be `--chain testnet`) +0. Start the development environment via `npm start` +0. Connect to the [UI](http://localhost:3000) diff --git a/js/assets/fonts/Roboto/LICENSE.txt b/js/assets/fonts/Roboto/LICENSE.txt new file mode 100755 index 0000000000000000000000000000000000000000..75b52484ea471f882c29e02693b4f02dba175b5e --- /dev/null +++ b/js/assets/fonts/Roboto/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/js/assets/fonts/Roboto/font.css b/js/assets/fonts/Roboto/font.css new file mode 100644 index 0000000000000000000000000000000000000000..5eea2bfd1fe980b8e55c9ca9483a13da24995f8e --- /dev/null +++ b/js/assets/fonts/Roboto/font.css @@ -0,0 +1,56 @@ +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(v15/0eC6fl06luXEYWpBSJvXCIX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2'); + unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(v15/Fl4y0QdOxyyTHEGMXX8kcYX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2'); + unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(v15/-L14Jk06m6pUHB-5mXQQnYX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(v15/I3S1wsgSg9YCurV6PUkTOYX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(v15/NYDWBdD4gIq26G5XYbHsFIX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2'); + unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(v15/Pru33qjShpZSmG3z6VYwnYX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2'); + unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(v15/Hgo13k-tfSpn0qi1SFdUfZBw1xU1rKptJj_0jans920.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000; +} diff --git a/js/assets/fonts/Roboto/ttf/Roboto-Black.ttf b/js/assets/fonts/Roboto/ttf/Roboto-Black.ttf new file mode 100755 index 0000000000000000000000000000000000000000..fbde625d403cc1fe3be06e15ae90c448c013eee5 Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-Black.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-BlackItalic.ttf b/js/assets/fonts/Roboto/ttf/Roboto-BlackItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..60f7782a2e4aba9bbc96d7634799eaa05512c927 Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-BlackItalic.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-Bold.ttf b/js/assets/fonts/Roboto/ttf/Roboto-Bold.ttf new file mode 100755 index 0000000000000000000000000000000000000000..a355c27cde02b13da43c30ae060c5fb164b36b76 Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-Bold.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-BoldItalic.ttf b/js/assets/fonts/Roboto/ttf/Roboto-BoldItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..3c9a7a37361b6ae0571b33f09b6b55367e188cfe Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-BoldItalic.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-Italic.ttf b/js/assets/fonts/Roboto/ttf/Roboto-Italic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..ff6046d5bfa7cd4498ad4a549d2d9028f6c73372 Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-Italic.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-Light.ttf b/js/assets/fonts/Roboto/ttf/Roboto-Light.ttf new file mode 100755 index 0000000000000000000000000000000000000000..94c6bcc67e09602f6d90ac10f449b5c05c2f7021 Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-Light.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-LightItalic.ttf b/js/assets/fonts/Roboto/ttf/Roboto-LightItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..04cc002302024c4e032d32319f0d40a32b54aada Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-LightItalic.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-Medium.ttf b/js/assets/fonts/Roboto/ttf/Roboto-Medium.ttf new file mode 100755 index 0000000000000000000000000000000000000000..39c63d7461796094c0b8889ee8fe2706d344a99a Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-Medium.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-MediumItalic.ttf b/js/assets/fonts/Roboto/ttf/Roboto-MediumItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..dc743f0a66cf3741e90f712aba22a91197b7e59c Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-MediumItalic.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-Regular.ttf b/js/assets/fonts/Roboto/ttf/Roboto-Regular.ttf new file mode 100755 index 0000000000000000000000000000000000000000..8c082c8de090865264d37594e396c4d6c0099fe4 Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-Regular.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-Thin.ttf b/js/assets/fonts/Roboto/ttf/Roboto-Thin.ttf new file mode 100755 index 0000000000000000000000000000000000000000..d69555029c3e184189c6cf9961c9cb21205bda96 Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-Thin.ttf differ diff --git a/js/assets/fonts/Roboto/ttf/Roboto-ThinItalic.ttf b/js/assets/fonts/Roboto/ttf/Roboto-ThinItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..07172ff666ad2d590e29324165b6c7b8e2be72ee Binary files /dev/null and b/js/assets/fonts/Roboto/ttf/Roboto-ThinItalic.ttf differ diff --git a/js/assets/fonts/Roboto/v15/-L14Jk06m6pUHB-5mXQQnYX0hVgzZQUfRDuZrPvH3D8.woff2 b/js/assets/fonts/Roboto/v15/-L14Jk06m6pUHB-5mXQQnYX0hVgzZQUfRDuZrPvH3D8.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..58fd4bcd24711c74b7c0ecf045cef580471f02f1 Binary files /dev/null and b/js/assets/fonts/Roboto/v15/-L14Jk06m6pUHB-5mXQQnYX0hVgzZQUfRDuZrPvH3D8.woff2 differ diff --git a/js/assets/fonts/Roboto/v15/0eC6fl06luXEYWpBSJvXCIX0hVgzZQUfRDuZrPvH3D8.woff2 b/js/assets/fonts/Roboto/v15/0eC6fl06luXEYWpBSJvXCIX0hVgzZQUfRDuZrPvH3D8.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..eacda321c795555dcaf46c05373bff8ddd7b11a8 Binary files /dev/null and b/js/assets/fonts/Roboto/v15/0eC6fl06luXEYWpBSJvXCIX0hVgzZQUfRDuZrPvH3D8.woff2 differ diff --git a/js/assets/fonts/Roboto/v15/Fl4y0QdOxyyTHEGMXX8kcYX0hVgzZQUfRDuZrPvH3D8.woff2 b/js/assets/fonts/Roboto/v15/Fl4y0QdOxyyTHEGMXX8kcYX0hVgzZQUfRDuZrPvH3D8.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..cc16b36c5848dbd0175f6fa5b4d57966f9b61a39 Binary files /dev/null and b/js/assets/fonts/Roboto/v15/Fl4y0QdOxyyTHEGMXX8kcYX0hVgzZQUfRDuZrPvH3D8.woff2 differ diff --git a/js/assets/fonts/Roboto/v15/Hgo13k-tfSpn0qi1SFdUfZBw1xU1rKptJj_0jans920.woff2 b/js/assets/fonts/Roboto/v15/Hgo13k-tfSpn0qi1SFdUfZBw1xU1rKptJj_0jans920.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..4411cbc8754cf7ec78501ba711efabe15b936675 Binary files /dev/null and b/js/assets/fonts/Roboto/v15/Hgo13k-tfSpn0qi1SFdUfZBw1xU1rKptJj_0jans920.woff2 differ diff --git a/js/assets/fonts/Roboto/v15/I3S1wsgSg9YCurV6PUkTOYX0hVgzZQUfRDuZrPvH3D8.woff2 b/js/assets/fonts/Roboto/v15/I3S1wsgSg9YCurV6PUkTOYX0hVgzZQUfRDuZrPvH3D8.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..0028bd81e9db90411095790d72c9568f1778bd66 Binary files /dev/null and b/js/assets/fonts/Roboto/v15/I3S1wsgSg9YCurV6PUkTOYX0hVgzZQUfRDuZrPvH3D8.woff2 differ diff --git a/js/assets/fonts/Roboto/v15/NYDWBdD4gIq26G5XYbHsFIX0hVgzZQUfRDuZrPvH3D8.woff2 b/js/assets/fonts/Roboto/v15/NYDWBdD4gIq26G5XYbHsFIX0hVgzZQUfRDuZrPvH3D8.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..a5cefc9c67e2f5e20dccc3408988f16cbd6336ea Binary files /dev/null and b/js/assets/fonts/Roboto/v15/NYDWBdD4gIq26G5XYbHsFIX0hVgzZQUfRDuZrPvH3D8.woff2 differ diff --git a/js/assets/fonts/Roboto/v15/Pru33qjShpZSmG3z6VYwnYX0hVgzZQUfRDuZrPvH3D8.woff2 b/js/assets/fonts/Roboto/v15/Pru33qjShpZSmG3z6VYwnYX0hVgzZQUfRDuZrPvH3D8.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..feec9f1e6a187f63cbb826958bbc01c050b5b9c8 Binary files /dev/null and b/js/assets/fonts/Roboto/v15/Pru33qjShpZSmG3z6VYwnYX0hVgzZQUfRDuZrPvH3D8.woff2 differ diff --git a/js/assets/fonts/RobotoMono/LICENSE.txt b/js/assets/fonts/RobotoMono/LICENSE.txt new file mode 100755 index 0000000000000000000000000000000000000000..75b52484ea471f882c29e02693b4f02dba175b5e --- /dev/null +++ b/js/assets/fonts/RobotoMono/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/js/assets/fonts/RobotoMono/font.css b/js/assets/fonts/RobotoMono/font.css new file mode 100644 index 0000000000000000000000000000000000000000..5e9ab5721c1c8ef8630df6cae54949872434a253 --- /dev/null +++ b/js/assets/fonts/RobotoMono/font.css @@ -0,0 +1,56 @@ +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(v4/N4duVc9C58uwPiY8_59Fz0ExlR2MysFCBK8OirNw2kM.woff2) format('woff2'); + unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(v4/N4duVc9C58uwPiY8_59Fz2dsm03krrxlabhmVQFB99s.woff2) format('woff2'); + unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(v4/N4duVc9C58uwPiY8_59FzyJ0caWjaSBdV-xZbEgst_k.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(v4/N4duVc9C58uwPiY8_59Fz2MSHb9EAJwuSzGfuRChQzQ.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(v4/N4duVc9C58uwPiY8_59Fz-pRBTtN4E2_qSPBnw6AgMc.woff2) format('woff2'); + unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(v4/N4duVc9C58uwPiY8_59Fz9Dnm4qiMZlH5rhYv_7LI2Y.woff2) format('woff2'); + unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(v4/N4duVc9C58uwPiY8_59Fz9TIkQYohD4BpHvJ3NvbHoA.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000; +} diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-Bold.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Bold.ttf new file mode 100755 index 0000000000000000000000000000000000000000..07ef607d50c2e0b48d251910fc75c7eb83a41b34 Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Bold.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-BoldItalic.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-BoldItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..1cca0bf456a3b6b42b3c92e81b4f4ebfa7d41f95 Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-BoldItalic.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-Italic.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Italic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..ef92c372cf47ec6ac92644bdc52ef131867037b3 Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Italic.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-Light.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Light.ttf new file mode 100755 index 0000000000000000000000000000000000000000..63229b2805b102f626c06e29752fe28e1ce9471f Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Light.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-LightItalic.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-LightItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..f25bed56adba942784c953710324ef0bba7577fa Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-LightItalic.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-Medium.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Medium.ttf new file mode 100755 index 0000000000000000000000000000000000000000..88ff0c15a56bd3275b7938d7e7bedc56f71ccb8f Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Medium.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-MediumItalic.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-MediumItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..307efad8fcaa533cdc695b8f1aae696ba662431e Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-MediumItalic.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-Regular.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Regular.ttf new file mode 100755 index 0000000000000000000000000000000000000000..b158a334eb372a9ab2ecd4f2566e60d561e71a9f Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Regular.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-Thin.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Thin.ttf new file mode 100755 index 0000000000000000000000000000000000000000..309484d3239a307904ad64f95d87c38fb6d24b7b Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-Thin.ttf differ diff --git a/js/assets/fonts/RobotoMono/ttf/RobotoMono-ThinItalic.ttf b/js/assets/fonts/RobotoMono/ttf/RobotoMono-ThinItalic.ttf new file mode 100755 index 0000000000000000000000000000000000000000..e1bb9121ec6568d6b8772d121eafeaa5da0db928 Binary files /dev/null and b/js/assets/fonts/RobotoMono/ttf/RobotoMono-ThinItalic.ttf differ diff --git a/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz-pRBTtN4E2_qSPBnw6AgMc.woff2 b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz-pRBTtN4E2_qSPBnw6AgMc.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..f1fdb93524e7a84934cc4f6d4b731006059705f1 Binary files /dev/null and b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz-pRBTtN4E2_qSPBnw6AgMc.woff2 differ diff --git a/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz0ExlR2MysFCBK8OirNw2kM.woff2 b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz0ExlR2MysFCBK8OirNw2kM.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..501a4d77720aec360723de2ad0292c49eb10caf9 Binary files /dev/null and b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz0ExlR2MysFCBK8OirNw2kM.woff2 differ diff --git a/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz2MSHb9EAJwuSzGfuRChQzQ.woff2 b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz2MSHb9EAJwuSzGfuRChQzQ.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..54484b1e3edcbac1fc80f13cfa4a03cb29c84bf1 Binary files /dev/null and b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz2MSHb9EAJwuSzGfuRChQzQ.woff2 differ diff --git a/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz2dsm03krrxlabhmVQFB99s.woff2 b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz2dsm03krrxlabhmVQFB99s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..c3f35ca2911c1db7e8afb85f28e23f7db0ae986c Binary files /dev/null and b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz2dsm03krrxlabhmVQFB99s.woff2 differ diff --git a/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz9Dnm4qiMZlH5rhYv_7LI2Y.woff2 b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz9Dnm4qiMZlH5rhYv_7LI2Y.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..72a43ab3c0332b0539f230c402090fdbab079956 Binary files /dev/null and b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz9Dnm4qiMZlH5rhYv_7LI2Y.woff2 differ diff --git a/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz9TIkQYohD4BpHvJ3NvbHoA.woff2 b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz9TIkQYohD4BpHvJ3NvbHoA.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..62b3a15f698a5e966f5f6b4a5b6d5081e340c654 Binary files /dev/null and b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59Fz9TIkQYohD4BpHvJ3NvbHoA.woff2 differ diff --git a/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59FzyJ0caWjaSBdV-xZbEgst_k.woff2 b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59FzyJ0caWjaSBdV-xZbEgst_k.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..2d4fda538a22e1046718d4d158e7512eae086f69 Binary files /dev/null and b/js/assets/fonts/RobotoMono/v4/N4duVc9C58uwPiY8_59FzyJ0caWjaSBdV-xZbEgst_k.woff2 differ diff --git a/js/assets/images/contracts/ethereum-black-64x64.png b/js/assets/images/contracts/ethereum-black-64x64.png new file mode 100644 index 0000000000000000000000000000000000000000..8e80e4ff134759b9cfbbc6f535791b93aac64a49 Binary files /dev/null and b/js/assets/images/contracts/ethereum-black-64x64.png differ diff --git a/js/assets/images/contracts/ethereum-black.png b/js/assets/images/contracts/ethereum-black.png new file mode 100644 index 0000000000000000000000000000000000000000..d7bdc4c904012b2224306216f1d36c78eb29122a Binary files /dev/null and b/js/assets/images/contracts/ethereum-black.png differ diff --git a/js/assets/images/contracts/ethereum-white.png b/js/assets/images/contracts/ethereum-white.png new file mode 100644 index 0000000000000000000000000000000000000000..0691d09aeaffaa78db1a267f3527a79072d71b73 Binary files /dev/null and b/js/assets/images/contracts/ethereum-white.png differ diff --git a/js/assets/images/contracts/unknown-64x64.png b/js/assets/images/contracts/unknown-64x64.png new file mode 100644 index 0000000000000000000000000000000000000000..c2b39a80a372151cb98f216568917953a2b76727 Binary files /dev/null and b/js/assets/images/contracts/unknown-64x64.png differ diff --git a/js/assets/images/contracts/unknown.png b/js/assets/images/contracts/unknown.png new file mode 100644 index 0000000000000000000000000000000000000000..204ffa486372bfed2b04aca09f3f5eaa63115845 Binary files /dev/null and b/js/assets/images/contracts/unknown.png differ diff --git a/js/assets/images/dapps/blocks-350.jpg b/js/assets/images/dapps/blocks-350.jpg new file mode 100644 index 0000000000000000000000000000000000000000..524f9267c50777c162f3f2081933716329926907 Binary files /dev/null and b/js/assets/images/dapps/blocks-350.jpg differ diff --git a/js/assets/images/dapps/coins-64x64.jpg b/js/assets/images/dapps/coins-64x64.jpg new file mode 100644 index 0000000000000000000000000000000000000000..987d7400efbc19054a194526625f07bfa1e6f458 Binary files /dev/null and b/js/assets/images/dapps/coins-64x64.jpg differ diff --git a/js/assets/images/dapps/coins.jpg b/js/assets/images/dapps/coins.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8fba5e65c1c04fa072b53351a02c2e306e830075 Binary files /dev/null and b/js/assets/images/dapps/coins.jpg differ diff --git a/js/assets/images/dapps/hex-64x64.jpg b/js/assets/images/dapps/hex-64x64.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8c6a1d5cc103e2e561e1ba5c999f36ab9e773266 Binary files /dev/null and b/js/assets/images/dapps/hex-64x64.jpg differ diff --git a/js/assets/images/dapps/hex.jpg b/js/assets/images/dapps/hex.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8e09f49aa27a47f13a2dfa0b14eba4af1d9e0109 Binary files /dev/null and b/js/assets/images/dapps/hex.jpg differ diff --git a/js/assets/images/dapps/interlock-64x64.png b/js/assets/images/dapps/interlock-64x64.png new file mode 100644 index 0000000000000000000000000000000000000000..f4b342489a3a573421069402e57ffdc8aefb5f11 Binary files /dev/null and b/js/assets/images/dapps/interlock-64x64.png differ diff --git a/js/assets/images/dapps/interlock.png b/js/assets/images/dapps/interlock.png new file mode 100644 index 0000000000000000000000000000000000000000..e8aeb275d11d1e946d17cefaf881c7c9b6d97953 Binary files /dev/null and b/js/assets/images/dapps/interlock.png differ diff --git a/js/assets/images/dapps/link-64x64.jpg b/js/assets/images/dapps/link-64x64.jpg new file mode 100644 index 0000000000000000000000000000000000000000..14f9c11906e50ce3439bbd40bef30e79f1146ccf Binary files /dev/null and b/js/assets/images/dapps/link-64x64.jpg differ diff --git a/js/assets/images/dapps/link.jpg b/js/assets/images/dapps/link.jpg new file mode 100644 index 0000000000000000000000000000000000000000..546c67e205a721e2588be2054899d499cd75ca09 Binary files /dev/null and b/js/assets/images/dapps/link.jpg differ diff --git a/js/assets/images/dapps/register-64x64.jpg b/js/assets/images/dapps/register-64x64.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ff8fc6c2feaf59c83ce896718b5dd6f23179c63d Binary files /dev/null and b/js/assets/images/dapps/register-64x64.jpg differ diff --git a/js/assets/images/dapps/register.jpg b/js/assets/images/dapps/register.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cd47bd81ef6308794d8c9e3c23acd39fd1c25440 Binary files /dev/null and b/js/assets/images/dapps/register.jpg differ diff --git a/js/assets/images/dapps/signature.png b/js/assets/images/dapps/signature.png new file mode 100644 index 0000000000000000000000000000000000000000..36b341a036642764e48a0a958077b2440f370cbe Binary files /dev/null and b/js/assets/images/dapps/signature.png differ diff --git a/js/assets/images/parity-logo-black-no-text.ico b/js/assets/images/parity-logo-black-no-text.ico new file mode 100644 index 0000000000000000000000000000000000000000..8edfa3e6a9d902ee4b9f9ff54659a61a1b52a55c Binary files /dev/null and b/js/assets/images/parity-logo-black-no-text.ico differ diff --git a/js/assets/images/parity-logo-black-no-text.png b/js/assets/images/parity-logo-black-no-text.png new file mode 100644 index 0000000000000000000000000000000000000000..b2aea789e82472d574be6e74a9f3bb9dc92004df Binary files /dev/null and b/js/assets/images/parity-logo-black-no-text.png differ diff --git a/js/assets/images/parity-logo-black-no-text.svg b/js/assets/images/parity-logo-black-no-text.svg new file mode 100644 index 0000000000000000000000000000000000000000..a4f104838702e3a6c431cf3113f866101ddecafc --- /dev/null +++ b/js/assets/images/parity-logo-black-no-text.svg @@ -0,0 +1,65 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/js/assets/images/parity-logo-black.svg b/js/assets/images/parity-logo-black.svg new file mode 100644 index 0000000000000000000000000000000000000000..f2b2fa72633bd2de0d810e99bdc2365ebcdf4882 --- /dev/null +++ b/js/assets/images/parity-logo-black.svg @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/js/assets/images/parity-logo-white-no-text.svg b/js/assets/images/parity-logo-white-no-text.svg new file mode 100644 index 0000000000000000000000000000000000000000..213ab1db441d60a7bb04e4a84fef845c97020eec --- /dev/null +++ b/js/assets/images/parity-logo-white-no-text.svg @@ -0,0 +1,66 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/js/assets/images/parity-logo-white.svg b/js/assets/images/parity-logo-white.svg new file mode 100644 index 0000000000000000000000000000000000000000..7360ef6a6d7c36ded131a370c71fd146226a5a84 --- /dev/null +++ b/js/assets/images/parity-logo-white.svg @@ -0,0 +1,100 @@ + + + +image/svg+xml diff --git a/js/assets/images/paritybar.png b/js/assets/images/paritybar.png new file mode 100644 index 0000000000000000000000000000000000000000..f0b0e1457409c386690e52ab1091393de19aedc4 Binary files /dev/null and b/js/assets/images/paritybar.png differ diff --git a/js/assets/images/shapeshift-btn.png b/js/assets/images/shapeshift-btn.png new file mode 100644 index 0000000000000000000000000000000000000000..1650ecf375660f706f59ae7bf2f4455dedeb8aae Binary files /dev/null and b/js/assets/images/shapeshift-btn.png differ diff --git a/js/assets/images/shapeshift-logo.png b/js/assets/images/shapeshift-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..586a01ef13a7ce480d46b88fe6dc457d3083c966 Binary files /dev/null and b/js/assets/images/shapeshift-logo.png differ diff --git a/js/build-server.js b/js/build-server.js new file mode 100644 index 0000000000000000000000000000000000000000..9153f5ed281401720a41c6418dc6aee5c7381750 --- /dev/null +++ b/js/build-server.js @@ -0,0 +1,61 @@ +// 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 . + +/** + * Run `PARITY_URL="127.0.0.1:8180" NODE_ENV="production" npm run build` + * to build the project ; use this server to test that the minifed + * version is working (this is a simple proxy server) + */ + +var express = require('express'); +var proxy = require('http-proxy-middleware'); + +var app = express(); +var wsProxy = proxy('ws://127.0.0.1:8180', { changeOrigin: true }); + +app.use(express.static('.build')); + +app.use('/api/*', proxy({ + target: 'http://127.0.0.1:8080', + changeOrigin: true +})); + +app.use('/app/*', proxy({ + target: 'http://127.0.0.1:8080', + changeOrigin: true, + pathRewrite: { + '^/app': '' + } +})); + +app.use('/parity-utils/*', proxy({ + target: 'http://127.0.0.1:3000', + changeOrigin: true, + pathRewrite: { + '^/parity-utils': '' + } +})); + +app.use('/rpc/*', proxy({ + target: 'http://127.0.0.1:8080', + changeOrigin: true +})); + +app.use(wsProxy); + +var server = app.listen(3000); + +server.on('upgrade', wsProxy.upgrade); diff --git a/ethcore/src/common.rs b/js/build.rs similarity index 75% rename from ethcore/src/common.rs rename to js/build.rs index 41fdd53975c783ed3964068eb8b27c59cbeca183..82bf1ac93f381a74ac768b27b51de89506c4adba 100644 --- a/ethcore/src/common.rs +++ b/js/build.rs @@ -14,14 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -pub use util::*; -pub use basic_types::*; -pub use error::*; -pub use env_info::*; -pub use views::*; -pub use builtin::*; -pub use header::*; -pub use transaction::*; -pub use log_entry::*; -pub use receipt::*; -pub use action_params::*; +extern crate parity_dapps_glue; + +fn main() { + parity_dapps_glue::js::build(env!("CARGO_MANIFEST_DIR"), "build"); + parity_dapps_glue::generate(); +} diff --git a/js/package.json b/js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ec66486d9b2d15fb58cdb9958f46f281c0387d38 --- /dev/null +++ b/js/package.json @@ -0,0 +1,151 @@ +{ + "name": "parity.js", + "version": "0.1.37", + "main": "release/index.js", + "jsnext:main": "src/index.js", + "author": "Parity Team ", + "maintainers": [ + "Jaco Greeff" + ], + "contributors": [], + "license": "GPL-3.0", + "repository": { + "type": "git", + "url": "git+https://github.com/ethcore/parity.git" + }, + "keywords": [ + "Ethereum", + "ABI", + "API", + "Web3", + "RPC", + "Parity", + "Promise" + ], + "scripts": { + "build": "npm run build:dll && npm run build:app && npm run build:lib", + "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: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: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", + "lint": "eslint --ignore-path .gitignore ./src/", + "test": "mocha 'src/**/*.spec.js'", + "test:coverage": "istanbul cover _mocha -- 'src/**/*.spec.js'", + "test:e2e": "mocha 'src/**/*.e2e.js'" + }, + "devDependencies": { + "babel-cli": "^6.10.1", + "babel-core": "^6.10.4", + "babel-eslint": "^6.1.2", + "babel-loader": "^6.2.3", + "babel-plugin-lodash": "^3.2.2", + "babel-plugin-transform-class-properties": "^6.11.5", + "babel-plugin-transform-decorators-legacy": "^1.3.4", + "babel-plugin-transform-react-remove-prop-types": "^0.2.9", + "babel-plugin-transform-runtime": "^6.9.0", + "babel-polyfill": "^6.13.0", + "babel-preset-es2015": "^6.9.0", + "babel-preset-es2015-rollup": "^1.1.1", + "babel-preset-es2016": "^6.11.3", + "babel-preset-es2017": "^6.14.0", + "babel-preset-react": "^6.5.0", + "babel-preset-stage-0": "^6.5.0", + "babel-register": "6.9.0", + "babel-runtime": "^6.9.2", + "chai": "^3.5.0", + "chai-enzyme": "0.4.2", + "cheerio": "0.20.0", + "copy-webpack-plugin": "^4.0.0", + "core-js": "^2.4.1", + "coveralls": "^2.11.11", + "css-loader": "^0.23.1", + "enzyme": "2.3.0", + "eslint": "^3.1.0", + "eslint-config-semistandard": "^6.0.2", + "eslint-config-standard": "^5.3.5", + "eslint-config-standard-react": "^3.0.0", + "eslint-plugin-promise": "^2.0.0", + "eslint-plugin-react": "^5.1.1", + "eslint-plugin-standard": "^2.0.0", + "extract-loader": "0.0.2", + "extract-text-webpack-plugin": "^1.0.1", + "file-loader": "^0.8.5", + "fs-extra": "^0.30.0", + "happypack": "^2.2.1", + "history": "^2.0.0", + "html-loader": "^0.4.4", + "ignore-styles": "2.0.0", + "image-webpack-loader": "^1.8.0", + "istanbul": "^1.0.0-alpha.2", + "jsdom": "9.2.1", + "json-loader": "^0.5.4", + "mocha": "^3.0.0-1", + "mock-local-storage": "1.0.2", + "mock-socket": "^3.0.1", + "nock": "^8.0.0", + "postcss-import": "^8.1.2", + "postcss-loader": "^0.8.1", + "postcss-nested": "^1.0.0", + "postcss-simple-vars": "^3.0.0", + "react-addons-test-utils": "^15.3.0", + "react-copy-to-clipboard": "^4.2.3", + "react-hot-loader": "^1.3.0", + "rucksack-css": "^0.8.6", + "sinon": "^1.17.4", + "sinon-as-promised": "^4.0.2", + "sinon-chai": "^2.8.0", + "style-loader": "^0.13.0", + "url-loader": "^0.5.7", + "webpack": "^1.13.2", + "webpack-dev-server": "^1.15.2", + "webpack-error-notification": "0.1.6", + "webpack-hot-middleware": "^2.7.1", + "websocket": "^1.0.23" + }, + "dependencies": { + "bignumber.js": "^2.3.0", + "blockies": "0.0.2", + "bytes": "^2.4.0", + "chart.js": "^2.3.0", + "es6-promise": "^3.2.1", + "file-saver": "^1.3.3", + "format-json": "^1.0.3", + "format-number": "^2.0.1", + "geopattern": "^1.2.3", + "isomorphic-fetch": "^2.2.1", + "js-sha3": "^0.5.2", + "lodash": "^4.11.1", + "marked": "^0.3.6", + "material-ui": "^0.16.1", + "material-ui-chip-input": "^0.8.0", + "moment": "^2.14.1", + "qs": "^6.3.0", + "react": "^15.2.1", + "react-addons-css-transition-group": "^15.2.1", + "react-chartjs-2": "^1.5.0", + "react-dom": "^15.2.1", + "react-redux": "^4.4.5", + "react-router": "^2.6.1", + "react-router-redux": "^4.0.5", + "react-tap-event-plugin": "^1.0.0", + "react-tooltip": "^2.0.3", + "recharts": "^0.15.2", + "redux": "^3.5.2", + "redux-actions": "^0.10.1", + "redux-thunk": "^2.1.0", + "rlp": "^2.0.0", + "store": "^1.3.20", + "utf8": "^2.1.1", + "validator": "^5.7.0", + "web3": "^0.17.0-beta", + "whatwg-fetch": "^1.0.0" + } +} diff --git a/js/parity.md b/js/parity.md new file mode 100644 index 0000000000000000000000000000000000000000..3e42f5c8d59fb5cfc1618027d9507f1d1505020f --- /dev/null +++ b/js/parity.md @@ -0,0 +1,81 @@ +# parity.js + +Parity.js is a thin, fast, Promise-based wrapper around the Ethereum APIs. + +## installation + +Install the package with `npm install --save @parity/parity.js` + +## usage + +### initialisation + +```javascript +// import the actual Api class +import { Api } from '@parity/parity.js'; + +// do the setup +const transport = new Api.Transport.Http('http://localhost:8545'); +const api = new Api(transport); +``` + +### making calls + +perform a call + +```javascript +api.eth + .coinbase() + .then((coinbase) => { + console.log(`The coinbase is ${coinbase}`); + }); +``` + +multiple promises + +```javascript +Promise + .all([ + api.eth.coinbase(), + api.net.listening() + ]) + .then(([coinbase, listening]) => { + // do stuff here + }); +``` + +chaining promises + +```javascript +api.eth + .newFilter({...}) + .then((filterId) => api.eth.getFilterChanges(filterId)) + .then((changes) => { + console.log(changes); + }); +``` + +### contracts + +attach contract + +```javascript +const abi = [{ name: 'callMe', inputs: [{ type: 'bool', ...}, { type: 'string', ...}]}, ...abi...]; +const address = '0x123456...9abc'; +const contract = new api.newContract(abi, address); +``` + +find & call a function + +```javascript +contract.instance + .callMe + .call({ gas: 21000 }, [true, 'someString']) // or estimateGas or postTransaction + .then((result) => { + console.log(`the result was ${result}`); + }); +``` + +## apis + +APIs implement the calls as exposed in the [Ethcore JSON Ethereum RPC](https://github.com/ethcore/ethereum-rpc-json/) definitions. Mapping follows the naming conventions of the originals, i.e. `eth_call` becomes `eth.call`, `personal_accounts` becomes `personal.accounts`, etc. diff --git a/js/parity.package.json b/js/parity.package.json new file mode 100644 index 0000000000000000000000000000000000000000..7d18cc5ed3474f2fc253844c6d46bcb9f3ca502d --- /dev/null +++ b/js/parity.package.json @@ -0,0 +1,32 @@ +{ + "name": "@parity/parity.js", + "description": "The Parity Promise-base API & ABI library for interfacing with Ethereum over RPC", + "version": "0.0.0", + "main": "library.js", + "author": "Parity Team ", + "maintainers": [ + "Jaco Greeff" + ], + "contributors": [], + "license": "GPL-3.0", + "repository": { + "type": "git", + "url": "git+https://github.com/ethcore/parity.git" + }, + "keywords": [ + "Ethereum", + "ABI", + "API", + "RPC", + "Parity", + "Promise" + ], + "scripts": { + }, + "devDependencies": { + }, + "dependencies": { + "bignumber.js": "^2.3.0", + "js-sha3": "^0.5.2" + } +} diff --git a/js/scripts/build.sh b/js/scripts/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..a6f4a913c02b488940066affd7009e10868f9697 --- /dev/null +++ b/js/scripts/build.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# change into the js directory (one down from scripts) +pushd `dirname $0` +cd .. + +# run build (production) and store the exit code +EXITCODE=0 +BUILDDIR=./.dist +rm -rf $BUILDDIR +mkdir -p $BUILDDIR/src +BUILD_DEST=$BUILDDIR/build npm run ci:build || EXITCODE=1 + +# Copy rust files +cp Cargo.precompiled.toml $BUILDDIR/Cargo.toml +cp build.rs $BUILDDIR +cp src/lib.rs* $BUILDDIR/src + +# back to root +popd + +# exit with exit code +exit $EXITCODE diff --git a/js/scripts/install-deps.sh b/js/scripts/install-deps.sh new file mode 100755 index 0000000000000000000000000000000000000000..96c2f36b11cef4e927f5f234d849b27bb983e4e4 --- /dev/null +++ b/js/scripts/install-deps.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +# change into the js directory (one down from scripts) +pushd `dirname $0` +cd .. + +# install deps and store the exit code +EXITCODE=0 +node --version +npm --version +npm install --progress=false || EXITCODE=1 + +# back to root +popd + +# exit with exit code +exit $EXITCODE diff --git a/js/scripts/lint.sh b/js/scripts/lint.sh new file mode 100755 index 0000000000000000000000000000000000000000..147bb0a2d01fd36bc94cabba51e3eba947e42824 --- /dev/null +++ b/js/scripts/lint.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# change into the js directory (one down from scripts) +pushd `dirname $0` +cd .. + +# run lint & tests and store the exit code +EXITCODE=0 +npm run lint || EXITCODE=1 + +# back to root +popd + +# exit with exit code +exit $EXITCODE diff --git a/js/scripts/release.sh b/js/scripts/release.sh new file mode 100755 index 0000000000000000000000000000000000000000..22fd91ab60562d58eac41cbb73bc665d09d01d9a --- /dev/null +++ b/js/scripts/release.sh @@ -0,0 +1,84 @@ +#!/bin/bash +set -e + +# variables +UTCDATE=`date -u "+%Y%m%d-%H%M%S"` +PACKAGES=( "parity.js" ) +BRANCH=$CI_BUILD_REF_NAME +GIT_JS_PRECOMPILED="https://${GITHUB_JS_PRECOMPILED}:@github.com/ethcore/js-precompiled.git" +GIT_PARITY="https://${GITHUB_JS_PRECOMPILED}:@github.com/ethcore/parity.git" + +# setup the git user defaults for the current repo +function setup_git_user { + git config push.default simple + git config merge.ours.driver true + git config user.email "$GITHUB_EMAIL" + git config user.name "GitLab Build Bot" +} + +# change into the build directory +BASEDIR=`dirname $0` +GITLOG=./.git/gitcommand.log +pushd $BASEDIR +cd ../.dist + +# add local files and send it up +echo "*** Setting up GitHub config for js-precompiled" +rm -rf ./.git +git init +setup_git_user + +echo "*** Checking out $BRANCH branch" +git remote add origin $GIT_JS_PRECOMPILED +git fetch origin 2>$GITLOG +git checkout -b $BRANCH + +echo "*** Committing compiled files for $UTCDATE" +git add . +git commit -m "$UTCDATE" + +echo "*** Merging remote" +git merge origin/$BRANCH -X ours --commit -m "$UTCDATE [release]" +git push origin HEAD:refs/heads/$BRANCH 2>$GITLOG +PRECOMPILED_HASH=`git rev-parse HEAD` + +# move to root +cd ../.. + +echo "*** Setting up GitHub config for parity" +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 .. + +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 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 + +# exit with exit code +exit 0 diff --git a/js/scripts/test.sh b/js/scripts/test.sh new file mode 100755 index 0000000000000000000000000000000000000000..6827b243ca64bdacd03691100dafc65a68bc5e65 --- /dev/null +++ b/js/scripts/test.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# change into the js directory (one down from scripts) +pushd `dirname $0` +cd .. + +# run lint & tests and store the exit code +EXITCODE=0 +npm run test || EXITCODE=1 + +# back to root +popd + +# exit with exit code +exit $EXITCODE diff --git a/js/scripts/update-precompiled.sh b/js/scripts/update-precompiled.sh new file mode 100755 index 0000000000000000000000000000000000000000..0b9461bf0b1f29ce20ac8cacc8ccea0e9d83b813 --- /dev/null +++ b/js/scripts/update-precompiled.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -e + +# change into main dir +pushd `dirname $0` +cd ../../ + +cargo update -p parity-ui-precompiled + +popd +exit 0 diff --git a/js/src/3rdparty/etherscan/account.js b/js/src/3rdparty/etherscan/account.js new file mode 100644 index 0000000000000000000000000000000000000000..cb99c22c6780b1a95ecf35a72daac8ae7e60eadf --- /dev/null +++ b/js/src/3rdparty/etherscan/account.js @@ -0,0 +1,75 @@ +// 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 BigNumber from 'bignumber.js'; + +const PAGE_SIZE = 25; + +import util from '../../api/util'; +import { call } from './call'; + +function _call (method, params, test) { + return call('account', method, params, test); +} + +function balance (address, test = false) { + return _call('balance', { + address: address, + tag: 'latest' + }, test).then((balance) => { + // same format as balancemulti below + return { + account: address, + balance: balance + }; + }); +} + +function balances (addresses, test = false) { + return _call('balancemulti', { + address: addresses.join(','), + tag: 'latest' + }, test); +} + +function transactions (address, page, test = false) { + // page offset from 0 + return _call('txlist', { + address: address, + page: (page || 0) + 1, + offset: PAGE_SIZE, + sort: 'desc' + }, test).then((transactions) => { + return transactions.map((tx) => { + return { + from: util.toChecksumAddress(tx.from), + to: util.toChecksumAddress(tx.to), + hash: tx.hash, + blockNumber: new BigNumber(tx.blockNumber), + timeStamp: tx.timeStamp, + value: tx.value + }; + }); + }); +} + +const account = { + balance: balance, + balances: balances, + transactions: transactions +}; + +export { account }; diff --git a/js/src/3rdparty/etherscan/account.spec.js b/js/src/3rdparty/etherscan/account.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..283fab3d2925ef2aa60c0fe20b247f4532ec8350 --- /dev/null +++ b/js/src/3rdparty/etherscan/account.spec.js @@ -0,0 +1,69 @@ +// 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 etherscan from './'; + +const TESTADDR = '0xbf885e2b55c6bcc84556a3c5f07d3040833c8d00'; + +describe.skip('etherscan/account', () => { + const checkBalance = function (balance, addr) { + expect(balance).to.be.ok; + expect(balance.account).to.equal(addr); + expect(balance.balance).to.be.ok; + }; + + it('retrieves an account balance', () => { + return etherscan.account + .balance(TESTADDR) + .then((balance) => { + checkBalance(balance, TESTADDR); + }); + }); + + it('retrieves multi account balances', () => { + const addresses = ['0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae', TESTADDR]; + + return etherscan.account + .balances(addresses) + .then((balances) => { + expect(balances).to.be.ok; + expect(balances.length).to.equal(2); + balances.forEach((balance, idx) => { + checkBalance(balance, addresses[idx]); + }); + }); + }); + + describe('transactions', () => { + it('retrieves a list of transactions (default)', () => { + return etherscan.account + .transactions(TESTADDR) + .then((transactions) => { + expect(transactions).to.be.ok; + expect(transactions.length).to.equal(25); + }); + }); + + it('retrieves a list of transactions (page 1)', () => { + return etherscan.account + .transactions(TESTADDR, 1) + .then((transactions) => { + expect(transactions).to.be.ok; + expect(transactions.length).to.equal(25); + }); + }); + }); +}); diff --git a/js/src/3rdparty/etherscan/call.js b/js/src/3rdparty/etherscan/call.js new file mode 100644 index 0000000000000000000000000000000000000000..5c6cd5945df064eaccc77927c47c2eacce339be2 --- /dev/null +++ b/js/src/3rdparty/etherscan/call.js @@ -0,0 +1,48 @@ +// 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 { stringify } from 'qs'; + +const options = { + method: 'GET', + headers: { + 'Accept': 'application/json' + } +}; + +export function call (module, action, _params, test) { + const host = test ? 'testnet.etherscan.io' : 'api.etherscan.io'; + + const query = stringify(Object.assign({ + module, action + }, _params || {})); + + return fetch(`https://${host}/api?${query}`, options) + .then((response) => { + if (!response.ok) { + throw { code: response.status, message: response.statusText }; // eslint-disable-line + } + + return response.json(); + }) + .then((result) => { + if (result.message === 'NOTOK') { + throw { code: -1, message: result.result }; // eslint-disable-line + } + + return result.result; + }); +} diff --git a/js/src/3rdparty/etherscan/index.js b/js/src/3rdparty/etherscan/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ada1503cdf42db520af183ad0bc2cdd798914911 --- /dev/null +++ b/js/src/3rdparty/etherscan/index.js @@ -0,0 +1,28 @@ +// 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 { account } from './account'; +import { stats } from './stats'; +import { txLink, addressLink } from './links'; + +const etherscan = { + account: account, + stats: stats, + txLink: txLink, + addressLink: addressLink +}; + +export default etherscan; diff --git a/js/src/3rdparty/etherscan/links.js b/js/src/3rdparty/etherscan/links.js new file mode 100644 index 0000000000000000000000000000000000000000..2745873fc56b3e74ab9f43c45cbeb34dd878921e --- /dev/null +++ b/js/src/3rdparty/etherscan/links.js @@ -0,0 +1,23 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export const txLink = (hash, isTestnet = false) => { + return `https://${isTestnet ? 'testnet.' : ''}etherscan.io/tx/${hash}`; +}; + +export const addressLink = (address, isTestnet = false) => { + return `https://${isTestnet ? 'testnet.' : ''}etherscan.io/address/${address}`; +}; diff --git a/js/src/3rdparty/etherscan/stats.js b/js/src/3rdparty/etherscan/stats.js new file mode 100644 index 0000000000000000000000000000000000000000..ecefefe7d862af2d4b1871ab4f703e6689e7c450 --- /dev/null +++ b/js/src/3rdparty/etherscan/stats.js @@ -0,0 +1,36 @@ +// 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 { call } from './call'; + +function _call (action, test) { + return call('stats', action, null, test); +} + +function price (test = false) { + return _call('ethprice', test); +} + +function supply (test = false) { + return _call('ethsupply', test); +} + +const stats = { + price: price, + supply: supply +}; + +export { stats }; diff --git a/js/src/3rdparty/etherscan/stats.spec.js b/js/src/3rdparty/etherscan/stats.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..fde2b035c2e6a3bae2e9e7b5218df44432198f66 --- /dev/null +++ b/js/src/3rdparty/etherscan/stats.spec.js @@ -0,0 +1,35 @@ +// 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 etherscan from './'; + +describe.skip('etherscan/stats', () => { + it('retrieves the latest price', () => { + return etherscan.stats + .price() + .then((price) => { + expect(price).to.be.ok; + }); + }); + + it('retrieves the ether total', () => { + return etherscan.stats + .supply() + .then((supply) => { + expect(supply).to.be.ok; + }); + }); +}); diff --git a/js/src/3rdparty/shapeshift/helpers.spec.js b/js/src/3rdparty/shapeshift/helpers.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a82b2f6c39fdc37f30af8570c735dbdb9d48b06f --- /dev/null +++ b/js/src/3rdparty/shapeshift/helpers.spec.js @@ -0,0 +1,71 @@ +// 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 chai from 'chai'; +import nock from 'nock'; + +global.expect = chai.expect; // eslint-disable-line no-undef + +import 'isomorphic-fetch'; +import es6Promise from 'es6-promise'; +es6Promise.polyfill(); + +import initShapeshift from './'; +import initRpc from './rpc'; + +const APIKEY = '0x123454321'; + +const shapeshift = initShapeshift(APIKEY); +const rpc = initRpc(APIKEY); + +function mockget (requests) { + let scope = nock(rpc.ENDPOINT); + + requests.forEach((request) => { + scope = scope + .get(`/${request.path}`) + .reply(request.code || 200, () => { + return request.reply; + }); + }); + + return scope; +} + +function mockpost (requests) { + let scope = nock(rpc.ENDPOINT); + + requests.forEach((request) => { + scope = scope + .post(`/${request.path}`) + .reply(request.code || 200, (uri, body) => { + scope.body = scope.body || {}; + scope.body[request.path] = body; + + return request.reply; + }); + }); + + return scope; +} + +export { + APIKEY, + mockget, + mockpost, + shapeshift, + rpc +}; diff --git a/js/src/3rdparty/shapeshift/index.js b/js/src/3rdparty/shapeshift/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5dd91e4f42ecd7bb03aa8a281a1d3e8d691c8e93 --- /dev/null +++ b/js/src/3rdparty/shapeshift/index.js @@ -0,0 +1,22 @@ +// 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 initRpc from './rpc'; +import initShapeshift from './shapeshift'; + +export default function (apikey) { + return initShapeshift(initRpc(apikey)); +} diff --git a/js/src/3rdparty/shapeshift/rpc.js b/js/src/3rdparty/shapeshift/rpc.js new file mode 100644 index 0000000000000000000000000000000000000000..919f0b07f695d692a94b72872364577935558eda --- /dev/null +++ b/js/src/3rdparty/shapeshift/rpc.js @@ -0,0 +1,67 @@ +// 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 . + +const ENDPOINT = 'https://cors.shapeshift.io'; + +function call (method, options) { + return fetch(`${ENDPOINT}/${method}`, options) + .then((response) => { + if (!response.ok) { + throw new Error(response.statusText); + } + + return response.json(); + }) + .then((result) => { + if (result.error) { + throw new Error(result.error); + } + + return result; + }); +} + +export default function (apiKey) { + function get (method) { + return call(method, { + method: 'GET', + headers: { + 'Accept': 'application/json' + } + }); + } + + function post (method, data) { + const params = Object.assign({}, { apiKey }, data); + const body = JSON.stringify(params); + + return call(method, { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Content-Length': body.length + }, + body + }); + } + + return { + ENDPOINT, + get, + post + }; +} diff --git a/js/src/3rdparty/shapeshift/rpc.spec.js b/js/src/3rdparty/shapeshift/rpc.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..8de9e86413fa92b7dfd1d98c32491665fe54775c --- /dev/null +++ b/js/src/3rdparty/shapeshift/rpc.spec.js @@ -0,0 +1,77 @@ +// 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 { APIKEY, mockget, mockpost, rpc } from './helpers.spec.js'; + +describe('shapeshift/rpc', () => { + describe('GET', () => { + const REPLY = { test: 'this is some result' }; + + let scope; + let result; + + beforeEach(() => { + scope = mockget([{ path: 'test', reply: REPLY }]); + + return rpc + .get('test') + .then((_result) => { + result = _result; + }); + }); + + it('does GET', () => { + expect(scope.isDone()).to.be.true; + }); + + it('retrieves the info', () => { + expect(result).to.deep.equal(REPLY); + }); + }); + + describe('POST', () => { + const REPLY = { test: 'this is some result' }; + + let scope; + let result; + + beforeEach(() => { + scope = mockpost([{ path: 'test', reply: REPLY }]); + + return rpc + .post('test', { input: 'stuff' }) + .then((_result) => { + result = _result; + }); + }); + + it('does POST', () => { + expect(scope.isDone()).to.be.true; + }); + + it('retrieves the info', () => { + expect(result).to.deep.equal(REPLY); + }); + + it('passes the input object', () => { + expect(scope.body.test.input).to.equal('stuff'); + }); + + it('passes the apikey specified', () => { + expect(scope.body.test.apiKey).to.equal(APIKEY); + }); + }); +}); diff --git a/js/src/3rdparty/shapeshift/shapeshift.js b/js/src/3rdparty/shapeshift/shapeshift.js new file mode 100644 index 0000000000000000000000000000000000000000..344a448022a75aff985c5ea2bd0283217a0cb5b4 --- /dev/null +++ b/js/src/3rdparty/shapeshift/shapeshift.js @@ -0,0 +1,93 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default function (rpc) { + const subscriptions = []; + + function getCoins () { + return rpc.get('getcoins'); + } + + function getMarketInfo (pair) { + return rpc.get(`marketinfo/${pair}`); + } + + function getStatus (depositAddress) { + return rpc.get(`txStat/${depositAddress}`); + } + + function shift (toAddress, returnAddress, pair) { + return rpc.post('shift', { + withdrawal: toAddress, + pair: pair, + returnAddress: returnAddress + }); + } + + function subscribe (depositAddress, callback) { + const idx = subscriptions.length; + + subscriptions.push({ + depositAddress, + callback, + idx + }); + } + + function _getSubscriptionStatus (subscription) { + if (!subscription) { + return; + } + + getStatus(subscription.depositAddress) + .then((result) => { + switch (result.status) { + case 'no_deposits': + case 'received': + subscription.callback(null, result); + return; + + case 'complete': + subscription.callback(null, result); + subscriptions[subscription.idx] = null; + return; + + case 'failed': + subscription.callback({ + message: status.error, + fatal: true + }); + subscriptions[subscription.idx] = null; + return; + } + }) + .catch(subscription.callback); + } + + function _pollStatus () { + subscriptions.forEach(_getSubscriptionStatus); + } + + setInterval(_pollStatus, 2000); + + return { + getCoins, + getMarketInfo, + getStatus, + shift, + subscribe + }; +} diff --git a/js/src/3rdparty/shapeshift/shapeshift.spec.js b/js/src/3rdparty/shapeshift/shapeshift.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..36b1506a271b3141af0f8349885697367c77614f --- /dev/null +++ b/js/src/3rdparty/shapeshift/shapeshift.spec.js @@ -0,0 +1,124 @@ +// 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 { mockget, mockpost, shapeshift } from './helpers.spec.js'; + +describe('shapeshift/calls', () => { + describe('getCoins', () => { + const REPLY = { + BTC: { + name: 'Bitcoin', + symbol: 'BTC', + image: 'https://shapeshift.io/images/coins/bitcoin.png', + status: 'available' + }, + ETH: { + name: 'Ether', + symbol: 'ETH', + image: 'https://shapeshift.io/images/coins/ether.png', + status: 'available' + } + }; + + let scope; + + before(() => { + scope = mockget([{ path: 'getcoins', reply: REPLY }]); + + return shapeshift.getCoins(); + }); + + it('makes the call', () => { + expect(scope.isDone()).to.be.ok; + }); + }); + + describe('getMarketInfo', () => { + const REPLY = { + pair: 'btc_ltc', + rate: 128.17959917, + minerFee: 0.003, + limit: 0, + minimum: 0.00004632 + }; + + let scope; + + before(() => { + scope = mockget([{ path: 'marketinfo/btc_ltc', reply: REPLY }]); + + return shapeshift.getMarketInfo('btc_ltc'); + }); + + it('makes the call', () => { + expect(scope.isDone()).to.be.ok; + }); + }); + + describe('getStatus', () => { + const REPLY = { + status: '0x123', + address: '0x123' + }; + + let scope; + + before(() => { + scope = mockget([{ path: 'txStat/0x123', reply: REPLY }]); + + return shapeshift.getStatus('0x123'); + }); + + it('makes the call', () => { + expect(scope.isDone()).to.be.ok; + }); + }); + + describe('shift', () => { + const REPLY = { + deposit: '1BTC', + depositType: 'btc', + withdrawal: '0x456', + withdrawalType: 'eth' + }; + + let scope; + + before(() => { + scope = mockpost([{ path: 'shift', reply: REPLY }]); + + return shapeshift.shift('0x456', '1BTC', 'btc_eth'); + }); + + it('makes the call', () => { + expect(scope.isDone()).to.be.ok; + }); + + describe('body', () => { + it('has withdrawal set', () => { + expect(scope.body.shift.withdrawal).to.equal('0x456'); + }); + + it('has returnAddress set', () => { + expect(scope.body.shift.returnAddress).to.equal('1BTC'); + }); + + it('has pair set', () => { + expect(scope.body.shift.pair).to.equal('btc_eth'); + }); + }); + }); +}); diff --git a/js/src/abi/README.md b/js/src/abi/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6ad6098593b2edf503f8b275caf56e37c4d3cc8b --- /dev/null +++ b/js/src/abi/README.md @@ -0,0 +1,32 @@ +# ethabi-js + +A very early, very POC-type port of [https://github.com/ethcore/ethabi](https://github.com/ethcore/ethabi) to JavaScript + +[![Build Status](https://travis-ci.org/jacogr/ethabi-js.svg?branch=master)](https://travis-ci.org/jacogr/ethabi-js) +[![Coverage Status](https://coveralls.io/repos/github/jacogr/ethabi-js/badge.svg?branch=master)](https://coveralls.io/github/jacogr/ethabi-js?branch=master) +[![Dependency Status](https://david-dm.org/jacogr/ethabi-js.svg)](https://david-dm.org/jacogr/ethabi-js) +[![devDependency Status](https://david-dm.org/jacogr/ethabi-js/dev-status.svg)](https://david-dm.org/jacogr/ethabi-js#info=devDependencies) + +## contributing + +Clone the repo and install dependencies via `npm install`. Tests can be executed via + +- `npm run testOnce` (100% covered unit tests) + +## installation + +Install the package with `npm install --save ethabi-js` from the [npm registry ethabi-js](https://www.npmjs.com/package/ethabi-js) + + +## implementation +### approach + +- this version tries to stay as close to the original Rust version in intent, function names & purpose +- it is a basic port of the Rust version, relying on effectively the same test-suite (expanded where deemed appropriate) +- it is meant as a library to be used in other projects, i.e. [ethapi-js](https://www.npmjs.com/package/ethapi-js) + +### differences to original Rust version + +- internally the library operates on string binary representations as opposed to Vector bytes, lengths are therefore 64 bytes as opposed to 32 bytes +- function names are adapted from the Rust standard snake_case to the JavaScript standard camelCase +- due to the initial library focus, the cli component (as implemented by the original) is not supported nor mplemented diff --git a/js/src/abi/abi.js b/js/src/abi/abi.js new file mode 100644 index 0000000000000000000000000000000000000000..cdf3b1f63958eddbdbb56baff38266f24e983dfa --- /dev/null +++ b/js/src/abi/abi.js @@ -0,0 +1,20 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import Interface from './spec/interface'; + +export default class Abi extends Interface { +} diff --git a/js/src/abi/decoder/bytesTaken.js b/js/src/abi/decoder/bytesTaken.js new file mode 100644 index 0000000000000000000000000000000000000000..49b443d2137927c8e642e889573b82f768d82a0a --- /dev/null +++ b/js/src/abi/decoder/bytesTaken.js @@ -0,0 +1,30 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class BytesTaken { + constructor (bytes, newOffset) { + this._bytes = bytes; + this._newOffset = newOffset; + } + + get bytes () { + return this._bytes; + } + + get newOffset () { + return this._newOffset; + } +} diff --git a/js/src/abi/decoder/bytesTaken.spec.js b/js/src/abi/decoder/bytesTaken.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..65bb9e1b6f17db950033ac3d7006630d62ab26e4 --- /dev/null +++ b/js/src/abi/decoder/bytesTaken.spec.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import BytesTaken from './bytesTaken'; + +describe('abi/decoder/BytesTaken', () => { + describe('constructor', () => { + it('sets the bytes of the object', () => { + expect((new BytesTaken(1, 2)).bytes).to.equal(1); + }); + + it('sets the newOffset of the object', () => { + expect((new BytesTaken(3, 4)).newOffset).to.equal(4); + }); + }); +}); diff --git a/js/src/abi/decoder/decodeResult.js b/js/src/abi/decoder/decodeResult.js new file mode 100644 index 0000000000000000000000000000000000000000..8595642dfb995899dfac131bb4826228bea93d98 --- /dev/null +++ b/js/src/abi/decoder/decodeResult.js @@ -0,0 +1,30 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class DecodeResult { + constructor (token, newOffset) { + this._token = token; + this._newOffset = newOffset; + } + + get token () { + return this._token; + } + + get newOffset () { + return this._newOffset; + } +} diff --git a/js/src/abi/decoder/decodeResult.spec.js b/js/src/abi/decoder/decodeResult.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..892836d07aadab78f6630537d7327f7050211920 --- /dev/null +++ b/js/src/abi/decoder/decodeResult.spec.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import DecodeResult from './decodeResult'; + +describe('abi/decoder/DecodeResult', () => { + describe('constructor', () => { + it('sets the token of the object', () => { + expect((new DecodeResult('token', 2)).token).to.equal('token'); + }); + + it('sets the newOffset of the object', () => { + expect((new DecodeResult('baz', 4)).newOffset).to.equal(4); + }); + }); +}); diff --git a/js/src/abi/decoder/decoder.js b/js/src/abi/decoder/decoder.js new file mode 100644 index 0000000000000000000000000000000000000000..0d218312220249222895a59f79841a542b63d0a8 --- /dev/null +++ b/js/src/abi/decoder/decoder.js @@ -0,0 +1,145 @@ +// 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 utf8 from 'utf8'; + +import Token from '../token/token'; +import BytesTaken from './bytesTaken'; +import DecodeResult from './decodeResult'; +import ParamType from '../spec/paramType/paramType'; +import { sliceData } from '../util/slice'; +import { asAddress, asBool, asI32, asU32 } from '../util/sliceAs'; +import { isArray, isInstanceOf } from '../util/types'; + +const NULL = '0000000000000000000000000000000000000000000000000000000000000000'; + +export default class Decoder { + static decode (params, data) { + if (!isArray(params)) { + throw new Error('Parameters should be array of ParamType'); + } + + const slices = sliceData(data); + let offset = 0; + + return params.map((param) => { + const result = Decoder.decodeParam(param, slices, offset); + offset = result.newOffset; + return result.token; + }); + } + + static peek (slices, position) { + if (!slices || !slices[position]) { + return NULL; + } + + return slices[position]; + } + + static takeBytes (slices, position, length) { + const slicesLength = Math.floor((length + 31) / 32); + let bytesStr = ''; + + for (let idx = 0; idx < slicesLength; idx++) { + bytesStr = `${bytesStr}${Decoder.peek(slices, position + idx)}`; + } + + const bytes = (bytesStr.substr(0, length * 2).match(/.{1,2}/g) || []).map((code) => parseInt(code, 16)); + + return new BytesTaken(bytes, position + slicesLength); + } + + static decodeParam (param, slices, offset) { + if (!isInstanceOf(param, ParamType)) { + throw new Error('param should be instanceof ParamType'); + } + + const tokens = []; + let taken; + let lengthOffset; + let length; + let newOffset; + + switch (param.type) { + case 'address': + return new DecodeResult(new Token(param.type, asAddress(Decoder.peek(slices, offset))), offset + 1); + + case 'bool': + return new DecodeResult(new Token(param.type, asBool(Decoder.peek(slices, offset))), offset + 1); + + case 'int': + return new DecodeResult(new Token(param.type, asI32(Decoder.peek(slices, offset))), offset + 1); + + case 'uint': + return new DecodeResult(new Token(param.type, asU32(Decoder.peek(slices, offset))), offset + 1); + + case 'fixedBytes': + taken = Decoder.takeBytes(slices, offset, param.length); + + return new DecodeResult(new Token(param.type, taken.bytes), taken.newOffset); + + case 'bytes': + lengthOffset = asU32(Decoder.peek(slices, offset)).div(32).toNumber(); + length = asU32(Decoder.peek(slices, lengthOffset)).toNumber(); + taken = Decoder.takeBytes(slices, lengthOffset + 1, length); + + return new DecodeResult(new Token(param.type, taken.bytes), offset + 1); + + case 'string': + if (param.indexed) { + taken = Decoder.takeBytes(slices, offset, 32); + + return new DecodeResult(new Token('fixedBytes', taken.bytes), offset + 1); + } + + lengthOffset = asU32(Decoder.peek(slices, offset)).div(32).toNumber(); + length = asU32(Decoder.peek(slices, lengthOffset)).toNumber(); + taken = Decoder.takeBytes(slices, lengthOffset + 1, length); + + const str = taken.bytes.map((code) => String.fromCharCode(code)).join(''); + + return new DecodeResult(new Token(param.type, utf8.decode(str)), offset + 1); + + case 'array': + lengthOffset = asU32(Decoder.peek(slices, offset)).div(32).toNumber(); + length = asU32(Decoder.peek(slices, lengthOffset)).toNumber(); + newOffset = lengthOffset + 1; + + for (let idx = 0; idx < length; idx++) { + const result = Decoder.decodeParam(param.subtype, slices, newOffset); + newOffset = result.newOffset; + tokens.push(result.token); + } + + return new DecodeResult(new Token(param.type, tokens), offset + 1); + + case 'fixedArray': + newOffset = offset; + + for (let idx = 0; idx < param.length; idx++) { + const result = Decoder.decodeParam(param.subtype, slices, newOffset); + newOffset = result.newOffset; + tokens.push(result.token); + } + + return new DecodeResult(new Token(param.type, tokens), newOffset); + + default: + throw new Error(`Invalid param type ${param.type} in decodeParam`); + } + } +} diff --git a/js/src/abi/decoder/decoder.spec.js b/js/src/abi/decoder/decoder.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..eeaf716c8949d6332abd6383bd928b209b35f31c --- /dev/null +++ b/js/src/abi/decoder/decoder.spec.js @@ -0,0 +1,310 @@ +// 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 BigNumber from 'bignumber.js'; + +import Decoder from './decoder'; +import ParamType from '../spec/paramType'; +import Token from '../token'; +import { padU32 } from '../util/pad'; + +describe('abi/decoder/Decoder', () => { + const stringToBytes = function (str) { + return str.match(/.{1,2}/g).map((code) => parseInt(code, 16)); + }; + + const address1 = '0000000000000000000000001111111111111111111111111111111111111111'; + const address2 = '0000000000000000000000002222222222222222222222222222222222222222'; + const address3 = '0000000000000000000000003333333333333333333333333333333333333333'; + const address4 = '0000000000000000000000004444444444444444444444444444444444444444'; + const bool1 = '0000000000000000000000000000000000000000000000000000000000000001'; + const bytes1 = '1234000000000000000000000000000000000000000000000000000000000000'; + const bytes2 = '1000000000000000000000000000000000000000000000000000000000000000'; + const bytes3 = '10000000000000000000000000000000000000000000000000000000000002'; + const bytes4 = '0010000000000000000000000000000000000000000000000000000000000002'; + const int1 = '0111111111111111111111111111111111111111111111111111111111111111'; + const intn = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff85'; + const string1 = '6761766f66796f726b0000000000000000000000000000000000000000000000'; + const tokenAddress1 = new Token('address', `0x${address1.slice(-40)}`); + const tokenAddress2 = new Token('address', `0x${address2.slice(-40)}`); + const tokenAddress3 = new Token('address', `0x${address3.slice(-40)}`); + const tokenAddress4 = new Token('address', `0x${address4.slice(-40)}`); + const tokenBool1 = new Token('bool', true); + const tokenFixedBytes1 = new Token('fixedBytes', [0x12, 0x34]); + const tokenBytes1 = new Token('bytes', [0x12, 0x34]); + const tokenBytes2 = new Token('bytes', stringToBytes(bytes2).concat(stringToBytes(bytes2))); + const tokenBytes3 = new Token('bytes', stringToBytes(bytes3)); + const tokenBytes4 = new Token('bytes', stringToBytes(bytes4)); + const tokenInt1 = new Token('int', new BigNumber(int1, 16)); + const tokenIntn = new Token('int', new BigNumber(-123)); + const tokenUint1 = new Token('uint', new BigNumber(int1, 16)); + const tokenUintn = new Token('uint', new BigNumber(intn, 16)); + const tokenString1 = new Token('string', 'gavofyork'); + const slices = [ address1, address2, address3, address4 ]; + + describe('peek', () => { + it('returns the slice at the correct position', () => { + expect(Decoder.peek(slices, 1)).to.equal(slices[1]); + }); + + it('returns empty on invalid slices', () => { + expect(Decoder.peek(null, 4)).to.equal('0000000000000000000000000000000000000000000000000000000000000000'); + }); + }); + + describe('takeBytes', () => { + it('returns a single slice', () => { + expect(Decoder.takeBytes(slices, 0, 32).bytes).to.deep.equal(stringToBytes(slices[0])); + }); + + it('returns a single partial slice', () => { + expect(Decoder.takeBytes(slices, 0, 20).bytes).to.deep.equal(stringToBytes(slices[0].substr(0, 40))); + }); + + it('returns multiple slices', () => { + expect(Decoder.takeBytes(slices, 0, 64).bytes).to.deep.equal(stringToBytes(`${slices[0]}${slices[1]}`)); + }); + + it('returns a single offset slice', () => { + expect(Decoder.takeBytes(slices, 1, 32).bytes).to.deep.equal(stringToBytes(slices[1])); + }); + + it('returns multiple offset slices', () => { + expect(Decoder.takeBytes(slices, 1, 64).bytes).to.deep.equal(stringToBytes(`${slices[1]}${slices[2]}`)); + }); + + it('returns the requires length from slices', () => { + expect( + Decoder.takeBytes(slices, 1, 75).bytes + ).to.deep.equal(stringToBytes(`${slices[1]}${slices[2]}${slices[3]}`.substr(0, 150))); + }); + }); + + describe('decodeParam', () => { + it('throws an error on non ParamType param', () => { + expect(() => Decoder.decodeParam({})).to.throw(/ParamType/); + }); + + it('throws an error on invalid param type', () => { + const pt = new ParamType('address'); + pt._type = 'noMatch'; + + expect(() => Decoder.decodeParam(pt)).to.throw(/noMatch/); + }); + + it('decodes an address', () => { + expect( + Decoder.decodeParam(new ParamType('address'), [address1], 0).token + ).to.deep.equal(tokenAddress1); + }); + + it('decodes a bool', () => { + expect( + Decoder.decodeParam(new ParamType('bool'), [bool1], 0).token + ).to.deep.equal(tokenBool1); + }); + + it('decodes an int', () => { + expect( + Decoder.decodeParam(new ParamType('int'), [int1], 0).token + ).to.deep.equal(tokenInt1); + }); + + it('decodes a negative int', () => { + expect( + Decoder.decodeParam(new ParamType('int'), [intn], 0).token + ).to.deep.equal(tokenIntn); + }); + + it('decodes an uint', () => { + expect( + Decoder.decodeParam(new ParamType('uint'), [int1], 0).token + ).to.deep.equal(tokenUint1); + }); + + it('decodes an uint (negative as int)', () => { + expect( + Decoder.decodeParam(new ParamType('uint'), [intn], 0).token + ).to.deep.equal(tokenUintn); + }); + + it('decodes fixedBytes', () => { + expect( + Decoder.decodeParam(new ParamType('fixedBytes', null, 2), [bytes1], 0).token + ).to.deep.equal(tokenFixedBytes1); + }); + + it('decodes bytes', () => { + expect( + Decoder.decodeParam(new ParamType('bytes'), [padU32(0x20), padU32(2), bytes1], 0).token + ).to.deep.equal(tokenBytes1); + }); + + it('decodes string', () => { + expect( + Decoder.decodeParam(new ParamType('string'), [padU32(0x20), padU32(9), string1], 0).token + ).to.deep.equal(tokenString1); + }); + + it('decodes string (indexed)', () => { + expect( + Decoder.decodeParam(new ParamType('string', null, 0, true), [bytes1], 0) + ).to.deep.equal(Decoder.decodeParam(new ParamType('fixedBytes', null, 32, true), [bytes1], 0)); + }); + }); + + describe('decode', () => { + it('throws an error on invalid params', () => { + expect(() => Decoder.decode(null, '123')).to.throw(/array/); + }); + + describe('address', () => { + it('decodes an address', () => { + expect( + Decoder.decode( + [new ParamType('address')], + `${address1}` + ) + ).to.deep.equal([tokenAddress1]); + }); + + it('decodes 2 addresses', () => { + expect( + Decoder.decode( + [new ParamType('address'), new ParamType('address')], + `${address1}${address2}` + ) + ).to.deep.equal([tokenAddress1, tokenAddress2]); + }); + + it('decodes a fixedArray of addresses', () => { + expect( + Decoder.decode( + [new ParamType('fixedArray', new ParamType('address'), 2)], + `${address1}${address2}` + ) + ).to.deep.equal([new Token('fixedArray', [tokenAddress1, tokenAddress2])]); + }); + + it('decodes a dynamic array of addresses', () => { + expect( + Decoder.decode( + [new ParamType('array', new ParamType('address'))], + `${padU32(0x20)}${padU32(2)}${address1}${address2}` + ) + ).to.deep.equal([new Token('array', [tokenAddress1, tokenAddress2])]); + }); + + it('decodes a dynamic array of fixed arrays', () => { + expect( + Decoder.decode( + [new ParamType('array', new ParamType('fixedArray', new ParamType('address'), 2))], + `${padU32(0x20)}${padU32(2)}${address1}${address2}${address3}${address4}` + ) + ).to.deep.equal([ + new Token('array', [ + new Token('fixedArray', [tokenAddress1, tokenAddress2]), + new Token('fixedArray', [tokenAddress3, tokenAddress4]) + ]) + ]); + }); + }); + + describe('int', () => { + it('decodes an int', () => { + expect( + Decoder.decode( + [new ParamType('int')], + `${int1}` + ) + ).to.deep.equal([tokenInt1]); + }); + }); + + describe('uint', () => { + it('decodes an uint', () => { + expect( + Decoder.decode( + [new ParamType('uint')], + `${int1}` + ) + ).to.deep.equal([tokenUint1]); + }); + }); + + describe('fixedBytes', () => { + it('decodes fixedBytes', () => { + expect( + Decoder.decode( + [new ParamType('fixedBytes', null, 2)], + `${bytes1}` + ) + ).to.deep.equal([tokenFixedBytes1]); + }); + }); + + describe('bytes', () => { + it('decodes bytes', () => { + expect( + Decoder.decode( + [new ParamType('bytes')], + `${padU32(0x20)}${padU32(2)}${bytes1}` + ) + ).to.deep.equal([tokenBytes1]); + }); + + it('decodes bytes sequence', () => { + expect( + Decoder.decode( + [new ParamType('bytes')], + `${padU32(0x20)}${padU32(0x40)}${bytes2}${bytes2}` + ) + ).to.deep.equal([tokenBytes2]); + }); + + it('decodes bytes seuence (2)', () => { + expect( + Decoder.decode( + [new ParamType('bytes'), new ParamType('bytes')], + `${padU32(0x40)}${padU32(0x80)}${padU32(0x1f)}${bytes3}00${padU32(0x20)}${bytes4}` + ) + ).to.deep.equal([tokenBytes3, tokenBytes4]); + }); + }); + + describe('bool', () => { + it('decodes a single bool', () => { + expect( + Decoder.decode( + [new ParamType('bool')], + bool1 + ) + ).to.deep.equal([tokenBool1]); + }); + }); + + describe('string', () => { + it('decodes a string', () => { + expect( + Decoder.decode( + [new ParamType('string')], + `${padU32(0x20)}${padU32(9)}${string1}` + ) + ).to.deep.equal([tokenString1]); + }); + }); + }); +}); diff --git a/js/src/abi/decoder/index.js b/js/src/abi/decoder/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f9839c10d8af76e13bb5913f500c2deeafa2ce81 --- /dev/null +++ b/js/src/abi/decoder/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './decoder'; diff --git a/js/src/abi/encoder/encoder.js b/js/src/abi/encoder/encoder.js new file mode 100644 index 0000000000000000000000000000000000000000..bb3a17d264ee7e863762d3b4152e52a4ba511512 --- /dev/null +++ b/js/src/abi/encoder/encoder.js @@ -0,0 +1,72 @@ +// 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 { padAddress, padBool, padBytes, padFixedBytes, padU32, padString } from '../util/pad'; +import Mediate from './mediate'; +import Token from '../token/token'; +import { isArray, isInstanceOf } from '../util/types'; + +export default class Encoder { + static encode (tokens) { + if (!isArray(tokens)) { + throw new Error('tokens should be array of Token'); + } + + const mediates = tokens.map((token) => Encoder.encodeToken(token)); + const inits = mediates + .map((mediate, idx) => mediate.init(Mediate.offsetFor(mediates, idx))) + .join(''); + const closings = mediates + .map((mediate, idx) => mediate.closing(Mediate.offsetFor(mediates, idx))) + .join(''); + + return `${inits}${closings}`; + } + + static encodeToken (token) { + if (!isInstanceOf(token, Token)) { + throw new Error('token should be instanceof Token'); + } + + switch (token.type) { + case 'address': + return new Mediate('raw', padAddress(token.value)); + + case 'int': + case 'uint': + return new Mediate('raw', padU32(token.value)); + + case 'bool': + return new Mediate('raw', padBool(token.value)); + + case 'fixedBytes': + return new Mediate('raw', padFixedBytes(token.value)); + + case 'bytes': + return new Mediate('prefixed', padBytes(token.value)); + + case 'string': + return new Mediate('prefixed', padString(token.value)); + + case 'fixedArray': + case 'array': + return new Mediate(token.type, token.value.map((token) => Encoder.encodeToken(token))); + + default: + throw new Error(`Invalid token type ${token.type} in encodeToken`); + } + } +} diff --git a/js/src/abi/encoder/encoder.spec.js b/js/src/abi/encoder/encoder.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..008861602d1b244e86e246946b50be38af16f1ab --- /dev/null +++ b/js/src/abi/encoder/encoder.spec.js @@ -0,0 +1,290 @@ +// 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 Encoder from './encoder'; +import Token from '../token'; +import { padAddress, padFixedBytes, padU32 } from '../util/pad'; + +describe('abi/encoder/Encoder', () => { + describe('encodeToken', () => { + it('requires token as Token', () => { + expect(() => Encoder.encodeToken()).to.throw(/Token/); + }); + + it('encodes address tokens in Mediate(raw)', () => { + const mediate = Encoder.encodeToken(new Token('address', '123')); + + expect(mediate.type).to.equal('raw'); + expect(mediate.value).to.be.ok; + }); + + it('encodes bool tokens in Mediate(raw)', () => { + const mediatet = Encoder.encodeToken(new Token('bool', true)); + const mediatef = Encoder.encodeToken(new Token('bool', false)); + + expect(mediatet.type).to.equal('raw'); + expect(mediatet.value).to.be.ok; + + expect(mediatef.type).to.equal('raw'); + expect(mediatef.value).to.be.ok; + }); + + it('encodes int tokens in Mediate(raw)', () => { + const mediate = Encoder.encodeToken(new Token('int', '123')); + + expect(mediate.type).to.equal('raw'); + expect(mediate.value).to.be.ok; + }); + + it('encodes uint tokens in Mediate(raw)', () => { + const mediate = Encoder.encodeToken(new Token('uint', '123')); + + expect(mediate.type).to.equal('raw'); + expect(mediate.value).to.be.ok; + }); + + it('encodes fixedBytes tokens in Mediate(raw)', () => { + const mediate = Encoder.encodeToken(new Token('fixedBytes', '123')); + + expect(mediate.type).to.equal('raw'); + expect(mediate.value).to.be.ok; + }); + + it('encodes bytes tokens in Mediate(prefixed)', () => { + const mediate = Encoder.encodeToken(new Token('bytes', '123')); + + expect(mediate.type).to.equal('prefixed'); + expect(mediate.value).to.be.ok; + }); + + it('encodes string tokens in Mediate(prefixed)', () => { + const mediate = Encoder.encodeToken(new Token('string', '123')); + + expect(mediate.type).to.equal('prefixed'); + expect(mediate.value).to.be.ok; + }); + + it('encodes fixedArray tokens in Mediate(fixedArray)', () => { + const mediate = Encoder.encodeToken(new Token('fixedArray', [new Token('uint', '123')])); + + expect(mediate.type).to.equal('fixedArray'); + expect(mediate.value).to.be.ok; + }); + + it('encodes array tokens in Mediate(array)', () => { + const mediate = Encoder.encodeToken(new Token('array', [new Token('uint', '123')])); + + expect(mediate.type).to.equal('array'); + expect(mediate.value).to.be.ok; + }); + + it('throws an Error on invalid tokens', () => { + const token = new Token('address'); + token._type = 'noMatch'; + + expect(() => Encoder.encodeToken(token)).to.throw(/noMatch/); + }); + }); + + describe('encode', () => { + it('requires tokens array', () => { + expect(() => Encoder.encode()).to.throw(/array/); + }); + + describe('addresses', () => { + const address1 = '1111111111111111111111111111111111111111'; + const address2 = '2222222222222222222222222222222222222222'; + const address3 = '3333333333333333333333333333333333333333'; + const address4 = '4444444444444444444444444444444444444444'; + const encAddress1 = padAddress(address1); + const encAddress2 = padAddress(address2); + const encAddress3 = padAddress(address3); + const encAddress4 = padAddress(address4); + const tokenAddress1 = new Token('address', address1); + const tokenAddress2 = new Token('address', address2); + const tokenAddress3 = new Token('address', address3); + const tokenAddress4 = new Token('address', address4); + + it('encodes an address', () => { + const token = tokenAddress1; + + expect(Encoder.encode([token])).to.equal(encAddress1); + }); + + it('encodes an array of addresses', () => { + const expected = `${padU32(0x20)}${padU32(2)}${encAddress1}${encAddress2}`; + const token = new Token('array', [tokenAddress1, tokenAddress2]); + + expect(Encoder.encode([token])).to.equal(expected); + }); + + it('encodes an fixedArray of addresses', () => { + const expected = `${encAddress1}${encAddress2}`; + const token = new Token('fixedArray', [tokenAddress1, tokenAddress2]); + + expect(Encoder.encode([token])).to.equal(expected); + }); + + it('encodes two addresses', () => { + const expected = `${encAddress1}${encAddress2}`; + const tokens = [tokenAddress1, tokenAddress2]; + + expect(Encoder.encode(tokens)).to.equal(expected); + }); + + it('encodes fixed array of dynamic array addresses', () => { + const tokens1 = new Token('array', [tokenAddress1, tokenAddress2]); + const tokens2 = new Token('array', [tokenAddress3, tokenAddress4]); + const fixed = new Token('fixedArray', [tokens1, tokens2]); + const expected = `${padU32(0x40)}${padU32(0xa0)}${padU32(2)}${encAddress1}${encAddress2}${padU32(2)}${encAddress3}${encAddress4}`; + + expect(Encoder.encode([fixed])).to.equal(expected); + }); + + it('encodes dynamic array of fixed array addresses', () => { + const tokens1 = new Token('fixedArray', [tokenAddress1, tokenAddress2]); + const tokens2 = new Token('fixedArray', [tokenAddress3, tokenAddress4]); + const dynamic = new Token('array', [tokens1, tokens2]); + const expected = `${padU32(0x20)}${padU32(2)}${encAddress1}${encAddress2}${encAddress3}${encAddress4}`; + + expect(Encoder.encode([dynamic])).to.equal(expected); + }); + + it('encodes dynamic array of dynamic array addresses', () => { + const tokens1 = new Token('array', [tokenAddress1]); + const tokens2 = new Token('array', [tokenAddress2]); + const dynamic = new Token('array', [tokens1, tokens2]); + const expected = `${padU32(0x20)}${padU32(2)}${padU32(0x80)}${padU32(0xc0)}${padU32(1)}${encAddress1}${padU32(1)}${encAddress2}`; + + expect(Encoder.encode([dynamic])).to.equal(expected); + }); + + it('encodes dynamic array of dynamic array addresses (2)', () => { + const tokens1 = new Token('array', [tokenAddress1, tokenAddress2]); + const tokens2 = new Token('array', [tokenAddress3, tokenAddress4]); + const dynamic = new Token('array', [tokens1, tokens2]); + const expected = `${padU32(0x20)}${padU32(2)}${padU32(0x80)}${padU32(0xe0)}${padU32(2)}${encAddress1}${encAddress2}${padU32(2)}${encAddress3}${encAddress4}`; + + expect(Encoder.encode([dynamic])).to.equal(expected); + }); + + it('encodes fixed array of fixed array addresses', () => { + const tokens1 = new Token('fixedArray', [tokenAddress1, tokenAddress2]); + const tokens2 = new Token('fixedArray', [tokenAddress3, tokenAddress4]); + const dynamic = new Token('fixedArray', [tokens1, tokens2]); + const expected = `${encAddress1}${encAddress2}${encAddress3}${encAddress4}`; + + expect(Encoder.encode([dynamic])).to.equal(expected); + }); + }); + + describe('bytes', () => { + const bytes1 = '0x1234'; + const bytes2 = '0x10000000000000000000000000000000000000000000000000000000000002'; + const bytes3 = '0x1000000000000000000000000000000000000000000000000000000000000000'; + + it('encodes fixed bytes', () => { + const token = new Token('fixedBytes', bytes1); + + expect(Encoder.encode([token])).to.equal(padFixedBytes(bytes1)); + }); + + it('encodes bytes', () => { + const token = new Token('bytes', bytes1); + + expect(Encoder.encode([token])).to.equal(`${padU32(0x20)}${padU32(2)}${padFixedBytes(bytes1)}`); + }); + + it('encodes bytes (short of boundary)', () => { + const token = new Token('bytes', bytes2); + + expect(Encoder.encode([token])).to.equal(`${padU32(0x20)}${padU32(0x1f)}${padFixedBytes(bytes2)}`); + }); + + it('encodes bytes (two blocks)', () => { + const input = `${bytes3}${bytes3.slice(-64)}`; + const token = new Token('bytes', input); + + expect(Encoder.encode([token])).to.equal(`${padU32(0x20)}${padU32(0x40)}${padFixedBytes(input)}`); + }); + + it('encodes two consecutive bytes', () => { + const in1 = '0x10000000000000000000000000000000000000000000000000000000000002'; + const in2 = '0x0010000000000000000000000000000000000000000000000000000000000002'; + const tokens = [new Token('bytes', in1), new Token('bytes', in2)]; + + expect(Encoder.encode(tokens)).to.equal(`${padU32(0x40)}${padU32(0x80)}${padU32(0x1f)}${padFixedBytes(in1)}${padU32(0x20)}${padFixedBytes(in2)}`); + }); + }); + + describe('string', () => { + it('encodes a string', () => { + const string = 'gavofyork'; + const stringEnc = padFixedBytes('0x6761766f66796f726b'); + const token = new Token('string', string); + + expect(Encoder.encode([token])).to.equal(`${padU32(0x20)}${padU32(string.length.toString(16))}${stringEnc}`); + }); + }); + + describe('uint', () => { + it('encodes a uint', () => { + const token = new Token('uint', 4); + + expect(Encoder.encode([token])).to.equal(padU32(4)); + }); + }); + + describe('int', () => { + it('encodes a int', () => { + const token = new Token('int', 4); + + expect(Encoder.encode([token])).to.equal(padU32(4)); + }); + }); + + describe('bool', () => { + it('encodes a bool (true)', () => { + const token = new Token('bool', true); + + expect(Encoder.encode([token])).to.equal(padU32(1)); + }); + + it('encodes a bool (false)', () => { + const token = new Token('bool', false); + + expect(Encoder.encode([token])).to.equal(padU32(0)); + }); + }); + + describe('comprehensive test', () => { + it('encodes a complex sequence', () => { + const bytes = '0x131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b'; + const tokens = [new Token('int', 5), new Token('bytes', bytes), new Token('int', 3), new Token('bytes', bytes)]; + + expect(Encoder.encode(tokens)).to.equal(`${padU32(5)}${padU32(0x80)}${padU32(3)}${padU32(0xe0)}${padU32(0x40)}${bytes.substr(2)}${padU32(0x40)}${bytes.substr(2)}`); + }); + + it('encodes a complex sequence (nested)', () => { + const array = [new Token('int', 5), new Token('int', 6), new Token('int', 7)]; + const tokens = [new Token('int', 1), new Token('string', 'gavofyork'), new Token('int', 2), new Token('int', 3), new Token('int', 4), new Token('array', array)]; + const stringEnc = padFixedBytes('0x6761766f66796f726b'); + + expect(Encoder.encode(tokens)).to.equal(`${padU32(1)}${padU32(0xc0)}${padU32(2)}${padU32(3)}${padU32(4)}${padU32(0x100)}${padU32(9)}${stringEnc}${padU32(3)}${padU32(5)}${padU32(6)}${padU32(7)}`); + }); + }); + }); +}); diff --git a/js/src/abi/encoder/index.js b/js/src/abi/encoder/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e19ff81e6745f016db28decc6d71fbcd69706554 --- /dev/null +++ b/js/src/abi/encoder/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './encoder'; diff --git a/js/src/abi/encoder/mediate.js b/js/src/abi/encoder/mediate.js new file mode 100644 index 0000000000000000000000000000000000000000..cb7fce6a75380844392a79d948c8c2777e78354f --- /dev/null +++ b/js/src/abi/encoder/mediate.js @@ -0,0 +1,142 @@ +// 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 . + +const TYPES = ['raw', 'prefixed', 'fixedArray', 'array']; + +import { padU32 } from '../util/pad'; + +export default class Mediate { + constructor (type, value) { + Mediate.validateType(type); + + this._type = type; + this._value = value; + } + + initLength () { + switch (this._type) { + case 'raw': + return this._value.length / 2; + + case 'array': + case 'prefixed': + return 32; + + case 'fixedArray': + return this._value + .reduce((total, mediate) => { + return total + mediate.initLength(); + }, 0); + } + } + + closingLength () { + switch (this._type) { + case 'raw': + return 0; + + case 'prefixed': + return this._value.length / 2; + + case 'array': + return this._value + .reduce((total, mediate) => { + return total + mediate.initLength(); + }, 32); + + case 'fixedArray': + return this._value + .reduce((total, mediate) => { + return total + mediate.initLength() + mediate.closingLength(); + }, 0); + } + } + + init (suffixOffset) { + switch (this._type) { + case 'raw': + return this._value; + + case 'fixedArray': + return this._value + .map((mediate, idx) => mediate.init(Mediate.offsetFor(this._value, idx)).toString(16)) + .join(''); + + case 'prefixed': + case 'array': + return padU32(suffixOffset); + } + } + + closing (offset) { + switch (this._type) { + case 'raw': + return ''; + + case 'prefixed': + return this._value; + + case 'fixedArray': + return this._value + .map((mediate, idx) => mediate.closing(Mediate.offsetFor(this._value, idx)).toString(16)) + .join(''); + + case 'array': + const prefix = padU32(this._value.length); + const inits = this._value + .map((mediate, idx) => mediate.init(offset + Mediate.offsetFor(this._value, idx) + 32).toString(16)) + .join(''); + const closings = this._value + .map((mediate, idx) => mediate.closing(offset + Mediate.offsetFor(this._value, idx)).toString(16)) + .join(''); + + return `${prefix}${inits}${closings}`; + } + } + + get type () { + return this._type; + } + + get value () { + return this._value; + } + + static offsetFor (mediates, position) { + if (position < 0 || position >= mediates.length) { + throw new Error(`Invalid position ${position} specified for Mediate.offsetFor`); + } + + const initLength = mediates + .reduce((total, mediate) => { + return total + mediate.initLength(); + }, 0); + + return mediates + .slice(0, position) + .reduce((total, mediate) => { + return total + mediate.closingLength(); + }, initLength); + } + + static validateType (type) { + if (TYPES.filter((_type) => type === _type).length) { + return true; + } + + throw new Error(`Invalid type ${type} received for Mediate.validateType`); + } +} diff --git a/js/src/abi/encoder/mediate.spec.js b/js/src/abi/encoder/mediate.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..cfd0211f2f933fd9b4e5cac5deb4f25aaafe7bdf --- /dev/null +++ b/js/src/abi/encoder/mediate.spec.js @@ -0,0 +1,105 @@ +// 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 Mediate from './mediate'; + +describe('abi/encoder/Mediate', () => { + const LONG15 = '1234567890abcdef000000000000000000000000000000000000000000000000'; + const DOUBLE15 = `${LONG15}${LONG15}`; + const ARRAY = [new Mediate('raw', DOUBLE15), new Mediate('raw', LONG15)]; + + describe('validateType', () => { + it('validates raw', () => { + expect(Mediate.validateType('raw')).to.be.true; + }); + + it('validates prefixed', () => { + expect(Mediate.validateType('prefixed')).to.be.true; + }); + + it('validates fixedArray', () => { + expect(Mediate.validateType('fixedArray')).to.be.true; + }); + + it('validates array', () => { + expect(Mediate.validateType('array')).to.be.true; + }); + + it('throws an error on invalid types', () => { + expect(() => Mediate.validateType('noMatch')).to.throw(/noMatch/); + }); + }); + + describe('offsetFor', () => { + it('thows an error when offset < 0', () => { + expect(() => Mediate.offsetFor([1], -1)).to.throw(/Invalid position/); + }); + + it('throws an error when offset >= length', () => { + expect(() => Mediate.offsetFor([1], 1)).to.throw(/Invalid position/); + }); + }); + + describe('constructor', () => { + it('throws an error on invalid types', () => { + expect(() => new Mediate('noMatch', '1')).to.throw(/noMatch/); + }); + + it('sets the type of the object', () => { + expect((new Mediate('raw', '1')).type).to.equal('raw'); + }); + + it('sets the value of the object', () => { + expect((new Mediate('raw', '1')).value).to.equal('1'); + }); + }); + + describe('initLength', () => { + it('returns correct variable byte length for raw', () => { + expect(new Mediate('raw', DOUBLE15).initLength()).to.equal(64); + }); + + it('returns correct fixed byte length for array', () => { + expect(new Mediate('array', [1, 2, 3, 4]).initLength()).to.equal(32); + }); + + it('returns correct fixed byte length for prefixed', () => { + expect(new Mediate('prefixed', 0).initLength()).to.equal(32); + }); + + it('returns correct variable byte length for fixedArray', () => { + expect(new Mediate('fixedArray', ARRAY).initLength()).to.equal(96); + }); + }); + + describe('closingLength', () => { + it('returns 0 byte length for raw', () => { + expect(new Mediate('raw', DOUBLE15).closingLength()).to.equal(0); + }); + + it('returns prefix + size for prefixed', () => { + expect(new Mediate('prefixed', DOUBLE15).closingLength()).to.equal(64); + }); + + it('returns prefix + size for array', () => { + expect(new Mediate('array', ARRAY).closingLength()).to.equal(128); + }); + + it('returns total length for fixedArray', () => { + expect(new Mediate('fixedArray', ARRAY).closingLength()).to.equal(96); + }); + }); +}); diff --git a/js/src/abi/index.js b/js/src/abi/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f055a69133e282b5754600adcb8c580c659670d5 --- /dev/null +++ b/js/src/abi/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './abi'; diff --git a/js/src/abi/spec/constructor.js b/js/src/abi/spec/constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..89ea99610efb5a8f083954027ffb8b73770895a3 --- /dev/null +++ b/js/src/abi/spec/constructor.js @@ -0,0 +1,36 @@ +// 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 Encoder from '../encoder/encoder'; +import Param from './param'; + +export default class Constructor { + constructor (abi) { + this._inputs = Param.toParams(abi.inputs || []); + } + + get inputs () { + return this._inputs; + } + + inputParamTypes () { + return this._inputs.map((input) => input.kind); + } + + encodeCall (tokens) { + return Encoder.encode(tokens); + } +} diff --git a/js/src/abi/spec/constructor.spec.js b/js/src/abi/spec/constructor.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e02f6cf71f150f8f2c4da1e8e0a3e208289c1c99 --- /dev/null +++ b/js/src/abi/spec/constructor.spec.js @@ -0,0 +1,52 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import Constructor from './constructor'; +import Param from './param'; +import Token from '../token'; + +describe('abi/spec/Constructor', () => { + const inputsArr = [{ name: 'boolin', type: 'bool' }, { name: 'stringin', type: 'string' }]; + const bool = new Param('boolin', 'bool'); + const string = new Param('stringin', 'string'); + + const inputs = [bool, string]; + const cr = new Constructor({ inputs: inputsArr }); + + describe('constructor', () => { + it('stores the inputs as received', () => { + expect(cr.inputs).to.deep.equal(inputs); + }); + + it('matches empty inputs with []', () => { + expect(new Constructor({}).inputs).to.deep.equal([]); + }); + }); + + describe('inputParamTypes', () => { + it('retrieves the input types as received', () => { + expect(cr.inputParamTypes()).to.deep.equal([bool.kind, string.kind]); + }); + }); + + describe('encodeCall', () => { + it('encodes correctly', () => { + const result = cr.encodeCall([new Token('bool', true), new Token('string', 'jacogr')]); + + expect(result).to.equal('0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066a61636f67720000000000000000000000000000000000000000000000000000'); + }); + }); +}); diff --git a/js/src/abi/spec/event/decodedLog.js b/js/src/abi/spec/event/decodedLog.js new file mode 100644 index 0000000000000000000000000000000000000000..3993b527b57ec876839af58f7a65f3216916128e --- /dev/null +++ b/js/src/abi/spec/event/decodedLog.js @@ -0,0 +1,30 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class DecodedLog { + constructor (params, address) { + this._params = params; + this._address = address; + } + + get address () { + return this._address; + } + + get params () { + return this._params; + } +} diff --git a/js/src/abi/spec/event/decodedLog.spec.js b/js/src/abi/spec/event/decodedLog.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e6ed1a022940552ff238982b2e533417dd2e82a8 --- /dev/null +++ b/js/src/abi/spec/event/decodedLog.spec.js @@ -0,0 +1,28 @@ +// 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 DecodedLog from './decodedLog'; + +const log = new DecodedLog('someParams', 'someAddress'); + +describe('abi/spec/event/DecodedLog', () => { + describe('constructor', () => { + it('sets internal state', () => { + expect(log.params).to.equal('someParams'); + expect(log.address).to.equal('someAddress'); + }); + }); +}); diff --git a/js/src/abi/spec/event/decodedLogParam.js b/js/src/abi/spec/event/decodedLogParam.js new file mode 100644 index 0000000000000000000000000000000000000000..ed456fcce8b5471414714392f8e92e40fc03fdfe --- /dev/null +++ b/js/src/abi/spec/event/decodedLogParam.js @@ -0,0 +1,45 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import ParamType from '../paramType/paramType'; +import Token from '../../token/token'; +import { isInstanceOf } from '../../util/types'; + +export default class DecodedLogParam { + constructor (name, kind, token) { + if (!isInstanceOf(kind, ParamType)) { + throw new Error('kind not instanceof ParamType'); + } else if (!isInstanceOf(token, Token)) { + throw new Error('token not instanceof Token'); + } + + this._name = name; + this._kind = kind; + this._token = token; + } + + get name () { + return this._name; + } + + get kind () { + return this._kind; + } + + get token () { + return this._token; + } +} diff --git a/js/src/abi/spec/event/decodedLogParam.spec.js b/js/src/abi/spec/event/decodedLogParam.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a031282ad87ab00bbe9fe2a08d172b90a1c5e36e --- /dev/null +++ b/js/src/abi/spec/event/decodedLogParam.spec.js @@ -0,0 +1,42 @@ +// 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 DecodedLogParam from './decodedLogParam'; +import ParamType from '../paramType'; +import Token from '../../token'; + +describe('abi/spec/event/DecodedLogParam', () => { + describe('constructor', () => { + const pt = new ParamType('bool'); + const tk = new Token('bool'); + + it('disallows kind not instanceof ParamType', () => { + expect(() => new DecodedLogParam('test', 'param')).to.throw(/ParamType/); + }); + + it('disallows token not instanceof Token', () => { + expect(() => new DecodedLogParam('test', pt, 'token')).to.throw(/Token/); + }); + + it('stores all parameters received', () => { + const log = new DecodedLogParam('test', pt, tk); + + expect(log.name).to.equal('test'); + expect(log.kind).to.equal(pt); + expect(log.token).to.equal(tk); + }); + }); +}); diff --git a/js/src/abi/spec/event/event.js b/js/src/abi/spec/event/event.js new file mode 100644 index 0000000000000000000000000000000000000000..f64fe0498b44b1298f56f620708d131c6c910c8e --- /dev/null +++ b/js/src/abi/spec/event/event.js @@ -0,0 +1,113 @@ +// 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 Decoder from '../../decoder/decoder'; +import DecodedLog from './decodedLog'; +import DecodedLogParam from './decodedLogParam'; +import EventParam from './eventParam'; +import { asAddress } from '../../util/sliceAs'; +import { eventSignature } from '../../util/signature'; + +export default class Event { + constructor (abi) { + this._name = abi.name; + this._inputs = EventParam.toEventParams(abi.inputs || []); + this._anonymous = !!abi.anonymous; + + const { id, signature } = eventSignature(this._name, this.inputParamTypes()); + this._id = id; + this._signature = signature; + } + + get name () { + return this._name; + } + + get id () { + return this._id; + } + + get inputs () { + return this._inputs; + } + + get anonymous () { + return this._anonymous; + } + + get signature () { + return this._signature; + } + + inputParamTypes () { + return this._inputs.map((input) => input.kind); + } + + inputParamNames () { + return this._inputs.map((input) => input.name); + } + + indexedParams (indexed) { + return this._inputs.filter((input) => input.indexed === indexed); + } + + decodeLog (topics, data) { + const topicParams = this.indexedParams(true); + const dataParams = this.indexedParams(false); + + let address; + let toSkip; + + if (!this.anonymous) { + address = asAddress(topics[0]); + toSkip = 1; + } else { + toSkip = 0; + } + + const topicTypes = topicParams.map((param) => param.kind); + const flatTopics = topics + .filter((topic, idx) => idx >= toSkip) + .map((topic) => { + return (topic.substr(0, 2) === '0x') + ? topic.substr(2) + : topic; + }).join(''); + const topicTokens = Decoder.decode(topicTypes, flatTopics); + + if (topicTokens.length !== (topics.length - toSkip)) { + throw new Error('Invalid topic data'); + } + + const dataTypes = dataParams.map((param) => param.kind); + const dataTokens = Decoder.decode(dataTypes, data); + + const namedTokens = {}; + + topicParams.forEach((param, idx) => { + namedTokens[param.name] = topicTokens[idx]; + }); + dataParams.forEach((param, idx) => { + namedTokens[param.name] = dataTokens[idx]; + }); + + const inputParamTypes = this.inputParamTypes(); + const decodedParams = this.inputParamNames() + .map((name, idx) => new DecodedLogParam(name, inputParamTypes[idx], namedTokens[name])); + + return new DecodedLog(decodedParams, address); + } +} diff --git a/js/src/abi/spec/event/event.spec.js b/js/src/abi/spec/event/event.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..f7252a9d2d798ae78a0491ab3fc60a4da70726cd --- /dev/null +++ b/js/src/abi/spec/event/event.spec.js @@ -0,0 +1,111 @@ +// 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 BigNumber from 'bignumber.js'; + +import Event from './event'; +import EventParam from './eventParam'; +import DecodedLogParam from './decodedLogParam'; +import ParamType from '../paramType'; +import Token from '../../token'; + +describe('abi/spec/event/Event', () => { + const inputArr = [{ name: 'a', type: 'bool' }, { name: 'b', type: 'uint', indexed: true }]; + const inputs = [new EventParam('a', 'bool', false), new EventParam('b', 'uint', true)]; + const event = new Event({ name: 'test', inputs: inputArr, anonymous: true }); + + describe('constructor', () => { + it('stores the parameters as received', () => { + expect(event.name).to.equal('test'); + expect(event.inputs).to.deep.equal(inputs); + expect(event.anonymous).to.be.true; + }); + + it('matches empty inputs with []', () => { + expect(new Event({ name: 'test' }).inputs).to.deep.equal([]); + }); + + it('sets the event signature', () => { + expect(new Event({ name: 'baz' }).signature) + .to.equal('a7916fac4f538170f7cd12c148552e2cba9fcd72329a2dd5b07a6fa906488ddf'); + }); + }); + + describe('inputParamTypes', () => { + it('returns all the types', () => { + expect(event.inputParamTypes()).to.deep.equal([new ParamType('bool'), new ParamType('uint', null, 256, true)]); + }); + }); + + describe('inputParamNames', () => { + it('returns all the names', () => { + expect(event.inputParamNames()).to.deep.equal(['a', 'b']); + }); + }); + + describe('indexedParams', () => { + it('returns all indexed parameters (indexed)', () => { + expect(event.indexedParams(true)).to.deep.equal([inputs[1]]); + }); + + it('returns all indexed parameters (non-indexed)', () => { + expect(event.indexedParams(false)).to.deep.equal([inputs[0]]); + }); + }); + + describe('decodeLog', () => { + it('decodes an event', () => { + const event = new Event({ + name: 'foo', + inputs: [ + { name: 'a', type: 'int' }, + { name: 'b', type: 'int', indexed: true }, + { name: 'c', type: 'address' }, + { name: 'd', type: 'address', indexed: true } + ] + }); + const decoded = event.decodeLog([ + '0000000000000000000000004444444444444444444444444444444444444444', + '0000000000000000000000000000000000000000000000000000000000000002', + '0000000000000000000000001111111111111111111111111111111111111111' ], + '00000000000000000000000000000000000000000000000000000000000000030000000000000000000000002222222222222222222222222222222222222222'); + + expect(decoded.address).to.equal('0x4444444444444444444444444444444444444444'); + expect(decoded.params).to.deep.equal([ + new DecodedLogParam('a', new ParamType('int', null, 256), new Token('int', new BigNumber(3))), + new DecodedLogParam('b', new ParamType('int', null, 256, true), new Token('int', new BigNumber(2))), + new DecodedLogParam('c', new ParamType('address'), new Token('address', '0x2222222222222222222222222222222222222222')), + new DecodedLogParam('d', new ParamType('address', null, 0, true), new Token('address', '0x1111111111111111111111111111111111111111')) + ]); + }); + + it('decodes an anonymous event', () => { + const event = new Event({ name: 'foo', inputs: [{ name: 'a', type: 'int' }], anonymous: true }); + const decoded = event.decodeLog([], '0000000000000000000000000000000000000000000000000000000000000003'); + + expect(decoded.address).to.not.be.ok; + expect(decoded.params).to.deep.equal([ + new DecodedLogParam('a', new ParamType('int', null, 256), new Token('int', new BigNumber(3))) + ]); + }); + + it('throws on invalid topics', () => { + const event = new Event({ name: 'foo', inputs: [{ name: 'a', type: 'int' }], anonymous: true }); + + expect(() => event.decodeLog(['0000000000000000000000004444444444444444444444444444444444444444'], '0000000000000000000000000000000000000000000000000000000000000003')).to.throw(/Invalid/); + }); + }); +}); diff --git a/js/src/abi/spec/event/eventParam.js b/js/src/abi/spec/event/eventParam.js new file mode 100644 index 0000000000000000000000000000000000000000..d8a3b585d8704e3356ac26642bdb740305f76e83 --- /dev/null +++ b/js/src/abi/spec/event/eventParam.js @@ -0,0 +1,41 @@ +// 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 { toParamType } from '../paramType/format'; + +export default class EventParam { + constructor (name, type, indexed = false) { + this._name = name; + this._indexed = indexed; + this._kind = toParamType(type, indexed); + } + + get name () { + return this._name; + } + + get kind () { + return this._kind; + } + + get indexed () { + return this._indexed; + } + + static toEventParams (params) { + return params.map((param) => new EventParam(param.name, param.type, param.indexed)); + } +} diff --git a/js/src/abi/spec/event/eventParam.spec.js b/js/src/abi/spec/event/eventParam.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..6858e980017f282f88a4d0b3a672e526e5c5fabc --- /dev/null +++ b/js/src/abi/spec/event/eventParam.spec.js @@ -0,0 +1,43 @@ +// 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 EventParam from './eventParam'; + +describe('abi/spec/event/EventParam', () => { + describe('constructor', () => { + it('sets the properties', () => { + const param = new EventParam('foo', 'uint', true); + expect(param.name).to.equal('foo'); + expect(param.kind.type).to.equal('uint'); + expect(param.indexed).to.be.true; + }); + + it('uses defaults for indexed', () => { + expect(new EventParam('foo', 'uint').indexed).to.be.false; + }); + }); + + describe('toEventParams', () => { + it('maps an array of params', () => { + const params = EventParam.toEventParams([{ name: 'foo', type: 'uint' }]); + + expect(params.length).to.equal(1); + expect(params[0].indexed).to.be.false; + expect(params[0].name).to.equal('foo'); + expect(params[0].kind.type).to.equal('uint'); + }); + }); +}); diff --git a/js/src/abi/spec/event/index.js b/js/src/abi/spec/event/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0925882d3e3ed35d3e6e0decfd8ab3e18d451052 --- /dev/null +++ b/js/src/abi/spec/event/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './event'; diff --git a/js/src/abi/spec/function.js b/js/src/abi/spec/function.js new file mode 100644 index 0000000000000000000000000000000000000000..0c91a9b6f9843b0e287fe96fc0990d6a00c194df --- /dev/null +++ b/js/src/abi/spec/function.js @@ -0,0 +1,87 @@ +// 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 Decoder from '../decoder/decoder'; +import Encoder from '../encoder/encoder'; +import Param from './param'; +import { methodSignature } from '../util/signature'; + +export default class Func { + constructor (abi) { + this._abi = abi; + this._name = abi.name; + this._constant = !!abi.constant; + this._payable = abi.payable; + this._inputs = Param.toParams(abi.inputs || []); + this._outputs = Param.toParams(abi.outputs || []); + + const { id, signature } = methodSignature(this._name, this.inputParamTypes()); + this._id = id; + this._signature = signature; + } + + get abi () { + return this._abi; + } + + get constant () { + return this._constant; + } + + get name () { + return this._name; + } + + get id () { + return this._id; + } + + get payable () { + return this._payable; + } + + get inputs () { + return this._inputs; + } + + get outputs () { + return this._outputs; + } + + get signature () { + return this._signature; + } + + inputParamTypes () { + return this._inputs.map((input) => input.kind); + } + + outputParamTypes () { + return this._outputs.map((output) => output.kind); + } + + encodeCall (tokens) { + return `${this._signature}${Encoder.encode(tokens)}`; + } + + decodeInput (data) { + return Decoder.decode(this.inputParamTypes(), data); + } + + decodeOutput (data) { + return Decoder.decode(this.outputParamTypes(), data); + } +} diff --git a/js/src/abi/spec/function.spec.js b/js/src/abi/spec/function.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..1650bd3146463b2a8530c36b116bb3df7eabbb7a --- /dev/null +++ b/js/src/abi/spec/function.spec.js @@ -0,0 +1,89 @@ +// 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 Func from './function'; +import Param from './param'; +import Token from '../token'; + +describe('abi/spec/Function', () => { + const inputsArr = [{ name: 'boolin', type: 'bool' }, { name: 'stringin', type: 'string' }]; + const outputsArr = [{ name: 'output', type: 'uint' }]; + + const uint = new Param('output', 'uint'); + const bool = new Param('boolin', 'bool'); + const string = new Param('stringin', 'string'); + const inputs = [bool, string]; + const outputs = [uint]; + + const func = new Func({ + name: 'test', + inputs: inputsArr, + outputs: outputsArr + }); + + describe('constructor', () => { + it('stores the parameters as received', () => { + expect(func.name).to.equal('test'); + expect(func.constant).to.be.false; + expect(func.inputs).to.deep.equal(inputs); + expect(func.outputs).to.deep.equal(outputs); + }); + + it('matches empty inputs with []', () => { + expect(new Func({ name: 'test', outputs: outputsArr }).inputs).to.deep.equal([]); + }); + + it('matches empty outputs with []', () => { + expect(new Func({ name: 'test', inputs: inputsArr }).outputs).to.deep.equal([]); + }); + + it('sets the method signature', () => { + expect(new Func({ name: 'baz' }).signature).to.equal('a7916fac'); + }); + + it('allows constant functions', () => { + expect(new Func({ name: 'baz', constant: true }).constant).to.be.true; + }); + }); + + describe('inputParamTypes', () => { + it('retrieves the input types as received', () => { + expect(func.inputParamTypes()).to.deep.equal([bool.kind, string.kind]); + }); + }); + + describe('outputParamTypes', () => { + it('retrieves the output types as received', () => { + expect(func.outputParamTypes()).to.deep.equal([uint.kind]); + }); + }); + + describe('encodeCall', () => { + it('encodes the call correctly', () => { + const result = func.encodeCall([new Token('bool', true), new Token('string', 'jacogr')]); + + expect(result).to.equal('023562050000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066a61636f67720000000000000000000000000000000000000000000000000000'); + }); + }); + + describe('decodeOutput', () => { + it('decodes the result correctly', () => { + const result = func.decodeOutput('1111111111111111111111111111111111111111111111111111111111111111'); + + expect(result[0].value.toString(16)).to.equal('1111111111111111111111111111111111111111111111111111111111111111'); + }); + }); +}); diff --git a/js/src/abi/spec/index.js b/js/src/abi/spec/index.js new file mode 100644 index 0000000000000000000000000000000000000000..89354d49b5b08cd5c4ca5583199ad383ba7bab77 --- /dev/null +++ b/js/src/abi/spec/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './interface'; diff --git a/js/src/abi/spec/interface.js b/js/src/abi/spec/interface.js new file mode 100644 index 0000000000000000000000000000000000000000..1ea32e9a9c4e7c3c78ae752ebc7022489fc3d9e1 --- /dev/null +++ b/js/src/abi/spec/interface.js @@ -0,0 +1,73 @@ +// 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 Constructor from './constructor'; +import Event from './event/event'; +import Func from './function'; +import Token from '../token'; + +export default class Interface { + constructor (abi) { + this._interface = Interface.parseABI(abi); + } + + get interface () { + return this._interface; + } + + get constructors () { + return this._interface.filter((item) => item instanceof Constructor); + } + + get events () { + return this._interface.filter((item) => item instanceof Event); + } + + get functions () { + return this._interface.filter((item) => item instanceof Func); + } + + encodeTokens (paramTypes, values) { + const createToken = function (paramType, value) { + if (paramType.subtype) { + return new Token(paramType.type, value.map((entry) => createToken(paramType.subtype, entry))); + } + + return new Token(paramType.type, value); + }; + + return paramTypes.map((paramType, idx) => createToken(paramType, values[idx])); + } + + static parseABI (abi) { + return abi.map((item) => { + switch (item.type) { + case 'constructor': + return new Constructor(item); + + case 'event': + return new Event(item); + + case 'function': + case 'fallback': + return new Func(item); + + default: + throw new Error(`Unknown ABI type ${item.type}`); + } + }); + } +} diff --git a/js/src/abi/spec/interface.spec.js b/js/src/abi/spec/interface.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..ba5c38a28a073d70acd0171d9b50e152954d0fd1 --- /dev/null +++ b/js/src/abi/spec/interface.spec.js @@ -0,0 +1,126 @@ +// 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 Interface from './interface'; +import ParamType from './paramType'; +import Token from '../token'; + +describe('abi/spec/Interface', () => { + const construct = { + type: 'constructor', + inputs: [] + }; + const event = { + type: 'event', + name: 'Event2', + anonymous: false, + inputs: [{ name: 'a', type: 'uint256', indexed: true }, { name: 'b', type: 'bytes32', indexed: false }] + }; + const func = { + type: 'function', + name: 'foo', + inputs: [{ name: 'a', type: 'uint256' }], + outputs: [] + }; + + describe('parseABI', () => { + it('throws on invalid types', () => { + expect(() => Interface.parseABI([{ type: 'noMatch' }])).to.throw(/noMatch/); + }); + + it('creates constructors', () => { + expect(Interface.parseABI([ construct ])).to.deep.equal([{ _inputs: [] }]); + }); + + it('creates events', () => { + expect(Interface.parseABI([ event ])[0].name).to.equal('Event2'); + }); + + it('creates functions', () => { + expect(Interface.parseABI([ func ])[0].name).to.equal('foo'); + }); + + it('parse complex interfaces', () => { + expect(Interface.parseABI([ construct, event, func ]).length).to.equal(3); + }); + }); + + describe('constructor', () => { + const int = new Interface([ construct, event, func ]); + + it('contains the full interface', () => { + expect(int.interface.length).to.equal(3); + }); + + it('contains the constructors', () => { + expect(int.constructors.length).to.equal(1); + }); + + it('contains the events', () => { + expect(int.events.length).to.equal(1); + }); + + it('contains the functions', () => { + expect(int.functions.length).to.equal(1); + }); + }); + + describe('encodeTokens', () => { + const int = new Interface([ construct, event, func ]); + + it('encodes simple types', () => { + expect( + int.encodeTokens( + [new ParamType('bool'), new ParamType('string'), new ParamType('int'), new ParamType('uint')], + [true, 'gavofyork', -123, 123] + ) + ).to.deep.equal([ + new Token('bool', true), new Token('string', 'gavofyork'), new Token('int', -123), new Token('uint', 123) + ]); + }); + + it('encodes array', () => { + expect( + int.encodeTokens( + [new ParamType('array', new ParamType('bool'))], + [[true, false, true]] + ) + ).to.deep.equal([ + new Token('array', [ + new Token('bool', true), new Token('bool', false), new Token('bool', true) + ]) + ]); + }); + + it('encodes simple with array of array', () => { + expect( + int.encodeTokens( + [ + new ParamType('bool'), + new ParamType('fixedArray', new ParamType('array', new ParamType('uint')), 2) + ], + [true, [[0, 1], [2, 3]]] + ) + ).to.deep.equal([ + new Token('bool', true), + new Token('fixedArray', [ + new Token('array', [new Token('uint', 0), new Token('uint', 1)]), + new Token('array', [new Token('uint', 2), new Token('uint', 3)]) + ]) + ]); + }); + }); +}); diff --git a/js/src/abi/spec/param.js b/js/src/abi/spec/param.js new file mode 100644 index 0000000000000000000000000000000000000000..95c3b9d18f53c48aa11460fb458001c31eb888cd --- /dev/null +++ b/js/src/abi/spec/param.js @@ -0,0 +1,36 @@ +// 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 { toParamType } from './paramType/format'; + +export default class Param { + constructor (name, type) { + this._name = name; + this._kind = toParamType(type); + } + + get name () { + return this._name; + } + + get kind () { + return this._kind; + } + + static toParams (params) { + return params.map((param) => new Param(param.name, param.type)); + } +} diff --git a/js/src/abi/spec/param.spec.js b/js/src/abi/spec/param.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..bd172e4a6cbf2fe2c3d7742d7e40bc4f4a7834f2 --- /dev/null +++ b/js/src/abi/spec/param.spec.js @@ -0,0 +1,38 @@ +// 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 Param from './param'; + +describe('abi/spec/Param', () => { + describe('constructor', () => { + const param = new Param('foo', 'uint'); + + it('sets the properties', () => { + expect(param.name).to.equal('foo'); + expect(param.kind.type).to.equal('uint'); + }); + }); + + describe('toParams', () => { + it('maps an array of params', () => { + const params = Param.toParams([{ name: 'foo', type: 'uint' }]); + + expect(params.length).to.equal(1); + expect(params[0].name).to.equal('foo'); + expect(params[0].kind.type).to.equal('uint'); + }); + }); +}); diff --git a/js/src/abi/spec/paramType/format.js b/js/src/abi/spec/paramType/format.js new file mode 100644 index 0000000000000000000000000000000000000000..459eb15f43f1344920b9118aeabc6affe2298090 --- /dev/null +++ b/js/src/abi/spec/paramType/format.js @@ -0,0 +1,80 @@ +// 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 ParamType from './paramType'; + +export function toParamType (type, indexed) { + if (type[type.length - 1] === ']') { + const last = type.lastIndexOf('['); + const length = type.substr(last + 1, type.length - last - 2); + const subtype = toParamType(type.substr(0, last)); + + if (length.length === 0) { + return new ParamType('array', subtype, 0, indexed); + } + + return new ParamType('fixedArray', subtype, parseInt(length, 10), indexed); + } + + switch (type) { + case 'address': + case 'bool': + case 'bytes': + case 'string': + return new ParamType(type, null, 0, indexed); + + case 'int': + case 'uint': + return new ParamType(type, null, 256, indexed); + + default: + if (type.indexOf('uint') === 0) { + return new ParamType('uint', null, parseInt(type.substr(4), 10), indexed); + } else if (type.indexOf('int') === 0) { + return new ParamType('int', null, parseInt(type.substr(3), 10), indexed); + } else if (type.indexOf('bytes') === 0) { + return new ParamType('fixedBytes', null, parseInt(type.substr(5), 10), indexed); + } + + throw new Error(`Cannot convert ${type} to valid ParamType`); + } +} + +export function fromParamType (paramType) { + switch (paramType.type) { + case 'address': + case 'bool': + case 'bytes': + case 'string': + return paramType.type; + + case 'int': + case 'uint': + return `${paramType.type}${paramType.length}`; + + case 'fixedBytes': + return `bytes${paramType.length}`; + + case 'fixedArray': + return `${fromParamType(paramType.subtype)}[${paramType.length}]`; + + case 'array': + return `${fromParamType(paramType.subtype)}[]`; + + default: + throw new Error(`Cannot convert from ParamType ${paramType.type}`); + } +} diff --git a/js/src/abi/spec/paramType/format.spec.js b/js/src/abi/spec/paramType/format.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..90e5229d5bb20743629746449372458c8509677d --- /dev/null +++ b/js/src/abi/spec/paramType/format.spec.js @@ -0,0 +1,228 @@ +// 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 ParamType from './paramType'; +import { fromParamType, toParamType } from './format'; + +describe('abi/spec/paramType/format', () => { + describe('fromParamType', () => { + it('errors on invalid types', () => { + expect(() => fromParamType({ type: 'noMatch' })).to.throw(/noMatch/); + }); + + describe('simple types', () => { + it('converts address to address', () => { + const pt = new ParamType('address'); + + expect(fromParamType(pt)).to.equal('address'); + }); + + it('converts bool to bool', () => { + const pt = new ParamType('bool'); + + expect(fromParamType(pt)).to.equal('bool'); + }); + + it('converts bytes to bytes', () => { + const pt = new ParamType('bytes'); + + expect(fromParamType(pt)).to.equal('bytes'); + }); + + it('converts string to string', () => { + const pt = new ParamType('string'); + + expect(fromParamType(pt)).to.equal('string'); + }); + }); + + describe('length types', () => { + it('converts int32 to int32', () => { + const pt = new ParamType('int', null, 32); + + expect(fromParamType(pt)).to.equal('int32'); + }); + + it('converts uint64 to int64', () => { + const pt = new ParamType('uint', null, 64); + + expect(fromParamType(pt)).to.equal('uint64'); + }); + + it('converts fixedBytes8 to bytes8', () => { + const pt = new ParamType('fixedBytes', null, 8); + + expect(fromParamType(pt)).to.equal('bytes8'); + }); + }); + + describe('arrays', () => { + it('converts string[2] to string[2]', () => { + const pt = new ParamType('fixedArray', new ParamType('string'), 2); + + expect(fromParamType(pt)).to.equal('string[2]'); + }); + + it('converts bool[] to bool[]', () => { + const pt = new ParamType('array', new ParamType('bool')); + + expect(fromParamType(pt)).to.equal('bool[]'); + }); + + it('converts bool[][2] to bool[][2]', () => { + const pt = new ParamType('fixedArray', new ParamType('array', new ParamType('bool')), 2); + + expect(fromParamType(pt)).to.equal('bool[][2]'); + }); + + it('converts bool[2][] to bool[2][]', () => { + const pt = new ParamType('array', new ParamType('fixedArray', new ParamType('bool'), 2)); + + expect(fromParamType(pt)).to.equal('bool[2][]'); + }); + }); + }); + + describe('toParamType', () => { + it('errors on invalid types', () => { + expect(() => toParamType('noMatch')).to.throw(/noMatch/); + }); + + describe('simple mapping', () => { + it('converts address to address', () => { + const pt = toParamType('address'); + + expect(pt.type).to.equal('address'); + }); + + it('converts bool to bool', () => { + const pt = toParamType('bool'); + + expect(pt.type).to.equal('bool'); + }); + + it('converts bytes to bytes', () => { + const pt = toParamType('bytes'); + + expect(pt.type).to.equal('bytes'); + }); + + it('converts string to string', () => { + const pt = toParamType('string'); + + expect(pt.type).to.equal('string'); + }); + }); + + describe('number', () => { + it('converts int to int256', () => { + const pt = toParamType('int'); + + expect(pt.type).to.equal('int'); + expect(pt.length).to.equal(256); + }); + + it('converts uint to uint256', () => { + const pt = toParamType('uint'); + + expect(pt.type).to.equal('uint'); + expect(pt.length).to.equal(256); + }); + }); + + describe('sized types', () => { + it('converts int32 to int32', () => { + const pt = toParamType('int32'); + + expect(pt.type).to.equal('int'); + expect(pt.length).to.equal(32); + }); + + it('converts uint16 to uint16', () => { + const pt = toParamType('uint32'); + + expect(pt.type).to.equal('uint'); + expect(pt.length).to.equal(32); + }); + + it('converts bytes8 to fixedBytes8', () => { + const pt = toParamType('bytes8'); + + expect(pt.type).to.equal('fixedBytes'); + expect(pt.length).to.equal(8); + }); + }); + + describe('arrays', () => { + describe('fixed arrays', () => { + it('creates fixed array', () => { + const pt = toParamType('bytes[8]'); + + expect(pt.type).to.equal('fixedArray'); + expect(pt.subtype.type).to.equal('bytes'); + expect(pt.length).to.equal(8); + }); + + it('creates fixed arrays of fixed arrays', () => { + const pt = toParamType('bytes[45][3]'); + + expect(pt.type).to.equal('fixedArray'); + expect(pt.length).to.equal(3); + expect(pt.subtype.type).to.equal('fixedArray'); + expect(pt.subtype.length).to.equal(45); + expect(pt.subtype.subtype.type).to.equal('bytes'); + }); + }); + + describe('dynamic arrays', () => { + it('creates a dynamic array', () => { + const pt = toParamType('bytes[]'); + + expect(pt.type).to.equal('array'); + expect(pt.subtype.type).to.equal('bytes'); + }); + + it('creates a dynamic array of dynamic arrays', () => { + const pt = toParamType('bool[][]'); + + expect(pt.type).to.equal('array'); + expect(pt.subtype.type).to.equal('array'); + expect(pt.subtype.subtype.type).to.equal('bool'); + }); + }); + + describe('mixed arrays', () => { + it('creates a fixed dynamic array', () => { + const pt = toParamType('bool[][3]'); + + expect(pt.type).to.equal('fixedArray'); + expect(pt.length).to.equal(3); + expect(pt.subtype.type).to.equal('array'); + expect(pt.subtype.subtype.type).to.equal('bool'); + }); + + it('creates a dynamic fixed array', () => { + const pt = toParamType('bool[3][]'); + + expect(pt.type).to.equal('array'); + expect(pt.subtype.type).to.equal('fixedArray'); + expect(pt.subtype.length).to.equal(3); + expect(pt.subtype.subtype.type).to.equal('bool'); + }); + }); + }); + }); +}); diff --git a/js/src/abi/spec/paramType/index.js b/js/src/abi/spec/paramType/index.js new file mode 100644 index 0000000000000000000000000000000000000000..23bb83f067c6dcaa47e136136ccb8682f65a115a --- /dev/null +++ b/js/src/abi/spec/paramType/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './paramType'; diff --git a/js/src/abi/spec/paramType/paramType.js b/js/src/abi/spec/paramType/paramType.js new file mode 100644 index 0000000000000000000000000000000000000000..99a2915d65c6e0af304b319df1821aba10b0160a --- /dev/null +++ b/js/src/abi/spec/paramType/paramType.js @@ -0,0 +1,52 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import TYPES from './types'; + +export default class ParamType { + constructor (type, subtype = null, length = 0, indexed = false) { + ParamType.validateType(type); + + this._type = type; + this._subtype = subtype; + this._length = length; + this._indexed = indexed; + } + + get type () { + return this._type; + } + + get subtype () { + return this._subtype; + } + + get length () { + return this._length; + } + + get indexed () { + return this._indexed; + } + + static validateType (type) { + if (TYPES.filter((_type) => type === _type).length) { + return true; + } + + throw new Error(`Invalid type ${type} received for ParamType`); + } +} diff --git a/js/src/abi/spec/paramType/paramType.spec.js b/js/src/abi/spec/paramType/paramType.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e8d8c32540c29a0ae62a9161907fd7293de6647c --- /dev/null +++ b/js/src/abi/spec/paramType/paramType.spec.js @@ -0,0 +1,87 @@ +// 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 ParamType from './paramType'; + +describe('abi/spec/paramType/ParamType', () => { + describe('validateType', () => { + it('validates address', () => { + expect(ParamType.validateType('address')).to.be.true; + }); + + it('validates fixedArray', () => { + expect(ParamType.validateType('fixedArray')).to.be.true; + }); + + it('validates array', () => { + expect(ParamType.validateType('array')).to.be.true; + }); + + it('validates fixedBytes', () => { + expect(ParamType.validateType('fixedBytes')).to.be.true; + }); + + it('validates bytes', () => { + expect(ParamType.validateType('bytes')).to.be.true; + }); + + it('validates bool', () => { + expect(ParamType.validateType('bool')).to.be.true; + }); + + it('validates int', () => { + expect(ParamType.validateType('int')).to.be.true; + }); + + it('validates uint', () => { + expect(ParamType.validateType('uint')).to.be.true; + }); + + it('validates string', () => { + expect(ParamType.validateType('string')).to.be.true; + }); + + it('throws an error on invalid types', () => { + expect(() => ParamType.validateType('noMatch')).to.throw(/noMatch/); + }); + }); + + describe('constructor', () => { + it('throws an error on invalid types', () => { + expect(() => new ParamType('noMatch')).to.throw(/noMatch/); + }); + + it('sets the type of the object', () => { + expect((new ParamType('bool', null, 1)).type).to.equal('bool'); + }); + + it('sets the subtype of the object', () => { + expect((new ParamType('array', 'bool', 1)).subtype).to.equal('bool'); + }); + + it('sets the length of the object', () => { + expect((new ParamType('array', 'bool', 1)).length).to.equal(1); + }); + + it('sets the index of the object', () => { + expect((new ParamType('array', 'bool', 1, true)).indexed).to.be.true; + }); + + it('sets default values where none supplied', () => { + expect(Object.values(new ParamType('string'))).to.deep.equal(['string', null, 0, false]); + }); + }); +}); diff --git a/js/src/abi/spec/paramType/types.js b/js/src/abi/spec/paramType/types.js new file mode 100644 index 0000000000000000000000000000000000000000..d789a6ed80333872549856e499412472e8881dd8 --- /dev/null +++ b/js/src/abi/spec/paramType/types.js @@ -0,0 +1,19 @@ +// 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 . + +const TYPES = ['address', 'bytes', 'int', 'uint', 'bool', 'string', 'array', 'fixedBytes', 'fixedArray']; + +export default TYPES; diff --git a/js/src/abi/token/index.js b/js/src/abi/token/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b822b4bdf7c1d731ef6e68055be06e6cc85d0ec --- /dev/null +++ b/js/src/abi/token/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './token'; diff --git a/js/src/abi/token/token.js b/js/src/abi/token/token.js new file mode 100644 index 0000000000000000000000000000000000000000..84c675ee63ee3fd44177b1ce54d2a1b3bba91e0e --- /dev/null +++ b/js/src/abi/token/token.js @@ -0,0 +1,42 @@ +// 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 TYPES from '../spec/paramType/types'; + +export default class Token { + constructor (type, value) { + Token.validateType(type); + + this._type = type; + this._value = value; + } + + get type () { + return this._type; + } + + get value () { + return this._value; + } + + static validateType (type) { + if (TYPES.filter((_type) => type === _type).length) { + return true; + } + + throw new Error(`Invalid type ${type} received for Token`); + } +} diff --git a/js/src/abi/token/token.spec.js b/js/src/abi/token/token.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..2abaad6ac9016350123c5a29359ef6d770e6b983 --- /dev/null +++ b/js/src/abi/token/token.spec.js @@ -0,0 +1,75 @@ +// 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 Token from './token'; + +describe('abi/token/token', () => { + describe('validateType', () => { + it('validates address', () => { + expect(Token.validateType('address')).to.be.true; + }); + + it('validates fixedArray', () => { + expect(Token.validateType('fixedArray')).to.be.true; + }); + + it('validates array', () => { + expect(Token.validateType('array')).to.be.true; + }); + + it('validates fixedBytes', () => { + expect(Token.validateType('fixedBytes')).to.be.true; + }); + + it('validates bytes', () => { + expect(Token.validateType('bytes')).to.be.true; + }); + + it('validates bool', () => { + expect(Token.validateType('bool')).to.be.true; + }); + + it('validates int', () => { + expect(Token.validateType('int')).to.be.true; + }); + + it('validates uint', () => { + expect(Token.validateType('uint')).to.be.true; + }); + + it('validates string', () => { + expect(Token.validateType('string')).to.be.true; + }); + + it('throws an error on invalid types', () => { + expect(() => Token.validateType('noMatch')).to.throw(/noMatch/); + }); + }); + + describe('constructor', () => { + it('throws an error on invalid types', () => { + expect(() => new Token('noMatch', '1')).to.throw(/noMatch/); + }); + + it('sets the type of the object', () => { + expect((new Token('bool', '1')).type).to.equal('bool'); + }); + + it('sets the value of the object', () => { + expect((new Token('bool', '1')).value).to.equal('1'); + }); + }); +}); diff --git a/js/src/abi/util/address.js b/js/src/abi/util/address.js new file mode 100644 index 0000000000000000000000000000000000000000..f0e188f2c374766d02a4a7ee7d3c6e4e8a4e3a5e --- /dev/null +++ b/js/src/abi/util/address.js @@ -0,0 +1,65 @@ +// 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 { keccak_256 } from 'js-sha3'; // eslint-disable-line camelcase + +export function isChecksumValid (_address) { + const address = _address.replace('0x', ''); + const hash = keccak_256(address.toLowerCase(address)); + + for (let n = 0; n < 40; n++) { + const hashval = parseInt(hash[n], 16); + const isLower = address[n].toUpperCase() !== address[n]; + const isUpper = address[n].toLowerCase() !== address[n]; + + if ((hashval > 7 && isLower) || (hashval <= 7 && isUpper)) { + return false; + } + } + + return true; +} + +export function isAddress (address) { + if (address && address.length === 42) { + if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { + return false; + } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { + return true; + } + + return isChecksumValid(address); + } + + return false; +} + +export function toChecksumAddress (_address) { + const address = (_address || '').toLowerCase(); + + if (!isAddress(address)) { + return ''; + } + + const hash = keccak_256(address.slice(-40)); + let result = '0x'; + + for (let n = 0; n < 40; n++) { + result = `${result}${parseInt(hash[n], 16) > 7 ? address[n + 2].toUpperCase() : address[n + 2]}`; + } + + return result; +} diff --git a/js/src/abi/util/address.spec.js b/js/src/abi/util/address.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9b0ec38cbbb9cc8053ea1698eef1cf7cc503f165 --- /dev/null +++ b/js/src/abi/util/address.spec.js @@ -0,0 +1,100 @@ +// 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 { isChecksumValid, isAddress, toChecksumAddress } from './address'; + +describe('abi/util/address', () => { + const value = '63Cf90D3f0410092FC0fca41846f596223979195'; + const address = `0x${value}`; + const lowercase = `0x${value.toLowerCase()}`; + const uppercase = `0x${value.toUpperCase()}`; + const invalid = '0x' + value.split('').map((char) => { + if (char >= 'a' && char <= 'f') { + return char.toUpperCase(); + } else if (char >= 'A' && char <= 'F') { + return char.toLowerCase(); + } + + return char; + }).join(''); + const invalidhex = '0x01234567890123456789012345678901234567gh'; + + describe('isChecksumValid', () => { + it('returns false when fully lowercase', () => { + expect(isChecksumValid(lowercase)).to.be.false; + }); + + it('returns false when fully uppercase', () => { + expect(isChecksumValid(uppercase)).to.be.false; + }); + + it('returns false on a mixed-case address', () => { + expect(isChecksumValid(invalid)).to.be.false; + }); + + it('returns true on a checksummed address', () => { + expect(isChecksumValid(address)).to.be.true; + }); + }); + + describe('isAddress', () => { + it('returns true when fully lowercase', () => { + expect(isAddress(lowercase)).to.be.true; + }); + + it('returns true when fully uppercase', () => { + expect(isAddress(uppercase)).to.be.true; + }); + + it('returns true when checksummed', () => { + expect(isAddress(address)).to.be.true; + }); + + it('returns false when invalid checksum', () => { + expect(isAddress(invalid)).to.be.false; + }); + + it('returns false on valid length, non-hex', () => { + expect(isAddress(invalidhex)).to.be.false; + }); + }); + + describe('toChecksumAddress', () => { + it('returns empty when no address specified', () => { + expect(toChecksumAddress()).to.equal(''); + }); + + it('returns empty on invalid address structure', () => { + expect(toChecksumAddress('0xnotaddress')).to.equal(''); + }); + + it('returns formatted address on checksum input', () => { + expect(toChecksumAddress(address)).to.equal(address); + }); + + it('returns formatted address on lowercase input', () => { + expect(toChecksumAddress(lowercase)).to.equal(address); + }); + + it('returns formatted address on uppercase input', () => { + expect(toChecksumAddress(uppercase)).to.equal(address); + }); + + it('returns formatted address on mixed input', () => { + expect(toChecksumAddress(invalid)).to.equal(address); + }); + }); +}); diff --git a/js/src/abi/util/pad.js b/js/src/abi/util/pad.js new file mode 100644 index 0000000000000000000000000000000000000000..a7d94043169ae83ca61d50a0fe38a3c2f087640b --- /dev/null +++ b/js/src/abi/util/pad.js @@ -0,0 +1,75 @@ +// 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 BigNumber from 'bignumber.js'; +import utf8 from 'utf8'; + +import { isArray } from './types'; + +const ZERO_64 = '0000000000000000000000000000000000000000000000000000000000000000'; + +export function padAddress (_input) { + const input = _input.substr(0, 2) === '0x' ? _input.substr(2) : _input; + + return `${ZERO_64}${input}`.slice(-64); +} + +export function padBool (input) { + return `${ZERO_64}${input ? '1' : '0'}`.slice(-64); +} + +export function padU32 (input) { + let bn = new BigNumber(input); + + if (bn.lessThan(0)) { + bn = new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16) + .plus(bn).plus(1); + } + + return `${ZERO_64}${bn.toString(16)}`.slice(-64); +} + +function stringToBytes (input) { + if (isArray(input)) { + return input; + } else if (input.substr(0, 2) === '0x') { + return input.substr(2).toLowerCase().match(/.{1,2}/g).map((value) => parseInt(value, 16)); + } else { + return input.split('').map((char) => char.charCodeAt(0)); + } +} + +export function padBytes (_input) { + const input = stringToBytes(_input); + + return `${padU32(input.length)}${padFixedBytes(input)}`; +} + +export function padFixedBytes (_input) { + const input = stringToBytes(_input); + const sinput = input.map((code) => `0${code.toString(16)}`.slice(-2)).join(''); + const max = Math.floor((sinput.length + 63) / 64) * 64; + + return `${sinput}${ZERO_64}`.substr(0, max); +} + +export function padString (input) { + const array = utf8.encode(input) + .split('') + .map((char) => char.charCodeAt(0)); + + return padBytes(array); +} diff --git a/js/src/abi/util/pad.spec.js b/js/src/abi/util/pad.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..96c733682487db63d1adf3616baf3a6b5977e123 --- /dev/null +++ b/js/src/abi/util/pad.spec.js @@ -0,0 +1,124 @@ +// 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 BigNumber from 'bignumber.js'; +import { padAddress, padBool, padBytes, padFixedBytes, padString, padU32 } from './pad'; + +describe('abi/util/pad', () => { + const SHORT15 = '1234567890abcdef'; + const BYTES15 = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; + const LONG15 = `${SHORT15}000000000000000000000000000000000000000000000000`; + const PAD123 = '0000000000000000000000000000000000000000000000000000000000000123'; + + describe('padAddress', () => { + it('pads to 64 characters', () => { + expect(padAddress('123')).to.equal(PAD123); + }); + + it('strips leading 0x when passed in', () => { + expect(padFixedBytes(`0x${PAD123}`)).to.equal(PAD123); + }); + }); + + describe('padBool', () => { + const TRUE = '0000000000000000000000000000000000000000000000000000000000000001'; + const FALSE = '0000000000000000000000000000000000000000000000000000000000000000'; + + it('pads true to 64 characters', () => { + expect(padBool(true)).to.equal(TRUE); + }); + + it('pads false to 64 characters', () => { + expect(padBool(false)).to.equal(FALSE); + }); + }); + + describe('padU32', () => { + it('left pads length < 64 bytes to 64 bytes', () => { + expect(padU32(1)).to.equal('0000000000000000000000000000000000000000000000000000000000000001'); + }); + + it('pads hex representation', () => { + expect(padU32(0x123)).to.equal(PAD123); + }); + + it('pads decimal representation', () => { + expect(padU32(291)).to.equal(PAD123); + }); + + it('pads string representation', () => { + expect(padU32('0x123')).to.equal(PAD123); + }); + + it('pads BigNumber representation', () => { + expect(padU32(new BigNumber(0x123))).to.equal(PAD123); + }); + + it('converts negative numbers to 2s complement', () => { + expect(padU32(-123)).to.equal('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff85'); + }); + }); + + describe('padFixedBytes', () => { + it('right pads length < 64 bytes to 64 bytes (string)', () => { + expect(padFixedBytes(`0x${SHORT15}`)).to.equal(LONG15); + }); + + it('right pads length < 64 bytes to 64 bytes (array)', () => { + expect(padFixedBytes(BYTES15)).to.equal(LONG15); + }); + + it('right pads length > 64 bytes (64 byte multiples)', () => { + expect(padFixedBytes(`0x${LONG15}${SHORT15}`)).to.equal(`${LONG15}${LONG15}`); + }); + + it('strips leading 0x when passed in', () => { + expect(padFixedBytes(`0x${SHORT15}`)).to.equal(LONG15); + }); + }); + + describe('padBytes', () => { + it('right pads length < 64, adding the length (string)', () => { + const result = padBytes(`0x${SHORT15}`); + + expect(result.length).to.equal(128); + expect(result).to.equal(`${padU32(8)}${LONG15}`); + }); + + it('right pads length < 64, adding the length (array)', () => { + const result = padBytes(BYTES15); + + expect(result.length).to.equal(128); + expect(result).to.equal(`${padU32(8)}${LONG15}`); + }); + + it('right pads length > 64, adding the length', () => { + const result = padBytes(`0x${LONG15}${SHORT15}`); + + expect(result.length).to.equal(192); + expect(result).to.equal(`${padU32(0x28)}${LONG15}${LONG15}`); + }); + }); + + describe('padString', () => { + it('correctly converts & pads strings', () => { + const result = padString('gavofyork'); + + expect(result.length).to.equal(128); + expect(result).to.equal(padBytes('0x6761766f66796f726b')); + }); + }); +}); diff --git a/js/src/abi/util/signature.js b/js/src/abi/util/signature.js new file mode 100644 index 0000000000000000000000000000000000000000..10aedf13f98d1ef402e31116efaa9d2f3e5fd67b --- /dev/null +++ b/js/src/abi/util/signature.js @@ -0,0 +1,31 @@ +// 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 { keccak_256 } from 'js-sha3'; // eslint-disable-line camelcase +import { fromParamType } from '../spec/paramType/format'; + +export function eventSignature (name, params) { + const types = (params || []).map(fromParamType).join(','); + const id = `${name || ''}(${types})`; + + return { id, signature: keccak_256(id) }; +} + +export function methodSignature (name, params) { + const { id, signature } = eventSignature(name, params); + + return { id, signature: signature.substr(0, 8) }; +} diff --git a/js/src/abi/util/signature.spec.js b/js/src/abi/util/signature.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..61664b8fcad8b4ac0ab546f7851b99d1b1ac922a --- /dev/null +++ b/js/src/abi/util/signature.spec.js @@ -0,0 +1,68 @@ +// 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 { eventSignature, methodSignature } from './signature'; + +describe('abi/util/signature', () => { + describe('eventSignature', () => { + it('encodes signature baz() correctly', () => { + expect(eventSignature('baz', [])) + .to.deep.equal({ id: 'baz()', signature: 'a7916fac4f538170f7cd12c148552e2cba9fcd72329a2dd5b07a6fa906488ddf' }); + }); + + it('encodes signature baz(uint32) correctly', () => { + expect(eventSignature('baz', [{ type: 'uint', length: 32 }])) + .to.deep.equal({ id: 'baz(uint32)', signature: '7d68785e8fc871be024b75964bd86d093511d4bc2dc7cf7bea32c48a0efaecb1' }); + }); + + it('encodes signature baz(uint32, bool) correctly', () => { + expect(eventSignature('baz', [{ type: 'uint', length: 32 }, { type: 'bool' }])) + .to.deep.equal({ id: 'baz(uint32,bool)', signature: 'cdcd77c0992ec5bbfc459984220f8c45084cc24d9b6efed1fae540db8de801d2' }); + }); + + it('encodes no-name signature correctly as ()', () => { + expect(eventSignature(undefined, [])) + .to.deep.equal({ id: '()', signature: '861731d50c3880a2ca1994d5ec287b94b2f4bd832a67d3e41c08177bdd5674fe' }); + }); + + it('encodes no-params signature correctly as ()', () => { + expect(eventSignature(undefined, undefined)) + .to.deep.equal({ id: '()', signature: '861731d50c3880a2ca1994d5ec287b94b2f4bd832a67d3e41c08177bdd5674fe' }); + }); + }); + + describe('methodSignature', () => { + it('encodes signature baz() correctly', () => { + expect(methodSignature('baz', [])).to.deep.equal({ id: 'baz()', signature: 'a7916fac' }); + }); + + it('encodes signature baz(uint32) correctly', () => { + expect(methodSignature('baz', [{ type: 'uint', length: 32 }])).to.deep.equal({ id: 'baz(uint32)', signature: '7d68785e' }); + }); + + it('encodes signature baz(uint32, bool) correctly', () => { + expect(methodSignature('baz', [{ type: 'uint', length: 32 }, { type: 'bool' }])).to.deep.equal({ id: 'baz(uint32,bool)', signature: 'cdcd77c0' }); + }); + + it('encodes no-name signature correctly as ()', () => { + expect(methodSignature(undefined, [])).to.deep.equal({ id: '()', signature: '861731d5' }); + }); + + it('encodes no-params signature correctly as ()', () => { + expect(methodSignature(undefined, undefined)).to.deep.equal({ id: '()', signature: '861731d5' }); + }); + }); +}); diff --git a/js/src/abi/util/slice.js b/js/src/abi/util/slice.js new file mode 100644 index 0000000000000000000000000000000000000000..417efea54d15d27c8e2b6cb38ff26db71ec0c1fa --- /dev/null +++ b/js/src/abi/util/slice.js @@ -0,0 +1,35 @@ +// 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 { padAddress } from './pad'; + +export function sliceData (_data) { + if (!_data || !_data.length) { + return []; + } + + let data = (_data.substr(0, 2) === '0x') ? _data.substr(2) : _data; + + if (!data.length) { + data = padAddress(''); + } + + if (data.length % 64) { + throw new Error(`Invalid data length (not mod 64) passed to sliceData, ${data}, % 64 == ${data.length % 64}`); + } + + return data.match(/.{1,64}/g); +} diff --git a/js/src/abi/util/slice.spec.js b/js/src/abi/util/slice.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..92608c5906c430da1d4a647c36c2b00de4f4078b --- /dev/null +++ b/js/src/abi/util/slice.spec.js @@ -0,0 +1,48 @@ +// 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 { sliceData } from './slice'; + +describe('abi/util/slice', () => { + describe('sliceData', () => { + const slice1 = '131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b'; + const slice2 = '2124768576358735263578356373526387638357635873563586353756358763'; + + it('throws an error on mod 64 != 0', () => { + expect(() => sliceData('123')).to.throw(/sliceData/); + }); + + it('returns an empty array when length === 0', () => { + expect(sliceData('')).to.deep.equal([]); + }); + + it('returns an array with the slices otherwise', () => { + const sliced = sliceData(`${slice1}${slice2}`); + + expect(sliced.length).to.equal(2); + expect(sliced[0]).to.equal(slice1); + expect(sliced[1]).to.equal(slice2); + }); + + it('removes leading 0x when passed in', () => { + const sliced = sliceData(`0x${slice1}${slice2}`); + + expect(sliced.length).to.equal(2); + expect(sliced[0]).to.equal(slice1); + expect(sliced[1]).to.equal(slice2); + }); + }); +}); diff --git a/js/src/abi/util/sliceAs.js b/js/src/abi/util/sliceAs.js new file mode 100644 index 0000000000000000000000000000000000000000..47c3e9758def9e1e16da25a7f91a436e1d2f44b9 --- /dev/null +++ b/js/src/abi/util/sliceAs.js @@ -0,0 +1,47 @@ +// 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 BigNumber from 'bignumber.js'; + +import { toChecksumAddress } from './address'; + +export function asU32 (slice) { + // TODO: validation + + return new BigNumber(slice, 16); +} + +export function asI32 (slice) { + if (new BigNumber(slice.substr(0, 1), 16).toString(2)[0] === '1') { + return new BigNumber(slice, 16) + .minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)) + .minus(1); + } + + return new BigNumber(slice, 16); +} + +export function asAddress (slice) { + // TODO: address validation? + + return toChecksumAddress(`0x${slice.slice(-40)}`); +} + +export function asBool (slice) { + // TODO: everything else should be 0 + + return new BigNumber(slice[63]).eq(1); +} diff --git a/js/src/abi/util/sliceAs.spec.js b/js/src/abi/util/sliceAs.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..af68860089f5f7b7a5d6b7cb0c61d00d21b7cbc4 --- /dev/null +++ b/js/src/abi/util/sliceAs.spec.js @@ -0,0 +1,54 @@ +// 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 { asAddress, asBool, asI32, asU32 } from './sliceAs'; + +describe('abi/util/sliceAs', () => { + const MAX_INT = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; + + describe('asAddress', () => { + it('correctly returns the last 0x40 characters', () => { + const address = '1111111111222222222233333333334444444444'; + expect(asAddress(`000000000000000000000000${address}`)).to.equal(`0x${address}`); + }); + }); + + describe('asBool', () => { + it('correctly returns true', () => { + expect(asBool('0000000000000000000000000000000000000000000000000000000000000001')).to.be.true; + }); + + it('correctly returns false', () => { + expect(asBool('0000000000000000000000000000000000000000000000000000000000000000')).to.be.false; + }); + }); + + describe('asI32', () => { + it('correctly decodes positive numbers', () => { + expect(asI32('000000000000000000000000000000000000000000000000000000000000007b').toString()).to.equal('123'); + }); + + it('correctly decodes negative numbers', () => { + expect(asI32('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff85').toString()).to.equal('-123'); + }); + }); + + describe('asU32', () => { + it('returns a maxium U32', () => { + expect(asU32(MAX_INT).toString(16)).to.equal(MAX_INT); + }); + }); +}); diff --git a/js/src/abi/util/types.js b/js/src/abi/util/types.js new file mode 100644 index 0000000000000000000000000000000000000000..649f26db6cd5e88da1539616d04feae935f7fc31 --- /dev/null +++ b/js/src/abi/util/types.js @@ -0,0 +1,27 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export function isArray (test) { + return Object.prototype.toString.call(test) === '[object Array]'; +} + +export function isString (test) { + return Object.prototype.toString.call(test) === '[object String]'; +} + +export function isInstanceOf (test, clazz) { + return test instanceof clazz; +} diff --git a/js/src/abi/util/types.spec.js b/js/src/abi/util/types.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..2e1a538a6a6081c213af3bfc244dfedf4347ce7b --- /dev/null +++ b/js/src/abi/util/types.spec.js @@ -0,0 +1,62 @@ +// 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 { isArray, isString, isInstanceOf } from './types'; +import Token from '../token'; + +describe('abi/util/types', () => { + describe('isArray', () => { + it('correctly identifies empty arrays as Array', () => { + expect(isArray([])).to.be.true; + }); + + it('correctly identifies non-empty arrays as Array', () => { + expect(isArray([1, 2, 3])).to.be.true; + }); + + it('correctly identifies strings as non-Array', () => { + expect(isArray('not an array')).to.be.false; + }); + + it('correctly identifies objects as non-Array', () => { + expect(isArray({})).to.be.false; + }); + }); + + describe('isString', () => { + it('correctly identifies empty string as string', () => { + expect(isString('')).to.be.true; + }); + + it('correctly identifies string as string', () => { + expect(isString('123')).to.be.true; + }); + }); + + describe('isInstanceOf', () => { + it('correctly identifies build-in instanceof', () => { + expect(isInstanceOf(new String('123'), String)).to.be.true; // eslint-disable-line no-new-wrappers + }); + + it('correctly identifies own instanceof', () => { + expect(isInstanceOf(new Token('int', 123), Token)).to.be.true; + }); + + it('correctly reports false for own', () => { + expect(isInstanceOf({ type: 'int' }, Token)).to.be.false; + }); + }); +}); diff --git a/js/src/api/README.md b/js/src/api/README.md new file mode 100644 index 0000000000000000000000000000000000000000..691a24cca981ffd8537eec5c863dd999960a0461 --- /dev/null +++ b/js/src/api/README.md @@ -0,0 +1,145 @@ +# ethapi-js + +A thin, fast, low-level Promise-based wrapper around the Ethereum APIs. + +[![Build Status](https://travis-ci.org/jacogr/ethapi-js.svg?branch=master)](https://travis-ci.org/jacogr/ethapi-js) +[![Coverage Status](https://coveralls.io/repos/github/jacogr/ethapi-js/badge.svg?branch=master)](https://coveralls.io/github/jacogr/ethapi-js?branch=master) +[![Dependency Status](https://david-dm.org/jacogr/ethapi-js.svg)](https://david-dm.org/jacogr/ethapi-js) +[![devDependency Status](https://david-dm.org/jacogr/ethapi-js/dev-status.svg)](https://david-dm.org/jacogr/ethapi-js#info=devDependencies) + +## contributing + +Clone the repo and install dependencies via `npm install`. Tests can be executed via + +- `npm run testOnce` (100% covered unit tests) +- `npm run testE2E` (E2E against a running RPC-enabled testnet Parity/Geth instance, `parity --testnet` and for WebScokets, `geth --testnet --ws --wsorigins '*' --rpc`) +- setting the environment `DEBUG=true` will display the RPC POST bodies and responses on E2E tests + +## installation + +Install the package with `npm install --save ethapi-js` from the [npm registry ethapi-js](https://www.npmjs.com/package/ethapi-js) + +## usage + +### initialisation + +```javascript +// import the actual EthApi class +import EthApi from 'ethapi-js'; + +// do the setup +const transport = new EthApi.Transport.Http('http://localhost:8545'); // or .Ws('ws://localhost:8546') +const ethapi = new EthApi(transport); +``` + +You will require native Promises and fetch support (latest browsers only), they can be utilised by + +```javascript +import 'isomorphic-fetch'; + +import es6Promise from 'es6-promise'; +es6Promise.polyfill(); +``` + +### making calls + +perform a call + +```javascript +ethapi.eth + .coinbase() + .then((coinbase) => { + console.log(`The coinbase is ${coinbase}`); + }); +``` + +multiple promises + +```javascript +Promise + .all([ + ethapi.eth.coinbase(), + ethapi.net.listening() + ]) + .then(([coinbase, listening]) => { + // do stuff here + }); +``` + +chaining promises + +```javascript +ethapi.eth + .newFilter({...}) + .then((filterId) => ethapi.eth.getFilterChanges(filterId)) + .then((changes) => { + console.log(changes); + }); +``` + +### contracts + +attach contract + +```javascript +const abi = [{ name: 'callMe', inputs: [{ type: 'bool', ...}, { type: 'string', ...}]}, ...abi...]; +const contract = new ethapi.newContract(abi); +``` + +deploy + +```javascript +contract + .deploy('0xc0de', [params], 'superPassword') + .then((address) => { + console.log(`the contract was deployed at ${address}`); + }); +``` + +attach a contract at address + +```javascript +// via the constructor & .at function +const contract = api.newContract(abi).at('0xa9280...7347b'); +// or on an already initialised contract +contract.at('0xa9280...7347b'); +// perform calls here +``` + +find & call a function + +```javascript +contract.named + .callMe + .call({ gas: 21000 }, [true, 'someString']) // or estimateGas or sendTransaction + .then((result) => { + console.log(`the result was ${result}`); + }); +``` + +parse events from transaction receipt + +```javascript +contract + .parseTransactionEvents(txReceipt) + .then((receipt) => { + receipt.logs.forEach((log) => { + console.log('log parameters', log.params); + }); + }); +``` + +## apis + +APIs implement the calls as exposed in the [Ethcore JSON Ethereum RPC](https://github.com/ethcore/ethereum-rpc-json/) definitions. Mapping follows the naming conventions of the originals, i.e. `eth_call` becomes `eth.call`, `personal_accounts` becomes `personal.accounts`, etc. + +- [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.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.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) + +As a verification step, all exposed interfaces are tested for existing and pointing to the correct endpoints by using the generated interfaces from the above repo. diff --git a/js/src/api/api.js b/js/src/api/api.js new file mode 100644 index 0000000000000000000000000000000000000000..9768b9acb1999a9bf1e54a9755b83d19e68d3e07 --- /dev/null +++ b/js/src/api/api.js @@ -0,0 +1,125 @@ +// 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 { Http, Ws } from './transport'; +import Contract from './contract'; + +import { Db, Eth, Ethcore, Net, Personal, Shh, Trace, Web3 } from './rpc'; +import Subscriptions from './subscriptions'; +import util from './util'; +import { isFunction } from './util/types'; + +export default class Api { + constructor (transport) { + if (!transport || !isFunction(transport.execute)) { + throw new Error('EthApi needs transport with execute() function defined'); + } + + this._transport = transport; + + this._db = new Db(transport); + this._eth = new Eth(transport); + this._ethcore = new Ethcore(transport); + this._net = new Net(transport); + this._personal = new Personal(transport); + this._shh = new Shh(transport); + this._trace = new Trace(transport); + this._web3 = new Web3(transport); + + this._subscriptions = new Subscriptions(this); + } + + get db () { + return this._db; + } + + get eth () { + return this._eth; + } + + get ethcore () { + return this._ethcore; + } + + get net () { + return this._net; + } + + get personal () { + return this._personal; + } + + get shh () { + return this._shh; + } + + get trace () { + return this._trace; + } + + get transport () { + return this._transport; + } + + get web3 () { + return this._web3; + } + + get util () { + return util; + } + + newContract (abi, address) { + return new Contract(this, abi).at(address); + } + + subscribe (subscriptionName, callback) { + return this._subscriptions.subscribe(subscriptionName, callback); + } + + unsubscribe (subscriptionId) { + return this._subscriptions.unsubscribe(subscriptionId); + } + + pollMethod (method, input, validate) { + const [_group, endpoint] = method.split('_'); + const group = `_${_group}`; + + return new Promise((resolve, reject) => { + const timeout = () => { + this[group][endpoint](input) + .then((result) => { + if (validate ? validate(result) : result) { + resolve(result); + } else { + setTimeout(timeout, 500); + } + }) + .catch((error) => { + console.error('pollMethod', error); + reject(error); + }); + }; + + timeout(); + }); + } + + static Transport = { + Http: Http, + Ws: Ws + } +} diff --git a/js/src/api/api.spec.js b/js/src/api/api.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..bbd140d4d73d0be1df85e8d9ec7b7562737547fa --- /dev/null +++ b/js/src/api/api.spec.js @@ -0,0 +1,47 @@ +// 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 { TEST_HTTP_URL, endpointTest } from '../../test/mockRpc'; + +import Api from './api'; + +import ethereumRpc from '../jsonrpc/'; + +describe('api/Api', () => { + describe('constructor', () => { + it('requires defined/non-null transport object', () => { + expect(() => new Api()).to.throw(/Api needs transport/); + expect(() => new Api(null)).to.throw(/Api needs transport/); + }); + + it('requires an execute function on the transport object', () => { + expect(() => new Api({})).to.throw(/Api needs transport/); + expect(() => new Api({ execute: true })).to.throw(/Api needs transport/); + }); + }); + + describe('interface', () => { + const api = new Api(new Api.Transport.Http(TEST_HTTP_URL)); + + Object.keys(ethereumRpc).sort().forEach((endpoint) => { + describe(endpoint, () => { + Object.keys(ethereumRpc[endpoint]).sort().forEach((method) => { + endpointTest(api, endpoint, method); + }); + }); + }); + }); +}); diff --git a/js/src/api/contract/contract.js b/js/src/api/contract/contract.js new file mode 100644 index 0000000000000000000000000000000000000000..cef75eda7344690dd3b470f7b0d66b97db0e57ae --- /dev/null +++ b/js/src/api/contract/contract.js @@ -0,0 +1,321 @@ +// 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 Abi from '../../abi'; +import Api from '../api'; +import { isInstanceOf } from '../util/types'; + +let nextSubscriptionId = 0; + +export default class Contract { + constructor (api, abi) { + if (!isInstanceOf(api, Api)) { + throw new Error('API instance needs to be provided to Contract'); + } else if (!abi) { + throw new Error('ABI needs to be provided to Contract instance'); + } + + this._api = api; + this._abi = new Abi(abi); + + this._subscriptions = {}; + this._constructors = this._abi.constructors.map(this._bindFunction); + this._functions = this._abi.functions.map(this._bindFunction); + this._events = this._abi.events.map(this._bindEvent); + + this._instance = {}; + + this._events.forEach((evt) => { + this._instance[evt.name] = evt; + }); + this._functions.forEach((fn) => { + this._instance[fn.name] = fn; + }); + + this._sendSubscriptionChanges(); + } + + get address () { + return this._address; + } + + get constructors () { + return this._constructors; + } + + get events () { + return this._events; + } + + get functions () { + return this._functions; + } + + get instance () { + this._instance.address = this._address; + return this._instance; + } + + get api () { + return this._api; + } + + get abi () { + return this._abi; + } + + at (address) { + this._address = address; + return this; + } + + deploy (options, values, statecb) { + let gas; + + const setState = (state) => { + if (!statecb) { + return; + } + + return statecb(null, state); + }; + + setState({ state: 'estimateGas' }); + + return this._api.eth + .estimateGas(this._encodeOptions(this.constructors[0], options, values)) + .then((_gas) => { + gas = _gas.mul(1.2); + options.gas = gas.toFixed(0); + + setState({ state: 'postTransaction', gas }); + return this._api.eth.postTransaction(this._encodeOptions(this.constructors[0], options, values)); + }) + .then((requestId) => { + setState({ state: 'checkRequest', requestId }); + return this._pollCheckRequest(requestId); + }) + .then((txhash) => { + setState({ state: 'getTransactionReceipt', txhash }); + return this._pollTransactionReceipt(txhash, gas); + }) + .then((receipt) => { + if (receipt.gasUsed.eq(gas)) { + throw new Error(`Contract not deployed, gasUsed == ${gas.toFixed(0)}`); + } + + setState({ state: 'hasReceipt', receipt }); + this._address = receipt.contractAddress; + return this._address; + }) + .then((address) => { + setState({ state: 'getCode' }); + return this._api.eth.getCode(this._address); + }) + .then((code) => { + if (code === '0x') { + throw new Error('Contract not deployed, getCode returned 0x'); + } + + setState({ state: 'completed' }); + return this._address; + }); + } + + parseEventLogs (logs) { + return logs.map((log) => { + const signature = log.topics[0].substr(2); + const event = this.events.find((evt) => evt.signature === signature); + + if (!event) { + throw new Error(`Unable to find event matching signature ${signature}`); + } + + const decoded = event.decodeLog(log.topics, log.data); + + log.params = {}; + log.event = event.name; + + decoded.params.forEach((param) => { + const { type, value } = param.token; + + log.params[param.name] = { type, value }; + }); + + return log; + }); + } + + parseTransactionEvents (receipt) { + receipt.logs = this.parseEventLogs(receipt.logs); + + return receipt; + } + + _pollCheckRequest = (requestId) => { + return this._api.pollMethod('eth_checkRequest', requestId); + } + + _pollTransactionReceipt = (txhash, gas) => { + return this.api.pollMethod('eth_getTransactionReceipt', txhash, (receipt) => { + if (!receipt || !receipt.blockNumber || receipt.blockNumber.eq(0)) { + return false; + } + + return true; + }); + } + + _encodeOptions (func, options, values) { + const tokens = func ? this._abi.encodeTokens(func.inputParamTypes(), values) : null; + const call = tokens ? func.encodeCall(tokens) : null; + + if (options.data && options.data.substr(0, 2) === '0x') { + options.data = options.data.substr(2); + } + options.data = `0x${options.data || ''}${call || ''}`; + + return options; + } + + _addOptionsTo (options = {}) { + return Object.assign({ + to: this._address + }, options); + } + + _bindFunction = (func) => { + func.call = (options, values = []) => { + return this._api.eth + .call(this._encodeOptions(func, this._addOptionsTo(options), values)) + .then((encoded) => func.decodeOutput(encoded)) + .then((tokens) => tokens.map((token) => token.value)) + .then((returns) => returns.length === 1 ? returns[0] : returns); + }; + + if (!func.constant) { + func.postTransaction = (options, values = []) => { + return this._api.eth + .postTransaction(this._encodeOptions(func, this._addOptionsTo(options), values)); + }; + + func.estimateGas = (options, values = []) => { + return this._api.eth + .estimateGas(this._encodeOptions(func, this._addOptionsTo(options), values)); + }; + } + + return func; + } + + _bindEvent = (event) => { + event.subscribe = (options = {}, callback) => { + return this._subscribe(event, options, callback); + }; + + event.unsubscribe = (subscriptionId) => { + return this.unsubscribe(subscriptionId); + }; + + return event; + } + + subscribe (eventName = null, options = {}, callback) { + return new Promise((resolve, reject) => { + let event = null; + + if (eventName) { + event = this._events.find((evt) => evt.name === eventName); + + if (!event) { + const events = this._events.map((evt) => evt.name).join(', '); + reject(new Error(`${eventName} is not a valid eventName, subscribe using one of ${events} (or null to include all)`)); + return; + } + } + + return this._subscribe(event, options, callback).then(resolve).catch(reject); + }); + } + + _subscribe (event = null, _options, callback) { + const subscriptionId = nextSubscriptionId++; + const options = Object.assign({}, _options, { + address: this._address, + topics: [event ? event.signature : null] + }); + + return this._api.eth + .newFilter(options) + .then((filterId) => { + return this._api.eth + .getFilterLogs(filterId) + .then((logs) => { + callback(null, this.parseEventLogs(logs)); + this._subscriptions[subscriptionId] = { + options, + callback, + filterId + }; + + return subscriptionId; + }); + }); + } + + unsubscribe (subscriptionId) { + return this._api.eth + .uninstallFilter(this._subscriptions[subscriptionId].filterId) + .then(() => { + delete this._subscriptions[subscriptionId]; + }) + .catch((error) => { + console.error('unsubscribe', error); + }); + } + + _sendSubscriptionChanges = () => { + const subscriptions = Object.values(this._subscriptions); + const timeout = () => setTimeout(this._sendSubscriptionChanges, 1000); + + Promise + .all( + subscriptions.map((subscription) => { + return this._api.eth.getFilterChanges(subscription.filterId); + }) + ) + .then((logsArray) => { + logsArray.forEach((logs, idx) => { + if (!logs || !logs.length) { + return; + } + + try { + subscriptions[idx].callback(null, this.parseEventLogs(logs)); + } catch (error) { + this.unsubscribe(idx); + console.error('_sendSubscriptionChanges', error); + } + }); + + timeout(); + }) + .catch((error) => { + console.error('_sendSubscriptionChanges', error); + timeout(); + }); + } +} diff --git a/js/src/api/contract/contract.spec.js b/js/src/api/contract/contract.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..0d6169e2626ab4225c1bc6271d7e1f10e4a65fe7 --- /dev/null +++ b/js/src/api/contract/contract.spec.js @@ -0,0 +1,539 @@ +// 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 BigNumber from 'bignumber.js'; +import sinon from 'sinon'; + +import { TEST_HTTP_URL, mockHttp } from '../../../test/mockRpc'; + +import Abi from '../../abi'; + +import Api from '../api'; +import Contract from './contract'; +import { isInstanceOf, isFunction } from '../util/types'; + +const transport = new Api.Transport.Http(TEST_HTTP_URL); +const eth = new Api(transport); + +describe('api/contract/Contract', () => { + const ADDR = '0x0123456789'; + const ABI = [ + { + type: 'function', name: 'test', + inputs: [{ name: 'boolin', type: 'bool' }, { name: 'stringin', type: 'string' }], + outputs: [{ type: 'uint' }] + }, + { + type: 'function', name: 'test2', + outputs: [{ type: 'uint' }, { type: 'uint' }] + }, + { type: 'constructor' }, + { type: 'event', name: 'baz' }, + { type: 'event', name: 'foo' } + ]; + const VALUES = [true, 'jacogr']; + const ENCODED = '0x023562050000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000066a61636f67720000000000000000000000000000000000000000000000000000'; + const RETURN1 = '0000000000000000000000000000000000000000000000000000000000123456'; + const RETURN2 = '0000000000000000000000000000000000000000000000000000000000456789'; + let scope; + + describe('constructor', () => { + it('needs an EthAbi instance', () => { + expect(() => new Contract()).to.throw(/API instance needs to be provided to Contract/); + }); + + it('needs an ABI', () => { + expect(() => new Contract(eth)).to.throw(/ABI needs to be provided to Contract instance/); + }); + + describe('internal setup', () => { + const contract = new Contract(eth, ABI); + + it('sets EthApi & parsed interface', () => { + expect(contract.address).to.not.be.ok; + expect(contract.api).to.deep.equal(eth); + expect(isInstanceOf(contract.abi, Abi)).to.be.ok; + }); + + it('attaches functions', () => { + expect(contract.functions.length).to.equal(2); + expect(contract.functions[0].name).to.equal('test'); + }); + + it('attaches constructors', () => { + expect(contract.constructors.length).to.equal(1); + }); + + it('attaches events', () => { + expect(contract.events.length).to.equal(2); + expect(contract.events[0].name).to.equal('baz'); + }); + }); + }); + + describe('at', () => { + it('sets returns the functions, events & sets the address', () => { + const contract = new Contract(eth, [ + { + constant: true, + inputs: [{ + name: '_who', + type: 'address' + }], + name: 'balanceOf', + outputs: [{ + name: '', + type: 'uint256' + }], + type: 'function' + }, + { + anonymous: false, + inputs: [{ + indexed: false, + name: 'amount', + type: 'uint256' + }], + name: 'Drained', + type: 'event' + } + ]); + contract.at('6789'); + + expect(Object.keys(contract.instance)).to.deep.equal(['Drained', 'balanceOf', 'address']); + expect(contract.address).to.equal('6789'); + }); + }); + + describe('parseTransactionEvents', () => { + it('checks for unmatched signatures', () => { + const contract = new Contract(eth, [{ anonymous: false, name: 'Message', type: 'event' }]); + expect(() => contract.parseTransactionEvents({ + logs: [{ + data: '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000063cf90d3f0410092fc0fca41846f5962239791950000000000000000000000000000000000000000000000000000000056e6c85f0000000000000000000000000000000000000000000000000001000000004fcd00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000d706f7374286d6573736167652900000000000000000000000000000000000000', + topics: [ + '0x954ba6c157daf8a26539574ffa64203c044691aa57251af95f4b48d85ec00dd5', + '0x0000000000000000000000000000000000000000000000000001000000004fe0' + ] + }] + })).to.throw(/event matching signature/); + }); + + it('parses a transaction log into the data', () => { + const contract = new Contract(eth, [ + { + anonymous: false, name: 'Message', type: 'event', + inputs: [ + { indexed: true, name: 'postId', type: 'uint256' }, + { indexed: false, name: 'parentId', type: 'uint256' }, + { indexed: false, name: 'sender', type: 'address' }, + { indexed: false, name: 'at', type: 'uint256' }, + { indexed: false, name: 'messageId', type: 'uint256' }, + { indexed: false, name: 'message', type: 'string' } + ] + } + ]); + const decoded = contract.parseTransactionEvents({ + blockHash: '0xa9280530a3b47bee2fc80f2862fd56502ae075350571d724d6442ea4c597347b', + blockNumber: '0x4fcd', + cumulativeGasUsed: '0xb57f', + gasUsed: '0xb57f', + logs: [{ + address: '0x22bff18ec62281850546a664bb63a5c06ac5f76c', + blockHash: '0xa9280530a3b47bee2fc80f2862fd56502ae075350571d724d6442ea4c597347b', + blockNumber: '0x4fcd', + data: '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000063cf90d3f0410092fc0fca41846f5962239791950000000000000000000000000000000000000000000000000000000056e6c85f0000000000000000000000000000000000000000000000000001000000004fcd00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000d706f7374286d6573736167652900000000000000000000000000000000000000', + logIndex: '0x0', + topics: [ + '0x954ba6c157daf8a26539574ffa64203c044691aa57251af95f4b48d85ec00dd5', + '0x0000000000000000000000000000000000000000000000000001000000004fe0' + ], + transactionHash: '0xca16f537d761d13e4e80953b754e2b15541f267d6cad9381f750af1bae1e4917', + transactionIndex: '0x0' + }], + to: '0x22bff18ec62281850546a664bb63a5c06ac5f76c', + transactionHash: '0xca16f537d761d13e4e80953b754e2b15541f267d6cad9381f750af1bae1e4917', + transactionIndex: '0x0' + }); + const log = decoded.logs[0]; + + expect(log.event).to.equal('Message'); + expect(log.address).to.equal('0x22bff18ec62281850546a664bb63a5c06ac5f76c'); + expect(log.params).to.deep.equal({ + at: { type: 'uint', value: new BigNumber('1457965151') }, + message: { type: 'string', value: 'post(message)' }, + messageId: { type: 'uint', value: new BigNumber('281474976731085') }, + parentId: { type: 'uint', value: new BigNumber(0) }, + postId: { type: 'uint', value: new BigNumber('281474976731104') }, + sender: { type: 'address', value: '0x63Cf90D3f0410092FC0fca41846f596223979195' } + }); + }); + }); + + describe('_pollTransactionReceipt', () => { + const contract = new Contract(eth, ABI); + const ADDRESS = '0xD337e80eEdBdf86eDBba021797d7e4e00Bb78351'; + const BLOCKNUMBER = '555000'; + const RECEIPT = { contractAddress: ADDRESS.toLowerCase(), blockNumber: BLOCKNUMBER }; + const EXPECT = { contractAddress: ADDRESS, blockNumber: new BigNumber(BLOCKNUMBER) }; + + let scope; + let receipt; + + describe('success', () => { + before(() => { + scope = mockHttp([ + { method: 'eth_getTransactionReceipt', reply: { result: null } }, + { method: 'eth_getTransactionReceipt', reply: { result: null } }, + { method: 'eth_getTransactionReceipt', reply: { result: RECEIPT } } + ]); + + return contract + ._pollTransactionReceipt('0x123') + .then((_receipt) => { + receipt = _receipt; + }); + }); + + it('sends multiple getTransactionReceipt calls', () => { + expect(scope.isDone()).to.be.true; + }); + + it('passes the txhash through', () => { + expect(scope.body.eth_getTransactionReceipt.params[0]).to.equal('0x123'); + }); + + it('receives the final receipt', () => { + expect(receipt).to.deep.equal(EXPECT); + }); + }); + + describe('error', () => { + before(() => { + scope = mockHttp([{ method: 'eth_getTransactionReceipt', reply: { error: { code: -1, message: 'failure' } } }]); + }); + + it('returns the errors', () => { + return contract + ._pollTransactionReceipt('0x123') + .catch((error) => { + expect(error.message).to.match(/failure/); + }); + }); + }); + }); + + describe('deploy', () => { + const contract = new Contract(eth, ABI); + const ADDRESS = '0xD337e80eEdBdf86eDBba021797d7e4e00Bb78351'; + const RECEIPT_PEND = { contractAddress: ADDRESS.toLowerCase(), gasUsed: 50, blockNumber: 0 }; + const RECEIPT_DONE = { contractAddress: ADDRESS.toLowerCase(), gasUsed: 50, blockNumber: 2500 }; + const RECEIPT_EXCP = { contractAddress: ADDRESS.toLowerCase(), gasUsed: 1200, blockNumber: 2500 }; + + let scope; + + describe('success', () => { + 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: 'eth_getTransactionReceipt', reply: { result: null } }, + { method: 'eth_getTransactionReceipt', reply: { result: RECEIPT_PEND } }, + { method: 'eth_getTransactionReceipt', reply: { result: RECEIPT_DONE } }, + { method: 'eth_getCode', reply: { result: '0x456' } } + ]); + + return contract.deploy({ data: '0x123' }, []); + }); + + it('calls estimateGas, postTransaction, checkRequest, getTransactionReceipt & getCode in order', () => { + expect(scope.isDone()).to.be.true; + }); + + it('passes the options through to postTransaction (incl. gas calculation)', () => { + expect(scope.body.eth_postTransaction.params).to.deep.equal([ + { data: '0x123', gas: '0x4b0' } + ]); + }); + + it('sets the address of the contract', () => { + expect(contract.address).to.equal(ADDRESS); + }); + }); + + describe('error', () => { + 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: 'eth_getTransactionReceipt', reply: { result: RECEIPT_EXCP } } + ]); + + return contract + .deploy({ data: '0x123' }, []) + .catch((error) => { + expect(error.message).to.match(/not deployed, gasUsed/); + }); + }); + + 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: 'eth_getTransactionReceipt', reply: { result: RECEIPT_DONE } }, + { method: 'eth_getCode', reply: { result: '0x' } } + ]); + + return contract + .deploy({ data: '0x123' }, []) + .catch((error) => { + expect(error.message).to.match(/not deployed, getCode/); + }); + }); + }); + }); + + describe('bindings', () => { + let contract; + let cons; + let func; + + beforeEach(() => { + contract = new Contract(eth, ABI); + contract.at(ADDR); + cons = contract.constructors[0]; + func = contract.functions.find((fn) => fn.name === 'test'); + }); + + describe('_addOptionsTo', () => { + it('works on no object specified', () => { + expect(contract._addOptionsTo()).to.deep.equal({ to: ADDR }); + }); + + it('uses the contract address when none specified', () => { + expect(contract._addOptionsTo({ from: 'me' })).to.deep.equal({ to: ADDR, from: 'me' }); + }); + + it('overrides the contract address when specified', () => { + expect(contract._addOptionsTo({ to: 'you', from: 'me' })).to.deep.equal({ to: 'you', from: 'me' }); + }); + }); + + describe('attachments', () => { + it('attaches .call, .postTransaction & .estimateGas to constructors', () => { + expect(isFunction(cons.call)).to.be.true; + expect(isFunction(cons.postTransaction)).to.be.true; + expect(isFunction(cons.estimateGas)).to.be.true; + }); + + it('attaches .call, .postTransaction & .estimateGas to functions', () => { + expect(isFunction(func.call)).to.be.true; + expect(isFunction(func.postTransaction)).to.be.true; + expect(isFunction(func.estimateGas)).to.be.true; + }); + + it('attaches .call only to constant functions', () => { + func = (new Contract(eth, [{ type: 'function', name: 'test', constant: true }])).functions[0]; + + expect(isFunction(func.call)).to.be.true; + expect(isFunction(func.postTransaction)).to.be.false; + expect(isFunction(func.estimateGas)).to.be.false; + }); + }); + + describe('postTransaction', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_postTransaction', reply: { result: ['hashId'] } }]); + }); + + it('encodes options and mades an eth_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({ + someExtras: 'foo', + to: ADDR, + data: ENCODED + }); + }); + }); + }); + + describe('estimateGas', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_estimateGas', reply: { result: ['0x123'] } }]); + }); + + it('encodes options and mades an eth_estimateGas call', () => { + return func + .estimateGas({ someExtras: 'foo' }, VALUES) + .then((amount) => { + expect(scope.isDone()).to.be.true; + expect(amount.toString(16)).to.equal('123'); + expect(scope.body.eth_estimateGas.params).to.deep.equal([{ + someExtras: 'foo', + to: ADDR, + data: ENCODED + }]); + }); + }); + }); + + describe('call', () => { + it('encodes options and mades an eth_call call', () => { + scope = mockHttp([{ method: 'eth_call', reply: { result: RETURN1 } }]); + + return func + .call({ someExtras: 'foo' }, VALUES) + .then((result) => { + expect(scope.isDone()).to.be.true; + expect(scope.body.eth_call.params).to.deep.equal([{ + someExtras: 'foo', + to: ADDR, + data: ENCODED + }, 'latest']); + expect(result.toString(16)).to.equal('123456'); + }); + }); + + it('encodes options and mades an eth_call call (multiple returns)', () => { + scope = mockHttp([{ method: 'eth_call', reply: { result: `${RETURN1}${RETURN2}` } }]); + + return contract.functions[1] + .call({}, []) + .then((result) => { + expect(scope.isDone()).to.be.true; + expect(result.length).to.equal(2); + expect(result[0].toString(16)).to.equal('123456'); + expect(result[1].toString(16)).to.equal('456789'); + }); + }); + }); + }); + + describe('subscribe', () => { + const abi = [ + { + anonymous: false, name: 'Message', type: 'event', + inputs: [ + { indexed: true, name: 'postId', type: 'uint256' }, + { indexed: false, name: 'parentId', type: 'uint256' }, + { indexed: false, name: 'sender', type: 'address' }, + { indexed: false, name: 'at', type: 'uint256' }, + { indexed: false, name: 'messageId', type: 'uint256' }, + { indexed: false, name: 'message', type: 'string' } + ] + } + ]; + const logs = [{ + address: '0x22bff18ec62281850546a664bb63a5c06ac5f76c', + blockHash: '0xa9280530a3b47bee2fc80f2862fd56502ae075350571d724d6442ea4c597347b', + blockNumber: '0x4fcd', + data: '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000063cf90d3f0410092fc0fca41846f5962239791950000000000000000000000000000000000000000000000000000000056e6c85f0000000000000000000000000000000000000000000000000001000000004fcd00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000d706f7374286d6573736167652900000000000000000000000000000000000000', + logIndex: '0x0', + topics: [ + '0x954ba6c157daf8a26539574ffa64203c044691aa57251af95f4b48d85ec00dd5', + '0x0000000000000000000000000000000000000000000000000001000000004fe0' + ], + transactionHash: '0xca16f537d761d13e4e80953b754e2b15541f267d6cad9381f750af1bae1e4917', + transactionIndex: '0x0' + }]; + const parsed = [{ + address: '0x22bfF18ec62281850546a664bb63a5C06AC5F76C', + blockHash: '0xa9280530a3b47bee2fc80f2862fd56502ae075350571d724d6442ea4c597347b', + blockNumber: new BigNumber(20429), + data: '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000063cf90d3f0410092fc0fca41846f5962239791950000000000000000000000000000000000000000000000000000000056e6c85f0000000000000000000000000000000000000000000000000001000000004fcd00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000d706f7374286d6573736167652900000000000000000000000000000000000000', + event: 'Message', + logIndex: new BigNumber(0), + params: { + at: { type: 'uint', value: new BigNumber(1457965151) }, + message: { type: 'string', value: 'post(message)' }, + messageId: { type: 'uint', value: new BigNumber(281474976731085) }, + parentId: { type: 'uint', value: new BigNumber(0) }, + postId: { type: 'uint', value: new BigNumber(281474976731104) }, + sender: { type: 'address', value: '0x63Cf90D3f0410092FC0fca41846f596223979195' } + }, + topics: [ + '0x954ba6c157daf8a26539574ffa64203c044691aa57251af95f4b48d85ec00dd5', '0x0000000000000000000000000000000000000000000000000001000000004fe0' + ], + transactionHash: '0xca16f537d761d13e4e80953b754e2b15541f267d6cad9381f750af1bae1e4917', + transactionIndex: new BigNumber(0) + }]; + let contract; + + beforeEach(() => { + contract = new Contract(eth, abi); + contract.at(ADDR); + }); + + describe('invalid events', () => { + it('fails to subscribe to an invalid names', () => { + return contract + .subscribe('invalid') + .catch((error) => { + expect(error.message).to.match(/invalid is not a valid eventName/); + }); + }); + }); + + describe('valid events', () => { + let cbb; + let cbe; + + beforeEach(() => { + scope = mockHttp([ + { method: 'eth_newFilter', reply: { result: '0x123' } }, + { method: 'eth_getFilterLogs', reply: { result: logs } }, + { method: 'eth_newFilter', reply: { result: '0x123' } }, + { method: 'eth_getFilterLogs', reply: { result: logs } } + ]); + cbb = sinon.stub(); + cbe = sinon.stub(); + + return contract.subscribe('Message', {}, cbb); + }); + + it('sets the subscriptionId returned', () => { + return contract + .subscribe('Message', {}, cbe) + .then((subscriptionId) => { + expect(subscriptionId).to.equal(1); + }); + }); + + it('creates a new filter and retrieves the logs on it', () => { + return contract + .subscribe('Message', {}, cbe) + .then((subscriptionId) => { + expect(scope.isDone()).to.be.true; + }); + }); + + it('returns the logs to the callback', () => { + return contract + .subscribe('Message', {}, cbe) + .then((subscriptionId) => { + expect(cbe).to.have.been.calledWith(null, parsed); + }); + }); + }); + }); +}); diff --git a/js/src/api/contract/index.js b/js/src/api/contract/index.js new file mode 100644 index 0000000000000000000000000000000000000000..18051a69f910ea8d9baa3a541e8ed553f3fb0966 --- /dev/null +++ b/js/src/api/contract/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './contract'; diff --git a/js/src/api/format/input.js b/js/src/api/format/input.js new file mode 100644 index 0000000000000000000000000000000000000000..b46148cdc4c4297f0791ba2439c9322b3f32a91c --- /dev/null +++ b/js/src/api/format/input.js @@ -0,0 +1,164 @@ +// 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 BigNumber from 'bignumber.js'; + +import { isArray, isHex, isInstanceOf, isString } from '../util/types'; + +export function inAddress (address) { + // TODO: address validation if we have upper-lower addresses + return inHex(address); +} + +export function inBlockNumber (blockNumber) { + if (isString(blockNumber)) { + switch (blockNumber) { + case 'earliest': + case 'latest': + case 'pending': + return blockNumber; + } + } + + return inNumber16(blockNumber); +} + +export function inData (data) { + if (data && data.length && !isHex(data)) { + data = data.split('').map((chr) => { + return `0${chr.charCodeAt(0).toString(16)}`.slice(-2); + }).join(''); + } + + return inHex(data); +} + +export function inHash (hash) { + return inHex(hash); +} + +export function inTopics (_topics) { + let topics = (_topics || []) + .filter((topic) => topic) + .map(inHex); + + while (topics.length < 4) { + topics.push(null); + } + + return topics; +} + +export function inFilter (options) { + if (options) { + Object.keys(options).forEach((key) => { + switch (key) { + case 'address': + if (isArray(options[key])) { + options[key] = options[key].map(inAddress); + } else { + options[key] = inAddress(options[key]); + } + break; + + case 'fromBlock': + case 'toBlock': + options[key] = inBlockNumber(options[key]); + break; + + case 'limit': + options[key] = inNumber10(options[key]); + break; + + case 'topics': + options[key] = inTopics(options[key]); + } + }); + } + + return options; +} + +export function inHex (str) { + if (str && str.substr(0, 2) === '0x') { + return str.toLowerCase(); + } + + return `0x${(str || '').toLowerCase()}`; +} + +export function inNumber10 (number) { + if (isInstanceOf(number, BigNumber)) { + return number.toNumber(); + } + + return (new BigNumber(number || 0)).toNumber(); +} + +export function inNumber16 (number) { + if (isInstanceOf(number, BigNumber)) { + return inHex(number.toString(16)); + } + + return inHex((new BigNumber(number || 0)).toString(16)); +} + +export function inOptions (options) { + if (options) { + Object.keys(options).forEach((key) => { + switch (key) { + case 'from': + case 'to': + options[key] = inAddress(options[key]); + break; + + case 'gas': + case 'gasPrice': + case 'value': + case 'nonce': + options[key] = inNumber16(options[key]); + break; + + case 'data': + options[key] = inData(options[key]); + break; + } + }); + } + + return options; +} + +export function inTraceFilter (filterObject) { + if (filterObject) { + Object.keys(filterObject).forEach((key) => { + switch (key) { + case 'fromAddress': + case 'toAddress': + filterObject[key] = [].concat(filterObject[key]) + .map(address => inAddress(address)); + break; + + case 'toBlock': + case 'fromBlock': + filterObject[key] = inBlockNumber(filterObject[key]); + break; + } + }); + } + + return filterObject; +} diff --git a/js/src/api/format/input.spec.js b/js/src/api/format/input.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..219886d05f0c945015ce999c28cca44b24e40a7c --- /dev/null +++ b/js/src/api/format/input.spec.js @@ -0,0 +1,245 @@ +// 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 BigNumber from 'bignumber.js'; + +import { inAddress, inBlockNumber, inData, inFilter, inHex, inNumber10, inNumber16, inOptions } from './input'; +import { isAddress } from '../../../test/types'; + +describe('api/format/input', () => { + const address = '0x63cf90d3f0410092fc0fca41846f596223979195'; + + describe('inAddress', () => { + const address = '63cf90d3f0410092fc0fca41846f596223979195'; + + it('adds the leading 0x as required', () => { + expect(inAddress(address)).to.equal(`0x${address}`); + }); + + it('returns verified addresses as-is', () => { + expect(inAddress(`0x${address}`)).to.equal(`0x${address}`); + }); + + it('returns lowercase equivalents', () => { + expect(inAddress(address.toUpperCase())).to.equal(`0x${address}`); + }); + + it('returns 0x on null addresses', () => { + expect(inAddress()).to.equal('0x'); + }); + }); + + describe('inBlockNumber()', () => { + it('returns earliest as-is', () => { + expect(inBlockNumber('earliest')).to.equal('earliest'); + }); + + it('returns latest as-is', () => { + expect(inBlockNumber('latest')).to.equal('latest'); + }); + + it('returns pending as-is', () => { + expect(inBlockNumber('pending')).to.equal('pending'); + }); + + it('formats existing BigNumber into hex', () => { + expect(inBlockNumber(new BigNumber(0x123456))).to.equal('0x123456'); + }); + + it('formats hex strings into hex', () => { + expect(inBlockNumber('0x123456')).to.equal('0x123456'); + }); + + it('formats numbers into hex', () => { + expect(inBlockNumber(0x123456)).to.equal('0x123456'); + }); + }); + + describe('inData', () => { + it('formats to hex', () => { + expect(inData('123456')).to.equal('0x123456'); + }); + + it('converts a string to a hex representation', () => { + expect(inData('jaco')).to.equal('0x6a61636f'); + }); + }); + + describe('inHex', () => { + it('leaves leading 0x as-is', () => { + expect(inHex('0x123456')).to.equal('0x123456'); + }); + + it('adds a leading 0x', () => { + expect(inHex('123456')).to.equal('0x123456'); + }); + + it('returns uppercase as lowercase (leading 0x)', () => { + expect(inHex('0xABCDEF')).to.equal('0xabcdef'); + }); + + it('returns uppercase as lowercase (no leading 0x)', () => { + expect(inHex('ABCDEF')).to.equal('0xabcdef'); + }); + + it('handles empty & null', () => { + expect(inHex()).to.equal('0x'); + expect(inHex('')).to.equal('0x'); + }); + }); + + describe('inFilter', () => { + ['address'].forEach((input) => { + it(`formats ${input} address as address`, () => { + const block = {}; + block[input] = address; + const formatted = inFilter(block)[input]; + + expect(isAddress(formatted)).to.be.true; + expect(formatted).to.equal(address); + }); + }); + + ['fromBlock', 'toBlock'].forEach((input) => { + it(`formats ${input} number as blockNumber`, () => { + const block = {}; + block[input] = 0x123; + const formatted = inFilter(block)[input]; + + expect(formatted).to.equal('0x123'); + }); + }); + + it('ignores and passes through unknown keys', () => { + expect(inFilter({ someRandom: 'someRandom' })).to.deep.equal({ someRandom: 'someRandom' }); + }); + + it('formats an filter options object with relevant entries converted', () => { + expect( + inFilter({ + address: address, + fromBlock: 'latest', + toBlock: 0x101, + extraData: 'someExtraStuffInHere', + limit: 0x32 + }) + ).to.deep.equal({ + address: address, + fromBlock: 'latest', + toBlock: '0x101', + extraData: 'someExtraStuffInHere', + limit: 50 + }); + }); + }); + + describe('inNumber10()', () => { + it('formats existing BigNumber into number', () => { + expect(inNumber10(new BigNumber(123))).to.equal(123); + }); + + it('formats hex strings into decimal', () => { + expect(inNumber10('0x0a')).to.equal(10); + }); + + it('formats numbers into number', () => { + expect(inNumber10(123)).to.equal(123); + }); + + it('formats undefined into 0', () => { + expect(inNumber10()).to.equal(0); + }); + }); + + describe('inNumber16()', () => { + it('formats existing BigNumber into hex', () => { + expect(inNumber16(new BigNumber(0x123456))).to.equal('0x123456'); + }); + + it('formats hex strings into hex', () => { + expect(inNumber16('0x123456')).to.equal('0x123456'); + }); + + it('formats numbers into hex', () => { + expect(inNumber16(0x123456)).to.equal('0x123456'); + }); + + it('formats undefined into 0', () => { + expect(inNumber16()).to.equal('0x0'); + }); + }); + + describe('inOptions', () => { + ['data'].forEach((input) => { + it(`converts ${input} to hex data`, () => { + const block = {}; + block[input] = '1234'; + const formatted = inData(block[input]); + + expect(formatted).to.equal('0x1234'); + }); + }); + + ['from', 'to'].forEach((input) => { + it(`formats ${input} address as address`, () => { + const block = {}; + block[input] = address; + const formatted = inOptions(block)[input]; + + expect(isAddress(formatted)).to.be.true; + expect(formatted).to.equal(address); + }); + }); + + ['gas', 'gasPrice', 'value', 'nonce'].forEach((input) => { + it(`formats ${input} number as hexnumber`, () => { + const block = {}; + block[input] = 0x123; + const formatted = inOptions(block)[input]; + + expect(formatted).to.equal('0x123'); + }); + }); + + it('ignores and passes through unknown keys', () => { + expect(inOptions({ someRandom: 'someRandom' })).to.deep.equal({ someRandom: 'someRandom' }); + }); + + it('formats an options object with relevant entries converted', () => { + expect( + inOptions({ + from: address, + to: address, + gas: new BigNumber('0x100'), + gasPrice: 0x101, + value: 258, + nonce: '0x104', + data: '0123456789', + extraData: 'someExtraStuffInHere' + }) + ).to.deep.equal({ + from: address, + to: address, + gas: '0x100', + gasPrice: '0x101', + value: '0x102', + nonce: '0x104', + data: '0x0123456789', + extraData: 'someExtraStuffInHere' + }); + }); + }); +}); diff --git a/js/src/api/format/output.js b/js/src/api/format/output.js new file mode 100644 index 0000000000000000000000000000000000000000..8461df20f0203711494f0ee763b3cd4b78fbbbc7 --- /dev/null +++ b/js/src/api/format/output.js @@ -0,0 +1,256 @@ +// 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 BigNumber from 'bignumber.js'; + +import { toChecksumAddress } from '../../abi/util/address'; + +export function outAccountInfo (infos) { + const ret = {}; + + Object.keys(infos).forEach((address) => { + const info = infos[address]; + + ret[outAddress(address)] = { + name: info.name, + uuid: info.uuid, + meta: JSON.parse(info.meta) + }; + }); + + return ret; +} + +export function outAddress (address) { + return toChecksumAddress(address); +} + +export function outBlock (block) { + if (block) { + Object.keys(block).forEach((key) => { + switch (key) { + case 'author': + case 'miner': + block[key] = outAddress(block[key]); + break; + + case 'difficulty': + case 'gasLimit': + case 'gasUsed': + case 'nonce': + case 'number': + case 'totalDifficulty': + block[key] = outNumber(block[key]); + break; + + case 'timestamp': + block[key] = outDate(block[key]); + break; + } + }); + } + + return block; +} + +export function outDate (date) { + return new Date(outNumber(date).toNumber() * 1000); +} + +export function outHistogram (histogram) { + if (histogram) { + Object.keys(histogram).forEach((key) => { + switch (key) { + case 'bucketBounds': + case 'counts': + histogram[key] = histogram[key].map(outNumber); + } + }); + } + + return histogram; +} + +export function outLog (log) { + Object.keys(log).forEach((key) => { + switch (key) { + case 'blockNumber': + case 'logIndex': + case 'transactionIndex': + log[key] = outNumber(log[key]); + break; + + case 'address': + log[key] = outAddress(log[key]); + break; + } + }); + + return log; +} + +export function outNumber (number) { + return new BigNumber(number || 0); +} + +export function outPeers (peers) { + return { + active: outNumber(peers.active), + connected: outNumber(peers.connected), + max: outNumber(peers.max) + }; +} + +export function outReceipt (receipt) { + if (receipt) { + Object.keys(receipt).forEach((key) => { + switch (key) { + case 'blockNumber': + case 'cumulativeGasUsed': + case 'gasUsed': + case 'transactionIndex': + receipt[key] = outNumber(receipt[key]); + break; + + case 'contractAddress': + receipt[key] = outAddress(receipt[key]); + break; + } + }); + } + + return receipt; +} + +export function outSignerRequest (request) { + if (request) { + Object.keys(request).forEach((key) => { + switch (key) { + case 'id': + request[key] = outNumber(request[key]); + break; + + case 'payload': + request[key].transaction = outTransaction(request[key].transaction); + break; + } + }); + } + + return request; +} + +export function outSyncing (syncing) { + if (syncing && syncing !== 'false') { + Object.keys(syncing).forEach((key) => { + switch (key) { + case 'currentBlock': + case 'highestBlock': + case 'startingBlock': + case 'warpChunksAmount': + case 'warpChunksProcessed': + syncing[key] = outNumber(syncing[key]); + break; + + case 'blockGap': + syncing[key] = syncing[key] ? syncing[key].map(outNumber) : syncing[key]; + break; + } + }); + } + + return syncing; +} + +export function outTransaction (tx) { + if (tx) { + Object.keys(tx).forEach((key) => { + switch (key) { + case 'blockNumber': + case 'gasPrice': + case 'gas': + case 'nonce': + case 'transactionIndex': + case 'value': + tx[key] = outNumber(tx[key]); + break; + + case 'creates': + case 'from': + case 'to': + tx[key] = outAddress(tx[key]); + break; + } + }); + } + + return tx; +} + +export function outTrace (trace) { + if (trace) { + if (trace.action) { + Object.keys(trace.action).forEach(key => { + switch (key) { + case 'gas': + case 'value': + case 'balance': + trace.action[key] = outNumber(trace.action[key]); + break; + + case 'from': + case 'to': + case 'address': + case 'refundAddress': + trace.action[key] = outAddress(trace.action[key]); + break; + } + }); + } + + if (trace.result) { + Object.keys(trace.result).forEach(key => { + switch (key) { + case 'gasUsed': + trace.result[key] = outNumber(trace.result[key]); + break; + + case 'address': + trace.action[key] = outAddress(trace.action[key]); + break; + } + }); + } + + if (trace.traceAddress) { + trace.traceAddress.forEach((address, index) => { + trace.traceAddress[index] = outNumber(address); + }); + } + + Object.keys(trace).forEach((key) => { + switch (key) { + case 'subtraces': + case 'transactionPosition': + case 'blockNumber': + trace[key] = outNumber(trace[key]); + break; + } + }); + } + + return trace; +} diff --git a/js/src/api/format/output.spec.js b/js/src/api/format/output.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..aac433d701eb73c409a54acd8e0e67cbd17f95b5 --- /dev/null +++ b/js/src/api/format/output.spec.js @@ -0,0 +1,318 @@ +// 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 BigNumber from 'bignumber.js'; + +import { outBlock, outAccountInfo, outAddress, outDate, outHistogram, outNumber, outPeers, outReceipt, outSyncing, outTransaction, outTrace } from './output'; +import { isAddress, isBigNumber, isInstanceOf } from '../../../test/types'; + +describe('api/format/output', () => { + const address = '0x63cf90d3f0410092fc0fca41846f596223979195'; + const checksum = '0x63Cf90D3f0410092FC0fca41846f596223979195'; + + describe('outAccountInfo', () => { + it('returns meta objects parsed', () => { + expect(outAccountInfo( + { '0x63cf90d3f0410092fc0fca41846f596223979195': { + name: 'name', uuid: 'uuid', meta: '{"name":"456"}' } + } + )).to.deep.equal({ + '0x63Cf90D3f0410092FC0fca41846f596223979195': { + name: 'name', uuid: 'uuid', meta: { name: '456' } + } + }); + }); + }); + + describe('outAddress', () => { + it('retuns the address as checksummed', () => { + expect(outAddress(address)).to.equal(checksum); + }); + + it('retuns the checksum as checksummed', () => { + expect(outAddress(checksum)).to.equal(checksum); + }); + }); + + describe('outBlock', () => { + ['author', 'miner'].forEach((input) => { + it(`formats ${input} address as address`, () => { + const block = {}; + block[input] = address; + const formatted = outBlock(block)[input]; + + expect(isAddress(formatted)).to.be.true; + expect(formatted).to.equal(checksum); + }); + }); + + ['difficulty', 'gasLimit', 'gasUsed', 'number', 'nonce', 'totalDifficulty'].forEach((input) => { + it(`formats ${input} number as hexnumber`, () => { + const block = {}; + block[input] = 0x123; + const formatted = outBlock(block)[input]; + + expect(isInstanceOf(formatted, BigNumber)).to.be.true; + expect(formatted.toString(16)).to.equal('123'); + }); + }); + + ['timestamp'].forEach((input) => { + it(`formats ${input} number as Date`, () => { + const block = {}; + block[input] = 0x57513668; + const formatted = outBlock(block)[input]; + + expect(isInstanceOf(formatted, Date)).to.be.true; + expect(formatted.getTime()).to.equal(1464940136000); + }); + }); + + it('ignores and passes through unknown keys', () => { + expect(outBlock({ someRandom: 'someRandom' })).to.deep.equal({ someRandom: 'someRandom' }); + }); + + it('formats a block with all the info converted', () => { + expect( + outBlock({ + author: address, + miner: address, + difficulty: '0x100', + gasLimit: '0x101', + gasUsed: '0x102', + number: '0x103', + nonce: '0x104', + totalDifficulty: '0x105', + timestamp: '0x57513668', + extraData: 'someExtraStuffInHere' + }) + ).to.deep.equal({ + author: checksum, + miner: checksum, + difficulty: new BigNumber('0x100'), + gasLimit: new BigNumber('0x101'), + gasUsed: new BigNumber('0x102'), + number: new BigNumber('0x103'), + nonce: new BigNumber('0x104'), + totalDifficulty: new BigNumber('0x105'), + timestamp: new Date('2016-06-03T07:48:56.000Z'), + extraData: 'someExtraStuffInHere' + }); + }); + }); + + describe('outDate', () => { + it('converts a second date in unix timestamp', () => { + expect(outDate(0x57513668)).to.deep.equal(new Date('2016-06-03T07:48:56.000Z')); + }); + }); + + describe('outHistogram', () => { + ['bucketBounds', 'counts'].forEach((type) => { + it(`formats ${type} as number arrays`, () => { + expect( + outHistogram({ [type]: [0x123, 0x456, 0x789] }) + ).to.deep.equal({ + [type]: [new BigNumber(0x123), new BigNumber(0x456), new BigNumber(0x789)] + }); + }); + }); + }); + + describe('outNumber', () => { + it('returns a BigNumber equalling the value', () => { + const bn = outNumber('0x123456'); + + expect(isBigNumber(bn)).to.be.true; + expect(bn.eq(0x123456)).to.be.true; + }); + + it('assumes 0 when ivalid input', () => { + expect(outNumber().eq(0)).to.be.true; + }); + }); + + describe('outPeers', () => { + it('converts all internal numbers to BigNumbers', () => { + expect(outPeers({ active: 789, connected: '456', max: 0x7b })).to.deep.equal({ + active: new BigNumber(789), + connected: new BigNumber(456), + max: new BigNumber(123) + }); + }); + }); + + describe('outReceipt', () => { + ['contractAddress'].forEach((input) => { + it(`formats ${input} address as address`, () => { + const block = {}; + block[input] = address; + const formatted = outReceipt(block)[input]; + + expect(isAddress(formatted)).to.be.true; + expect(formatted).to.equal(checksum); + }); + }); + + ['blockNumber', 'cumulativeGasUsed', 'cumulativeGasUsed', 'gasUsed', 'transactionIndex'].forEach((input) => { + it(`formats ${input} number as hexnumber`, () => { + const block = {}; + block[input] = 0x123; + const formatted = outReceipt(block)[input]; + + expect(isInstanceOf(formatted, BigNumber)).to.be.true; + expect(formatted.toString(16)).to.equal('123'); + }); + }); + + it('ignores and passes through unknown keys', () => { + expect(outReceipt({ someRandom: 'someRandom' })).to.deep.equal({ someRandom: 'someRandom' }); + }); + + it('formats a receipt with all the info converted', () => { + expect( + outReceipt({ + contractAddress: address, + blockNumber: '0x100', + cumulativeGasUsed: '0x101', + gasUsed: '0x102', + transactionIndex: '0x103', + extraData: 'someExtraStuffInHere' + }) + ).to.deep.equal({ + contractAddress: checksum, + blockNumber: new BigNumber('0x100'), + cumulativeGasUsed: new BigNumber('0x101'), + gasUsed: new BigNumber('0x102'), + transactionIndex: new BigNumber('0x103'), + extraData: 'someExtraStuffInHere' + }); + }); + }); + + describe('outSyncing', () => { + ['currentBlock', 'highestBlock', 'startingBlock', 'warpChunksAmount', 'warpChunksProcessed'].forEach((input) => { + it(`formats ${input} numbers as a number`, () => { + expect(outSyncing({ [input]: '0x123' })).to.deep.equal({ + [input]: new BigNumber('0x123') + }); + }); + }); + + it('formats blockGap properly', () => { + expect(outSyncing({ blockGap: [0x123, 0x456] })).to.deep.equal({ + blockGap: [new BigNumber(0x123), new BigNumber(0x456)] + }); + }); + }); + + describe('outTransaction', () => { + ['from', 'to'].forEach((input) => { + it(`formats ${input} address as address`, () => { + const block = {}; + block[input] = address; + const formatted = outTransaction(block)[input]; + + expect(isAddress(formatted)).to.be.true; + expect(formatted).to.equal(checksum); + }); + }); + + ['blockNumber', 'gasPrice', 'gas', 'nonce', 'transactionIndex', 'value'].forEach((input) => { + it(`formats ${input} number as hexnumber`, () => { + const block = {}; + block[input] = 0x123; + const formatted = outTransaction(block)[input]; + + expect(isInstanceOf(formatted, BigNumber)).to.be.true; + expect(formatted.toString(16)).to.equal('123'); + }); + }); + + it('ignores and passes through unknown keys', () => { + expect(outTransaction({ someRandom: 'someRandom' })).to.deep.equal({ someRandom: 'someRandom' }); + }); + + it('formats a transaction with all the info converted', () => { + expect( + outTransaction({ + from: address, + to: address, + blockNumber: '0x100', + gasPrice: '0x101', + gas: '0x102', + nonce: '0x103', + transactionIndex: '0x104', + value: '0x105', + extraData: 'someExtraStuffInHere' + }) + ).to.deep.equal({ + from: checksum, + to: checksum, + blockNumber: new BigNumber('0x100'), + gasPrice: new BigNumber('0x101'), + gas: new BigNumber('0x102'), + nonce: new BigNumber('0x103'), + transactionIndex: new BigNumber('0x104'), + value: new BigNumber('0x105'), + extraData: 'someExtraStuffInHere' + }); + }); + }); + + describe('outTrace', () => { + it('ignores and passes through unknown keys', () => { + expect(outTrace({ someRandom: 'someRandom' })).to.deep.equal({ someRandom: 'someRandom' }); + }); + + it('formats a trace with all the info converted', () => { + const formatted = outTrace({ + type: 'call', + action: { + from: address, + to: address, + value: '0x06', + gas: '0x07', + input: '0x1234', + callType: 'call' + }, + result: { + gasUsed: '0x08', + output: '0x5678' + }, + traceAddress: [ '0x2' ], + subtraces: 3, + transactionPosition: '0xb', + transactionHash: '0x000000000000000000000000000000000000000000000000000000000000000c', + blockNumber: '0x0d', + blockHash: '0x000000000000000000000000000000000000000000000000000000000000000e' + }); + + expect(isBigNumber(formatted.action.gas)).to.be.true; + expect(formatted.action.gas.toNumber()).to.equal(7); + expect(isBigNumber(formatted.action.value)).to.be.true; + expect(formatted.action.value.toNumber()).to.equal(6); + + expect(formatted.action.from).to.equal(checksum); + expect(formatted.action.to).to.equal(checksum); + + expect(isBigNumber(formatted.blockNumber)).to.be.true; + expect(formatted.blockNumber.toNumber()).to.equal(13); + expect(isBigNumber(formatted.transactionPosition)).to.be.true; + expect(formatted.transactionPosition.toNumber()).to.equal(11); + }); + }); +}); diff --git a/js/src/api/index.js b/js/src/api/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b03419eacc6613dfae1c4f3cc7776cb520de7e9c --- /dev/null +++ b/js/src/api/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './api'; diff --git a/js/src/api/rpc/db/db.js b/js/src/api/rpc/db/db.js new file mode 100644 index 0000000000000000000000000000000000000000..9b20316006edecd2a2e16019f54fd3a9abec1aad --- /dev/null +++ b/js/src/api/rpc/db/db.js @@ -0,0 +1,43 @@ +// 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 { inHex } from '../../format/input'; + +export default class Db { + constructor (transport) { + this._transport = transport; + } + + getHex (dbName, keyName) { + return this._transport + .execute('db_getHex', dbName, keyName); + } + + getString (dbName, keyName) { + return this._transport + .execute('db_getString', dbName, keyName); + } + + putHex (dbName, keyName, hexData) { + return this._transport + .execute('db_putHex', dbName, keyName, inHex(hexData)); + } + + putString (dbName, keyName, stringData) { + return this._transport + .execute('db_putString', dbName, keyName, stringData); + } +} diff --git a/js/src/api/rpc/db/db.spec.js b/js/src/api/rpc/db/db.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4379b51c4161ee347f992b2b951b5fc71b18d46e --- /dev/null +++ b/js/src/api/rpc/db/db.spec.js @@ -0,0 +1,38 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; + +import Http from '../../transport/http'; +import Db from './db'; + +const instance = new Db(new Http(TEST_HTTP_URL)); + +describe('api/rpc/Db', () => { + let scope; + + describe('putHex', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'db_putHex', reply: { result: [] } }]); + }); + + it('formats the inputs correctly', () => { + return instance.putHex('db', 'key', '1234').then(() => { + expect(scope.body.db_putHex.params).to.deep.equal(['db', 'key', '0x1234']); + }); + }); + }); +}); diff --git a/js/src/api/rpc/db/index.js b/js/src/api/rpc/db/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cd7c2b0b84a234a5cc2ae816c55fd0e946036401 --- /dev/null +++ b/js/src/api/rpc/db/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './db'; diff --git a/js/src/api/rpc/eth/eth.e2e.js b/js/src/api/rpc/eth/eth.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..973ea1c517a92357fcc69a1cf86a670c77cef880 --- /dev/null +++ b/js/src/api/rpc/eth/eth.e2e.js @@ -0,0 +1,170 @@ +// 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 { createHttpApi } from '../../../../test/e2e/ethapi'; +import { isAddress } from '../../../../test/types'; + +describe('ethapi.eth', () => { + const ethapi = createHttpApi(); + const address = '0x63cf90d3f0410092fc0fca41846f596223979195'; + + let latestBlockNumber; + let latestBlockHash; + + describe('accounts', () => { + it('returns the available accounts', () => { + return ethapi.eth.accounts().then((accounts) => { + accounts.forEach((account) => { + expect(isAddress(account)).to.be.true; + }); + }); + }); + }); + + describe('blockNumber', () => { + it('returns the current blockNumber', () => { + return ethapi.eth.blockNumber().then((blockNumber) => { + latestBlockNumber = blockNumber; + expect(blockNumber.gt(0xabcde)).to.be.true; + }); + }); + }); + + describe('coinbase', () => { + it('returns the coinbase', () => { + return ethapi.eth.coinbase().then((coinbase) => { + expect(isAddress(coinbase)).to.be.true; + }); + }); + }); + + describe('gasPrice', () => { + it('returns the current gasPrice', () => { + return ethapi.eth.gasPrice().then((gasPrice) => { + expect(gasPrice.gt(0)).to.be.true; + }); + }); + }); + + describe('getBalance', () => { + it('returns the balance for latest block', () => { + return ethapi.eth.getBalance(address).then((balance) => { + expect(balance.gt(0)).to.be.true; + }); + }); + + it('returns the balance for a very early block', () => { + const atBlock = '0x65432'; + const atValue = '18e07120a6e164fee1b'; + + return ethapi.eth + .getBalance(address, atBlock) + .then((balance) => { + expect(balance.toString(16)).to.equal(atValue); + }) + .catch((error) => { + // Parity doesn't support pruned-before-block balance lookups + expect(error.message).to.match(/not supported/); + }); + }); + + it('returns the balance for a recent/out-of-pruning-range block', () => { + return ethapi.eth + .getBalance(address, latestBlockNumber.minus(1000)) + .then((balance) => { + expect(balance.gt(0)).to.be.true; + }); + }); + }); + + describe('getBlockByNumber', () => { + it('returns the latest block', () => { + return ethapi.eth.getBlockByNumber().then((block) => { + expect(block).to.be.ok; + }); + }); + + it('returns a block by blockNumber', () => { + return ethapi.eth.getBlockByNumber(latestBlockNumber).then((block) => { + latestBlockHash = block.hash; + expect(block).to.be.ok; + }); + }); + + it('returns a block by blockNumber (full)', () => { + return ethapi.eth.getBlockByNumber(latestBlockNumber, true).then((block) => { + expect(block).to.be.ok; + }); + }); + }); + + describe('getBlockByHash', () => { + it('returns the specified block', () => { + return ethapi.eth.getBlockByHash(latestBlockHash).then((block) => { + expect(block).to.be.ok; + expect(block.hash).to.equal(latestBlockHash); + }); + }); + + it('returns the specified block (full)', () => { + return ethapi.eth.getBlockByHash(latestBlockHash, true).then((block) => { + expect(block).to.be.ok; + expect(block.hash).to.equal(latestBlockHash); + }); + }); + }); + + describe('getBlockTransactionCountByHash', () => { + it('returns the transactions of the specified hash', () => { + return ethapi.eth.getBlockTransactionCountByHash(latestBlockHash).then((count) => { + expect(count).to.be.ok; + expect(count.gte(0)).to.be.true; + }); + }); + }); + + describe('getBlockTransactionCountByNumber', () => { + it('returns the transactions of latest', () => { + return ethapi.eth.getBlockTransactionCountByNumber().then((count) => { + expect(count).to.be.ok; + expect(count.gte(0)).to.be.true; + }); + }); + + it('returns the transactions of a specified number', () => { + return ethapi.eth.getBlockTransactionCountByNumber(latestBlockNumber).then((count) => { + expect(count).to.be.ok; + expect(count.gte(0)).to.be.true; + }); + }); + }); + + describe('getTransactionCount', () => { + it('returns the count for an address', () => { + return ethapi.eth.getTransactionCount(address).then((count) => { + expect(count).to.be.ok; + expect(count.gte(0x1000c2)).to.be.ok; + }); + }); + + it('returns the count for an address at specified blockNumber', () => { + return ethapi.eth.getTransactionCount(address, latestBlockNumber).then((count) => { + expect(count).to.be.ok; + expect(count.gte(0x1000c2)).to.be.ok; + }); + }); + }); +}); diff --git a/js/src/api/rpc/eth/eth.js b/js/src/api/rpc/eth/eth.js new file mode 100644 index 0000000000000000000000000000000000000000..703f3ed11ef29ce0d42825d15a61ea7d756ac533 --- /dev/null +++ b/js/src/api/rpc/eth/eth.js @@ -0,0 +1,330 @@ +// 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, inBlockNumber, inData, inFilter, inHash, inHex, inNumber16, inOptions } from '../../format/input'; +import { outAddress, outBlock, outLog, outNumber, outReceipt, outSyncing, outTransaction } from '../../format/output'; + +export default class Eth { + constructor (transport) { + this._transport = transport; + } + + accounts () { + return this._transport + .execute('eth_accounts') + .then((accounts) => (accounts || []).map(outAddress)); + } + + blockNumber () { + return this._transport + .execute('eth_blockNumber') + .then(outNumber); + } + + call (options, blockNumber = 'latest') { + return this._transport + .execute('eth_call', inOptions(options), inBlockNumber(blockNumber)); + } + + checkRequest (requestId) { + return this._transport + .execute('eth_checkRequest', inNumber16(requestId)); + } + + coinbase () { + return this._transport + .execute('eth_coinbase') + .then(outAddress); + } + + compileLLL (code) { + return this._transport + .execute('eth_compileLLL', inData(code)); + } + + compileSerpent (code) { + return this._transport + .execute('eth_compileSerpent', inData(code)); + } + + compileSolidity (code) { + return this._transport + .execute('eth_compileSolidity', inData(code)); + } + + estimateGas (options) { + return this._transport + .execute('eth_estimateGas', inOptions(options)) + .then(outNumber); + } + + fetchQueuedTransactions () { + return this._transport + .execute('eth_fetchQueuedTransactions'); + } + + flush () { + return this._transport + .execute('eth_flush'); + } + + gasPrice () { + return this._transport + .execute('eth_gasPrice') + .then(outNumber); + } + + getBalance (address, blockNumber = 'latest') { + return this._transport + .execute('eth_getBalance', inAddress(address), inBlockNumber(blockNumber)) + .then(outNumber); + } + + getBlockByHash (hash, full = false) { + return this._transport + .execute('eth_getBlockByHash', inHex(hash), full) + .then(outBlock); + } + + getBlockByNumber (blockNumber = 'latest', full = false) { + return this._transport + .execute('eth_getBlockByNumber', inBlockNumber(blockNumber), full) + .then(outBlock); + } + + getBlockTransactionCountByHash (hash) { + return this._transport + .execute('eth_getBlockTransactionCountByHash', inHex(hash)) + .then(outNumber); + } + + getBlockTransactionCountByNumber (blockNumber = 'latest') { + return this._transport + .execute('eth_getBlockTransactionCountByNumber', inBlockNumber(blockNumber)) + .then(outNumber); + } + + getCode (address, blockNumber = 'latest') { + return this._transport + .execute('eth_getCode', inAddress(address), inBlockNumber(blockNumber)); + } + + getCompilers () { + return this._transport + .execute('eth_getCompilers'); + } + + getFilterChanges (filterId) { + return this._transport + .execute('eth_getFilterChanges', inNumber16(filterId)) + .then((logs) => logs.map(outLog)); + } + + getFilterChangesEx (filterId) { + return this._transport + .execute('eth_getFilterChangesEx', inNumber16(filterId)); + } + + getFilterLogs (filterId) { + return this._transport + .execute('eth_getFilterLogs', inNumber16(filterId)) + .then((logs) => logs.map(outLog)); + } + + getFilterLogsEx (filterId) { + return this._transport + .execute('eth_getFilterLogsEx', inNumber16(filterId)); + } + + getLogs (options) { + return this._transport + .execute('eth_getLogs', inFilter(options)); + } + + getLogsEx (options) { + return this._transport + .execute('eth_getLogsEx', inFilter(options)); + } + + getStorageAt (address, index = 0, blockNumber = 'latest') { + return this._transport + .execute('eth_getStorageAt', inAddress(address), inNumber16(index), inBlockNumber(blockNumber)); + } + + getTransactionByBlockHashAndIndex (hash, index = 0) { + return this._transport + .execute('eth_getTransactionByBlockHashAndIndex', inHex(hash), inNumber16(index)) + .then(outTransaction); + } + + getTransactionByBlockNumberAndIndex (blockNumber = 'latest', index = 0) { + return this._transport + .execute('eth_getTransactionByBlockNumberAndIndex', inBlockNumber(blockNumber), inNumber16(index)) + .then(outTransaction); + } + + getTransactionByHash (hash) { + return this._transport + .execute('eth_getTransactionByHash', inHex(hash)) + .then(outTransaction); + } + + getTransactionCount (address, blockNumber = 'latest') { + return this._transport + .execute('eth_getTransactionCount', inAddress(address), inBlockNumber(blockNumber)) + .then(outNumber); + } + + getTransactionReceipt (txhash) { + return this._transport + .execute('eth_getTransactionReceipt', inHex(txhash)) + .then(outReceipt); + } + + getUncleByBlockHashAndIndex (hash, index = 0) { + return this._transport + .execute('eth_getUncleByBlockHashAndIndex', inHex(hash), inNumber16(index)); + } + + getUncleByBlockNumberAndIndex (blockNumber = 'latest', index = 0) { + return this._transport + .execute('eth_getUncleByBlockNumberAndIndex', inBlockNumber(blockNumber), inNumber16(index)); + } + + getUncleCountByBlockHash (hash) { + return this._transport + .execute('eth_getUncleCountByBlockHash', inHex(hash)) + .then(outNumber); + } + + getUncleCountByBlockNumber (blockNumber = 'latest') { + return this._transport + .execute('eth_getUncleCountByBlockNumber', inBlockNumber(blockNumber)) + .then(outNumber); + } + + getWork () { + return this._transport + .execute('eth_getWork'); + } + + hashrate () { + return this._transport + .execute('eth_hashrate') + .then(outNumber); + } + + inspectTransaction () { + return this._transport + .execute('eth_inspectTransaction'); + } + + mining () { + return this._transport + .execute('eth_mining'); + } + + newBlockFilter () { + return this._transport + .execute('eth_newBlockFilter'); + } + + newFilter (options) { + return this._transport + .execute('eth_newFilter', inFilter(options)); + } + + newFilterEx (options) { + return this._transport + .execute('eth_newFilterEx', inFilter(options)); + } + + newPendingTransactionFilter () { + return this._transport + .execute('eth_newPendingTransactionFilter'); + } + + notePassword () { + return this._transport + .execute('eth_notePassword'); + } + + pendingTransactions () { + return this._transport + .execute('eth_pendingTransactions'); + } + + postTransaction (options) { + return this._transport + .execute('eth_postTransaction', inOptions(options)); + } + + protocolVersion () { + return this._transport + .execute('eth_protocolVersion'); + } + + register () { + return this._transport + .execute('eth_register'); + } + + sendRawTransaction (data) { + return this._transport + .execute('eth_sendRawTransaction', inData(data)); + } + + sendTransaction (options) { + return this._transport + .execute('eth_sendTransaction', inOptions(options)); + } + + sign (address, hash) { + return this._transport + .execute('eth_sign', inAddress(address), inHash(hash)); + } + + signTransaction () { + return this._transport + .execute('eth_signTransaction'); + } + + submitHashrate (hashrate, clientId) { + return this._transport + .execute('eth_submitHashrate', inNumber16(hashrate), clientId); + } + + submitWork (nonce, powHash, mixDigest) { + return this._transport + .execute('eth_submitWork', inNumber16(nonce), powHash, mixDigest); + } + + syncing () { + return this._transport + .execute('eth_syncing') + .then(outSyncing); + } + + uninstallFilter (filterId) { + return this._transport + .execute('eth_uninstallFilter', inHex(filterId)); + } + + unregister () { + return this._transport + .execute('eth_unregister'); + } +} diff --git a/js/src/api/rpc/eth/eth.spec.js b/js/src/api/rpc/eth/eth.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..65377db509bb2aa4b110789f628ad45a72ee60c9 --- /dev/null +++ b/js/src/api/rpc/eth/eth.spec.js @@ -0,0 +1,474 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; +import { isBigNumber } from '../../../../test/types'; + +import Http from '../../transport/http'; +import Eth from './eth'; + +const instance = new Eth(new Http(TEST_HTTP_URL)); + +describe('rpc/Eth', () => { + const address = '0x63Cf90D3f0410092FC0fca41846f596223979195'; + let scope; + + describe('accounts', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_accounts', reply: { result: [address.toLowerCase()] } }]); + }); + + it('returns a list of accounts, formatted', () => { + return instance.accounts().then((accounts) => { + expect(accounts).to.deep.equal([address]); + }); + }); + }); + + describe('blockNumber', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_blockNumber', reply: { result: '0x123456' } }]); + }); + + it('returns the current blockNumber, formatted', () => { + return instance.blockNumber().then((blockNumber) => { + expect(isBigNumber(blockNumber)).to.be.true; + expect(blockNumber.toString(16)).to.equal('123456'); + }); + }); + }); + + describe('call', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_call', reply: { result: [] } }]); + }); + + it('formats the input options & blockNumber', () => { + return instance.call({ data: '12345678' }, 'earliest').then(() => { + expect(scope.body.eth_call.params).to.deep.equal([{ data: '0x12345678' }, 'earliest']); + }); + }); + + it('provides a latest blockNumber when not specified', () => { + return instance.call({ data: '12345678' }).then(() => { + expect(scope.body.eth_call.params).to.deep.equal([{ data: '0x12345678' }, 'latest']); + }); + }); + }); + + describe('coinbase', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_coinbase', reply: { result: address.toLowerCase() } }]); + }); + + it('returns the coinbase, formatted', () => { + return instance.coinbase().then((account) => { + expect(account).to.deep.equal(address); + }); + }); + }); + + ['LLL', 'Serpent', 'Solidity'].forEach((type) => { + const method = `compile${type}`; + + describe(method, () => { + beforeEach(() => { + scope = mockHttp([{ method: `eth_${method}`, reply: { result: '0x123' } }]); + }); + + it('formats the input as data, returns the output', () => { + return instance[method]('0xabcdef').then((result) => { + expect(scope.body[`eth_${method}`].params).to.deep.equal(['0xabcdef']); + expect(result).to.equal('0x123'); + }); + }); + }); + }); + + describe('estimateGas', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_estimateGas', reply: { result: '0x123' } }]); + }); + + it('converts the options correctly', () => { + return instance.estimateGas({ gas: 21000 }).then(() => { + expect(scope.body.eth_estimateGas.params).to.deep.equal([{ gas: '0x5208' }]); + }); + }); + + it('returns the gas used', () => { + return instance.estimateGas({}).then((gas) => { + expect(isBigNumber(gas)).to.be.true; + expect(gas.toString(16)).to.deep.equal('123'); + }); + }); + }); + + describe('gasPrice', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_gasPrice', reply: { result: '0x123' } }]); + }); + + it('returns the fomratted price', () => { + return instance.gasPrice().then((price) => { + expect(isBigNumber(price)).to.be.true; + expect(price.toString(16)).to.deep.equal('123'); + }); + }); + }); + + describe('getBalance', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getBalance', reply: { result: '0x123' } }]); + }); + + it('passes in the address (default blockNumber)', () => { + return instance.getBalance(address).then(() => { + expect(scope.body.eth_getBalance.params).to.deep.equal([address.toLowerCase(), 'latest']); + }); + }); + + it('passes in the address & blockNumber', () => { + return instance.getBalance(address, 0x456).then(() => { + expect(scope.body.eth_getBalance.params).to.deep.equal([address.toLowerCase(), '0x456']); + }); + }); + + it('returns the balance', () => { + return instance.getBalance(address, 0x123).then((balance) => { + expect(isBigNumber(balance)).to.be.true; + expect(balance.toString(16)).to.deep.equal('123'); + }); + }); + }); + + describe('getBlockByHash', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getBlockByHash', reply: { result: { miner: address.toLowerCase() } } }]); + }); + + it('formats the input hash as a hash, default full', () => { + return instance.getBlockByHash('1234').then(() => { + expect(scope.body.eth_getBlockByHash.params).to.deep.equal(['0x1234', false]); + }); + }); + + it('formats the input hash as a hash, full true', () => { + return instance.getBlockByHash('1234', true).then(() => { + expect(scope.body.eth_getBlockByHash.params).to.deep.equal(['0x1234', true]); + }); + }); + + it('formats the output into block', () => { + return instance.getBlockByHash('1234').then((block) => { + expect(block.miner).to.equal(address); + }); + }); + }); + + describe('getBlockByNumber', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getBlockByNumber', reply: { result: { miner: address.toLowerCase() } } }]); + }); + + it('assumes blockNumber latest & full false', () => { + return instance.getBlockByNumber().then(() => { + expect(scope.body.eth_getBlockByNumber.params).to.deep.equal(['latest', false]); + }); + }); + + it('uses input blockNumber & full false', () => { + return instance.getBlockByNumber('0x1234').then(() => { + expect(scope.body.eth_getBlockByNumber.params).to.deep.equal(['0x1234', false]); + }); + }); + + it('formats the input blockNumber, full true', () => { + return instance.getBlockByNumber(0x1234, true).then(() => { + expect(scope.body.eth_getBlockByNumber.params).to.deep.equal(['0x1234', true]); + }); + }); + + it('formats the output into block', () => { + return instance.getBlockByNumber(0x1234).then((block) => { + expect(block.miner).to.equal(address); + }); + }); + }); + + describe('getBlockTransactionCountByHash', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getBlockTransactionCountByHash', reply: { result: '0x123' } }]); + }); + + it('formats input hash properly', () => { + return instance.getBlockTransactionCountByHash('abcdef').then(() => { + expect(scope.body.eth_getBlockTransactionCountByHash.params).to.deep.equal(['0xabcdef']); + }); + }); + + it('formats the output number', () => { + return instance.getBlockTransactionCountByHash('0x1234').then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.toString(16)).to.equal('123'); + }); + }); + }); + + describe('getBlockTransactionCountByNumber', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getBlockTransactionCountByNumber', reply: { result: '0x123' } }]); + }); + + it('specified blockNumber latest when none specified', () => { + return instance.getBlockTransactionCountByNumber().then(() => { + expect(scope.body.eth_getBlockTransactionCountByNumber.params).to.deep.equal(['latest']); + }); + }); + + it('formats input blockNumber properly', () => { + return instance.getBlockTransactionCountByNumber(0xabcdef).then(() => { + expect(scope.body.eth_getBlockTransactionCountByNumber.params).to.deep.equal(['0xabcdef']); + }); + }); + + it('formats the output number', () => { + return instance.getBlockTransactionCountByNumber('0x1234').then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.toString(16)).to.equal('123'); + }); + }); + }); + + describe('getCode', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getCode', reply: { result: '0x1234567890' } }]); + }); + + it('passes in the address (default blockNumber)', () => { + return instance.getCode(address).then(() => { + expect(scope.body.eth_getCode.params).to.deep.equal([address.toLowerCase(), 'latest']); + }); + }); + + it('passes in the address & blockNumber', () => { + return instance.getCode(address, 0x456).then(() => { + expect(scope.body.eth_getCode.params).to.deep.equal([address.toLowerCase(), '0x456']); + }); + }); + + it('returns the code', () => { + return instance.getCode(address, 0x123).then((code) => { + expect(code).to.equal('0x1234567890'); + }); + }); + }); + + describe('getStorageAt', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getStorageAt', reply: { result: '0x1234567890' } }]); + }); + + it('passes in the address (default index& blockNumber)', () => { + return instance.getStorageAt(address).then(() => { + expect(scope.body.eth_getStorageAt.params).to.deep.equal([address.toLowerCase(), '0x0', 'latest']); + }); + }); + + it('passes in the address, index & blockNumber', () => { + return instance.getStorageAt(address, 15, 0x456).then(() => { + expect(scope.body.eth_getStorageAt.params).to.deep.equal([address.toLowerCase(), '0xf', '0x456']); + }); + }); + + it('returns the storage', () => { + return instance.getStorageAt(address, 0x123).then((storage) => { + expect(storage).to.equal('0x1234567890'); + }); + }); + }); + + describe('getTransactionByBlockHashAndIndex', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getTransactionByBlockHashAndIndex', reply: { result: { to: address.toLowerCase() } } }]); + }); + + it('passes in the hash (default index)', () => { + return instance.getTransactionByBlockHashAndIndex('12345').then(() => { + expect(scope.body.eth_getTransactionByBlockHashAndIndex.params).to.deep.equal(['0x12345', '0x0']); + }); + }); + + it('passes in the hash & specified index', () => { + return instance.getTransactionByBlockHashAndIndex('6789', 0x456).then(() => { + expect(scope.body.eth_getTransactionByBlockHashAndIndex.params).to.deep.equal(['0x6789', '0x456']); + }); + }); + + it('returns the formatted transaction', () => { + return instance.getTransactionByBlockHashAndIndex('6789', 0x123).then((tx) => { + expect(tx).to.deep.equal({ to: address }); + }); + }); + }); + + describe('getTransactionByBlockNumberAndIndex', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getTransactionByBlockNumberAndIndex', reply: { result: { to: address.toLowerCase() } } }]); + }); + + it('passes in the default parameters', () => { + return instance.getTransactionByBlockNumberAndIndex().then(() => { + expect(scope.body.eth_getTransactionByBlockNumberAndIndex.params).to.deep.equal(['latest', '0x0']); + }); + }); + + it('passes in the blockNumber & specified index', () => { + return instance.getTransactionByBlockNumberAndIndex('0x6789', 0x456).then(() => { + expect(scope.body.eth_getTransactionByBlockNumberAndIndex.params).to.deep.equal(['0x6789', '0x456']); + }); + }); + + it('returns the formatted transaction', () => { + return instance.getTransactionByBlockNumberAndIndex('0x6789', 0x123).then((tx) => { + expect(tx).to.deep.equal({ to: address }); + }); + }); + }); + + describe('getTransactionByHash', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getTransactionByHash', reply: { result: { to: address.toLowerCase() } } }]); + }); + + it('passes in the hash', () => { + return instance.getTransactionByHash('12345').then(() => { + expect(scope.body.eth_getTransactionByHash.params).to.deep.equal(['0x12345']); + }); + }); + + it('returns the formatted transaction', () => { + return instance.getTransactionByHash('6789').then((tx) => { + expect(tx).to.deep.equal({ to: address }); + }); + }); + }); + + describe('getTransactionCount', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getTransactionCount', reply: { result: '0x123' } }]); + }); + + it('passes in the address (default blockNumber)', () => { + return instance.getTransactionCount(address).then(() => { + expect(scope.body.eth_getTransactionCount.params).to.deep.equal([address.toLowerCase(), 'latest']); + }); + }); + + it('passes in the address & blockNumber', () => { + return instance.getTransactionCount(address, 0x456).then(() => { + expect(scope.body.eth_getTransactionCount.params).to.deep.equal([address.toLowerCase(), '0x456']); + }); + }); + + it('returns the count, formatted', () => { + return instance.getTransactionCount(address, 0x123).then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.toString(16)).to.equal('123'); + }); + }); + }); + + describe('getUncleByBlockHashAndIndex', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getUncleByBlockHashAndIndex', reply: { result: [] } }]); + }); + + it('passes in the hash (default index)', () => { + return instance.getUncleByBlockHashAndIndex('12345').then(() => { + expect(scope.body.eth_getUncleByBlockHashAndIndex.params).to.deep.equal(['0x12345', '0x0']); + }); + }); + + it('passes in the hash & specified index', () => { + return instance.getUncleByBlockHashAndIndex('6789', 0x456).then(() => { + expect(scope.body.eth_getUncleByBlockHashAndIndex.params).to.deep.equal(['0x6789', '0x456']); + }); + }); + }); + + describe('getUncleByBlockNumberAndIndex', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getUncleByBlockNumberAndIndex', reply: { result: [] } }]); + }); + + it('passes in the default parameters', () => { + return instance.getUncleByBlockNumberAndIndex().then(() => { + expect(scope.body.eth_getUncleByBlockNumberAndIndex.params).to.deep.equal(['latest', '0x0']); + }); + }); + + it('passes in the blockNumber & specified index', () => { + return instance.getUncleByBlockNumberAndIndex('0x6789', 0x456).then(() => { + expect(scope.body.eth_getUncleByBlockNumberAndIndex.params).to.deep.equal(['0x6789', '0x456']); + }); + }); + }); + + describe('getUncleCountByBlockHash', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getUncleCountByBlockHash', reply: { result: '0x123' } }]); + }); + + it('passes in the hash', () => { + return instance.getUncleCountByBlockHash('12345').then(() => { + expect(scope.body.eth_getUncleCountByBlockHash.params).to.deep.equal(['0x12345']); + }); + }); + + it('formats the output number', () => { + return instance.getUncleCountByBlockHash('0x1234').then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.toString(16)).to.equal('123'); + }); + }); + }); + + describe('getUncleCountByBlockNumber', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'eth_getUncleCountByBlockNumber', reply: { result: '0x123' } }]); + }); + + it('passes in the default parameters', () => { + return instance.getUncleCountByBlockNumber().then(() => { + expect(scope.body.eth_getUncleCountByBlockNumber.params).to.deep.equal(['latest']); + }); + }); + + it('passes in the blockNumber', () => { + return instance.getUncleCountByBlockNumber('0x6789').then(() => { + expect(scope.body.eth_getUncleCountByBlockNumber.params).to.deep.equal(['0x6789']); + }); + }); + + it('formats the output number', () => { + return instance.getUncleCountByBlockNumber('0x1234').then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.toString(16)).to.equal('123'); + }); + }); + }); +}); diff --git a/js/src/api/rpc/eth/index.js b/js/src/api/rpc/eth/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0d0e8c5570c4b47dbce72d33d55d0df349f59012 --- /dev/null +++ b/js/src/api/rpc/eth/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './eth'; diff --git a/js/src/api/rpc/ethcore/ethcore.e2e.js b/js/src/api/rpc/ethcore/ethcore.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..aae7108e7f10d09e1d256c4eff38062d51a673aa --- /dev/null +++ b/js/src/api/rpc/ethcore/ethcore.e2e.js @@ -0,0 +1,71 @@ +// 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 { createHttpApi } from '../../../../test/e2e/ethapi'; + +describe('ethapi.ethcore', () => { + const ethapi = createHttpApi(); + + describe('gasFloorTarget', () => { + it('returns and translates the target', () => { + return ethapi.ethcore.gasFloorTarget().then((value) => { + expect(value.gt(0)).to.be.true; + }); + }); + }); + + describe('gasPriceHistogram', () => { + it('returns and translates the target', () => { + return ethapi.ethcore.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; + }); + }); + }); + + describe('netChain', () => { + it('returns and the chain', () => { + return ethapi.ethcore.netChain().then((value) => { + expect(value).to.equal('morden'); + }); + }); + }); + + describe('netPort', () => { + it('returns and translates the port', () => { + return ethapi.ethcore.netPort().then((value) => { + expect(value.gt(0)).to.be.true; + }); + }); + }); + + describe('transactionsLimit', () => { + it('returns and translates the limit', () => { + return ethapi.ethcore.transactionsLimit().then((value) => { + expect(value.gt(0)).to.be.true; + }); + }); + }); + + describe('rpcSettings', () => { + it('returns and translates the settings', () => { + return ethapi.ethcore.rpcSettings().then((value) => { + expect(value).to.be.ok; + }); + }); + }); +}); diff --git a/js/src/api/rpc/ethcore/ethcore.js b/js/src/api/rpc/ethcore/ethcore.js new file mode 100644 index 0000000000000000000000000000000000000000..663143f0d0ba6805fdd4a2eb49f7f6897f69f7f0 --- /dev/null +++ b/js/src/api/rpc/ethcore/ethcore.js @@ -0,0 +1,196 @@ +// 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/ethcore/ethcore.spec.js b/js/src/api/rpc/ethcore/ethcore.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..fd34550a71ec454b95ef58bc9080954afcb8bb7b --- /dev/null +++ b/js/src/api/rpc/ethcore/ethcore.spec.js @@ -0,0 +1,92 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; +import { isBigNumber } from '../../../../test/types'; + +import Http from '../../transport/http'; +import Ethcore from './ethcore'; + +const instance = new Ethcore(new Http(TEST_HTTP_URL)); + +describe('api/rpc/Ethcore', () => { + describe('gasFloorTarget', () => { + it('returns the gasfloor, formatted', () => { + mockHttp([{ method: 'ethcore_gasFloorTarget', reply: { result: '0x123456' } }]); + + return instance.gasFloorTarget().then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.eq(0x123456)).to.be.true; + }); + }); + }); + + describe('minGasPrice', () => { + it('returns the min gasprice, formatted', () => { + mockHttp([{ method: 'ethcore_minGasPrice', reply: { result: '0x123456' } }]); + + return instance.minGasPrice().then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.eq(0x123456)).to.be.true; + }); + }); + }); + + describe('netMaxPeers', () => { + it('returns the max peers, formatted', () => { + mockHttp([{ method: 'ethcore_netMaxPeers', reply: { result: 25 } }]); + + return instance.netMaxPeers().then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.eq(25)).to.be.true; + }); + }); + }); + + describe('newPeers', () => { + it('returns the peer structure, formatted', () => { + mockHttp([{ method: 'ethcore_netPeers', reply: { result: { active: 123, connected: 456, max: 789 } } }]); + + return instance.netPeers().then((peers) => { + expect(peers.active.eq(123)).to.be.true; + expect(peers.connected.eq(456)).to.be.true; + expect(peers.max.eq(789)).to.be.true; + }); + }); + }); + + describe('netPort', () => { + it('returns the connected port, formatted', () => { + mockHttp([{ method: 'ethcore_netPort', reply: { result: 33030 } }]); + + return instance.netPort().then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.eq(33030)).to.be.true; + }); + }); + }); + + describe('transactionsLimit', () => { + it('returns the tx limit, formatted', () => { + mockHttp([{ method: 'ethcore_transactionsLimit', reply: { result: 1024 } }]); + + return instance.transactionsLimit().then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.eq(1024)).to.be.true; + }); + }); + }); +}); diff --git a/js/src/api/rpc/ethcore/index.js b/js/src/api/rpc/ethcore/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2372a21715bb7f6fdf3603aa5230000399ce520d --- /dev/null +++ b/js/src/api/rpc/ethcore/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './ethcore'; diff --git a/js/src/api/rpc/index.js b/js/src/api/rpc/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e7e94b9edba0712f808a21fcd5e51f1f5a1ba139 --- /dev/null +++ b/js/src/api/rpc/index.js @@ -0,0 +1,24 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export Db from './db'; +export Eth from './eth'; +export Ethcore from './ethcore'; +export Net from './net'; +export Personal from './personal'; +export Shh from './shh'; +export Trace from './trace'; +export Web3 from './web3'; diff --git a/js/src/api/rpc/net/index.js b/js/src/api/rpc/net/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0739111e6af6df00b8dbd7b89f9c48f588e244ee --- /dev/null +++ b/js/src/api/rpc/net/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './net'; diff --git a/js/src/api/rpc/net/net.e2e.js b/js/src/api/rpc/net/net.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..51d84f7a107a89df8c11795564b5575aa482acee --- /dev/null +++ b/js/src/api/rpc/net/net.e2e.js @@ -0,0 +1,46 @@ +// 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 { createHttpApi } from '../../../../test/e2e/ethapi'; +import { isBoolean } from '../../../../test/types'; + +describe('ethapi.net', () => { + const ethapi = createHttpApi(); + + describe('listening', () => { + it('returns the listening status', () => { + return ethapi.net.listening().then((status) => { + expect(isBoolean(status)).to.be.true; + }); + }); + }); + + describe('peerCount', () => { + it('returns the peer count', () => { + return ethapi.net.peerCount().then((count) => { + expect(count.gte(0)).to.be.true; + }); + }); + }); + + describe('version', () => { + it('returns the version', () => { + return ethapi.net.version().then((version) => { + expect(version).to.be.ok; + }); + }); + }); +}); diff --git a/js/src/api/rpc/net/net.js b/js/src/api/rpc/net/net.js new file mode 100644 index 0000000000000000000000000000000000000000..96e99dc51f2bde7db4eeff3f1fbda7136a069372 --- /dev/null +++ b/js/src/api/rpc/net/net.js @@ -0,0 +1,39 @@ +// 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 { outNumber } from '../../format/output'; + +export default class Net { + constructor (transport) { + this._transport = transport; + } + + listening () { + return this._transport + .execute('net_listening'); + } + + peerCount () { + return this._transport + .execute('net_peerCount') + .then(outNumber); + } + + version () { + return this._transport + .execute('net_version'); + } +} diff --git a/js/src/api/rpc/net/net.spec.js b/js/src/api/rpc/net/net.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..55029a29ef7cfe4baa8ba98cb5636d891071917d --- /dev/null +++ b/js/src/api/rpc/net/net.spec.js @@ -0,0 +1,36 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; +import { isBigNumber } from '../../../../test/types'; + +import Http from '../../transport/http'; +import Net from './net'; + +const instance = new Net(new Http(TEST_HTTP_URL)); + +describe('api/rpc/Net', () => { + describe('peerCount', () => { + it('returns the connected peers, formatted', () => { + mockHttp([{ method: 'net_peerCount', reply: { result: '0x123456' } }]); + + return instance.peerCount().then((count) => { + expect(isBigNumber(count)).to.be.true; + expect(count.eq(0x123456)).to.be.true; + }); + }); + }); +}); diff --git a/js/src/api/rpc/personal/index.js b/js/src/api/rpc/personal/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a9ed260f25591d31b3ddc26e993774f7c068fc85 --- /dev/null +++ b/js/src/api/rpc/personal/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './personal'; diff --git a/js/src/api/rpc/personal/personal.e2e.js b/js/src/api/rpc/personal/personal.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..f7fe42c54b967ffb89cd1092313fd26c3f3723fb --- /dev/null +++ b/js/src/api/rpc/personal/personal.e2e.js @@ -0,0 +1,53 @@ +// 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 { createHttpApi } from '../../../../test/e2e/ethapi'; +import { isAddress, isBoolean } from '../../../../test/types'; + +describe.skip('ethapi.personal', () => { + const ethapi = createHttpApi(); + const password = 'P@55word'; + let address; + + describe('newAccount', () => { + it('creates a new account', () => { + return ethapi.personal.newAccount(password).then((_address) => { + address = _address; + expect(isAddress(address)).to.be.ok; + }); + }); + }); + + describe('listAccounts', () => { + it('has the newly-created account', () => { + return ethapi.personal.listAccounts(password).then((accounts) => { + expect(accounts.filter((_address) => _address === address)).to.deep.equal([address]); + accounts.forEach((account) => { + expect(isAddress(account)).to.be.true; + }); + }); + }); + }); + + describe('unlockAccount', () => { + it('unlocks the newly-created account', () => { + return ethapi.personal.unlockAccount(address, password).then((result) => { + expect(isBoolean(result)).to.be.true; + expect(result).to.be.true; + }); + }); + }); +}); diff --git a/js/src/api/rpc/personal/personal.js b/js/src/api/rpc/personal/personal.js new file mode 100644 index 0000000000000000000000000000000000000000..ca7dbce9b95439fba42e6ccd5e5f8d09f19dca58 --- /dev/null +++ b/js/src/api/rpc/personal/personal.js @@ -0,0 +1,128 @@ +// 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, inHex, inNumber10, inNumber16, inOptions } from '../../format/input'; +import { outAccountInfo, outAddress, outSignerRequest } 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 new file mode 100644 index 0000000000000000000000000000000000000000..70734c7ee3ec154eacc23a3703c12bcc71e50d27 --- /dev/null +++ b/js/src/api/rpc/personal/personal.spec.js @@ -0,0 +1,97 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; + +import Http from '../../transport/http'; +import Personal from './personal'; + +const instance = new Personal(new Http(TEST_HTTP_URL)); + +describe('rpc/Personal', () => { + const account = '0x63cf90d3f0410092fc0fca41846f596223979195'; + 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] } }]); + + return instance.listAccounts().then((result) => { + expect(result).to.deep.equal([checksum]); + }); + }); + + it('returns an empty list when none available', () => { + scope = mockHttp([{ method: 'personal_listAccounts', reply: { result: null } }]); + + return instance.listAccounts().then((result) => { + expect(result).to.deep.equal([]); + }); + }); + }); + + describe('newAccount', () => { + it('passes the password, returning the address', () => { + scope = mockHttp([{ method: 'personal_newAccount', reply: { result: account } }]); + + return instance.newAccount('password').then((result) => { + expect(scope.body.personal_newAccount.params).to.deep.equal(['password']); + expect(result).to.equal(checksum); + }); + }); + }); + + describe('unlockAccount', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'personal_unlockAccount', reply: { result: [] } }]); + }); + + it('passes account, password & duration', () => { + return instance.unlockAccount(account, 'password', 0xf).then(() => { + expect(scope.body.personal_unlockAccount.params).to.deep.equal([account, 'password', 15]); + }); + }); + + it('provides a default duration when not specified', () => { + return instance.unlockAccount(account, 'password').then(() => { + expect(scope.body.personal_unlockAccount.params).to.deep.equal([account, 'password', 1]); + }); + }); + }); +}); diff --git a/js/src/api/rpc/shh/index.js b/js/src/api/rpc/shh/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7b323aeed692dfa6fbf9b8889a7c815067616e29 --- /dev/null +++ b/js/src/api/rpc/shh/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './shh'; diff --git a/js/src/api/rpc/shh/shh.js b/js/src/api/rpc/shh/shh.js new file mode 100644 index 0000000000000000000000000000000000000000..ad545cac5989d8143ce2befa755749b95a9cea44 --- /dev/null +++ b/js/src/api/rpc/shh/shh.js @@ -0,0 +1,71 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class Personal { + constructor (transport) { + this._transport = transport; + } + + addToGroup (identity) { + return this._transport + .execute('shh_addToGroup', identity); + } + + getFilterChanges (filterId) { + return this._transport + .execute('shh_getFilterChanges', filterId); + } + + getMessages (filterId) { + return this._transport + .execute('shh_getMessages', filterId); + } + + hasIdentity (identity) { + return this._transport + .execute('shh_hasIdentity', identity); + } + + newFilter (options) { + return this._transport + .execute('shh_newFilter', options); + } + + newGroup () { + return this._transport + .execute('shh_newGroup'); + } + + newIdentity () { + return this._transport + .execute('shh_newIdentity'); + } + + post (options) { + return this._transport + .execute('shh_post', options); + } + + uninstallFilter (filterId) { + return this._transport + .execute('shh_uninstallFilter', filterId); + } + + version () { + return this._transport + .execute('shh_version'); + } +} diff --git a/js/src/api/rpc/trace/index.js b/js/src/api/rpc/trace/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a1408770931575966faf6426033be647b910d40d --- /dev/null +++ b/js/src/api/rpc/trace/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './trace'; diff --git a/js/src/api/rpc/trace/trace.e2e.js b/js/src/api/rpc/trace/trace.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..1a0720927ad2725227cf469fb87f384209a05754 --- /dev/null +++ b/js/src/api/rpc/trace/trace.e2e.js @@ -0,0 +1,35 @@ +// 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 { createHttpApi } from '../../../../test/e2e/ethapi'; + +describe('ethapi.trace', () => { + const ethapi = createHttpApi(); + + describe('block', () => { + it('returns the latest block', () => { + return ethapi.trace.block().then((block) => { + expect(block).to.be.ok; + }); + }); + + it('returns a specified block', () => { + return ethapi.trace.block('0x65432').then((block) => { + expect(block).to.be.ok; + }); + }); + }); +}); diff --git a/js/src/api/rpc/trace/trace.js b/js/src/api/rpc/trace/trace.js new file mode 100644 index 0000000000000000000000000000000000000000..95fed42307d9acc4116b2b0e362e0697f72982b5 --- /dev/null +++ b/js/src/api/rpc/trace/trace.js @@ -0,0 +1,48 @@ +// 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 { inBlockNumber, inHex, inNumber16, inTraceFilter } from '../../format/input'; +import { outTrace } from '../../format/output'; + +export default class Trace { + constructor (transport) { + this._transport = transport; + } + + filter (filterObj) { + return this._transport + .execute('trace_filter', inTraceFilter(filterObj)) + .then(traces => traces.map(trace => outTrace(trace))); + } + + get (txHash, position) { + return this._transport + .execute('trace_get', inHex(txHash), inNumber16(position)) + .then(trace => outTrace(trace)); + } + + transaction (txHash) { + return this._transport + .execute('trace_transaction', inHex(txHash)) + .then(traces => traces.map(trace => outTrace(trace))); + } + + block (blockNumber = 'latest') { + return this._transport + .execute('trace_block', inBlockNumber(blockNumber)) + .then(traces => traces.map(trace => outTrace(trace))); + } +} diff --git a/js/src/api/rpc/trace/trace.spec.js b/js/src/api/rpc/trace/trace.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4a38f7a3f718000af1b01d6ce918e86c34081e40 --- /dev/null +++ b/js/src/api/rpc/trace/trace.spec.js @@ -0,0 +1,44 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; + +import Http from '../../transport/http'; +import Trace from './trace'; + +const instance = new Trace(new Http(TEST_HTTP_URL)); + +describe('api/rpc/Trace', () => { + let scope; + + describe('block', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'trace_block', reply: { result: [] } }]); + }); + + it('assumes latest blockNumber when not specified', () => { + return instance.block().then(() => { + expect(scope.body.trace_block.params).to.deep.equal(['latest']); + }); + }); + + it('passed specified blockNumber', () => { + return instance.block(0x123).then(() => { + expect(scope.body.trace_block.params).to.deep.equal(['0x123']); + }); + }); + }); +}); diff --git a/js/src/api/rpc/web3/index.js b/js/src/api/rpc/web3/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d0bb22941d56524483d0cb4f27af18179ddaaa87 --- /dev/null +++ b/js/src/api/rpc/web3/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './web3'; diff --git a/js/src/api/rpc/web3/web3.e2e.js b/js/src/api/rpc/web3/web3.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..15cc1934fbfb19905b8b5764097c843a79e41666 --- /dev/null +++ b/js/src/api/rpc/web3/web3.e2e.js @@ -0,0 +1,44 @@ +// 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 { createHttpApi } from '../../../../test/e2e/ethapi'; +import { isHexNumber } from '../../../../test/types'; + +describe('ethapi.web3', () => { + const ethapi = createHttpApi(); + + describe('clientVersion', () => { + it('returns the client version', () => { + return ethapi.web3.clientVersion().then((version) => { + const [client] = version.split('/'); + + expect(client === 'Parity' || client === 'Geth').to.be.ok; + }); + }); + }); + + describe('sha3', () => { + it('returns a keccak256 sha', () => { + const sha = '0xa7916fac4f538170f7cd12c148552e2cba9fcd72329a2dd5b07a6fa906488ddf'; + const hexStr = 'baz()'.split('').map((char) => char.charCodeAt(0).toString(16)).join(''); + + return ethapi.web3.sha3(`0x${hexStr}`).then((hash) => { + expect(isHexNumber(hash)).to.be.true; + expect(hash).to.equal(sha); + }); + }); + }); +}); diff --git a/js/src/api/rpc/web3/web3.js b/js/src/api/rpc/web3/web3.js new file mode 100644 index 0000000000000000000000000000000000000000..eb52a8bb72a61f030f0b5d7bfd76f5e33e0bfc3f --- /dev/null +++ b/js/src/api/rpc/web3/web3.js @@ -0,0 +1,33 @@ +// 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 { inHex } from '../../format/input'; + +export default class Web3 { + constructor (transport) { + this._transport = transport; + } + + clientVersion () { + return this._transport + .execute('web3_clientVersion'); + } + + sha3 (hexStr) { + return this._transport + .execute('web3_sha3', inHex(hexStr)); + } +} diff --git a/js/src/api/rpc/web3/web3.spec.js b/js/src/api/rpc/web3/web3.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..eb4a59cd1636ee7a8059cb5d2a9f0ad328b5cab6 --- /dev/null +++ b/js/src/api/rpc/web3/web3.spec.js @@ -0,0 +1,38 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; + +import Http from '../../transport/http'; +import Web3 from './web3'; + +const instance = new Web3(new Http(TEST_HTTP_URL)); + +describe('api/rpc/Web3', () => { + let scope; + + describe('sha3', () => { + beforeEach(() => { + scope = mockHttp([{ method: 'web3_sha3', reply: { result: [] } }]); + }); + + it('formats the inputs correctly', () => { + return instance.sha3('1234').then(() => { + expect(scope.body.web3_sha3.params).to.deep.equal(['0x1234']); + }); + }); + }); +}); diff --git a/js/src/api/subscriptions/eth.js b/js/src/api/subscriptions/eth.js new file mode 100644 index 0000000000000000000000000000000000000000..28d9cc6ff995af0c5491fc939a2ad42e020ad9b8 --- /dev/null +++ b/js/src/api/subscriptions/eth.js @@ -0,0 +1,62 @@ +// 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 BigNumber from 'bignumber.js'; + +export default class Eth { + constructor (updateSubscriptions, api) { + this._api = api; + this._updateSubscriptions = updateSubscriptions; + this._started = false; + + this._lastBlock = new BigNumber(-1); + } + + get isStarted () { + return this._started; + } + + start () { + this._started = true; + + return this._blockNumber(); + } + + _blockNumber = () => { + const nextTimeout = (timeout = 1000) => { + setTimeout(() => { + this._blockNumber(); + }, timeout); + }; + + if (!this._api.transport.isConnected) { + nextTimeout(500); + return; + } + + return this._api.eth + .blockNumber() + .then((blockNumber) => { + if (!blockNumber.eq(this._lastBlock)) { + this._lastBlock = blockNumber; + this._updateSubscriptions('eth_blockNumber', null, blockNumber); + } + + nextTimeout(); + }) + .catch(nextTimeout); + } +} diff --git a/js/src/api/subscriptions/eth.spec.js b/js/src/api/subscriptions/eth.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..24398483e46013d3cec7c420dee536fd3f8f9ebb --- /dev/null +++ b/js/src/api/subscriptions/eth.spec.js @@ -0,0 +1,101 @@ +// 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 BigNumber from 'bignumber.js'; +import sinon from 'sinon'; +import 'sinon-as-promised'; + +import Eth from './eth'; + +const START_BLOCK = 5000; + +function stubApi (blockNumber) { + const _calls = { + blockNumber: [] + }; + + return { + _calls, + transport: { + isConnected: true + }, + eth: { + blockNumber: () => { + const stub = sinon.stub().resolves(new BigNumber(blockNumber || START_BLOCK))(); + _calls.blockNumber.push(stub); + return stub; + } + } + }; +} + +describe('api/subscriptions/eth', () => { + let api; + let eth; + let cb; + + beforeEach(() => { + api = stubApi(); + cb = sinon.stub(); + eth = new Eth(cb, api); + }); + + describe('constructor', () => { + it('starts the instance in a stopped state', () => { + expect(eth.isStarted).to.be.false; + }); + }); + + describe('start', () => { + describe('blockNumber available', () => { + beforeEach(() => { + return eth.start(); + }); + + it('sets the started status', () => { + expect(eth.isStarted).to.be.true; + }); + + it('calls eth_blockNumber', () => { + expect(api._calls.blockNumber.length).to.be.ok; + }); + + it('updates subscribers', () => { + expect(cb).to.have.been.calledWith('eth_blockNumber', null, new BigNumber(START_BLOCK)); + }); + }); + + describe('blockNumber not available', () => { + beforeEach(() => { + api = stubApi(-1); + eth = new Eth(cb, api); + return eth.start(); + }); + + it('sets the started status', () => { + expect(eth.isStarted).to.be.true; + }); + + it('calls eth_blockNumber', () => { + expect(api._calls.blockNumber.length).to.be.ok; + }); + + it('does not update subscribers', () => { + expect(cb).not.to.been.called; + }); + }); + }); +}); diff --git a/js/src/api/subscriptions/index.js b/js/src/api/subscriptions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3e627e62a1efff2ea2d38aa24e131a234cc28ec5 --- /dev/null +++ b/js/src/api/subscriptions/index.js @@ -0,0 +1,19 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export Logging from './logging'; + +export default from './manager'; diff --git a/js/src/api/subscriptions/logging.js b/js/src/api/subscriptions/logging.js new file mode 100644 index 0000000000000000000000000000000000000000..b03558207f3f17f845cd4c6247fa2bb36d725055 --- /dev/null +++ b/js/src/api/subscriptions/logging.js @@ -0,0 +1,44 @@ +// 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 . + +let instance = null; + +export default class Logging { + constructor (updateSubscriptions) { + this._updateSubscriptions = updateSubscriptions; + + instance = this; + } + + get isStarted () { + return true; + } + + start () { + } + + static send (method, params, json) { + if (!instance) { + return; + } + + return instance._updateSubscriptions('logging', null, { + method, + params, + json + }); + } +} diff --git a/js/src/api/subscriptions/logging.spec.js b/js/src/api/subscriptions/logging.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..2a1cabb46c9862603b3ae3065e9ac6ef1e35a887 --- /dev/null +++ b/js/src/api/subscriptions/logging.spec.js @@ -0,0 +1,49 @@ +// 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 sinon from 'sinon'; + +import Logging from './logging'; + +describe('api/subscriptions/logging', () => { + let cb; + let logging; + + beforeEach(() => { + cb = sinon.stub(); + logging = new Logging(cb); + }); + + describe('constructor', () => { + it('starts the instance in a started state', () => { + expect(logging.isStarted).to.be.true; + }); + }); + + describe('send', () => { + const method = 'method'; + const params = 'params'; + const json = 'json'; + + beforeEach(() => { + Logging.send(method, params, json); + }); + + it('calls the subscription update', () => { + expect(cb).to.have.been.calledWith('logging', null, { method, params, json }); + }); + }); +}); diff --git a/js/src/api/subscriptions/manager.js b/js/src/api/subscriptions/manager.js new file mode 100644 index 0000000000000000000000000000000000000000..61e06499eff7ae927b84e7b59dc465c054da5f1e --- /dev/null +++ b/js/src/api/subscriptions/manager.js @@ -0,0 +1,129 @@ +// 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 { isError } from '../util/types'; + +import Eth from './eth'; +import Logging from './logging'; +import Personal from './personal'; +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' } +}; + +export default class Manager { + constructor (api) { + this._api = api; + + this.subscriptions = []; + this.values = {}; + + Object.keys(events).forEach((subscriptionName) => { + this.values[subscriptionName] = { + error: null, + data: null + }; + }); + + this._logging = new Logging(this._updateSubscriptions); + this._eth = new Eth(this._updateSubscriptions, api); + this._personal = new Personal(this._updateSubscriptions, api, this); + this._signer = new Signer(this._updateSubscriptions, api, this); + } + + _validateType (subscriptionName) { + const subscription = events[subscriptionName]; + + if (!subscription) { + return new Error(`${subscriptionName} is not a valid interface, subscribe using one of ${Object.keys(events).join(', ')}`); + } + + return subscription; + } + + subscribe (subscriptionName, callback) { + return new Promise((resolve, reject) => { + const subscription = this._validateType(subscriptionName); + + if (isError(subscription)) { + reject(subscription); + return; + } + + const subscriptionId = this.subscriptions.length; + const { error, data } = this.values[subscriptionName]; + const engine = this[`_${subscription.module}`]; + + this.subscriptions[subscriptionId] = { + name: subscriptionName, + id: subscriptionId, + callback + }; + + if (!engine.isStarted) { + engine.start(); + } else { + this._sendData(subscriptionId, error, data); + } + + resolve(subscriptionId); + }); + } + + unsubscribe (subscriptionId) { + return new Promise((resolve, reject) => { + if (!this.subscriptions[subscriptionId]) { + reject(new Error(`Cannot find subscription ${subscriptionId}`)); + return; + } + + delete this.subscriptions[subscriptionId]; + resolve(); + }); + } + + _sendData (subscriptionId, error, data) { + const { callback } = this.subscriptions[subscriptionId]; + + try { + callback(error, data); + } catch (error) { + console.error(`Unable to update callback for subscriptionId ${subscriptionId}`, error); + this.unsubscribe(subscriptionId); + } + } + + _updateSubscriptions = (subscriptionName, error, data) => { + const subscriptions = this.subscriptions + .filter(subscription => subscription.name === subscriptionName); + + this.values[subscriptionName] = { error, data }; + + subscriptions + .forEach((subscription) => { + this._sendData(subscription.id, error, data); + }); + } +} + +export { + events +}; diff --git a/js/src/api/subscriptions/manager.spec.js b/js/src/api/subscriptions/manager.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5e434efec4eabc80649267d5b3663cfb3101f5c7 --- /dev/null +++ b/js/src/api/subscriptions/manager.spec.js @@ -0,0 +1,134 @@ +// 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 sinon from 'sinon'; + +import Manager, { events } from './manager'; + +function newStub () { + const start = () => manager._updateSubscriptions(manager.__test, null, 'test'); + + const manager = new Manager({ + transport: { + isConnected: true + } + }); + + manager._eth = { + isStarted: false, + start + }; + + manager._personal = { + isStarted: false, + start + }; + + manager._signer = { + isStarted: false, + start + }; + + return manager; +} + +describe('api/subscriptions/manager', () => { + let manager; + + beforeEach(() => { + manager = newStub(); + }); + + describe('constructor', () => { + it('sets up the subscription types & defaults', () => { + expect(manager.subscriptions).to.be.an.array; + expect(Object.keys(manager.values)).to.deep.equal(Object.keys(events)); + }); + }); + + describe('subscriptions', () => { + Object + .keys(events) + .filter((eventName) => eventName.indexOf('_') !== -1) + .forEach((eventName) => { + const { module } = events[eventName]; + let engine; + let cb; + let subscriptionId; + + describe(eventName, () => { + beforeEach(() => { + engine = manager[`_${module}`]; + manager.__test = eventName; + cb = sinon.stub(); + sinon.spy(engine, 'start'); + + return manager + .subscribe(eventName, cb) + .then((_subscriptionId) => { + subscriptionId = _subscriptionId; + }); + }); + + it(`puts the ${module} engine in a started state`, () => { + expect(engine.start).to.have.been.called; + }); + + it('returns a subscriptionId', () => { + expect(subscriptionId).to.be.a.number; + }); + + it('calls the subscription callback with updated values', () => { + expect(cb).to.have.been.calledWith(null, 'test'); + }); + }); + }); + }); + + describe('unsubscriptions', () => { + Object + .keys(events) + .filter((eventName) => eventName.indexOf('_') !== -1) + .forEach((eventName) => { + const { module } = events[eventName]; + let engine; + let cb; + + describe(eventName, () => { + beforeEach(() => { + engine = manager[`_${module}`]; + manager.__test = eventName; + cb = sinon.stub(); + sinon.spy(engine, 'start'); + + return manager + .subscribe(eventName, cb) + .then((_subscriptionId) => { + manager.unsubscribe(_subscriptionId); + }) + .then(() => { + manager._updateSubscriptions(manager.__test, null, 'test2'); + }); + }); + + it('does not call the callback after unsibscription', () => { + expect(cb).to.have.been.calledWith(null, 'test'); + expect(cb).to.not.have.been.calledWith(null, 'test2'); + }); + }); + }); + }); +}); diff --git a/js/src/api/subscriptions/personal.js b/js/src/api/subscriptions/personal.js new file mode 100644 index 0000000000000000000000000000000000000000..d654199629af6bca1404edd3fa25489ea951333e --- /dev/null +++ b/js/src/api/subscriptions/personal.js @@ -0,0 +1,77 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class Personal { + constructor (updateSubscriptions, api, subscriber) { + this._subscriber = subscriber; + this._api = api; + this._updateSubscriptions = updateSubscriptions; + this._started = false; + } + + get isStarted () { + return this._started; + } + + start () { + this._started = true; + + return Promise.all([ + this._listAccounts(), + this._accountsInfo(), + this._loggingSubscribe() + ]); + } + + _listAccounts = () => { + return this._api.personal + .listAccounts() + .then((accounts) => { + this._updateSubscriptions('personal_listAccounts', null, accounts); + }); + } + + _accountsInfo = () => { + return this._api.personal + .accountsInfo() + .then((info) => { + this._updateSubscriptions('personal_accountsInfo', null, info); + }); + } + + _loggingSubscribe () { + return this._subscriber.subscribe('logging', (error, data) => { + if (error || !data) { + return; + } + + switch (data.method) { + case 'personal_importGethAccounts': + case 'personal_newAccount': + case 'personal_newAccountFromPhrase': + case 'personal_newAccountFromWallet': + this._listAccounts(); + this._accountsInfo(); + return; + + case 'personal_setAccountName': + case 'personal_setAccountMeta': + this._accountsInfo(); + return; + } + }); + } +} diff --git a/js/src/api/subscriptions/personal.spec.js b/js/src/api/subscriptions/personal.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..1a77b5f61603d946861f18fc9ef7521073055851 --- /dev/null +++ b/js/src/api/subscriptions/personal.spec.js @@ -0,0 +1,122 @@ +// 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 sinon from 'sinon'; +import 'sinon-as-promised'; + +import Personal from './personal'; + +const TEST_INFO = { + '0xfa64203C044691aA57251aF95f4b48d85eC00Dd5': { + name: 'test' + } +}; +const TEST_LIST = ['0xfa64203C044691aA57251aF95f4b48d85eC00Dd5']; + +function stubApi (accounts, info) { + const _calls = { + accountsInfo: [], + listAccounts: [] + }; + + return { + _calls, + personal: { + accountsInfo: () => { + const stub = sinon.stub().resolves(info || TEST_INFO)(); + _calls.accountsInfo.push(stub); + return stub; + }, + + listAccounts: () => { + const stub = sinon.stub().resolves(accounts || TEST_LIST)(); + _calls.listAccounts.push(stub); + return stub; + } + } + }; +} + +function stubLogging () { + return { + subscribe: sinon.stub() + }; +} + +describe('api/subscriptions/personal', () => { + let api; + let cb; + let logging; + let personal; + + beforeEach(() => { + api = stubApi(); + cb = sinon.stub(); + logging = stubLogging(); + personal = new Personal(cb, api, logging); + }); + + describe('constructor', () => { + it('starts the instance in a stopped state', () => { + expect(personal.isStarted).to.be.false; + }); + }); + + describe('start', () => { + describe('info available', () => { + beforeEach(() => { + return personal.start(); + }); + + it('sets the started status', () => { + expect(personal.isStarted).to.be.true; + }); + + it('calls personal_accountsInfo', () => { + expect(api._calls.accountsInfo.length).to.be.ok; + }); + + it('calls personal_listAccounts', () => { + 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); + }); + }); + + describe('info not available', () => { + beforeEach(() => { + api = stubApi([], {}); + personal = new Personal(cb, api, logging); + return personal.start(); + }); + + it('sets the started status', () => { + expect(personal.isStarted).to.be.true; + }); + + it('calls personal_accountsInfo', () => { + expect(api._calls.accountsInfo.length).to.be.ok; + }); + + it('calls personal_listAccounts', () => { + expect(api._calls.listAccounts.length).to.be.ok; + }); + }); + }); +}); diff --git a/js/src/api/subscriptions/signer.js b/js/src/api/subscriptions/signer.js new file mode 100644 index 0000000000000000000000000000000000000000..af745261b45b67e410d12fcb4647a76b0ebecc10 --- /dev/null +++ b/js/src/api/subscriptions/signer.js @@ -0,0 +1,76 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class Signer { + constructor (updateSubscriptions, api, subscriber) { + this._subscriber = subscriber; + this._api = api; + this._updateSubscriptions = updateSubscriptions; + this._started = false; + } + + get isStarted () { + return this._started; + } + + start () { + this._started = true; + + return Promise.all([ + this._listRequests(true), + this._loggingSubscribe() + ]); + } + + _listRequests = (doTimeout) => { + const nextTimeout = (timeout = 1000) => { + if (doTimeout) { + setTimeout(() => { + this._listRequests(true); + }, timeout); + } + }; + + if (!this._api.transport.isConnected) { + nextTimeout(500); + return; + } + + return this._api.personal + .requestsToConfirm() + .then((requests) => { + this._updateSubscriptions('personal_requestsToConfirm', null, requests); + nextTimeout(); + }) + .catch(nextTimeout); + } + + _loggingSubscribe () { + return this._subscriber.subscribe('logging', (error, data) => { + if (error || !data) { + return; + } + + switch (data.method) { + case 'eth_postTransaction': + case 'eth_sendTranasction': + case 'eth_sendRawTransaction': + this._listRequests(false); + return; + } + }); + } +} diff --git a/js/src/api/transport/http/http.e2e.js b/js/src/api/transport/http/http.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..8f0aa48adc5fe53178a6d450671c93eb9141a74c --- /dev/null +++ b/js/src/api/transport/http/http.e2e.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import Http from './http'; + +const http = new Http('http://localhost:8545'); + +describe('transport/Http', () => { + it('connects and makes a call to web3_clientVersion', () => { + return http.execute('web3_clientVersion').then((version) => { + const [client] = version.split('/'); + + expect(client === 'Geth' || client === 'Parity').to.be.ok; + }); + }); +}); diff --git a/js/src/api/transport/http/http.js b/js/src/api/transport/http/http.js new file mode 100644 index 0000000000000000000000000000000000000000..65ba089cc459c127806baba4fc53beb4ec8b6488 --- /dev/null +++ b/js/src/api/transport/http/http.js @@ -0,0 +1,76 @@ +// 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 { Logging } from '../../subscriptions'; +import JsonRpcBase from '../jsonRpcBase'; + +/* global fetch */ +export default class Http extends JsonRpcBase { + constructor (url) { + super(); + + this._connected = true; + this._url = url; + } + + _encodeOptions (method, params) { + const json = this.encode(method, params); + + this.log(json); + + return { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Content-Length': json.length + }, + body: json + }; + } + + execute (method, ...params) { + const request = this._encodeOptions(method, params); + + return fetch(this._url, request) + .catch((error) => { + this._connected = false; + throw error; + }) + .then((response) => { + this._connected = true; + + if (response.status !== 200) { + this._connected = false; + this.error(JSON.stringify({ status: response.status, statusText: response.statusText })); + throw new Error(`${response.status}: ${response.statusText}`); + } + + return response.json(); + }) + .then((response) => { + Logging.send(method, params, { request, response }); + + if (response.error) { + this.error(JSON.stringify(response)); + throw new Error(`${response.error.code}: ${response.error.message}`); + } + + this.log(JSON.stringify(response)); + return response.result; + }); + } +} diff --git a/js/src/api/transport/http/http.spec.js b/js/src/api/transport/http/http.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..94441bc5190442bb0faaac91b01c0995285cd9ca --- /dev/null +++ b/js/src/api/transport/http/http.spec.js @@ -0,0 +1,122 @@ +// 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 { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; +import Http from './http'; + +const transport = new Http(TEST_HTTP_URL); + +describe('api/transport/Http', () => { + describe('instance', () => { + it('encodes the options correctly', () => { + const opt = transport._encodeOptions('someMethod', ['param']); + const enc = { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Content-Length': 65 + }, + body: `{"jsonrpc":"2.0","method":"someMethod","params":["param"],"id":${transport._id - 1}}` + }; + + expect(opt).to.deep.equal(enc); + }); + }); + + describe('transport', () => { + const RESULT = ['this is some result']; + + let scope; + let result; + + beforeEach(() => { + scope = mockHttp([{ method: 'eth_call', reply: { result: RESULT } }]); + + return transport + .execute('eth_call', 1, 2, 3, 'test') + .then((_result) => { + result = _result; + }); + }); + + it('makes POST', () => { + expect(scope.isDone()).to.be.true; + }); + + it('sets jsonrpc', () => { + expect(scope.body.eth_call.jsonrpc).to.equal('2.0'); + }); + + it('sets the method', () => { + expect(scope.body.eth_call.method).to.equal('eth_call'); + }); + + it('passes the params', () => { + expect(scope.body.eth_call.params).to.deep.equal([1, 2, 3, 'test']); + }); + + it('increments the id', () => { + expect(scope.body.eth_call.id).not.to.equal(0); + }); + + it('passes the actual result back', () => { + expect(result).to.deep.equal(RESULT); + }); + }); + + describe('HTTP errors', () => { + let scope; + let error; + + beforeEach(() => { + scope = mockHttp([{ method: 'eth_call', reply: {}, code: 500 }]); + + return transport + .execute('eth_call') + .catch((_error) => { + error = _error; + }); + }); + + it('returns HTTP errors as throws', () => { + expect(scope.isDone()).to.be.true; + expect(error.message).to.match(/Internal Server Error/); + }); + }); + + describe('RPC errors', () => { + const ERROR = { code: -1, message: 'ERROR: RPC failure' }; + + let scope; + let error; + + beforeEach(() => { + scope = mockHttp([{ method: 'eth_call', reply: { error: ERROR } }]); + + return transport + .execute('eth_call') + .catch((_error) => { + error = _error; + }); + }); + + it('returns RPC errors as throws', () => { + expect(scope.isDone()).to.be.true; + expect(error.message).to.match(/RPC failure/); + }); + }); +}); diff --git a/js/src/api/transport/http/index.js b/js/src/api/transport/http/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5ce7a652ea5c7b5ca93a4408c39f98c1d4cbf58b --- /dev/null +++ b/js/src/api/transport/http/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './http'; diff --git a/js/src/api/transport/index.js b/js/src/api/transport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8f67fba4d5381c4efdffe8b6eacea7009129f8e8 --- /dev/null +++ b/js/src/api/transport/index.js @@ -0,0 +1,18 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export Http from './http'; +export Ws from './ws'; diff --git a/js/src/api/transport/jsonRpcBase.js b/js/src/api/transport/jsonRpcBase.js new file mode 100644 index 0000000000000000000000000000000000000000..dc2f9bc8e9bc564df4c63b5e2f540a11d442ba90 --- /dev/null +++ b/js/src/api/transport/jsonRpcBase.js @@ -0,0 +1,62 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class JsonRpcBase { + constructor () { + this._id = 1; + this._debug = false; + this._connected = false; + } + + encode (method, params) { + const json = JSON.stringify({ + jsonrpc: '2.0', + method: method, + params: params, + id: this._id++ + }); + + return json; + } + + get id () { + return this._id; + } + + get isDebug () { + return this._debug; + } + + get isConnected () { + return this._connected; + } + + setDebug (flag) { + this._debug = flag; + } + + error (error) { + if (this.isDebug) { + console.error(error); + } + } + + log (log) { + if (this.isDebug) { + console.log(log); + } + } +} diff --git a/js/src/api/transport/jsonRpcBase.spec.js b/js/src/api/transport/jsonRpcBase.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..78fc6549c2f5dd7bae51ebacbb912f349d78a65e --- /dev/null +++ b/js/src/api/transport/jsonRpcBase.spec.js @@ -0,0 +1,88 @@ +// 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 sinon from 'sinon'; + +import JsonRpcBase from './jsonRpcBase'; + +const base = new JsonRpcBase(); + +describe('api/transport/JsonRpcBase', () => { + describe('encode', () => { + it('encodes the body correctly, incrementing id', () => { + const id = base.id; + const bdy = base.encode('someMethod', ['param1', 'param2']); + const enc = `{"jsonrpc":"2.0","method":"someMethod","params":["param1","param2"],"id":${id}}`; + + expect(bdy).to.equal(enc); + expect(base.id - id).to.equal(1); + }); + }); + + describe('setDebug', () => { + it('starts with disabled flag', () => { + expect(base.isDebug).to.be.false; + }); + + it('true flag switches on', () => { + base.setDebug(true); + expect(base.isDebug).to.be.true; + }); + + it('false flag switches off', () => { + base.setDebug(true); + expect(base.isDebug).to.be.true; + base.setDebug(false); + expect(base.isDebug).to.be.false; + }); + + describe('logging', () => { + beforeEach(() => { + sinon.spy(console, 'log'); + sinon.spy(console, 'error'); + }); + + afterEach(() => { + console.log.restore(); + console.error.restore(); + }); + + it('does not log errors with flag off', () => { + base.setDebug(false); + base.log('error'); + expect(console.log).to.not.be.called; + }); + + it('does not log errors with flag off', () => { + base.setDebug(false); + base.error('error'); + expect(console.error).to.not.be.called; + }); + + it('does log errors with flag on', () => { + base.setDebug(true); + base.log('error'); + expect(console.log).to.be.called; + }); + + it('does log errors with flag on', () => { + base.setDebug(true); + base.error('error'); + expect(console.error).to.be.called; + }); + }); + }); +}); diff --git a/js/src/api/transport/ws/index.js b/js/src/api/transport/ws/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7b6e35934678394c9bd0b82b1b7aacf366a109ab --- /dev/null +++ b/js/src/api/transport/ws/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './ws'; diff --git a/js/src/api/transport/ws/ws.e2e.js b/js/src/api/transport/ws/ws.e2e.js new file mode 100644 index 0000000000000000000000000000000000000000..19e4ab8eb4aa6a04442b74e4a37bcfdab746a05f --- /dev/null +++ b/js/src/api/transport/ws/ws.e2e.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import Ws from './ws'; + +const ws = new Ws('ws://localhost:8546/'); + +describe('transport/Ws', () => { + it('connects and makes a call to web3_clientVersion', () => { + return ws.execute('web3_clientVersion').then((version) => { + const [client] = version.split('/'); + + expect(client === 'Geth' || client === 'Parity').to.be.ok; + }); + }); +}); diff --git a/js/src/api/transport/ws/ws.js b/js/src/api/transport/ws/ws.js new file mode 100644 index 0000000000000000000000000000000000000000..119f4ba7643356a33e22f7f0fdcbb4ab7f99b988 --- /dev/null +++ b/js/src/api/transport/ws/ws.js @@ -0,0 +1,157 @@ +// 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 { keccak_256 } from 'js-sha3'; // eslint-disable-line camelcase + +import { Logging } from '../../subscriptions'; +import JsonRpcBase from '../jsonRpcBase'; + +/* global WebSocket */ +export default class Ws extends JsonRpcBase { + constructor (url, token) { + super(); + + this._url = url; + this._token = token; + this._messages = {}; + + this._connecting = true; + this._lastError = null; + this._autoConnect = false; + + this._connect(); + } + + updateToken (token) { + this._token = token; + this._autoConnect = false; + + this._connect(); + } + + _connect () { + const time = parseInt(new Date().getTime() / 1000, 10); + const sha3 = keccak_256(`${this._token}:${time}`); + const hash = `${sha3}_${time}`; + + if (this._ws) { + this._ws.onerror = null; + this._ws.onopen = null; + this._ws.onclose = null; + this._ws.onmessage = null; + this._ws = null; + } + + this._connecting = true; + this._connected = false; + this._lastError = null; + + this._ws = new WebSocket(this._url, hash); + this._ws.onerror = this._onError; + this._ws.onopen = this._onOpen; + this._ws.onclose = this._onClose; + this._ws.onmessage = this._onMessage; + } + + _onOpen = (event) => { + console.log('ws:onOpen', event); + this._connected = true; + this._connecting = false; + this._autoConnect = true; + + Object.keys(this._messages) + .filter((id) => this._messages[id].queued) + .forEach(this._send); + } + + _onClose = (event) => { + console.log('ws:onClose', event); + this._connected = false; + this._connecting = false; + + if (this._autoConnect) { + this._connect(); + } + } + + _onError = (event) => { + console.error('ws:onError', event); + this._lastError = event; + } + + _onMessage = (event) => { + // Event sent by Signer Broadcaster + if (event.data === 'new_message') { + return false; + } + + try { + const result = JSON.parse(event.data); + const { method, params, json, resolve, reject } = this._messages[result.id]; + + Logging.send(method, params, { json, result }); + + if (result.error) { + this.error(event.data); + + reject(new Error(`${result.error.code}: ${result.error.message}`)); + delete this._messages[result.id]; + return; + } + + resolve(result.result); + delete this._messages[result.id]; + } catch (e) { + console.error('ws::_onMessage', event.data, e); + } + } + + _send = (id) => { + const message = this._messages[id]; + + message.queued = !this._connected; + + if (this._connected) { + this._ws.send(message.json); + } + } + + execute (method, ...params) { + return new Promise((resolve, reject) => { + const id = this.id; + const json = this.encode(method, params); + + this._messages[id] = { id, method, params, json, resolve, reject }; + this._send(id); + }); + } + + get token () { + return this._token; + } + + get isAutoConnect () { + return this._autoConnect; + } + + get isConnecting () { + return this._connecting; + } + + get lastError () { + return this._lastError; + } +} diff --git a/js/src/api/transport/ws/ws.spec.js b/js/src/api/transport/ws/ws.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c417e89110c34c60637be253d19096bf3fd312c8 --- /dev/null +++ b/js/src/api/transport/ws/ws.spec.js @@ -0,0 +1,85 @@ +// 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 { TEST_WS_URL, mockWs } from '../../../../test/mockRpc'; +import Ws from './ws'; + +describe('api/transport/Ws', () => { + let transport; + let scope; + + describe('transport', () => { + let result; + + beforeEach(() => { + scope = mockWs([{ method: 'test_anyCall', reply: 'TestResult' }]); + transport = new Ws(TEST_WS_URL); + + return transport + .execute('test_anyCall', 1, 2, 3) + .then((_result) => { + result = _result; + }); + }); + + afterEach(() => { + scope.stop(); + }); + + it('makes call', () => { + expect(scope.isDone()).to.be.true; + }); + + it('sets jsonrpc', () => { + expect(scope.body.test_anyCall.jsonrpc).to.equal('2.0'); + }); + + it('sets the method', () => { + expect(scope.body.test_anyCall.method).to.equal('test_anyCall'); + }); + + it('passes the params', () => { + expect(scope.body.test_anyCall.params).to.deep.equal([1, 2, 3]); + }); + + it('increments the id', () => { + expect(scope.body.test_anyCall.id).not.to.equal(0); + }); + + it('passes the actual result back', () => { + expect(result).to.equal('TestResult'); + }); + }); + + describe('errors', () => { + beforeEach(() => { + scope = mockWs([{ method: 'test_anyCall', reply: { error: { code: 1, message: 'TestError' } } }]); + transport = new Ws(TEST_WS_URL); + }); + + afterEach(() => { + scope.stop(); + }); + + it('returns RPC errors when encountered', () => { + return transport + .execute('test_anyCall') + .catch((error) => { + expect(error).to.match(/TestError/); + }); + }); + }); +}); diff --git a/js/src/api/util/decode.js b/js/src/api/util/decode.js new file mode 100644 index 0000000000000000000000000000000000000000..2d6eee75ba22d19320926d8410eba88375b2fbb8 --- /dev/null +++ b/js/src/api/util/decode.js @@ -0,0 +1,83 @@ +// 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 { isHex } from './types'; + +import Func from '../../abi/spec/function'; +import { fromParamType, toParamType } from '../../abi/spec/paramType/format'; + +export function decodeCallData (data) { + if (!isHex(data)) { + throw new Error('Input to decodeCallData should be a hex value'); + } + + if (data.substr(0, 2) === '0x') { + return decodeCallData(data.slice(2)); + } else if (data.length < 8) { + throw new Error('Input to decodeCallData should be method signature + data'); + } + + const signature = data.substr(0, 8); + const paramdata = data.substr(8); + + return { + signature: `0x${signature}`, + paramdata: `0x${paramdata}` + }; +} + +export function decodeMethodInput (methodAbi, paramdata) { + if (!methodAbi) { + throw new Error('decodeMethodInput should receive valid method-specific ABI'); + } else if (paramdata && paramdata.length) { + if (!isHex(paramdata)) { + throw new Error('Input to decodeMethodInput should be a hex value'); + } else if (paramdata.substr(0, 2) === '0x') { + return decodeMethodInput(methodAbi, paramdata.slice(2)); + } else if (paramdata.length % 64 !== 0) { + throw new Error('Parameter length in decodeMethodInput not a multiple of 64 characters'); + } + } + + return new Func(methodAbi).decodeInput(paramdata).map((decoded) => decoded.value); +} + +// takes a method in form name(...,types) and returns the inferred abi definition +export function methodToAbi (method) { + const length = method.length; + const typesStart = method.indexOf('('); + const typesEnd = method.indexOf(')'); + + if (typesStart === -1) { + throw new Error(`Missing start ( in call to decodeMethod with ${method}`); + } else if (typesEnd === -1) { + throw new Error(`Missing end ) in call to decodeMethod with ${method}`); + } else if (typesEnd < typesStart) { + throw new Error(`End ) is before start ( in call to decodeMethod with ${method}`); + } else if (typesEnd !== length - 1) { + throw new Error(`Extra characters after end ) in call to decodeMethod with ${method}`); + } + + const name = method.substr(0, typesStart); + const types = method.substr(typesStart + 1, length - (typesStart + 1) - 1).split(','); + const inputs = types.filter((_type) => _type.length).map((_type) => { + const type = fromParamType(toParamType(_type)); + + return { type }; + }); + + return { type: 'function', name, inputs }; +} diff --git a/js/src/api/util/decode.spec.js b/js/src/api/util/decode.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..70bc44bc57127743b857d0299a844a9affd3c3ce --- /dev/null +++ b/js/src/api/util/decode.spec.js @@ -0,0 +1,97 @@ +// 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 BigNumber from 'bignumber.js'; +import { decodeCallData, decodeMethodInput, methodToAbi } from './decode'; + +describe('api/util/decode', () => { + const METH = '0x70a08231'; + const ENCO = '0x70a082310000000000000000000000005A5eFF38DA95b0D58b6C616f2699168B480953C9'; + const DATA = '0x0000000000000000000000005A5eFF38DA95b0D58b6C616f2699168B480953C9'; + + describe('decodeCallData', () => { + it('throws on non-hex inputs', () => { + expect(() => decodeCallData('invalid')).to.throw(/should be a hex value/); + }); + + it('throws when invalid signature length', () => { + expect(() => decodeCallData(METH.slice(-6))).to.throw(/should be method signature/); + }); + + it('splits valid inputs properly', () => { + expect(decodeCallData(ENCO)).to.deep.equal({ + signature: METH, + paramdata: DATA + }); + }); + }); + + describe('decodeMethodInput', () => { + it('expects a valid ABI', () => { + expect(() => decodeMethodInput(null, null)).to.throw(/should receive valid method/); + }); + + it('expect valid hex parameter data', () => { + expect(() => decodeMethodInput({}, 'invalid')).to.throw(/should be a hex value/); + }); + + it('throws on invalid lengths', () => { + expect(() => decodeMethodInput({}, DATA.slice(-32))).to.throw(/not a multiple of/); + }); + + it('correctly decodes valid inputs', () => { + expect(decodeMethodInput({ + type: 'function', + inputs: [ + { type: 'uint' } + ] + }, DATA)).to.deep.equal([ new BigNumber('0x5a5eff38da95b0d58b6c616f2699168b480953c9') ]); + }); + }); + + describe('methodToAbi', () => { + it('throws when no start ( specified', () => { + expect(() => methodToAbi('invalid,uint,bool)')).to.throw(/Missing start \(/); + }); + + it('throws when no end ) specified', () => { + expect(() => methodToAbi('invalid(uint,bool')).to.throw(/Missing end \)/); + }); + + it('throws when end ) is not in the last position', () => { + expect(() => methodToAbi('invalid(uint,bool)2')).to.throw(/Extra characters after end \)/); + }); + + it('throws when start ( is after end )', () => { + expect(() => methodToAbi('invalid)uint,bool(')).to.throw(/End \) is before start \(/); + }); + + it('throws when invalid types are present', () => { + expect(() => methodToAbi('method(invalidType,bool,uint)')).to.throw(/Cannot convert invalidType/); + }); + + it('returns a valid methodabi for a valid method', () => { + expect(methodToAbi('valid(uint,bool)')).to.deep.equals({ + type: 'function', + name: 'valid', + inputs: [ + { type: 'uint256' }, + { type: 'bool' } + ] + }); + }); + }); +}); diff --git a/js/src/api/util/format.js b/js/src/api/util/format.js new file mode 100644 index 0000000000000000000000000000000000000000..1b68e11388cc3ce336edbced5a6f6f32b7e189d1 --- /dev/null +++ b/js/src/api/util/format.js @@ -0,0 +1,19 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export function bytesToHex (bytes) { + return '0x' + bytes.map((b) => ('0' + b.toString(16)).slice(-2)).join(''); +} diff --git a/js/src/api/util/format.spec.js b/js/src/api/util/format.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c779d71efd30df34ddf93edafb9b07c51892d998 --- /dev/null +++ b/js/src/api/util/format.spec.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import { bytesToHex } from './format'; + +describe('api/util/format', () => { + describe('bytesToHex', () => { + it('correctly converts an empty array', () => { + expect(bytesToHex([])).to.equal('0x'); + }); + + it('correctly converts a non-empty array', () => { + expect(bytesToHex([0, 15, 16])).to.equal('0x000f10'); + }); + }); +}); diff --git a/js/src/api/util/identity.js b/js/src/api/util/identity.js new file mode 100644 index 0000000000000000000000000000000000000000..6a25590e3dbe9962acd421a80fe21e2a3ae24df9 --- /dev/null +++ b/js/src/api/util/identity.js @@ -0,0 +1,9 @@ +import blockies from 'blockies'; + +export function createIdentityImg (address, scale = 8) { + return blockies({ + seed: (address || '').toLowerCase(), + size: 8, + scale + }).toDataURL(); +} diff --git a/js/src/api/util/index.js b/js/src/api/util/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fb0f79076b74269f4cf7e81380538fb1f0edb631 --- /dev/null +++ b/js/src/api/util/index.js @@ -0,0 +1,41 @@ +// 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 { isAddress as isAddressValid, toChecksumAddress } from '../../abi/util/address'; +import { decodeCallData, decodeMethodInput, methodToAbi } from './decode'; +import { bytesToHex } from './format'; +import { fromWei, toWei } from './wei'; +import { sha3 } from './sha3'; +import { isArray, isFunction, isHex, isInstanceOf, isString } from './types'; +import { createIdentityImg } from './identity'; + +export default { + isAddressValid, + isArray, + isFunction, + isHex, + isInstanceOf, + isString, + bytesToHex, + createIdentityImg, + decodeCallData, + decodeMethodInput, + methodToAbi, + fromWei, + toChecksumAddress, + toWei, + sha3 +}; diff --git a/js/src/api/util/sha3.js b/js/src/api/util/sha3.js new file mode 100644 index 0000000000000000000000000000000000000000..fcbda091a23269cb851d15a8eae6e9c93e7b74a9 --- /dev/null +++ b/js/src/api/util/sha3.js @@ -0,0 +1,21 @@ +// 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 { keccak_256 } from 'js-sha3'; // eslint-disable-line camelcase + +export function sha3 (value) { + return `0x${keccak_256(value)}`; +} diff --git a/js/src/api/util/sha3.spec.js b/js/src/api/util/sha3.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..bede8bd600d8f8fcbb95917c0b4ed50c86b7edf1 --- /dev/null +++ b/js/src/api/util/sha3.spec.js @@ -0,0 +1,25 @@ +// 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 { sha3 } from './sha3'; + +describe('api/util/sha3', () => { + describe('sha3', () => { + it('constructs a correct sha3 value', () => { + expect(sha3('jacogr')).to.equal('0x2f4ff4b5a87abbd2edfed699db48a97744e028c7f7ce36444d40d29d792aa4dc'); + }); + }); +}); diff --git a/js/src/api/util/types.js b/js/src/api/util/types.js new file mode 100644 index 0000000000000000000000000000000000000000..a34f30649f6f649b463bb953fa30eeae638a6ff1 --- /dev/null +++ b/js/src/api/util/types.js @@ -0,0 +1,56 @@ +// 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 . + +const HEXDIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; + +export function isArray (test) { + return Object.prototype.toString.call(test) === '[object Array]'; +} + +export function isError (test) { + return Object.prototype.toString.call(test) === '[object Error]'; +} + +export function isFunction (test) { + return Object.prototype.toString.call(test) === '[object Function]'; +} + +export function isHex (_test) { + if (_test.substr(0, 2) === '0x') { + return isHex(_test.slice(2)); + } + + const test = _test.toLowerCase(); + let hex = true; + + for (let idx = 0; hex && idx < test.length; idx++) { + hex = HEXDIGITS.includes(test[idx]); + } + + return hex; +} + +export function isObject (test) { + return Object.prototype.toString.call(test) === '[object Object]'; +} + +export function isString (test) { + return Object.prototype.toString.call(test) === '[object String]'; +} + +export function isInstanceOf (test, clazz) { + return test instanceof clazz; +} diff --git a/js/src/api/util/types.spec.js b/js/src/api/util/types.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..252876be39e006cdac6d603f369820c295b6680d --- /dev/null +++ b/js/src/api/util/types.spec.js @@ -0,0 +1,112 @@ +// 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 sinon from 'sinon'; + +import { isArray, isError, isFunction, isHex, isInstanceOf, isObject, isString } from './types'; +import Eth from '../rpc/eth'; + +describe('api/util/types', () => { + describe('isArray', () => { + it('correctly identifies null as false', () => { + expect(isArray(null)).to.be.false; + }); + + it('correctly identifies empty array as true', () => { + expect(isArray([])).to.be.true; + }); + + it('correctly identifies array as true', () => { + expect(isArray([1, 2, 3])).to.be.true; + }); + }); + + describe('isError', () => { + it('correctly identifies null as false', () => { + expect(isError(null)).to.be.false; + }); + + it('correctly identifies Error as true', () => { + expect(isError(new Error('an error'))).to.be.true; + }); + }); + + describe('isFunction', () => { + it('correctly identifies null as false', () => { + expect(isFunction(null)).to.be.false; + }); + + it('correctly identifies function as true', () => { + expect(isFunction(sinon.stub())).to.be.true; + }); + }); + + describe('isHex', () => { + it('correctly identifies hex by leading 0x', () => { + expect(isHex('0x123')).to.be.true; + }); + + it('correctly identifies hex without leading 0x', () => { + expect(isHex('123')).to.be.true; + }); + + it('correctly identifies non-hex values', () => { + expect(isHex('123j')).to.be.false; + }); + }); + + describe('isInstanceOf', () => { + it('correctly identifies build-in instanceof', () => { + expect(isInstanceOf(new String('123'), String)).to.be.true; // eslint-disable-line no-new-wrappers + }); + + it('correctly identifies own instanceof', () => { + expect(isInstanceOf(new Eth({}), Eth)).to.be.true; + }); + + it('correctly reports false for own', () => { + expect(isInstanceOf({}, Eth)).to.be.false; + }); + }); + + describe('isObject', () => { + it('correctly identifies empty object as object', () => { + expect(isObject({})).to.be.true; + }); + + it('correctly identifies non-empty object as object', () => { + expect(isObject({ data: '123' })).to.be.true; + }); + + it('correctly identifies Arrays as non-objects', () => { + expect(isObject([1, 2, 3])).to.be.false; + }); + + it('correctly identifies Strings as non-objects', () => { + expect(isObject('123')).to.be.false; + }); + }); + + describe('isString', () => { + it('correctly identifies empty string as string', () => { + expect(isString('')).to.be.true; + }); + + it('correctly identifies string as string', () => { + expect(isString('123')).to.be.true; + }); + }); +}); diff --git a/js/src/api/util/wei.js b/js/src/api/util/wei.js new file mode 100644 index 0000000000000000000000000000000000000000..d04e73921f94fc7cbde264702eeccc85ebd60274 --- /dev/null +++ b/js/src/api/util/wei.js @@ -0,0 +1,37 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import BigNumber from 'bignumber.js'; + +const UNITS = ['wei', 'ada', 'babbage', 'shannon', 'szabo', 'finney', 'ether', 'kether', 'mether', 'gether', 'tether']; + +export function _getUnitMultiplier (unit) { + const position = UNITS.indexOf(unit.toLowerCase()); + + if (position === -1) { + throw new Error(`Unknown unit ${unit} passed to wei formatter`); + } + + return 10 ** (position * 3); +} + +export function fromWei (value, unit = 'ether') { + return new BigNumber(value).div(_getUnitMultiplier(unit)); +} + +export function toWei (value, unit = 'ether') { + return new BigNumber(value).mul(_getUnitMultiplier(unit)); +} diff --git a/js/src/api/util/wei.spec.js b/js/src/api/util/wei.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..8d0b1f09c7d6026b0b147d0ac00f37a5827500f0 --- /dev/null +++ b/js/src/api/util/wei.spec.js @@ -0,0 +1,57 @@ +// 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 { _getUnitMultiplier, fromWei, toWei } from './wei'; + +describe('api/util/wei', () => { + describe('_getUnitMultiplier', () => { + it('returns 10^0 for wei', () => { + expect(_getUnitMultiplier('wei')).to.equal(10 ** 0); + }); + + it('returns 10^15 for finney', () => { + expect(_getUnitMultiplier('finney')).to.equal(10 ** 15); + }); + + it('returns 10^18 for ether', () => { + expect(_getUnitMultiplier('ether')).to.equal(10 ** 18); + }); + + it('throws an error on invalid units', () => { + expect(() => _getUnitMultiplier('invalid')).to.throw(/passed to wei formatter/); + }); + }); + + describe('fromWei', () => { + it('formats into ether when nothing specified', () => { + expect(fromWei('1230000000000000000').toString()).to.equal('1.23'); + }); + + it('formats into finney when specified', () => { + expect(fromWei('1230000000000000000', 'finney').toString()).to.equal('1230'); + }); + }); + + describe('toWei', () => { + it('formats from ether when nothing specified', () => { + expect(toWei(1.23).toString()).to.equal('1230000000000000000'); + }); + + it('formats from finney when specified', () => { + expect(toWei(1230, 'finney').toString()).to.equal('1230000000000000000'); + }); + }); +}); diff --git a/js/src/contracts/abi/basiccoin.json b/js/src/contracts/abi/basiccoin.json new file mode 100644 index 0000000000000000000000000000000000000000..0bdc66666fcb4e4f15ca48dbe128c62474367415 --- /dev/null +++ b/js/src/contracts/abi/basiccoin.json @@ -0,0 +1 @@ +[{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_new","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"base","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"_totalSupply","type":"uint256"},{"name":"_owner","type":"address"}],"type":"constructor"},{"payable":false,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"old","type":"address"},{"indexed":true,"name":"current","type":"address"}],"name":"NewOwner","type":"event"}] diff --git a/js/src/contracts/abi/basiccoinmanager.json b/js/src/contracts/abi/basiccoinmanager.json new file mode 100644 index 0000000000000000000000000000000000000000..cafe09735c6d4f425e302f60001402d668fad002 --- /dev/null +++ b/js/src/contracts/abi/basiccoinmanager.json @@ -0,0 +1 @@ +[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"countByOwner","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"count","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_new","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"base","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_index","type":"uint256"}],"name":"get","outputs":[{"name":"coin","type":"address"},{"name":"owner","type":"address"},{"name":"tokenreg","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"drain","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_totalSupply","type":"uint256"},{"name":"_tla","type":"string"},{"name":"_name","type":"string"},{"name":"_tokenreg","type":"address"}],"name":"deploy","outputs":[{"name":"","type":"bool"}],"payable":true,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_index","type":"uint256"}],"name":"getByOwner","outputs":[{"name":"coin","type":"address"},{"name":"owner","type":"address"},{"name":"tokenreg","type":"address"}],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"tokenreg","type":"address"},{"indexed":true,"name":"coin","type":"address"}],"name":"Created","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"old","type":"address"},{"indexed":true,"name":"current","type":"address"}],"name":"NewOwner","type":"event"}] diff --git a/js/src/contracts/abi/dappreg.json b/js/src/contracts/abi/dappreg.json new file mode 100644 index 0000000000000000000000000000000000000000..f6bec35af13d798dd239543bc1b0673ef12a4fdd --- /dev/null +++ b/js/src/contracts/abi/dappreg.json @@ -0,0 +1 @@ +[{"constant":true,"inputs":[{"name":"_id","type":"bytes32"},{"name":"_key","type":"bytes32"}],"name":"meta","outputs":[{"name":"","type":"bytes32"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"count","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_new","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"bytes32"}],"name":"unregister","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_fee","type":"uint256"}],"name":"setFee","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_id","type":"bytes32"}],"name":"get","outputs":[{"name":"id","type":"bytes32"},{"name":"owner","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"bytes32"},{"name":"_key","type":"bytes32"},{"name":"_value","type":"bytes32"}],"name":"setMeta","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"drain","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"bytes32"},{"name":"_owner","type":"address"}],"name":"setDappOwner","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"fee","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_index","type":"uint256"}],"name":"at","outputs":[{"name":"id","type":"bytes32"},{"name":"owner","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"bytes32"}],"name":"register","outputs":[],"payable":true,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"bytes32"},{"indexed":true,"name":"key","type":"bytes32"},{"indexed":false,"name":"value","type":"bytes32"}],"name":"MetaChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"}],"name":"Registered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"bytes32"}],"name":"Unregistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"old","type":"address"},{"indexed":true,"name":"current","type":"address"}],"name":"NewOwner","type":"event"}] diff --git a/js/src/contracts/abi/eip20.json b/js/src/contracts/abi/eip20.json new file mode 100644 index 0000000000000000000000000000000000000000..6937e28c85b0e428e092fe89ae54c950b6899baa --- /dev/null +++ b/js/src/contracts/abi/eip20.json @@ -0,0 +1,163 @@ +[ + { + "constant": false, + "inputs": [ + { + "name": "_spender", + "type": "address" + }, + { + "name": "_value", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "total", + "type": "uint256" + } + ], + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_value", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "balance", + "type": "uint256" + } + ], + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_value", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_owner", + "type": "address" + }, + { + "name": "_spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "remaining", + "type": "uint256" + } + ], + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "value", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "value", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + } +] diff --git a/js/src/contracts/abi/gavcoin.json b/js/src/contracts/abi/gavcoin.json new file mode 100644 index 0000000000000000000000000000000000000000..5170326f5a4b58fe3b64ff40b306ae2e297e062a --- /dev/null +++ b/js/src/contracts/abi/gavcoin.json @@ -0,0 +1 @@ +[{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"_who","type":"address"},{"name":"_maxPrice","type":"uint256"}],"name":"buyin","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"remaining","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_price","type":"uint256"},{"name":"_units","type":"uint256"}],"name":"refund","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"_who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"price","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"buyer","type":"address"},{"indexed":true,"name":"price","type":"uint256"},{"indexed":true,"name":"amount","type":"uint256"}],"name":"Buyin","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"buyer","type":"address"},{"indexed":true,"name":"price","type":"uint256"},{"indexed":true,"name":"amount","type":"uint256"}],"name":"Refund","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"price","type":"uint256"}],"name":"NewTranch","type":"event"}] diff --git a/js/src/contracts/abi/githubhint.json b/js/src/contracts/abi/githubhint.json new file mode 100644 index 0000000000000000000000000000000000000000..bdbc162e4e516fa8732371a846465d199b1504cd --- /dev/null +++ b/js/src/contracts/abi/githubhint.json @@ -0,0 +1,81 @@ +[ + { + "constant":false, + "inputs":[ + { + "name":"_content", + "type":"bytes32" + }, + { + "name":"_url", + "type":"string" + } + ], + "name":"hintURL", + "outputs":[ + + ], + "type":"function" + }, + { + "constant":false, + "inputs":[ + { + "name":"_content", + "type":"bytes32" + }, + { + "name":"_accountSlashRepo", + "type":"string" + }, + { + "name":"_commit", + "type":"bytes20" + } + ], + "name":"hint", + "outputs":[ + + ], + "type":"function" + }, + { + "constant":true, + "inputs":[ + { + "name":"", + "type":"bytes32" + } + ], + "name":"entries", + "outputs":[ + { + "name":"accountSlashRepo", + "type":"string" + }, + { + "name":"commit", + "type":"bytes20" + }, + { + "name":"owner", + "type":"address" + } + ], + "type":"function" + }, + { + "constant":false, + "inputs":[ + { + "name":"_content", + "type":"bytes32" + } + ], + "name":"unhint", + "outputs":[ + + ], + "type":"function" + } +] diff --git a/js/src/contracts/abi/index.js b/js/src/contracts/abi/index.js new file mode 100644 index 0000000000000000000000000000000000000000..599f8a13b4a1075183190f4debe5846f11e6a6ae --- /dev/null +++ b/js/src/contracts/abi/index.js @@ -0,0 +1,39 @@ +// 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 basiccoin from './basiccoin.json'; +import basiccoinmanager from './basiccoinmanager.json'; +import dappreg from './dappreg.json'; +import eip20 from './eip20.json'; +import gavcoin from './gavcoin.json'; +import githubhint from './githubhint.json'; +import owned from './owned.json'; +import registry from './registry.json'; +import signaturereg from './signaturereg.json'; +import tokenreg from './tokenreg.json'; + +export { + basiccoin, + basiccoinmanager, + dappreg, + eip20, + gavcoin, + githubhint, + owned, + registry, + signaturereg, + tokenreg +}; diff --git a/js/src/contracts/abi/owned.json b/js/src/contracts/abi/owned.json new file mode 100644 index 0000000000000000000000000000000000000000..ccfeed85d06bc7e2bc78498968eaab93d88fde24 --- /dev/null +++ b/js/src/contracts/abi/owned.json @@ -0,0 +1 @@ +[{"constant":false,"inputs":[{"name":"_new","type":"address"}],"name":"setOwner","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"old","type":"address"},{"indexed":true,"name":"current","type":"address"}],"name":"NewOwner","type":"event"}] diff --git a/js/src/contracts/abi/registry.json b/js/src/contracts/abi/registry.json new file mode 100644 index 0000000000000000000000000000000000000000..f97dc20c72abad7ffb31de847af50f1a26b4e0af --- /dev/null +++ b/js/src/contracts/abi/registry.json @@ -0,0 +1 @@ +[{"constant":false,"inputs":[{"name":"_new","type":"address"}],"name":"setOwner","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"string"}],"name":"confirmReverse","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"reserve","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"},{"name":"_value","type":"bytes32"}],"name":"set","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"drop","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"getAddress","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[{"name":"_amount","type":"uint256"}],"name":"setFee","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_to","type":"address"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"reserved","outputs":[{"name":"reserved","type":"bool"}],"type":"function"},{"constant":false,"inputs":[],"name":"drain","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"string"},{"name":"_who","type":"address"}],"name":"proposeReverse","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"getUint","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"get","outputs":[{"name":"","type":"bytes32"}],"type":"function"},{"constant":true,"inputs":[],"name":"fee","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"reverse","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"},{"name":"_value","type":"uint256"}],"name":"setUint","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":false,"inputs":[],"name":"removeReverse","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"},{"name":"_value","type":"address"}],"name":"setAddress","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Drained","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"FeeChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"}],"name":"Reserved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"bytes32"},{"indexed":true,"name":"oldOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"Transferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"}],"name":"Dropped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"key","type":"string"},{"indexed":false,"name":"plainKey","type":"string"}],"name":"DataChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"string"},{"indexed":true,"name":"reverse","type":"address"}],"name":"ReverseProposed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"string"},{"indexed":true,"name":"reverse","type":"address"}],"name":"ReverseConfirmed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"string"},{"indexed":true,"name":"reverse","type":"address"}],"name":"ReverseRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"old","type":"address"},{"indexed":true,"name":"current","type":"address"}],"name":"NewOwner","type":"event"}] diff --git a/js/src/contracts/abi/signaturereg.json b/js/src/contracts/abi/signaturereg.json new file mode 100644 index 0000000000000000000000000000000000000000..a9b109ecd463a4873c3597eec690e20819132ef7 --- /dev/null +++ b/js/src/contracts/abi/signaturereg.json @@ -0,0 +1,128 @@ +[ + { + "constant": false, + "inputs": [ + { + "name": "_new", + "type": "address" + } + ], + "name": "setOwner", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSignatures", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "drain", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "", + "type": "bytes4" + } + ], + "name": "entries", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_method", + "type": "string" + } + ], + "name": "register", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "type": "function" + }, + { + "inputs": [], + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "creator", + "type": "address" + }, + { + "indexed": true, + "name": "signature", + "type": "bytes4" + }, + { + "indexed": false, + "name": "method", + "type": "string" + } + ], + "name": "Registered", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "old", + "type": "address" + }, + { + "indexed": true, + "name": "current", + "type": "address" + } + ], + "name": "NewOwner", + "type": "event" + } +] diff --git a/js/src/contracts/abi/tokenreg.json b/js/src/contracts/abi/tokenreg.json new file mode 100644 index 0000000000000000000000000000000000000000..e56a13eec48aa4dc1ae9f558b3a080c24174c065 --- /dev/null +++ b/js/src/contracts/abi/tokenreg.json @@ -0,0 +1 @@ +[{"constant":true,"inputs":[{"name":"_id","type":"uint256"}],"name":"token","outputs":[{"name":"addr","type":"address"},{"name":"tla","type":"string"},{"name":"base","type":"uint256"},{"name":"name","type":"string"},{"name":"owner","type":"address"}],"type":"function"},{"constant":false,"inputs":[{"name":"_new","type":"address"}],"name":"setOwner","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"},{"name":"_tla","type":"string"},{"name":"_base","type":"uint256"},{"name":"_name","type":"string"}],"name":"register","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"_fee","type":"uint256"}],"name":"setFee","outputs":[],"type":"function"},{"constant":true,"inputs":[{"name":"_id","type":"uint256"},{"name":"_key","type":"bytes32"}],"name":"meta","outputs":[{"name":"","type":"bytes32"}],"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"},{"name":"_tla","type":"string"},{"name":"_base","type":"uint256"},{"name":"_name","type":"string"},{"name":"_owner","type":"address"}],"name":"registerAs","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"_tla","type":"string"}],"name":"fromTLA","outputs":[{"name":"id","type":"uint256"},{"name":"addr","type":"address"},{"name":"base","type":"uint256"},{"name":"name","type":"string"},{"name":"owner","type":"address"}],"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"drain","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"tokenCount","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"uint256"}],"name":"unregister","outputs":[],"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"fromAddress","outputs":[{"name":"id","type":"uint256"},{"name":"tla","type":"string"},{"name":"base","type":"uint256"},{"name":"name","type":"string"},{"name":"owner","type":"address"}],"type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"uint256"},{"name":"_key","type":"bytes32"},{"name":"_value","type":"bytes32"}],"name":"setMeta","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"fee","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"tla","type":"string"},{"indexed":true,"name":"id","type":"uint256"},{"indexed":false,"name":"addr","type":"address"},{"indexed":false,"name":"name","type":"string"}],"name":"Registered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"tla","type":"string"},{"indexed":true,"name":"id","type":"uint256"}],"name":"Unregistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"uint256"},{"indexed":true,"name":"key","type":"bytes32"},{"indexed":false,"name":"value","type":"bytes32"}],"name":"MetaChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"old","type":"address"},{"indexed":true,"name":"current","type":"address"}],"name":"NewOwner","type":"event"}] diff --git a/js/src/contracts/contracts.js b/js/src/contracts/contracts.js new file mode 100644 index 0000000000000000000000000000000000000000..c9d1c2390a0bbf9292e2ee838ef7e584802d47a9 --- /dev/null +++ b/js/src/contracts/contracts.js @@ -0,0 +1,58 @@ +// 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 DappReg from './dappreg'; +import Registry from './registry'; +import SignatureReg from './signaturereg'; +import TokenReg from './tokenreg'; + +let instance = null; + +export default class Contracts { + constructor (api) { + instance = this; + + this._api = api; + this._registry = new Registry(api); + this._dappreg = new DappReg(api, this._registry); + this._signaturereg = new SignatureReg(api, this._registry); + this._tokenreg = new TokenReg(api, this._registry); + } + + get registry () { + return this._registry; + } + + get dappReg () { + return this._dappreg; + } + + get signatureReg () { + return this._signaturereg; + } + + get tokenReg () { + return this._tokenreg; + } + + static create (api) { + return new Contracts(api); + } + + static get () { + return instance; + } +} diff --git a/js/src/contracts/dappreg.js b/js/src/contracts/dappreg.js new file mode 100644 index 0000000000000000000000000000000000000000..5272f656126fe1e63be6e2a56b053f78b5b38b79 --- /dev/null +++ b/js/src/contracts/dappreg.js @@ -0,0 +1,60 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class DappReg { + constructor (api, registry) { + this._api = api; + this._registry = registry; + + this.getInstance(); + } + + getInstance () { + return this._registry.getContractInstance('dappreg'); + } + + count () { + return this.getInstance().then((instance) => { + return instance.count.call(); + }); + } + + at (index) { + return this.getInstance().then((instance) => { + return instance.at.call({}, [index]); + }); + } + + get (id) { + return this.getInstance().then((instance) => { + return instance.get.call({}, [id]); + }); + } + + meta (id, key) { + return this.getInstance().then((instance) => { + return instance.meta.call({}, [id, key]); + }); + } + + getImage (id) { + return this.meta(id, 'IMG'); + } + + getContent (id) { + return this.meta(id, 'CONTENT'); + } +} diff --git a/js/src/contracts/index.js b/js/src/contracts/index.js new file mode 100644 index 0000000000000000000000000000000000000000..075837ce6518cda55b6cb1b885a46d0b6b77eefa --- /dev/null +++ b/js/src/contracts/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './contracts'; diff --git a/js/src/contracts/registry.js b/js/src/contracts/registry.js new file mode 100644 index 0000000000000000000000000000000000000000..85b9d6bb51c99ff81f5cf1f65c3cbdd47f595116 --- /dev/null +++ b/js/src/contracts/registry.js @@ -0,0 +1,76 @@ +// 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 * as abis from './abi'; + +export default class Registry { + constructor (api) { + this._api = api; + this._contracts = []; + this._instance = null; + + this.getInstance(); + } + + getInstance () { + return new Promise((resolve, reject) => { + if (this._instance) { + resolve(this._instance); + return; + } + + this._api.ethcore + .registryAddress() + .then((address) => { + this._instance = this._api.newContract(abis.registry, address).instance; + resolve(this._instance); + }) + .catch(reject); + }); + } + + getContractInstance (_name) { + const name = _name.toLowerCase(); + + return new Promise((resolve, reject) => { + if (this._contracts[name]) { + resolve(this._contracts[name]); + return; + } + + this + .lookupAddress(name) + .then((address) => { + this._contracts[name] = this._api.newContract(abis[name], address).instance; + resolve(this._contracts[name]); + }) + .catch(reject); + }); + } + + lookupAddress (_name) { + const name = _name.toLowerCase(); + const sha3 = this._api.util.sha3(name); + + return this.getInstance().then((instance) => { + return instance.getAddress.call({}, [sha3, 'A']); + }) + .then((address) => { + console.log('lookupAddress', name, sha3, address); + return address; + }); + } +} diff --git a/js/src/contracts/signaturereg.js b/js/src/contracts/signaturereg.js new file mode 100644 index 0000000000000000000000000000000000000000..459f165b1d219e6ae2156b8462bc4e5b719f79f7 --- /dev/null +++ b/js/src/contracts/signaturereg.js @@ -0,0 +1,34 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class SignatureReg { + constructor (api, registry) { + this._api = api; + this._registry = registry; + + this.getInstance(); + } + + getInstance () { + return this._registry.getContractInstance('signaturereg'); + } + + lookup (signature) { + return this.getInstance().then((instance) => { + return instance.entries.call({}, [signature]); + }); + } +} diff --git a/js/src/contracts/tokenreg.js b/js/src/contracts/tokenreg.js new file mode 100644 index 0000000000000000000000000000000000000000..78bd5e4d9135dd33b1e6b441966df02ed7a720c7 --- /dev/null +++ b/js/src/contracts/tokenreg.js @@ -0,0 +1,40 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default class TokenReg { + constructor (api, registry) { + this._api = api; + this._registry = registry; + + this.getInstance(); + } + + getInstance () { + return this._registry.getContractInstance('tokenreg'); + } + + tokenCount () { + return this.getInstance().then((instance) => { + return instance.tokenCount.call(); + }); + } + + token (index) { + return this.getInstance().then((instance) => { + return instance.token.call({}, [index]); + }); + } +} diff --git a/js/src/dapps/basiccoin.html b/js/src/dapps/basiccoin.html new file mode 100644 index 0000000000000000000000000000000000000000..52bc8bc578ab2a7b40bee995b79439ac56d13c5e --- /dev/null +++ b/js/src/dapps/basiccoin.html @@ -0,0 +1,17 @@ + + + + + + + + Basic Token Deployment + + +

+ + + + + + diff --git a/js/src/dapps/basiccoin.js b/js/src/dapps/basiccoin.js new file mode 100644 index 0000000000000000000000000000000000000000..e02990d14ebe0bf2a48bfaf4a00011260404878a --- /dev/null +++ b/js/src/dapps/basiccoin.js @@ -0,0 +1,47 @@ +// 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 ReactDOM from 'react-dom'; +import React from 'react'; +import { createHashHistory } from 'history'; +import { Redirect, Router, Route, useRouterHistory } from 'react-router'; + +import injectTapEventPlugin from 'react-tap-event-plugin'; +injectTapEventPlugin(); + +import Deploy from './basiccoin/Deploy'; +import Application from './basiccoin/Application'; +import Overview from './basiccoin/Overview'; +import Transfer from './basiccoin/Transfer'; + +const routerHistory = useRouterHistory(createHashHistory)({}); + +import '../../assets/fonts/Roboto/font.css'; +import '../../assets/fonts/RobotoMono/font.css'; +import './style.css'; +import './basiccoin.html'; + +ReactDOM.render( + + + + + + + + , + document.querySelector('#container') +); diff --git a/js/src/dapps/basiccoin/AddressSelect/addressSelect.css b/js/src/dapps/basiccoin/AddressSelect/addressSelect.css new file mode 100644 index 0000000000000000000000000000000000000000..ddfd334e8bdcb570cb2448349d04cea141d39603 --- /dev/null +++ b/js/src/dapps/basiccoin/AddressSelect/addressSelect.css @@ -0,0 +1,23 @@ +/* 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 . +*/ + +.iconMenu { +} + +.iconMenu option { + padding-left: 30px; +} diff --git a/js/src/dapps/basiccoin/AddressSelect/addressSelect.js b/js/src/dapps/basiccoin/AddressSelect/addressSelect.js new file mode 100644 index 0000000000000000000000000000000000000000..529e7753d980b3f36797cc1b0108eaec55cd40e8 --- /dev/null +++ b/js/src/dapps/basiccoin/AddressSelect/addressSelect.js @@ -0,0 +1,93 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import styles from './addressSelect.css'; + +export default class AddressSelect extends Component { + static contextTypes = { + accounts: PropTypes.object.isRequired + } + + static propTypes = { + addresses: PropTypes.array.isRequired, + onChange: PropTypes.func.isRequired + } + + state = { + selected: null + } + + componentDidMount () { + const { addresses } = this.props; + + this.onChange({ + target: { + value: addresses[0] + } + }); + } + + componentWillReceiveProps (newProps) { + const { addresses } = this.props; + let changed = addresses.length !== newProps.addresses.length; + + if (!changed) { + changed = addresses.filter((address, index) => newProps.addresses[index] !== address).length; + } + + if (changed) { + this.onChange({ target: { value: newProps.addresses[0] } }); + } + } + + render () { + const { addresses } = this.props; + const { selectedAddress } = this.state; + const style = { + background: `rgba(255, 255, 255, 0.75) url(${api.util.createIdentityImg(selectedAddress, 3)}) no-repeat 98% center` + }; + + return ( + + ); + } + + renderOption = (address) => { + const { accounts } = this.context; + const account = accounts[address]; + + return ( + + ); + } + + onChange = (event) => { + this.setState({ selectedAddress: event.target.value }); + this.props.onChange(event); + } +} diff --git a/js/src/dapps/basiccoin/AddressSelect/index.js b/js/src/dapps/basiccoin/AddressSelect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..58059cd2e1ed7ab7091ed5e46191bdca69a0cf1e --- /dev/null +++ b/js/src/dapps/basiccoin/AddressSelect/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './addressSelect'; diff --git a/js/src/dapps/basiccoin/Application/Header/header.css b/js/src/dapps/basiccoin/Application/Header/header.css new file mode 100644 index 0000000000000000000000000000000000000000..5416d7c05c8ea8af321eb7272efc4f117332966b --- /dev/null +++ b/js/src/dapps/basiccoin/Application/Header/header.css @@ -0,0 +1,71 @@ +/* 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 . +*/ + +.header { +} + +.titlebar { + padding: 0.5em 1em; + margin: 0; + color: white; +} + +.navigation { + table-layout: fixed; + width: 100%; + border-spacing: 0.25em; + border-collapse: separate; + border-color: white; + background: white; +} + +.navigation tr { + height: 10em; +} + +.title { + font-size: 1.25em; + margin-bottom: 0.25em; +} + +.byline { + font-size: 1em; + opacity: 0.75; + margin-bottom: 0.25em; +} + +.description { + font-size: 0.5em; + opacity: 0.5; + line-height: 1.5em; +} + +.navNext, +.navCurrent { + color: white; + padding: 1em 2em; + vertical-align: middle; +} + +.navNext:hover { + cursor: pointer; + opacity: 0.8; +} + +.navCurrent { + font-size: 2em; +} diff --git a/js/src/dapps/basiccoin/Application/Header/header.js b/js/src/dapps/basiccoin/Application/Header/header.js new file mode 100644 index 0000000000000000000000000000000000000000..90fa909ef06df8a87352ce5898f3a97f4749890f --- /dev/null +++ b/js/src/dapps/basiccoin/Application/Header/header.js @@ -0,0 +1,80 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import PAGES from '../pages'; +import styles from './header.css'; + +export default class Header extends Component { + static contextTypes = { + router: PropTypes.object.isRequired + } + + render () { + const path = (window.location.hash || '').split('?')[0].split('/')[1]; + const offset = PAGES.findIndex((header) => header.path === path); + + return ( +
+ + + + { this.renderHeader(0, offset) } + { this.renderHeader(1, offset) } + + + { this.renderHeader(2, offset) } + + +
+
+ ); + } + + renderHeader (position, offset) { + const index = (position + offset) % PAGES.length; + const page = PAGES[index]; + const background = `rgba(102, 34, 34, ${1 - (0.1 * position)})`; + + return ( + +
+ { page.title } +
+
+ { page.byline } +
+
+ { position ? null : page.description } +
+ + ); + } + + onNavigate = (route) => { + const { router } = this.context; + + return (event) => { + router.push(`/${route}`); + }; + } +} diff --git a/js/src/dapps/basiccoin/Application/Header/index.js b/js/src/dapps/basiccoin/Application/Header/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4a51219067e9b777d9e8180f84449d146f85df3d --- /dev/null +++ b/js/src/dapps/basiccoin/Application/Header/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './header'; diff --git a/js/src/dapps/basiccoin/Application/Loading/index.js b/js/src/dapps/basiccoin/Application/Loading/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0468cab37dfd505cb0b1ef415376ca121ab9ca89 --- /dev/null +++ b/js/src/dapps/basiccoin/Application/Loading/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './loading'; diff --git a/js/src/dapps/basiccoin/Application/Loading/loading.css b/js/src/dapps/basiccoin/Application/Loading/loading.css new file mode 100644 index 0000000000000000000000000000000000000000..915cc77dc2142a569c8dce941a8f7d5cfa144e1f --- /dev/null +++ b/js/src/dapps/basiccoin/Application/Loading/loading.css @@ -0,0 +1,24 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.body { + width: 100%; + text-align: center; + padding-top: 5em; + font-size: 2em; + color: #999; +} diff --git a/js/src/dapps/basiccoin/Application/Loading/loading.js b/js/src/dapps/basiccoin/Application/Loading/loading.js new file mode 100644 index 0000000000000000000000000000000000000000..e698a0e80b395ead4e0b606c9abd9315fc78e5e7 --- /dev/null +++ b/js/src/dapps/basiccoin/Application/Loading/loading.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; + +import styles from './loading.css'; + +export default class Loading extends Component { + render () { + return ( +
+ Attaching to contract ... +
+ ); + } +} diff --git a/js/src/dapps/basiccoin/Application/application.css b/js/src/dapps/basiccoin/Application/application.css new file mode 100644 index 0000000000000000000000000000000000000000..97b66be8759fcb1748ea8bab2a91ca5c08a461ee --- /dev/null +++ b/js/src/dapps/basiccoin/Application/application.css @@ -0,0 +1,28 @@ +/* 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 . +*/ + +.container { + color: #444; + font-family: 'Roboto'; + vertical-align: middle; + min-height: 100vh; + position:relative; +} + +.body { + padding: 0 0.25em; +} diff --git a/js/src/dapps/basiccoin/Application/application.js b/js/src/dapps/basiccoin/Application/application.js new file mode 100644 index 0000000000000000000000000000000000000000..4ab97ab6c7fac6f8787f26ed783965ebcb284df9 --- /dev/null +++ b/js/src/dapps/basiccoin/Application/application.js @@ -0,0 +1,108 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import { attachInstances } from '../services'; + +import Header from './Header'; +import Loading from './Loading'; + +import styles from './application.css'; + +export default class Application extends Component { + static childContextTypes = { + accounts: PropTypes.object, + managerInstance: PropTypes.object, + registryInstance: PropTypes.object, + tokenregInstance: PropTypes.object + } + + static propTypes = { + children: PropTypes.node.isRequired + } + + state = { + accounts: null, + loading: true, + managerInstance: null, + registryInstance: null, + tokenregInstance: null + } + + componentDidMount () { + this.attachInstance(); + } + + render () { + const { children } = this.props; + const { loading } = this.state; + + if (loading) { + return ( + + ); + } + + return ( +
+
+
+ { children } +
+
+ ); + } + + getChildContext () { + const { accounts, managerInstance, registryInstance, tokenregInstance } = this.state; + + return { + accounts, + managerInstance, + registryInstance, + tokenregInstance + }; + } + + attachInstance () { + Promise + .all([ + attachInstances(), + api.personal.accountsInfo() + ]) + .then(([{ managerInstance, registryInstance, tokenregInstance }, accountsInfo]) => { + accountsInfo = accountsInfo || {}; + this.setState({ + loading: false, + managerInstance, + registryInstance, + tokenregInstance, + accounts: Object + .keys(accountsInfo) + .filter((address) => !accountsInfo[address].meta.deleted) + .sort((a, b) => { + return (accountsInfo[b].uuid || '').localeCompare(accountsInfo[a].uuid || ''); + }) + .reduce((accounts, address) => { + accounts[address] = Object.assign(accountsInfo[address], { address }); + return accounts; + }, {}) + }); + }); + } +} diff --git a/js/src/dapps/basiccoin/Application/index.js b/js/src/dapps/basiccoin/Application/index.js new file mode 100644 index 0000000000000000000000000000000000000000..236578226a80e822593c37acd1daad1c649950e1 --- /dev/null +++ b/js/src/dapps/basiccoin/Application/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './application'; diff --git a/js/src/dapps/basiccoin/Application/pages.js b/js/src/dapps/basiccoin/Application/pages.js new file mode 100644 index 0000000000000000000000000000000000000000..5ab422ee4aaf1425f26a2c4069af101c1acb7eed --- /dev/null +++ b/js/src/dapps/basiccoin/Application/pages.js @@ -0,0 +1,38 @@ +// 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 . + +const PAGES = [ + { + path: 'overview', + title: 'Overview', + byline: 'Display all the current information relating to your own deployed tokens', + description: 'View the total number of tokens in circulation, the number of different tokens associated with your accounts as well as the types of tokens created by you. In addition view the balances associated with your accounts in reltion to the total in circulation.' + }, + { + path: 'transfer', + title: 'Transfer', + byline: 'Send tokens associated with your accounts to other addresses', + description: 'Send any tokens created byt you or received from others. In addition have a bird\'s eye view of all events relating to token transfers, be it yours, created byt others, either local or globally available on the network.' + }, + { + path: 'deploy', + title: 'Deploy', + byline: 'Deploy a new token to the network', + description: 'Token registration has never been this easy. Select the name for your token, the TLA and the number of tokens in circulation. Start sending the tokens to contacts right from this interface. Optionally you can register the token with the Token Registry which would allow you to transaction in tokens from anywhere these transactions are allowed.' + } +]; + +export default PAGES; diff --git a/js/src/dapps/basiccoin/Container/container.css b/js/src/dapps/basiccoin/Container/container.css new file mode 100644 index 0000000000000000000000000000000000000000..7cc00e11e2100f4043429728a74e284da137001c --- /dev/null +++ b/js/src/dapps/basiccoin/Container/container.css @@ -0,0 +1,26 @@ +/* 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 . +*/ + +.content { + padding: 4em; + margin-bottom: 0.25em; + text-align: center; +} + +.content:nth-child(odd) { + background: rgba(102, 34, 34, 0.075); +} diff --git a/js/src/dapps/basiccoin/Container/container.js b/js/src/dapps/basiccoin/Container/container.js new file mode 100644 index 0000000000000000000000000000000000000000..82805e71b57f2a5ce7bcedc5b89fd1d8ce5d9ec3 --- /dev/null +++ b/js/src/dapps/basiccoin/Container/container.js @@ -0,0 +1,37 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import styles from './container.css'; + +export default class Container extends Component { + static propTypes = { + className: PropTypes.string, + children: PropTypes.node.isRequired + } + + render () { + const { className, children } = this.props; + const classes = `${styles.content} ${className}`; + + return ( +
+ { children } +
+ ); + } +} diff --git a/js/src/dapps/basiccoin/Container/index.js b/js/src/dapps/basiccoin/Container/index.js new file mode 100644 index 0000000000000000000000000000000000000000..87fbc567ef2f3db31a65d206720db12454dfcd7e --- /dev/null +++ b/js/src/dapps/basiccoin/Container/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './container'; diff --git a/js/src/dapps/basiccoin/Deploy/Deployment/deployment.css b/js/src/dapps/basiccoin/Deploy/Deployment/deployment.css new file mode 100644 index 0000000000000000000000000000000000000000..f24729cf78f137745c89c403460898956bbdf44e --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Deployment/deployment.css @@ -0,0 +1,19 @@ +/* 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 '../../_form.css'; +@import '../../_status.css'; diff --git a/js/src/dapps/basiccoin/Deploy/Deployment/deployment.js b/js/src/dapps/basiccoin/Deploy/Deployment/deployment.js new file mode 100644 index 0000000000000000000000000000000000000000..f9232789b11ce1079caecc46aadeaf8c6fa66c0c --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Deployment/deployment.js @@ -0,0 +1,320 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../../parity'; +import AddressSelect from '../../AddressSelect'; +import Container from '../../Container'; +import styles from './deployment.css'; + +const ERRORS = { + name: 'specify a valid name >2 & <32 characters', + tla: 'specify a valid TLA, 3 characters in length', + usedtla: 'the TLA used is not available for registration', + supply: 'supply needs to be valid >999 & <1 trillion' +}; + +export default class Deployment extends Component { + static contextTypes = { + accounts: PropTypes.object.isRequired, + router: PropTypes.object.isRequired, + managerInstance: PropTypes.object.isRequired, + registryInstance: PropTypes.object.isRequired, + tokenregInstance: PropTypes.object.isRequired + } + + state = { + base: null, + deployBusy: false, + deployDone: false, + deployError: null, + deployState: null, + globalReg: false, + globalFee: 0, + globalFeeText: '1.000', + fromAddress: null, + name: '', + nameError: ERRORS.name, + tla: '', + tlaError: ERRORS.tla, + totalSupply: '5000000', + totalSupplyError: null, + signerRequestId: null, + txHash: null + } + + componentDidMount () { + const { managerInstance, tokenregInstance } = this.context; + + Promise + .all([ + managerInstance.base.call(), + tokenregInstance.fee.call() + ]) + .then(([base, globalFee]) => { + this.setState({ + base, + baseText: base.toFormat(0), + globalFee, + globalFeeText: api.util.fromWei(globalFee).toFormat(3) + }); + }); + } + + render () { + const { deployBusy } = this.state; + + return deployBusy + ? this.renderDeploying() + : this.renderForm(); + } + + renderDeploying () { + const { deployDone, deployError, deployState } = this.state; + + if (deployDone) { + return ( + +
+ Your token has been deployed +
+
+ ); + } + + if (deployError) { + return ( + +
+ Your deployment has encountered an error +
+
+ { deployError } +
+
+ ); + } + + return ( + +
+ Your token is currently being deployed to the network +
+
+ { deployState } +
+
+ ); + } + + renderForm () { + const { accounts } = this.context; + const { baseText, name, nameError, tla, tlaError, totalSupply, totalSupplyError } = this.state; + const hasError = !!(nameError || tlaError || totalSupplyError); + const error = `${styles.input} ${styles.error}`; + const addresses = Object.keys(accounts).filter((address) => accounts[address].uuid); + + //
+ // + // + //
+ // register on network (fee: { globalFeeText }ETH) + //
+ //
+ + return ( + +
+
+ + +
+ the owner account to eploy from +
+
+
+ + +
+ { nameError || 'an identifying name for the token' } +
+
+
+ + +
+ { tlaError || 'unique network acronym for this token' } +
+
+
+ + +
+ { totalSupplyError || `number of tokens (base: ${baseText})` } +
+
+
+
+
+
+ ); + } + + onChangeFrom = (event) => { + const fromAddress = event.target.value; + + this.setState({ fromAddress }); + } + + onChangeName = (event) => { + const name = event.target.value; + const nameError = name && (name.length > 2) && (name.length < 32) + ? null + : ERRORS.name; + + this.setState({ name, nameError }); + } + + onChangeRegistrar = (event) => { + this.setState({ globalReg: event.target.value === 'yes' }, this.testTlaAvailability); + } + + onChangeSupply = (event) => { + const totalSupply = parseInt(event.target.value, 10); + const totalSupplyError = isFinite(totalSupply) && totalSupply > 999 + ? null + : ERRORS.supply; + + this.setState({ totalSupply, totalSupplyError }); + } + + onChangeTla = (event) => { + const _tla = event.target.value; + const tla = _tla && (_tla.length > 3) + ? _tla.substr(0, 3) + : _tla; + const tlaError = tla && (tla.length === 3) + ? null + : ERRORS.tla; + + this.setState({ tla, tlaError }, this.testTlaAvailability); + } + + testTlaAvailability = () => { + const { registryInstance, tokenregInstance } = this.context; + const { globalReg, tla, tlaError } = this.state; + const tokenreg = globalReg ? tokenregInstance : registryInstance; + + if (tlaError && tlaError !== ERRORS.usedtla) { + return; + } + + tokenreg + .fromTLA.call({}, [tla]) + .then(([id, addr, base, name, owner]) => { + if (owner !== '0x0000000000000000000000000000000000000000') { + this.setState({ tlaError: ERRORS.usedtla }); + } else if (tlaError === ERRORS.usedtla) { + this.setState({ tlaError: null }); + } + }) + .catch((error) => { + console.log('testTlaAvailability', error); + }); + } + + onDeploy = () => { + const { managerInstance, registryInstance, tokenregInstance } = this.context; + const { base, deployBusy, fromAddress, globalReg, globalFee, name, nameError, tla, tlaError, totalSupply, totalSupplyError } = this.state; + const hasError = !!(nameError || tlaError || totalSupplyError); + + if (hasError || deployBusy) { + return; + } + + const tokenreg = (globalReg ? tokenregInstance : registryInstance).address; + const values = [base.mul(totalSupply), tla, name, tokenreg]; + const options = { + from: fromAddress, + value: globalReg ? globalFee : 0 + }; + + this.setState({ deployBusy: true, deployState: 'Estimating gas for the transaction' }); + + managerInstance + .deploy.estimateGas(options, values) + .then((gas) => { + this.setState({ deployState: '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 managerInstance.deploy.postTransaction(options, values); + }) + .then((signerRequestId) => { + this.setState({ signerRequestId, deployState: 'Transaction posted, Waiting for transaction authorization' }); + + return api.pollMethod('eth_checkRequest', signerRequestId); + }) + .then((txHash) => { + this.setState({ txHash, deployState: 'Transaction authorized, Waiting for network confirmations' }); + + return api.pollMethod('eth_getTransactionReceipt', txHash, (receipt) => { + if (!receipt || !receipt.blockNumber || receipt.blockNumber.eq(0)) { + return false; + } + + return true; + }); + }) + .then((txReceipt) => { + this.setState({ txReceipt, deployDone: true, deployState: 'Network confirmed, Received transaction receipt' }); + }) + .catch((error) => { + console.error('onDeploy', error); + this.setState({ deployError: error.message }); + }); + } +} diff --git a/js/src/dapps/basiccoin/Deploy/Deployment/index.js b/js/src/dapps/basiccoin/Deploy/Deployment/index.js new file mode 100644 index 0000000000000000000000000000000000000000..927cff5691faf3477f0c4aceabd9018220a7c65d --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Deployment/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './deployment'; diff --git a/js/src/dapps/basiccoin/Deploy/Event/event.css b/js/src/dapps/basiccoin/Deploy/Event/event.css new file mode 100644 index 0000000000000000000000000000000000000000..52eada915cb0faeb50c8a45dd13669ab4914ef04 --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Event/event.css @@ -0,0 +1,58 @@ +/* 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 . +*/ + +a.link, a.link:visited { + text-decoration: none; +} + +a.link:hover { + text-decoration: underline; +} + +a.link, a.link:hover, a.link:visited { + color: #822; + cursor: pointer; +} + +.mined { +} + +.pending { + opacity: 0.5; +} + +.mined td, +.pending td { + padding: 0.5em 1em; + line-height: 24px; +} + +.blocknumber { + text-align: right; +} + +.address { + text-align: left; +} + +.description { + text-align: left; +} + +.center { + text-align: right; +} diff --git a/js/src/dapps/basiccoin/Deploy/Event/event.js b/js/src/dapps/basiccoin/Deploy/Event/event.js new file mode 100644 index 0000000000000000000000000000000000000000..889822208dce385df6c08e62b3cd98ce2b487e8e --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Event/event.js @@ -0,0 +1,103 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import moment from 'moment'; +import React, { Component, PropTypes } from 'react'; + +import { api } from '../../parity'; +import { getCoin, txLink } from '../../services'; +import IdentityIcon from '../../IdentityIcon'; + +import styles from './event.css'; + +export default class Event extends Component { + static contextTypes = { + accounts: PropTypes.object.isRequired, + registryInstance: PropTypes.object.isRequired, + tokenregInstance: PropTypes.object.isRequired + } + + static propTypes = { + event: PropTypes.object.isRequired + } + + state = { + block: null, + coin: {} + } + + componentDidMount () { + this.lookup(); + } + + render () { + const { event } = this.props; + const { block, coin } = this.state; + const isPending = event.type === 'pending'; + + return ( + + +
{ (isPending || !block) ? '' : moment(block.timestamp).fromNow() }
+
{ isPending ? 'Pending' : event.blockNumber.toFormat() }
+ + { event.event } + +
{ isPending ? '' : coin.tla }
+
{ isPending ? '' : coin.name }
+ + + { this.renderAddress(event.params.owner) } +
+ + { isPending || !coin.isGlobal ? '' : 'global' } + + ); + } + + renderAddress (address) { + const { accounts } = this.context; + const account = accounts[address]; + + return ( +
+ + { account ? account.name : address } +
+ ); + } + + renderHash (hash) { + return `${hash.substr(0, 10)}...${hash.slice(-10)}`; + } + + lookup () { + const { event } = this.props; + + if (event.type === 'pending') { + return; + } + + Promise + .all([ + api.eth.getBlockByNumber(event.blockNumber), + getCoin(event.params.tokenreg, event.params.coin) + ]) + .then(([block, coin]) => { + this.setState({ block, coin }); + }); + } +} diff --git a/js/src/dapps/basiccoin/Deploy/Event/index.js b/js/src/dapps/basiccoin/Deploy/Event/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0925882d3e3ed35d3e6e0decfd8ab3e18d451052 --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Event/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './event'; diff --git a/js/src/dapps/basiccoin/Deploy/Events/events.css b/js/src/dapps/basiccoin/Deploy/Events/events.css new file mode 100644 index 0000000000000000000000000000000000000000..3cefaacb0b7efdea5738b394da90023ab9b06fb4 --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Events/events.css @@ -0,0 +1,33 @@ +/* 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 . +*/ + +.statusHeader { + font-size: 1.25em; +} + +.eventList { + border: none; + margin: 0 auto; + border-collapse: collapse; +} + +.eventList tr:nth-child(even) { + background: rgba(102, 34, 34, 0.075); +} + +.eventList tr:nth-child(odd) { +} diff --git a/js/src/dapps/basiccoin/Deploy/Events/events.js b/js/src/dapps/basiccoin/Deploy/Events/events.js new file mode 100644 index 0000000000000000000000000000000000000000..4b51afb59b67847b03e5f3429b68809f7a650c26 --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Events/events.js @@ -0,0 +1,145 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../../parity'; +import Container from '../../Container'; +import Event from '../Event'; + +import styles from './events.css'; + +export default class Events extends Component { + static contextTypes = { + managerInstance: PropTypes.object.isRequired + } + + state = { + blocks: {}, + loading: true, + events: [], + minedEvents: [], + pendingEvents: [] + } + + componentDidMount () { + const { managerInstance } = this.context; + const options = { + fromBlock: 0, + toBlock: 'pending', + limit: 50 + }; + + managerInstance.Created + .subscribe(options, this.receiveCreatedEvents) + .then((subscriptionIdCreated) => { + this.setState({ subscriptionIdCreated }); + }); + } + + componentWillUnmount () { + const { managerInstance } = this.context; + const { subscriptionIdCreated } = this.state; + + managerInstance.Created.unsubscribe(subscriptionIdCreated); + } + + render () { + const { loading } = this.state; + + return ( + + { loading ? this.renderLoading() : this.renderEvents() } + + ); + } + + renderEvents () { + const { events } = this.state; + + return events.length + ? this.renderEventsList() + : this.renderEventsNone(); + } + + renderEventsNone () { + return ( +
+ There are currently no events available +
+ ); + } + + renderEventsList () { + const { events } = this.state; + const rows = events.map((event) => { + return ( + + ); + }); + + return ( + + + { rows } + +
+ ); + } + + renderLoading () { + return ( +
+ Loading events +
+ ); + } + + logToEvent = (log) => { + log.key = api.util.sha3(JSON.stringify(log)); + log.params = Object.keys(log.params).reduce((params, name) => { + params[name] = log.params[name].value; + return params; + }, {}); + + return log; + } + + receiveCreatedEvents = (error, logs) => { + if (error) { + console.error('receiveLogs', error); + return; + } + + const { minedEvents, pendingEvents } = this.state; + const minedNew = logs + .filter((log) => log.type === 'mined') + .map(this.logToEvent) + .filter((log) => !minedEvents.find((event) => event.transactionHash === log.transactionHash)) + .reverse() + .concat(minedEvents); + const pendingNew = logs + .filter((log) => log.type === 'pending') + .map(this.logToEvent) + .filter((log) => !pendingEvents.find((event) => event.transactionHash === log.transactionHash)) + .reverse() + .concat(pendingEvents) + .filter((log) => !minedNew.find((event) => event.transactionHash === log.transactionHash)); + const events = [].concat(pendingNew).concat(minedNew); + + this.setState({ loading: false, events, minedEvents: minedNew, pendingEvents: pendingNew }); + } +} diff --git a/js/src/dapps/basiccoin/Deploy/Events/index.js b/js/src/dapps/basiccoin/Deploy/Events/index.js new file mode 100644 index 0000000000000000000000000000000000000000..88ad6d407c91e416ead5fef1cf8c93201cac529b --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/Events/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './events'; diff --git a/js/src/dapps/basiccoin/Deploy/deploy.js b/js/src/dapps/basiccoin/Deploy/deploy.js new file mode 100644 index 0000000000000000000000000000000000000000..34c7eed8a32bfe6a998d042365aad629b9daac45 --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/deploy.js @@ -0,0 +1,31 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; + +import Deployment from './Deployment'; +import Events from './Events'; + +export default class Deploy extends Component { + render () { + return ( +
+ + +
+ ); + } +} diff --git a/js/src/dapps/basiccoin/Deploy/index.js b/js/src/dapps/basiccoin/Deploy/index.js new file mode 100644 index 0000000000000000000000000000000000000000..53b4dbcfe5502b3abff063551aeab808e1591b3a --- /dev/null +++ b/js/src/dapps/basiccoin/Deploy/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './deploy'; diff --git a/js/src/dapps/basiccoin/IdentityIcon/identityIcon.css b/js/src/dapps/basiccoin/IdentityIcon/identityIcon.css new file mode 100644 index 0000000000000000000000000000000000000000..6abbcf808b7519bf1886a7b345f8f069ce87d4d6 --- /dev/null +++ b/js/src/dapps/basiccoin/IdentityIcon/identityIcon.css @@ -0,0 +1,22 @@ +/* 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 . +*/ + +.icon { + width: 24px; + height: 24px; + margin: 0 0.5em -4px 0; +} diff --git a/js/src/dapps/basiccoin/IdentityIcon/identityIcon.js b/js/src/dapps/basiccoin/IdentityIcon/identityIcon.js new file mode 100644 index 0000000000000000000000000000000000000000..ee1374f7ec9ccea166612662ec012f826473684b --- /dev/null +++ b/js/src/dapps/basiccoin/IdentityIcon/identityIcon.js @@ -0,0 +1,38 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import styles from './identityIcon.css'; + +export default class IdentityIcon extends Component { + static propTypes = { + address: PropTypes.string.isRequired, + className: PropTypes.string + } + + render () { + const { address, className } = this.props; + const classes = `${styles.icon} ${className}`; + + return ( + + ); + } +} diff --git a/js/src/dapps/basiccoin/IdentityIcon/index.js b/js/src/dapps/basiccoin/IdentityIcon/index.js new file mode 100644 index 0000000000000000000000000000000000000000..76c107bfb7540f707a9b2665aac9b52f9d7590fa --- /dev/null +++ b/js/src/dapps/basiccoin/IdentityIcon/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './identityIcon'; diff --git a/js/src/dapps/basiccoin/Overview/Owner/index.js b/js/src/dapps/basiccoin/Overview/Owner/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4f38b38b9cce3c5fbb9318288f15177881490015 --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/Owner/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './owner'; diff --git a/js/src/dapps/basiccoin/Overview/Owner/owner.css b/js/src/dapps/basiccoin/Overview/Owner/owner.css new file mode 100644 index 0000000000000000000000000000000000000000..13e89d06123deeb3e97f4e8fa17e5a5cced2ca75 --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/Owner/owner.css @@ -0,0 +1,48 @@ +/* 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 . +*/ + +.info { +} + +.owner { + vertical-align: top; + text-align: right; +} + +.owner>div { + border-radius: 1px; + padding: 1em 2em; + white-space: nowrap; +} + +.tokens { + text-align: left; +} + +.tokens>div { + border-radius: 1px; + background: #988; + padding: 1em; + margin: 0 0 0.25em 0.25em; + display: inline-block; + white-space: nowrap; + color: white; +} + +.icon { + margin: 0 0 -4px 1em; +} diff --git a/js/src/dapps/basiccoin/Overview/Owner/owner.js b/js/src/dapps/basiccoin/Overview/Owner/owner.js new file mode 100644 index 0000000000000000000000000000000000000000..cc30036937c2f4718e9c20da6a1d4f5e272f233a --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/Owner/owner.js @@ -0,0 +1,74 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import IdentityIcon from '../../IdentityIcon'; +import Token from '../Token'; +import styles from './owner.css'; + +export default class Owner extends Component { + static contextTypes = { + accounts: PropTypes.object.isRequired, + managerInstance: PropTypes.object.isRequired + } + + static propTypes = { + address: PropTypes.string.isRequired, + tokens: PropTypes.array.isRequired + } + + state = { + tokens: [] + } + + render () { + const { accounts } = this.context; + const { address, tokens } = this.props; + + if (!tokens.length) { + return null; + } + + return ( + + +
+ { accounts[address].name } + +
+ + + { this.renderTokens() } + + + ); + } + + renderTokens () { + const { tokens } = this.props; + + return tokens.map((token) => ( +
+ +
+ )); + } +} diff --git a/js/src/dapps/basiccoin/Overview/Token/index.js b/js/src/dapps/basiccoin/Overview/Token/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b822b4bdf7c1d731ef6e68055be06e6cc85d0ec --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/Token/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './token'; diff --git a/js/src/dapps/basiccoin/Overview/Token/token.css b/js/src/dapps/basiccoin/Overview/Token/token.css new file mode 100644 index 0000000000000000000000000000000000000000..5324aa7c5a13bec460a86be3e19aa2bfc5e4e584 --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/Token/token.css @@ -0,0 +1,53 @@ +/* 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 . +*/ + +.info { +} + +.info>div { + display: inline-block; + padding: 0.25em 0.5em; + vertical-align: middle; +} + +.address { +} + +.tla { + background: #766; + border-radius: 1px; +} + +.name { +} + +.supply { +} + +.supply div { + display: block; + text-align: center; +} + +.supply .info { + font-size: 0.75em; + opacity: 0.75; +} + +.global { + font-size: 0.75em; +} diff --git a/js/src/dapps/basiccoin/Overview/Token/token.js b/js/src/dapps/basiccoin/Overview/Token/token.js new file mode 100644 index 0000000000000000000000000000000000000000..b0d4a965a677e09d0d99b73f4a59d2c2650a2fce --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/Token/token.js @@ -0,0 +1,68 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { totalSupply, getCoin } from '../../services'; +import styles from './token.css'; + +export default class Token extends Component { + static propTypes = { + address: PropTypes.string.isRequired, + tokenreg: PropTypes.string.isRequired + } + + state = { + coin: null, + totalSupply: null + } + + componentDidMount () { + this.lookupToken(); + } + + render () { + const { coin, totalSupply } = this.state; + + if (!coin) { + return null; + } + + return ( +
+
{ coin.tla }
+
{ coin.name }
+
+
{ totalSupply.div(1000000).toFormat(0) }
+
total supply
+
+
+ ); + } + + lookupToken () { + const { address, tokenreg } = this.props; + + Promise + .all([ + getCoin(tokenreg, address), + totalSupply(address) + ]) + .then(([coin, totalSupply]) => { + this.setState({ coin, totalSupply }); + }); + } +} diff --git a/js/src/dapps/basiccoin/Overview/index.js b/js/src/dapps/basiccoin/Overview/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d61fb3fb440eef130a4db9ad4f464cf94c533c27 --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './overview'; diff --git a/js/src/dapps/basiccoin/Overview/overview.css b/js/src/dapps/basiccoin/Overview/overview.css new file mode 100644 index 0000000000000000000000000000000000000000..9757a81458c022e0b4f3f12c0e958be523b5ed38 --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/overview.css @@ -0,0 +1,26 @@ +/* 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 '../_status.css'; + +.body { +} + +.ownerTable { + margin: 0 auto; + border-collapse: collapse; +} diff --git a/js/src/dapps/basiccoin/Overview/overview.js b/js/src/dapps/basiccoin/Overview/overview.js new file mode 100644 index 0000000000000000000000000000000000000000..46831d782ff6b2b3af60b2366816c9e3dcbbf1ea --- /dev/null +++ b/js/src/dapps/basiccoin/Overview/overview.js @@ -0,0 +1,107 @@ +// 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 BigNumber from 'bignumber.js'; +import React, { Component, PropTypes } from 'react'; + +import { loadOwnedTokens } from '../services'; +import Container from '../Container'; +import Owner from './Owner'; + +import styles from './overview.css'; + +export default class Overview extends Component { + static contextTypes = { + accounts: PropTypes.object.isRequired, + managerInstance: PropTypes.object.isRequired + } + + state = { + loading: true, + total: new BigNumber(0), + tokenOwners: [] + } + + componentDidMount () { + this.loadOwners(); + } + + render () { + const { loading } = this.state; + + return ( + + { loading ? this.renderLoading() : this.renderBody() } + + ); + } + + renderLoading () { + return ( +
+ Loading tokens +
+ ); + } + + renderBody () { + const { total } = this.state; + let owners = null; + + if (total.gt(0)) { + owners = ( + + + { this.renderOwners() } + +
+ ); + } + + return ( +
+
+ You have { total.toFormat(0) } tokens created by your accounts +
+ { owners } +
+ ); + } + + renderOwners () { + const { tokens } = this.state; + + return Object.keys(tokens).map((address) => ( + + )); + } + + loadOwners () { + const { accounts } = this.context; + const addresses = Object + .values(accounts) + .filter((account) => account.uuid) + .map((account) => account.address); + + loadOwnedTokens(addresses) + .then(({ tokens, total }) => { + this.setState({ tokens, total, loading: false }); + }); + } +} diff --git a/js/src/dapps/basiccoin/Transfer/Event/event.js b/js/src/dapps/basiccoin/Transfer/Event/event.js new file mode 100644 index 0000000000000000000000000000000000000000..190035b1d43579b0d286eff145cd140520a69dbb --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/Event/event.js @@ -0,0 +1,106 @@ +// 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 . + +// TODO: This is a copy & paste for Deploy/Event -> render() different. Not very DRY +import moment from 'moment'; +import React, { Component, PropTypes } from 'react'; + +import { api } from '../../parity'; +import { txLink } from '../../services'; +import IdentityIcon from '../../IdentityIcon'; +import styles from '../../Deploy/Event/event.css'; + +export default class Event extends Component { + static contextTypes = { + accounts: PropTypes.object.isRequired, + registryInstance: PropTypes.object.isRequired, + tokenregInstance: PropTypes.object.isRequired + } + + static propTypes = { + event: PropTypes.object.isRequired, + token: PropTypes.object.isRequired + } + + state = { + block: null + } + + componentDidMount () { + this.lookup(); + } + + render () { + const { event, token } = this.props; + const { block } = this.state; + const isPending = event.type === 'pending'; + + return ( + + +
{ (isPending || !block) ? '' : moment(block.timestamp).fromNow() }
+
{ isPending ? 'Pending' : event.blockNumber.toFormat() }
+ + { event.event } + +
{ isPending ? '' : token.coin.tla }
+
{ isPending ? '' : token.coin.name }
+ + + { this.renderAddress(event.params.from) } + + +
{ event.params.value.div(1000000).toFormat(6) }
+
+ + + + { this.renderAddress(event.params.to) } + + + ); + } + + renderAddress (address) { + const { accounts } = this.context; + const account = accounts[address]; + + return ( +
+ + { account ? account.name : address } +
+ ); + } + + renderHash (hash) { + return `${hash.substr(0, 10)}...${hash.slice(-10)}`; + } + + lookup () { + const { event } = this.props; + + if (event.type === 'pending') { + return; + } + + api.eth + .getBlockByNumber(event.blockNumber) + .then((block) => { + this.setState({ block }); + }); + } +} diff --git a/js/src/dapps/basiccoin/Transfer/Event/index.js b/js/src/dapps/basiccoin/Transfer/Event/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0925882d3e3ed35d3e6e0decfd8ab3e18d451052 --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/Event/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './event'; diff --git a/js/src/dapps/basiccoin/Transfer/Events/events.js b/js/src/dapps/basiccoin/Transfer/Events/events.js new file mode 100644 index 0000000000000000000000000000000000000000..101c77f73a34acf4f61d86e1ee239f31d6f521bf --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/Events/events.js @@ -0,0 +1,148 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; + +import { api } from '../../parity'; +import { loadAllTokens, subscribeEvents, unsubscribeEvents } from '../../services'; +import Container from '../../Container'; +import Event from '../Event'; + +import styles from '../../Deploy/Events/events.css'; + +export default class Events extends Component { + state = { + subscriptionId: 0, + loading: true, + events: [], + pendingEvents: [], + minedEvents: [], + tokens: [] + } + + componentDidMount () { + loadAllTokens() + .then((tokens) => { + const addresses = tokens.map((token) => token.address); + this.setState({ tokens }); + return subscribeEvents(addresses, this.eventCallback); + }) + .then((subscriptionId) => { + this.setState({ subscriptionId, loading: false }); + }) + .catch((error) => { + console.error('componentDidMount', error); + }); + } + + componentWillUnmount () { + const { subscriptionId } = this.state; + + if (subscriptionId) { + unsubscribeEvents(subscriptionId); + } + } + + render () { + const { loading } = this.state; + + return ( + + { loading ? this.renderLoading() : this.renderEvents() } + + ); + } + + renderLoading () { + return ( +
+ Attaching events +
+ ); + } + + renderEvents () { + const { events } = this.state; + + return events.length + ? this.renderEventsList() + : this.renderEventsNone(); + } + + renderEventsNone () { + return ( +
+ There are currently no events available +
+ ); + } + + renderEventsList () { + const { events, tokens } = this.state; + const rows = events.map((event) => { + const token = tokens.find((token) => token.address === event.address); + + return ( + + ); + }); + + return ( + + + { rows } + +
+ ); + } + + logToEvent = (log) => { + log.key = api.util.sha3(JSON.stringify(log)); + log.params = Object.keys(log.params).reduce((params, name) => { + params[name] = log.params[name].value; + return params; + }, {}); + + return log; + } + + eventCallback = (error, logs) => { + if (error) { + console.error('eventCallback', error); + return; + } + + const { minedEvents, pendingEvents } = this.state; + const minedNew = logs + .filter((log) => log.type === 'mined') + .map(this.logToEvent) + .filter((log) => !minedEvents.find((event) => event.transactionHash === log.transactionHash)) + .reverse() + .concat(minedEvents); + const pendingNew = logs + .filter((log) => log.type === 'pending') + .map(this.logToEvent) + .filter((log) => !pendingEvents.find((event) => event.transactionHash === log.transactionHash)) + .reverse() + .concat(pendingEvents) + .filter((log) => !minedNew.find((event) => event.transactionHash === log.transactionHash)); + const events = [].concat(pendingNew).concat(minedNew); + this.setState({ loading: false, events, minedEvents: minedNew, pendingEvents: pendingNew }); + } +} diff --git a/js/src/dapps/basiccoin/Transfer/Events/index.js b/js/src/dapps/basiccoin/Transfer/Events/index.js new file mode 100644 index 0000000000000000000000000000000000000000..88ad6d407c91e416ead5fef1cf8c93201cac529b --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/Events/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './events'; diff --git a/js/src/dapps/basiccoin/Transfer/Send/index.js b/js/src/dapps/basiccoin/Transfer/Send/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ad3107789e7043f9f7acbdfa3d3070c897f09cf8 --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/Send/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './send'; diff --git a/js/src/dapps/basiccoin/Transfer/Send/send.css b/js/src/dapps/basiccoin/Transfer/Send/send.css new file mode 100644 index 0000000000000000000000000000000000000000..f24729cf78f137745c89c403460898956bbdf44e --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/Send/send.css @@ -0,0 +1,19 @@ +/* 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 '../../_form.css'; +@import '../../_status.css'; diff --git a/js/src/dapps/basiccoin/Transfer/Send/send.js b/js/src/dapps/basiccoin/Transfer/Send/send.js new file mode 100644 index 0000000000000000000000000000000000000000..aee860fe25be69859511e4745367f945a6342865 --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/Send/send.js @@ -0,0 +1,327 @@ +// 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 BigNumber from 'bignumber.js'; +import React, { Component, PropTypes } from 'react'; + +import { eip20 } from '../../../../contracts/abi'; + +import { api } from '../../parity'; +import { loadBalances } from '../../services'; +import AddressSelect from '../../AddressSelect'; +import Container from '../../Container'; + +import styles from './send.css'; + +export default class Send extends Component { + static contextTypes = { + accounts: PropTypes.object.isRequired + } + + state = { + loading: true, + tokens: null, + selectedToken: null, + availableBalances: [], + fromAddress: null, + fromBalance: null, + toAddress: null, + toKnown: true, + amount: 0, + amountError: null, + sendBusy: false, + sendError: null, + sendState: null, + sendDone: false, + signerRequestId: null, + txHash: null, + txReceipt: null + } + + componentDidMount () { + this.loadBalances(); + this.onAmountChange({ target: { value: '0' } }); + } + + render () { + const { loading } = this.state; + + return loading + ? this.renderLoading() + : this.renderBody(); + } + + renderBody () { + const { sendBusy } = this.state; + + return sendBusy + ? this.renderSending() + : this.renderForm(); + } + + renderSending () { + const { sendDone, sendError, sendState } = this.state; + + if (sendDone) { + return ( + +
+ Your token value transfer has been completed +
+
+ ); + } + + if (sendError) { + return ( + +
+ Your deployment has encountered an error +
+
+ { sendError } +
+
+ ); + } + + return ( + +
+ Your token value is being transferred +
+
+ { sendState } +
+
+ ); + } + + renderLoading () { + return ( + +
+ Loading available tokens +
+
+ ); + } + + renderForm () { + const { accounts } = this.context; + const { availableBalances, fromAddress, amount, amountError, toKnown, toAddress } = this.state; + const fromBalance = availableBalances.find((balance) => balance.address === fromAddress); + const fromAddresses = availableBalances.map((balance) => balance.address); + const toAddresses = Object.keys(accounts); + const toInput = toKnown + ? + : ; + const hasError = amountError; + const error = `${styles.input} ${styles.error}`; + const maxAmountHint = `Value to transfer (max: ${fromBalance ? fromBalance.balance.div(1000000).toFormat(6) : '1'})`; + + return ( + +
+
+ + +
+ type of token to transfer +
+
+
+ + +
+ account to transfer from +
+
+
+ + +
+ the type of address input +
+
+
+
+
+ + +
+ { amountError || maxAmountHint } +
+
+
+
+
+
+ ); + } + + renderTokens () { + const { tokens } = this.state; + + return tokens.map((token) => ( + + )); + } + + onSelectFrom = (event) => { + const fromAddress = event.target.value; + + this.setState({ fromAddress }); + } + + onChangeTo = (event) => { + const toAddress = event.target.value; + + this.setState({ toAddress }); + } + + onChangeToType = (event) => { + const toKnown = event.target.value === 'known'; + + this.setState({ toKnown }); + } + + onSelectToken = (event) => { + const { tokens } = this.state; + const address = event.target.value; + const selectedToken = tokens.find((_token) => _token.address === address); + const availableBalances = selectedToken.balances.filter((balance) => balance.balance.gt(0)); + + this.setState({ selectedToken, availableBalances }); + this.onSelectFrom({ target: { value: availableBalances[0].address } }); + } + + onAmountChange = (event) => { + const amount = parseFloat(event.target.value); + const amountError = !isFinite(amount) || amount <= 0 + ? 'amount needs to be > 0' + : null; + + this.setState({ amount, amountError }); + } + + onSend = () => { + const { amount, fromAddress, toAddress, amountError, selectedToken, sendBusy } = this.state; + const hasError = amountError; + + if (hasError || sendBusy) { + return; + } + + const values = [toAddress, new BigNumber(amount).mul(1000000).toFixed(0)]; + const options = { + from: fromAddress + }; + const instance = api.newContract(eip20, selectedToken.address).instance; + + this.setState({ sendBusy: true, sendState: 'Estimating gas for the transaction' }); + + instance + .transfer.estimateGas(options, values) + .then((gas) => { + this.setState({ sendState: '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.transfer.postTransaction(options, values); + }) + .then((signerRequestId) => { + this.setState({ signerRequestId, sendState: 'Transaction posted, Waiting for transaction authorization' }); + + return api.pollMethod('eth_checkRequest', signerRequestId); + }) + .then((txHash) => { + this.setState({ txHash, sendState: 'Transaction authorized, Waiting for network confirmations' }); + + return api.pollMethod('eth_getTransactionReceipt', txHash, (receipt) => { + if (!receipt || !receipt.blockNumber || receipt.blockNumber.eq(0)) { + return false; + } + + return true; + }); + }) + .then((txReceipt) => { + this.setState({ txReceipt, sendDone: true, sendState: 'Network confirmed, Received transaction receipt' }); + }) + .catch((error) => { + console.error('onSend', error); + this.setState({ sendError: error.message }); + }); + } + + loadBalances () { + const { accounts } = this.context; + const myAccounts = Object + .values(accounts) + .filter((account) => account.uuid) + .map((account) => account.address); + + loadBalances(myAccounts) + .then((_tokens) => { + const tokens = _tokens.filter((token) => { + for (let index = 0; index < token.balances.length; index++) { + if (token.balances[index].balance.gt(0)) { + return true; + } + } + + return false; + }); + + this.setState({ tokens, loading: false }); + this.onSelectToken({ target: { value: tokens[0].address } }); + }); + } +} diff --git a/js/src/dapps/basiccoin/Transfer/index.js b/js/src/dapps/basiccoin/Transfer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..24d36d79637acc5ad834c1240dcde31298a766d1 --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './transfer'; diff --git a/js/src/dapps/basiccoin/Transfer/transfer.js b/js/src/dapps/basiccoin/Transfer/transfer.js new file mode 100644 index 0000000000000000000000000000000000000000..842d4b7bcfbe5542608bbac43543e070da01b8e0 --- /dev/null +++ b/js/src/dapps/basiccoin/Transfer/transfer.js @@ -0,0 +1,31 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; + +import Events from './Events'; +import Send from './Send'; + +export default class Transfer extends Component { + render () { + return ( +
+ + +
+ ); + } +} diff --git a/js/src/dapps/basiccoin/_form.css b/js/src/dapps/basiccoin/_form.css new file mode 100644 index 0000000000000000000000000000000000000000..ffafdbeafaea90ebd98fdba8bec718d73c92de02 --- /dev/null +++ b/js/src/dapps/basiccoin/_form.css @@ -0,0 +1,105 @@ +/* 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 . +*/ + +.button { + background: #622; +} + +.form { + text-align: left; + margin: 0 auto; + display: inline-block; +} + +.form .input { + margin-bottom: 1.5em; +} + +.form .input * { + display: inline-block; + margin: 0 0.5em; + padding: 0.5em; + font-size: 1em; +} + +.form label { + width: 25em; + opacity: 0.8; + text-align: right; +} + +.form .hint { + width: 25em; + opacity: 0.5; +} + +.form input, +.form select { + width: 18em; + color: #444; + background: rgba(255, 255, 255, 0.75); + border-radius: 1px; + border: 1px solid rgba(0, 0, 0, 0.25); + box-sizing: border-box; + -moz-appearance: none; + -webkit-appearance: none; + appearance: none; +} + +.form select { + height: 36px; +} + +.form input.small { + width: 9em; + margin-right: 9.5em; +} + +.form .error input { + border: 1px solid rgba(255, 0, 0, 0.5); + color: red; + background: rgba(255, 0, 0, 0.1); +} + +.form .error label { + color: red; +} + +.form .error .hint { + color: red; +} + +.buttonRow { + text-align: right; + width: 18em; +} + +.button { + color: white; + border: none; + border-radius: 1px; + padding: 1em 2em !important; + display: inline-block; + margin-left: 1em !important; + cursor: pointer; + position: relative; +} + +.button[disabled] { + opacity: 0.5; + cursor: default; +} diff --git a/js/src/dapps/basiccoin/_status.css b/js/src/dapps/basiccoin/_status.css new file mode 100644 index 0000000000000000000000000000000000000000..8fd93cfe4026992c5195aed354f1cac2431ac52c --- /dev/null +++ b/js/src/dapps/basiccoin/_status.css @@ -0,0 +1,36 @@ +/* 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 . +*/ + +.statusHeader { + font-size: 1.25em; + margin-bottom: 1.25em; + opacity: 0.75; +} + +.statusInfo { + margin-bottom: 0.25em; +} + +.statusState { + opacity: 0.75; + margin-top: 1em; +} + +.statusError { + color: red; + margin-top: 1em; +} diff --git a/js/src/dapps/basiccoin/background.jpg b/js/src/dapps/basiccoin/background.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c873064f581cff2718a31fd1dad77e11651a679c Binary files /dev/null and b/js/src/dapps/basiccoin/background.jpg differ diff --git a/js/src/dapps/basiccoin/parity.js b/js/src/dapps/basiccoin/parity.js new file mode 100644 index 0000000000000000000000000000000000000000..f6d59f44d5771db93be36fa0ed8af8889d14af51 --- /dev/null +++ b/js/src/dapps/basiccoin/parity.js @@ -0,0 +1,21 @@ +// 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 . + +const { api } = window.parity; + +export { + api +}; diff --git a/js/src/dapps/basiccoin/services.js b/js/src/dapps/basiccoin/services.js new file mode 100644 index 0000000000000000000000000000000000000000..28cc662a7dea3bfbc74e25b9163b5799a74746d2 --- /dev/null +++ b/js/src/dapps/basiccoin/services.js @@ -0,0 +1,270 @@ +// 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 BigNumber from 'bignumber.js'; + +import * as abis from '../../contracts/abi'; +import { api } from './parity'; + +let managerInstance; +let tokenregInstance; +let registryInstance; + +const registries = {}; +const subscriptions = {}; +let nextSubscriptionId = 1000; +let isTest = false; + +export function subscribeEvents (addresses, callback) { + const subscriptionId = nextSubscriptionId++; + const contract = api.newContract(abis.eip20); + const event = contract.events.filter((evt) => evt.name === 'Transfer'); + const options = { + address: addresses, + fromBlock: 0, + toBlock: 'pending', + limit: 50, + topics: [event.signature] + }; + + return api.eth + .newFilter(options) + .then((filterId) => { + subscriptions[subscriptionId] = { subscriptionId, filterId, addresses, callback, contract }; + + return api.eth.getFilterLogs(filterId); + }) + .then((logs) => callback(null, contract.parseEventLogs(logs))) + .then(() => subscriptionId) + .catch((error) => { + console.error('subscribeEvents', error); + throw error; + }); +} + +export function unsubscribeEvents (subscriptionId) { + api.eth + .uninstallFilter(subscriptions[subscriptionId].filterId) + .catch((error) => { + console.error('unsubscribeEvents', error); + }); + + delete subscriptions[subscriptionId]; +} + +function pollEvents () { + const loop = Object.values(subscriptions); + const timeout = () => setTimeout(pollEvents, 1000); + + Promise + .all(loop.map((subscription) => api.eth.getFilterChanges(subscription.filterId))) + .then((logsArray) => { + logsArray.forEach((logs, index) => { + const subscription = loop[index]; + + if (!logs || !logs.length) { + return; + } + + try { + subscription.callback(null, subscription.contract.parseEventLogs(logs)); + } catch (error) { + unsubscribeEvents(loop.subscriptionId); + console.error('pollEvents', error); + } + }); + + timeout(); + }) + .catch((error) => { + console.error('pollEvents', error); + timeout(); + }); +} + +export function attachInstances () { + pollEvents(); + + return Promise + .all([ + api.ethcore.registryAddress(), + api.ethcore.netChain() + ]) + .then(([registryAddress, netChain]) => { + const registry = api.newContract(abis.registry, registryAddress).instance; + isTest = netChain === 'morden' || netChain === 'testnet'; + + console.log(`contract was found at registry=${registryAddress}`); + console.log(`running on ${netChain}, isTest=${isTest}`); + + return Promise + .all([ + registry.getAddress.call({}, [api.util.sha3('basiccoinmgr'), 'A']), + registry.getAddress.call({}, [api.util.sha3('basiccoinreg'), 'A']), + registry.getAddress.call({}, [api.util.sha3('tokenreg'), 'A']) + ]); + }) + .then(([managerAddress, registryAddress, tokenregAddress]) => { + console.log(`contracts were found at basiccoinmgr=${managerAddress}, basiccoinreg=${registryAddress}, tokenreg=${registryAddress}`); + + managerInstance = api.newContract(abis.basiccoinmanager, managerAddress).instance; + registryInstance = api.newContract(abis.tokenreg, registryAddress).instance; + tokenregInstance = api.newContract(abis.tokenreg, tokenregAddress).instance; + + registries[registryInstance.address] = registryInstance; + registries[tokenregInstance.address] = tokenregInstance; + + return { + managerInstance, + registryInstance, + tokenregInstance + }; + }) + .catch((error) => { + console.error('attachInstances', error); + throw error; + }); +} + +export function totalSupply (address) { + return api.newContract(abis.eip20, address) + .instance.totalSupply.call(); +} + +export function getCoin (tokenreg, address) { + return registries[tokenreg].fromAddress + .call({}, [address]) + .then(([id, tla, base, name, owner]) => { + return { + id, tla, base, name, owner, + isGlobal: tokenregInstance.address === tokenreg + }; + }) + .catch((error) => { + console.error('getCoin', error); + throw error; + }); +} + +export function loadOwnedTokens (addresses) { + let total = new BigNumber(0); + + return Promise + .all( + addresses.map((address) => managerInstance.countByOwner.call({}, [address])) + ) + .then((counts) => { + return Promise.all( + addresses.reduce((promises, address, index) => { + total = counts[index].add(total); + for (let i = 0; counts[index].gt(i); i++) { + promises.push(managerInstance.getByOwner.call({}, [address, i])); + } + return promises; + }, []) + ); + }) + .then((_tokens) => { + const tokens = _tokens.reduce((tokens, token) => { + const [address, owner, tokenreg] = token; + tokens[owner] = tokens[owner] || []; + tokens[owner].push({ address, owner, tokenreg }); + return tokens; + }, {}); + + return { tokens, total }; + }) + .catch((error) => { + console.error('loadTokens', error); + throw error; + }); +} + +export function loadAllTokens () { + return managerInstance + .count.call() + .then((count) => { + const promises = []; + + for (let index = 0; count.gt(index); index++) { + promises.push(managerInstance.get.call({}, [index])); + } + + return Promise.all(promises); + }) + .then((_tokens) => { + const tokens = []; + + return Promise + .all( + _tokens.map(([address, owner, tokenreg]) => { + const isGlobal = tokenreg === tokenregInstance.address; + tokens.push({ address, owner, tokenreg, isGlobal }); + return registries[tokenreg].fromAddress.call({}, [address]); + }) + ) + .then((coins) => { + return tokens.map((token, index) => { + const [id, tla, base, name, owner] = coins[index]; + token.coin = { id, tla, base, name, owner }; + return token; + }); + }); + }) + .catch((error) => { + console.log('loadAllTokens', error); + throw error; + }); +} + +export function loadBalances (addresses) { + return loadAllTokens() + .then((tokens) => { + return Promise.all( + tokens.map((token) => { + return Promise.all( + addresses.map((address) => loadTokenBalance(token.address, address)) + ); + }) + ) + .then((_balances) => { + return tokens.map((token, tindex) => { + const balances = _balances[tindex]; + token.balances = addresses.map((address, aindex) => { + return { address, balance: balances[aindex] }; + }); + return token; + }); + }); + }) + .catch((error) => { + console.error('loadBalances', error); + throw error; + }); +} + +export function loadTokenBalance (tokenAddress, address) { + return api.newContract(abis.eip20, tokenAddress).instance + .balanceOf.call({}, [address]) + .catch((error) => { + console.error('loadTokenBalance', error); + throw error; + }); +} + +export function txLink (txHash) { + return `https://${isTest ? 'testnet.' : ''}etherscan.io/tx/${txHash}`; +} diff --git a/js/src/dapps/githubhint.html b/js/src/dapps/githubhint.html new file mode 100644 index 0000000000000000000000000000000000000000..631182fcbbe5e1b91f1b5e582fe0164901cfd30c --- /dev/null +++ b/js/src/dapps/githubhint.html @@ -0,0 +1,17 @@ + + + + + + + + GitHub Hint + + +
+ + + + + + diff --git a/js/src/dapps/githubhint.js b/js/src/dapps/githubhint.js new file mode 100644 index 0000000000000000000000000000000000000000..b73702990620eb76b7e2445de939c8760b5ef614 --- /dev/null +++ b/js/src/dapps/githubhint.js @@ -0,0 +1,33 @@ +// 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 ReactDOM from 'react-dom'; +import React from 'react'; + +import injectTapEventPlugin from 'react-tap-event-plugin'; +injectTapEventPlugin(); + +import Application from './githubhint/Application'; + +import '../../assets/fonts/Roboto/font.css'; +import '../../assets/fonts/RobotoMono/font.css'; +import './style.css'; +import './githubhint.html'; + +ReactDOM.render( + , + document.querySelector('#container') +); diff --git a/js/src/dapps/githubhint/Application/application.css b/js/src/dapps/githubhint/Application/application.css new file mode 100644 index 0000000000000000000000000000000000000000..be04ecf34f4a0bbbad673dfdc292443bb3eaa995 --- /dev/null +++ b/js/src/dapps/githubhint/Application/application.css @@ -0,0 +1,147 @@ +/* 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 . +*/ + +.container { + background: #333; + font-family: 'Roboto'; + vertical-align: middle; + padding: 4em 0; + text-align: center; +} + +.form { + text-align: right; + margin: 0 auto; + border-radius: 5px; + width: 44em; + color: #eee; +} + +.box { + padding: 2em; + background: rgba(255, 255, 255, 0.1); + border-radius: 5px; + margin-bottom: 2em; +} + +.buttons { + text-align: center; + margin: 0 auto 2em auto; +} + +.box .buttons { + text-align: right; + margin: 2em 0 0 0; + position: relative; +} + +.box .buttons .addressSelect { + position: absolute; + top: 0; + left: 0; +} + +.box .description { + margin: 0 0 2em 0; + text-align: center; + opacity: 0.75; +} + +.progress { + margin: 2em 0 0 0; + opacity: 0.75; + text-align: center; +} + +.statusHeader { + font-size: 1em; +} + +.statusState, .statusError { + padding: 1em 0 0 0; +} + +.statusError { + color: #f66; +} + +.capture { +} + +.capture+.capture { + margin-top: 0.5em; +} + +.capture * { + display: inline-block; + padding: 0.75em; + vertical-align: middle; + box-sizing: border-box; + width: 20em; +} + +.capture input { + color: #333; + background: #eee; + border: none; + border-radius: 5px; + width: 100%; + font-size: 1em; + text-align: center; +} + +.capture input[disabled] { + opacity: 0.5; +} + +.capture input.error { + background: #fcc; +} + +.hashError, .hashWarning, .hashOk { + padding-top: 0.5em; + text-align: center; +} + +.hashError { + color: #f66; +} + +.hashWarning { + color: #f80; +} + +.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 new file mode 100644 index 0000000000000000000000000000000000000000..4a25d38557371182cb26d85097017ee2033c1194 --- /dev/null +++ b/js/src/dapps/githubhint/Application/application.js @@ -0,0 +1,400 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; + +import { api } from '../parity'; +import { attachInterface } from '../services'; +import Button from '../Button'; +import IdentityIcon from '../IdentityIcon'; +import Loading from '../Loading'; + +import styles from './application.css'; + +const INVALID_URL_HASH = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; +const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; + +export default class Application extends Component { + state = { + fromAddress: null, + loading: true, + url: '', + urlError: null, + commit: '', + commitError: null, + contentHash: '', + contentHashError: null, + contentHashOwner: null, + registerBusy: false, + registerError: null, + registerState: '', + registerType: 'file' + } + + componentDidMount () { + attachInterface() + .then((state) => { + this.setState(state, () => { + this.setState({ loading: false }); + }); + }); + } + + render () { + const { loading } = this.state; + + return loading + ? this.renderLoading() + : this.renderPage(); + } + + renderLoading () { + return ( + + ); + } + + renderPage () { + const { fromAddress, registerBusy, url, urlError, contentHash, contentHashError, contentHashOwner, commit, commitError, registerType, repo, repoError } = this.state; + + let hashClass = null; + if (contentHashError) { + hashClass = contentHashOwner !== fromAddress ? styles.hashError : styles.hashWarning; + } else { + 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 } +
+ { registerBusy ? this.renderProgress() : this.renderButtons() } +
+
+
+ ); + } + + renderButtons () { + const { accounts, fromAddress, urlError, repoError, commitError, contentHashError, contentHashOwner } = this.state; + const account = accounts[fromAddress]; + + return ( +
+
+ +
+ +
+ ); + } + + renderProgress () { + const { registerError, registerState } = this.state; + + if (registerError) { + return ( +
+
+ Your registration has encountered an error +
+
+ { registerError } +
+
+ ); + } + + return ( +
+
+ Your URL is being registered +
+
+ { registerState } +
+
+ ); + } + + onClickTypeNormal = () => { + const { url } = this.state; + + this.setState({ registerType: 'file', commitError: null, repoError: null }, () => { + this.onChangeUrl({ target: { value: url } }); + }); + } + + onClickTypeContent = () => { + const { repo, commit } = this.state; + + this.setState({ registerType: 'content', urlError: null }, () => { + this.onChangeRepo({ target: { value: repo } }); + this.onChangeCommit({ target: { value: commit } }); + }); + } + + onChangeCommit = (event) => { + const commit = event.target.value; + const commitError = null; + + // TODO: field validation + + this.setState({ commit, commitError, contentHashError: 'hash lookup in progress' }, () => { + const { repo } = this.state; + this.lookupHash(`https://codeload.github.com/${repo}/zip/${commit}`); + }); + } + + onChangeRepo = (event) => { + let repo = event.target.value; + const repoError = null; + + // TODO: field validation + if (!repoError) { + repo = repo.replace('https://github.com/', ''); + } + + this.setState({ repo, repoError, contentHashError: 'hash lookup in progress' }, () => { + const { commit } = this.state; + this.lookupHash(`https://codeload.github.com/${repo}/zip/${commit}`); + }); + } + + onChangeUrl = (event) => { + let url = event.target.value; + const urlError = null; + + // TODO: field validation + if (!urlError) { + const parts = url.split('/'); + + 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(url); + }); + } + + onClickRegister = () => { + const { commit, commitError, contentHashError, contentHashOwner, fromAddress, url, urlError, registerType, repo, repoError } = this.state; + + // 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; + } + + if (registerType === 'file') { + this.registerUrl(url); + } else { + this.registerContent(repo, commit); + } + } + + trackRequest (promise) { + return promise + .then((signerRequestId) => { + this.setState({ signerRequestId, registerState: 'Transaction posted, Waiting for transaction authorization' }); + + return api.pollMethod('eth_checkRequest', signerRequestId); + }) + .then((txHash) => { + this.setState({ txHash, registerState: 'Transaction authorized, Waiting for network confirmations' }); + + return api.pollMethod('eth_getTransactionReceipt', txHash, (receipt) => { + if (!receipt || !receipt.blockNumber || receipt.blockNumber.eq(0)) { + return false; + } + + return true; + }); + }) + .then((txReceipt) => { + this.setState({ txReceipt, registerBusy: false, registerState: 'Network confirmed, Received transaction receipt', url: '', commit: '', commitError: null, contentHash: '', contentHashOwner: null, contentHashError: null }); + }) + .catch((error) => { + console.error('onSend', error); + this.setState({ registerError: error.message }); + }); + } + + registerContent (repo, commit) { + const { contentHash, fromAddress, instance } = this.state; + + this.setState({ registerBusy: true, registerState: 'Estimating gas for the transaction' }); + + const values = [contentHash, repo, 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); + let index = 0; + + addresses.forEach((address, _index) => { + if (address === fromAddress) { + index = _index; + } + }); + + index++; + if (index >= addresses.length) { + index = 0; + } + + this.setState({ fromAddress: addresses[index] }); + } + + lookupHash (url) { + const { instance } = this.state; + + if (!url || !url.length) { + return; + } + + console.log(`lookupHash ${url}`); + + api.ethcore + .hashContent(url) + .then((contentHash) => { + console.log('lookupHash', contentHash); + if (contentHash === INVALID_URL_HASH) { + this.setState({ contentHashError: 'invalid url endpoint', contentHash: null }); + return; + } + + instance.entries + .call({}, [contentHash]) + .then(([accountSlashRepo, commit, contentHashOwner]) => { + console.log('lookupHash', accountSlashRepo, api.util.bytesToHex(commit), contentHashOwner); + + if (contentHashOwner !== ZERO_ADDRESS) { + this.setState({ + contentHashError: contentHash, + contentHashOwner, + contentHash + }); + } else { + this.setState({ contentHashError: null, contentHashOwner, contentHash }); + } + }); + }) + .catch((error) => { + console.error('lookupHash', error); + this.setState({ contentHashError: error.message, contentHash: null }); + }); + } +} diff --git a/js/src/dapps/githubhint/Application/index.js b/js/src/dapps/githubhint/Application/index.js new file mode 100644 index 0000000000000000000000000000000000000000..236578226a80e822593c37acd1daad1c649950e1 --- /dev/null +++ b/js/src/dapps/githubhint/Application/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './application'; diff --git a/js/src/dapps/githubhint/Button/button.css b/js/src/dapps/githubhint/Button/button.css new file mode 100644 index 0000000000000000000000000000000000000000..28519094b2e38c246489b6691585be107a67d462 --- /dev/null +++ b/js/src/dapps/githubhint/Button/button.css @@ -0,0 +1,56 @@ +/* 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 . +*/ + +.button { + background: #08a; + color: white; + border-radius: 5px; + font-size: 1em; + line-height: 24px; + height: 24px; + padding: 0.75em 1.5em; + cursor: pointer; + display: inline-block; + text-align: center; +} + +.button.first { + border-radius: 5px 0 0 5px; +} + +.button.middle { + border-radius: 0; +} + +.button.last { + border-radius: 0 5px 5px 0; +} + +.button.disabled { + opacity: 0.25; + cursor: default; +} + +.button.inverse { + color: #08a; + background: white; +} + +.button * { + display: inline-block; + vertical-align: top; +} diff --git a/js/src/dapps/githubhint/Button/button.js b/js/src/dapps/githubhint/Button/button.js new file mode 100644 index 0000000000000000000000000000000000000000..42fca1af7d432905a797bb468ed3622388adfc7f --- /dev/null +++ b/js/src/dapps/githubhint/Button/button.js @@ -0,0 +1,53 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import styles from './button.css'; + +export default class Button extends Component { + static propTypes = { + children: PropTypes.node.isRequired, + className: PropTypes.string, + disabled: PropTypes.bool, + invert: PropTypes.bool, + first: PropTypes.bool, + last: PropTypes.bool, + middle: PropTypes.bool, + onClick: PropTypes.func.isRequired + } + + render () { + const { children, className, disabled, invert, first, last, middle } = this.props; + const classes = `${styles.button} ${disabled ? styles.disabled : ''} ${invert ? styles.inverse : ''} ${first ? styles.first : ''} ${last ? styles.last : ''} ${middle ? styles.middle : ''} ${className}`; + + return ( +
+ { children } +
+ ); + } + + onClick = (event) => { + const { disabled, onClick } = this.props; + + if (disabled) { + return; + } + + onClick(event); + } +} diff --git a/js/src/dapps/githubhint/Button/index.js b/js/src/dapps/githubhint/Button/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f69a65e3d53fd0e216cb4aefcbcd551417281e09 --- /dev/null +++ b/js/src/dapps/githubhint/Button/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './button'; diff --git a/js/src/dapps/githubhint/IdentityIcon/identityIcon.css b/js/src/dapps/githubhint/IdentityIcon/identityIcon.css new file mode 100644 index 0000000000000000000000000000000000000000..3fa1df99e4d29224b7dd7cc02fdaac2e68e490c7 --- /dev/null +++ b/js/src/dapps/githubhint/IdentityIcon/identityIcon.css @@ -0,0 +1,23 @@ +/* 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 . +*/ + +.icon { + width: 24px; + height: 24px; + border-radius: 50%; + margin-right: 0.5em; +} diff --git a/js/src/dapps/githubhint/IdentityIcon/identityIcon.js b/js/src/dapps/githubhint/IdentityIcon/identityIcon.js new file mode 100644 index 0000000000000000000000000000000000000000..0bc86731d4544432cae2af30ee573670fff5f9f7 --- /dev/null +++ b/js/src/dapps/githubhint/IdentityIcon/identityIcon.js @@ -0,0 +1,36 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import styles from './identityIcon.css'; + +export default class IdentityIcon extends Component { + static propTypes = { + address: PropTypes.string.isRequired + } + + render () { + const { address } = this.props; + + return ( + + ); + } +} diff --git a/js/src/dapps/githubhint/IdentityIcon/index.js b/js/src/dapps/githubhint/IdentityIcon/index.js new file mode 100644 index 0000000000000000000000000000000000000000..76c107bfb7540f707a9b2665aac9b52f9d7590fa --- /dev/null +++ b/js/src/dapps/githubhint/IdentityIcon/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './identityIcon'; diff --git a/js/src/dapps/githubhint/Loading/index.js b/js/src/dapps/githubhint/Loading/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0468cab37dfd505cb0b1ef415376ca121ab9ca89 --- /dev/null +++ b/js/src/dapps/githubhint/Loading/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './loading'; diff --git a/js/src/dapps/githubhint/Loading/loading.css b/js/src/dapps/githubhint/Loading/loading.css new file mode 100644 index 0000000000000000000000000000000000000000..b77d1a23725749001e0ff1e0675844afefa37aa8 --- /dev/null +++ b/js/src/dapps/githubhint/Loading/loading.css @@ -0,0 +1,24 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.loading { + width: 100%; + text-align: center; + padding-top: 5em; + font-size: 2em; + color: #999; +} diff --git a/js/src/dapps/githubhint/Loading/loading.js b/js/src/dapps/githubhint/Loading/loading.js new file mode 100644 index 0000000000000000000000000000000000000000..b884597d763299230e7f956d2778783141f41feb --- /dev/null +++ b/js/src/dapps/githubhint/Loading/loading.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; + +import styles from './loading.css'; + +export default class Loading extends Component { + render () { + return ( +
+ Attaching to contract ... +
+ ); + } +} diff --git a/js/src/dapps/githubhint/parity.js b/js/src/dapps/githubhint/parity.js new file mode 100644 index 0000000000000000000000000000000000000000..f6d59f44d5771db93be36fa0ed8af8889d14af51 --- /dev/null +++ b/js/src/dapps/githubhint/parity.js @@ -0,0 +1,21 @@ +// 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 . + +const { api } = window.parity; + +export { + api +}; diff --git a/js/src/dapps/githubhint/services.js b/js/src/dapps/githubhint/services.js new file mode 100644 index 0000000000000000000000000000000000000000..b7676d5f51cb7d157399626c57c7db0c787d61ef --- /dev/null +++ b/js/src/dapps/githubhint/services.js @@ -0,0 +1,65 @@ +// 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 * as abis from '../../contracts/abi'; +import { api } from './parity'; + +export function attachInterface () { + return api.ethcore + .registryAddress() + .then((registryAddress) => { + console.log(`the registry was found at ${registryAddress}`); + + const registry = api.newContract(abis.registry, registryAddress).instance; + + return Promise + .all([ + registry.getAddress.call({}, [api.util.sha3('githubhint'), 'A']), + api.eth.accounts(), + api.personal.accountsInfo() + ]); + }) + .then(([address, addresses, accountsInfo]) => { + accountsInfo = accountsInfo || {}; + console.log(`githubhint was found at ${address}`); + + const contract = api.newContract(abis.githubhint, address); + const accounts = addresses.reduce((obj, address) => { + const info = accountsInfo[address] || {}; + + return Object.assign(obj, { + [address]: { + address, + name: info.name, + uuid: info.uuid + } + }); + }, {}); + const fromAddress = Object.keys(accounts)[0]; + + return { + accounts, + address, + accountsInfo, + contract, + instance: contract.instance, + fromAddress + }; + }) + .catch((error) => { + console.error('attachInterface', error); + }); +} diff --git a/js/src/dapps/registry.html b/js/src/dapps/registry.html new file mode 100644 index 0000000000000000000000000000000000000000..ab399d1e3eefdcd23dabedbceb3569c3a3ca2583 --- /dev/null +++ b/js/src/dapps/registry.html @@ -0,0 +1,17 @@ + + + + + + + + Token Registry + + +
+ + + + + + diff --git a/js/src/dapps/registry.js b/js/src/dapps/registry.js new file mode 100644 index 0000000000000000000000000000000000000000..ebcff155a1ff79b68b6e33f939990d85131ef8ae --- /dev/null +++ b/js/src/dapps/registry.js @@ -0,0 +1,37 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React from 'react'; +import ReactDOM from 'react-dom'; +import { Provider } from 'react-redux'; + +import injectTapEventPlugin from 'react-tap-event-plugin'; +injectTapEventPlugin(); + +import store from './registry/store'; +import Container from './registry/Container'; + +import '../../assets/fonts/Roboto/font.css'; +import '../../assets/fonts/RobotoMono/font.css'; +import './style.css'; +import './registry.html'; + +ReactDOM.render( + + + , + document.querySelector('#container') +); diff --git a/js/src/dapps/registry/Accounts/accounts.css b/js/src/dapps/registry/Accounts/accounts.css new file mode 100644 index 0000000000000000000000000000000000000000..344a92867e27687ad450976dc9f038d6615efffc --- /dev/null +++ b/js/src/dapps/registry/Accounts/accounts.css @@ -0,0 +1,38 @@ +/* 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 . +*/ + +.button { + /* TODO remove !important once material design lite is used */ + padding: 0 !important; +} + +.icon { + /* TODO remove !important once material design lite is used */ + margin: 0 !important; + width: 30px !important; + height: 30px !important; +} + +.menuIcon { + display: inline-block; + vertical-align: middle; +} +.menuText { + display: inline-block; + line-height: 24px; + vertical-align: top; +} diff --git a/js/src/dapps/registry/Accounts/accounts.js b/js/src/dapps/registry/Accounts/accounts.js new file mode 100644 index 0000000000000000000000000000000000000000..e8d8c2bd20e579da8bf83341ee64d548d3c2d3d4 --- /dev/null +++ b/js/src/dapps/registry/Accounts/accounts.js @@ -0,0 +1,80 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import IconMenu from 'material-ui/IconMenu'; +import IconButton from 'material-ui/IconButton/IconButton'; +import AccountIcon from 'material-ui/svg-icons/action/account-circle'; +import MenuItem from 'material-ui/MenuItem'; + +import IdentityIcon from '../IdentityIcon'; +import renderAddress from '../ui/address'; + +import styles from './accounts.css'; + +export default class Accounts extends Component { + + static propTypes = { + actions: PropTypes.object.isRequired, + all: PropTypes.object.isRequired, + selected: PropTypes.object + } + + render () { + const { all, selected } = this.props; + + const origin = { horizontal: 'right', vertical: 'top' }; + + const accountsButton = ( + + { selected + ? () + : () + } + ); + + return ( + + { Object.values(all).map(this.renderAccount) } + + ); + } + + renderAccount = (account) => { + const { all, selected } = this.props; + const isSelected = selected && selected.address === account.address; + + return ( + + { renderAddress(account.address, all, {}) } + + ); + }; + + onAccountSelect = (e, address) => { + this.props.actions.select(address); + }; +} diff --git a/js/src/dapps/registry/Accounts/actions.js b/js/src/dapps/registry/Accounts/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..4f2bd3c7078c6d2ba2d2f12fbe831b75add22cfb --- /dev/null +++ b/js/src/dapps/registry/Accounts/actions.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export const select = (address) => ({ type: 'accounts select', address }); diff --git a/js/src/dapps/registry/Accounts/index.js b/js/src/dapps/registry/Accounts/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e9be1d557338144d69c09ec2d7adc0d2386d3999 --- /dev/null +++ b/js/src/dapps/registry/Accounts/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './accounts'; diff --git a/js/src/dapps/registry/Application/application.css b/js/src/dapps/registry/Application/application.css new file mode 100644 index 0000000000000000000000000000000000000000..ebdb23baaf26a0d8a00d42a07a21d76691de23b5 --- /dev/null +++ b/js/src/dapps/registry/Application/application.css @@ -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 . +*/ + +.header { + display: flex; + justify-content: space-between; + margin: 0; padding: .3em 1em; + color: #fff; + background-color: #333; +} + +.header h1 { + margin-top: 0; + margin-bottom: 0; + line-height: 50px; + font-size: 200%; + text-transform: uppercase; +} + +.address { + margin-bottom: 0; + padding: 1rem; + font-size: 80%; + background-color: #f0f0f0; +} + +.actions { + margin: 1em; + + * { + font-size: 1.3rem !important; + } + + > * { + padding-bottom: 0 !important; + } +} diff --git a/js/src/dapps/registry/Application/application.js b/js/src/dapps/registry/Application/application.js new file mode 100644 index 0000000000000000000000000000000000000000..e763069a5d684de1e070018b695e98deb02321c8 --- /dev/null +++ b/js/src/dapps/registry/Application/application.js @@ -0,0 +1,118 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . +import React, { Component, PropTypes } from 'react'; + +import getMuiTheme from 'material-ui/styles/getMuiTheme'; +import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'; +const muiTheme = getMuiTheme(lightBaseTheme); + +import CircularProgress from 'material-ui/CircularProgress'; +import { Card, CardText } from 'material-ui/Card'; +import styles from './application.css'; +import Accounts from '../Accounts'; +import Events from '../Events'; +import Lookup from '../Lookup'; +import Names from '../Names'; +import Records from '../Records'; + +const nullable = (type) => React.PropTypes.oneOfType([ React.PropTypes.oneOf([ null ]), type ]); + +export default class Application extends Component { + static childContextTypes = { + muiTheme: PropTypes.object.isRequired, + api: PropTypes.object.isRequired + }; + + getChildContext () { + return { muiTheme, api: window.parity.api }; + } + + static propTypes = { + actions: PropTypes.object.isRequired, + accounts: PropTypes.object.isRequired, + contacts: PropTypes.object.isRequired, + contract: nullable(PropTypes.object.isRequired), + fee: nullable(PropTypes.object.isRequired), + lookup: PropTypes.object.isRequired, + events: PropTypes.object.isRequired, + names: PropTypes.object.isRequired, + records: PropTypes.object.isRequired + }; + + render () { + const { + actions, + accounts, contacts, + contract, fee, + lookup, + events + } = this.props; + + return ( +
+
+

RΞgistry

+ +
+ { contract && fee ? ( +
+ + + { this.renderActions() } + + +

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

+
+ ) : ( + + ) } +
+ ); + } + + renderActions () { + const { + actions, + accounts, + fee, + names, + records + } = this.props; + + const hasAccount = !!accounts.selected; + + if (!hasAccount) { + return ( + + + Please select a valid account in order + to execute actions. + + + ); + } + + return ( +
+ + +
+ ); + } + +} diff --git a/js/src/dapps/registry/Application/index.js b/js/src/dapps/registry/Application/index.js new file mode 100644 index 0000000000000000000000000000000000000000..236578226a80e822593c37acd1daad1c649950e1 --- /dev/null +++ b/js/src/dapps/registry/Application/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './application'; diff --git a/js/src/dapps/registry/Container.js b/js/src/dapps/registry/Container.js new file mode 100644 index 0000000000000000000000000000000000000000..1464320e63c04fa2da2ff67310d334d5ae239bf0 --- /dev/null +++ b/js/src/dapps/registry/Container.js @@ -0,0 +1,66 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; + +import Application from './Application'; +import * as actions from './actions'; + +const nullable = (type) => React.PropTypes.oneOfType([ React.PropTypes.oneOf([ null ]), type ]); + +class Container extends Component { + static propTypes = { + actions: PropTypes.object.isRequired, + accounts: PropTypes.object.isRequired, + contacts: PropTypes.object.isRequired, + contract: nullable(PropTypes.object.isRequired), + owner: nullable(PropTypes.string.isRequired), + fee: nullable(PropTypes.object.isRequired), + lookup: PropTypes.object.isRequired, + events: PropTypes.object.isRequired + }; + + componentDidMount () { + Promise.all([ + this.props.actions.addresses.fetch(), + this.props.actions.fetchContract() + ]).then(() => { + this.props.actions.events.subscribe('Reserved'); + }); + } + + render () { + return (); + } +} + +export default connect( + // redux -> react connection + (state) => state, + // react -> redux connection + (dispatch) => { + const bound = bindActionCreators(actions, dispatch); + bound.addresses = bindActionCreators(actions.addresses, dispatch); + bound.accounts = bindActionCreators(actions.accounts, dispatch); + bound.lookup = bindActionCreators(actions.lookup, dispatch); + bound.events = bindActionCreators(actions.events, dispatch); + bound.names = bindActionCreators(actions.names, dispatch); + bound.records = bindActionCreators(actions.records, dispatch); + return { actions: bound }; + } +)(Container); diff --git a/js/src/dapps/registry/Events/actions.js b/js/src/dapps/registry/Events/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..e12c98c4f67b8d343c444a1b68817ca27fdcf3eb --- /dev/null +++ b/js/src/dapps/registry/Events/actions.js @@ -0,0 +1,85 @@ +// 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 { api } from '../parity.js'; + +export const start = (name, from, to) => ({ type: 'events subscribe start', name, from, to }); +export const fail = (name) => ({ type: 'events subscribe fail', name }); +export const success = (name, subscription) => ({ type: 'events subscribe success', name, subscription }); + +export const event = (name, event) => ({ type: 'events event', name, event }); + +export const subscribe = (name, from = 0, to = 'pending') => + (dispatch, getState) => { + const { contract } = getState(); + if (!contract) return; + const opt = { fromBlock: from, toBlock: to, limit: 50 }; + + dispatch(start(name, from, to)); + + contract + .subscribe(name, opt, (error, events) => { + if (error) { + console.error(`error receiving events for ${name}`, error); + return; + } + + events.forEach((e) => { + api.eth.getBlockByNumber(e.blockNumber) + .then((block) => { + const data = { + type: name, + key: '' + e.transactionHash + e.logIndex, + state: e.type, + block: e.blockNumber, + index: e.logIndex, + transaction: e.transactionHash, + parameters: e.params, + timestamp: block.timestamp + }; + dispatch(event(name, data)); + }) + .catch((err) => { + console.error(`could not fetch block ${e.blockNumber}.`); + console.error(err); + }); + }); + }) + .then((subscriptionId) => { + dispatch(success(name, subscriptionId)); + }) + .catch((error) => { + console.error('event subscription failed', error); + dispatch(fail(name)); + }); + }; + +export const unsubscribe = (name) => + (dispatch, getState) => { + const state = getState(); + if (!state.contract) return; + const subscriptions = state.events.subscriptions; + if (!(name in subscriptions) || subscriptions[name] === null) return; + + state.contract + .unsubscribe(subscriptions[name]) + .then(() => { + dispatch({ type: 'events unsubscribe', name }); + }) + .catch((error) => { + console.error('event unsubscribe failed', error); + }); + }; diff --git a/js/src/dapps/registry/Events/events.css b/js/src/dapps/registry/Events/events.css new file mode 100644 index 0000000000000000000000000000000000000000..66277dae3d56fdd575af12aba9c445dd2e94a40b --- /dev/null +++ b/js/src/dapps/registry/Events/events.css @@ -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 . +*/ + +.events { + margin: 1em; +} + +.options { + margin: 0 .5em; +} + +.reserved, .dropped, .dataChanged { +} + +.reserved abbr, .dropped abbr { + cursor: help; +} + +.pending { + opacity: .6; +} + +.owner code { + display: inline-block; + vertical-align: top; + line-height: 32px; + word-wrap: break-word; +} + +.eventsList { + width: 100%; + boder: none; +} + +.eventsList td { + padding: 0.25em 0.5em; +} diff --git a/js/src/dapps/registry/Events/events.js b/js/src/dapps/registry/Events/events.js new file mode 100644 index 0000000000000000000000000000000000000000..cb433068fef32b5b4ce1ee3be1911b25cd027e90 --- /dev/null +++ b/js/src/dapps/registry/Events/events.js @@ -0,0 +1,194 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { Card, CardHeader, CardActions, CardText } from 'material-ui/Card'; +import Toggle from 'material-ui/Toggle'; +import moment from 'moment'; + +import { bytesToHex } from '../parity'; +import renderHash from '../ui/hash'; +import renderAddress from '../ui/address'; +import styles from './events.css'; + +const inlineButton = { + display: 'inline-block', + width: 'auto', + marginRight: '1em' +}; + +const renderStatus = (timestamp, isPending) => { + timestamp = moment(timestamp); + if (isPending) { + return (pending); + } + return ( + + ); +}; + +const renderEvent = (classNames, verb) => (e, accounts, contacts) => { + const classes = e.state === 'pending' + ? classNames + ' ' + styles.pending : classNames; + + return ( + + { renderAddress(e.parameters.owner.value, accounts, contacts) } + { verb } + { renderHash(bytesToHex(e.parameters.name.value)) } + { renderStatus(e.timestamp, e.state === 'pending') } + + ); +}; + +const renderDataChanged = (e, accounts, contacts) => { + let classNames = styles.dataChanged; + if (e.state === 'pending') { + classNames += ' ' + styles.pending; + } + + return ( + + { renderAddress(e.parameters.owner.value, accounts, contacts) } + updated + + key { new Buffer(e.parameters.plainKey.value).toString('utf8') } of { renderHash(bytesToHex(e.parameters.name.value)) } + + { renderStatus(e.timestamp, e.state === 'pending') } + + ); +}; + +const eventTypes = { + Reserved: renderEvent(styles.reserved, 'reserved'), + Dropped: renderEvent(styles.dropped, 'dropped'), + DataChanged: renderDataChanged +}; + +export default class Events extends Component { + + static propTypes = { + actions: PropTypes.object.isRequired, + subscriptions: PropTypes.object.isRequired, + pending: PropTypes.object.isRequired, + events: PropTypes.array.isRequired, + accounts: PropTypes.object.isRequired, + contacts: PropTypes.object.isRequired + } + + render () { + const { subscriptions, pending, accounts, contacts } = this.props; + + const eventsObject = this.props.events + .filter((e) => eventTypes[e.type]) + .reduce((eventsObject, event) => { + const txHash = event.transaction; + + if ( + (eventsObject[txHash] && eventsObject[txHash].state === 'pending') || + !eventsObject[txHash] + ) { + eventsObject[txHash] = event; + } + + return eventsObject; + }, {}); + + const events = Object + .values(eventsObject) + .sort((evA, evB) => { + if (evA.state === 'pending') { + return -1; + } + + if (evB.state === 'pending') { + return 1; + } + + return evB.timestamp - evA.timestamp; + }) + .map((e) => eventTypes[e.type](e, accounts, contacts)); + + return ( + + + + + + + + + + + { events } + +
+
+
+ ); + } + + onReservedToggle = (e, isToggled) => { + const { pending, subscriptions, actions } = this.props; + if (!pending.Reserved) { + if (isToggled && subscriptions.Reserved === null) { + actions.subscribe('Reserved'); + } else if (!isToggled && subscriptions.Reserved !== null) { + actions.unsubscribe('Reserved'); + } + } + }; + onDroppedToggle = (e, isToggled) => { + const { pending, subscriptions, actions } = this.props; + if (!pending.Dropped) { + if (isToggled && subscriptions.Dropped === null) { + actions.subscribe('Dropped'); + } else if (!isToggled && subscriptions.Dropped !== null) { + actions.unsubscribe('Dropped'); + } + } + }; + onDataChangedToggle = (e, isToggled) => { + const { pending, subscriptions, actions } = this.props; + if (!pending.DataChanged) { + if (isToggled && subscriptions.DataChanged === null) { + actions.subscribe('DataChanged'); + } else if (!isToggled && subscriptions.DataChanged !== null) { + actions.unsubscribe('DataChanged'); + } + } + }; +} diff --git a/js/src/dapps/registry/Events/index.js b/js/src/dapps/registry/Events/index.js new file mode 100644 index 0000000000000000000000000000000000000000..15d43c375c19b9129180ccf0e1162a453353ec5c --- /dev/null +++ b/js/src/dapps/registry/Events/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './events.js'; diff --git a/js/src/dapps/registry/Events/reducers.js b/js/src/dapps/registry/Events/reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..6ff0011d34fe42c7ad16f0dbd00c4ab36e703cc0 --- /dev/null +++ b/js/src/dapps/registry/Events/reducers.js @@ -0,0 +1,76 @@ +// 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 . + +const initialState = { + subscriptions: { + Reserved: null, + Dropped: null, + DataChanged: null + }, + pending: { + Reserved: false, + Dropped: false, + DataChanged: false + }, + events: [] +}; + +const sortEvents = (a, b) => { + if (a.state === 'pending' && b.state !== 'pending') return -1; + if (a.state !== 'pending' && b.state === 'pending') return 1; + const d = b.block.minus(a.block).toFixed(0); + if (d === 0) return b.index.minus(a.index).toFixed(0); + return d; +}; + +export default (state = initialState, action) => { + if (!(action.name in state.subscriptions)) { // invalid event name + return state; + } + + if (action.type === 'events subscribe start') { + return { ...state, pending: { ...state.pending, [action.name]: true } }; + } + if (action.type === 'events subscribe fail') { + return { ...state, pending: { ...state.pending, [action.name]: false } }; + } + if (action.type === 'events subscribe success') { + return { + ...state, + pending: { ...state.pending, [action.name]: false }, + subscriptions: { ...state.subscriptions, [action.name]: action.subscription } + }; + } + + if (action.type === 'events unsubscribe') { + return { + ...state, + pending: { ...state.pending, [action.name]: false }, + subscriptions: { ...state.subscriptions, [action.name]: null }, + events: state.events.filter((event) => event.type !== action.name) + }; + } + + if (action.type === 'events event') { + return { ...state, events: state.events + .filter((event) => event.key !== action.event.key) + .concat(action.event) + .sort(sortEvents) + }; + } + + return state; +}; diff --git a/js/src/dapps/registry/IdentityIcon/identityIcon.css b/js/src/dapps/registry/IdentityIcon/identityIcon.css new file mode 100644 index 0000000000000000000000000000000000000000..3fa1df99e4d29224b7dd7cc02fdaac2e68e490c7 --- /dev/null +++ b/js/src/dapps/registry/IdentityIcon/identityIcon.css @@ -0,0 +1,23 @@ +/* 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 . +*/ + +.icon { + width: 24px; + height: 24px; + border-radius: 50%; + margin-right: 0.5em; +} diff --git a/js/src/dapps/registry/IdentityIcon/identityIcon.js b/js/src/dapps/registry/IdentityIcon/identityIcon.js new file mode 100644 index 0000000000000000000000000000000000000000..e4baf27057d9d7180ae6f908b27283b129234658 --- /dev/null +++ b/js/src/dapps/registry/IdentityIcon/identityIcon.js @@ -0,0 +1,39 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import styles from './identityIcon.css'; + +export default class IdentityIcon extends Component { + static propTypes = { + address: PropTypes.string.isRequired, + className: PropTypes.string, + style: PropTypes.object + } + + render () { + const { address, className, style } = this.props; + + return ( + + ); + } +} diff --git a/js/src/dapps/registry/IdentityIcon/index.js b/js/src/dapps/registry/IdentityIcon/index.js new file mode 100644 index 0000000000000000000000000000000000000000..76c107bfb7540f707a9b2665aac9b52f9d7590fa --- /dev/null +++ b/js/src/dapps/registry/IdentityIcon/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './identityIcon'; diff --git a/js/src/dapps/registry/Lookup/actions.js b/js/src/dapps/registry/Lookup/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..a7df875854fef8bdc5b045d02d9cdb9c222945c3 --- /dev/null +++ b/js/src/dapps/registry/Lookup/actions.js @@ -0,0 +1,42 @@ +// 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 { sha3 } from '../parity.js'; + +export const clear = () => ({ type: 'lookup clear' }); + +export const start = (name, key) => ({ type: 'lookup start', name, key }); + +export const success = (address) => ({ type: 'lookup success', result: address }); + +export const fail = () => ({ type: 'lookup error' }); + +export const lookup = (name, key) => (dispatch, getState) => { + const { contract } = getState(); + if (!contract) return; + const getAddress = contract.functions + .find((f) => f.name === 'getAddress'); + + name = name.toLowerCase(); + dispatch(start(name, key)); + getAddress.call({}, [sha3(name), key]) + .then((address) => dispatch(success(address))) + .catch((err) => { + console.error(`could not lookup ${key} for ${name}`); + if (err) console.error(err.stack); + dispatch(fail()); + }); +}; diff --git a/js/src/dapps/registry/Lookup/index.js b/js/src/dapps/registry/Lookup/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f4ade7c001e38d32a4d0460f88e6817c2309e075 --- /dev/null +++ b/js/src/dapps/registry/Lookup/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './lookup.js'; diff --git a/js/src/dapps/registry/Lookup/lookup.css b/js/src/dapps/registry/Lookup/lookup.css new file mode 100644 index 0000000000000000000000000000000000000000..12ddd040c087a90745aa088bcf7e6298bf6dafb4 --- /dev/null +++ b/js/src/dapps/registry/Lookup/lookup.css @@ -0,0 +1,28 @@ +/* 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 . +*/ + +.lookup { + margin: 1em; +} + +.box { + margin: 0 1em; +} + +.spacing { + margin-left: 1em; +} diff --git a/js/src/dapps/registry/Lookup/lookup.js b/js/src/dapps/registry/Lookup/lookup.js new file mode 100644 index 0000000000000000000000000000000000000000..4238f1160108808156eb2405c57293be3b355316 --- /dev/null +++ b/js/src/dapps/registry/Lookup/lookup.js @@ -0,0 +1,98 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { Card, CardHeader, CardText } from 'material-ui/Card'; +import TextField from 'material-ui/TextField'; +import RaisedButton from 'material-ui/RaisedButton'; +import SearchIcon from 'material-ui/svg-icons/action/search'; +import renderAddress from '../ui/address.js'; +import renderImage from '../ui/image.js'; + +import recordTypeSelect from '../ui/record-type-select.js'; +import styles from './lookup.css'; + +const nullable = (type) => React.PropTypes.oneOfType([ React.PropTypes.oneOf([ null ]), type ]); + +export default class Lookup extends Component { + + static propTypes = { + actions: PropTypes.object.isRequired, + name: PropTypes.string.isRequired, + type: PropTypes.string.isRequired, + result: nullable(PropTypes.string.isRequired), + accounts: PropTypes.object.isRequired, + contacts: PropTypes.object.isRequired + } + + state = { name: '', type: 'A' }; + + render () { + const name = this.state.name || this.props.name; + const type = this.state.type || this.props.type; + const { result, accounts, contacts } = this.props; + + let output = ''; + if (result) { + if (type === 'A') { + output = ({ renderAddress(result, accounts, contacts, false) }); + } else if (type === 'IMG') { + output = renderImage(result); + } else if (type === 'CONTENT') { + output = (
+ { result } +

This is most likely just the hash of the content you are looking for

+
); + } else { + output = ({ result }); + } + } + + return ( + + +
+ + { recordTypeSelect(type, this.onTypeChange, styles.spacing) } + } + onClick={ this.onLookupClick } + /> +
+ { output } +
+ ); + } + + onNameChange = (e) => { + this.setState({ name: e.target.value }); + }; + onTypeChange = (e, i, type) => { + this.setState({ type }); + this.props.actions.clear(); + }; + onLookupClick = () => { + this.props.actions.lookup(this.state.name, this.state.type); + }; +} diff --git a/js/src/dapps/registry/Lookup/reducers.js b/js/src/dapps/registry/Lookup/reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..f96e784bdbe533734139317a0e9f220172d69b79 --- /dev/null +++ b/js/src/dapps/registry/Lookup/reducers.js @@ -0,0 +1,53 @@ +// 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 . + +const initialState = { + pending: false, + name: '', type: '', + result: null +}; + +export default (state = initialState, action) => { + if (action.type === 'lookup clear') { + return { ...state, result: null }; + } + + if (action.type === 'lookup start') { + return { + pending: true, + name: action.name, type: action.entry, + result: null + }; + } + + if (action.type === 'lookup error') { + return { + pending: false, + name: initialState.name, type: initialState.type, + result: null + }; + } + + if (action.type === 'lookup success') { + return { + pending: false, + name: initialState.name, type: initialState.type, + result: action.result + }; + } + + return state; +}; diff --git a/js/src/dapps/registry/Names/actions.js b/js/src/dapps/registry/Names/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..ee73ad78e52c50bdffa08aeda50ceefcdff11729 --- /dev/null +++ b/js/src/dapps/registry/Names/actions.js @@ -0,0 +1,89 @@ +// 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 { sha3, toWei } from '../parity.js'; + +const alreadyQueued = (queue, action, name) => + !!queue.find((entry) => entry.action === action && entry.name === name); + +export const reserveStart = (name) => ({ type: 'names reserve start', name }); + +export const reserveSuccess = (name) => ({ type: 'names reserve success', name }); + +export const reserveFail = (name) => ({ type: 'names reserve fail', name }); + +export const reserve = (name) => (dispatch, getState) => { + const state = getState(); + const account = state.accounts.selected; + const contract = state.contract; + if (!contract || !account) return; + if (alreadyQueued(state.names.queue, 'reserve', name)) return; + const reserve = contract.functions.find((f) => f.name === 'reserve'); + + name = name.toLowerCase(); + const options = { + from: account.address, + value: toWei(1).toString() + }; + const values = [ sha3(name) ]; + + dispatch(reserveStart(name)); + reserve.estimateGas(options, values) + .then((gas) => { + options.gas = gas.mul(1.2).toFixed(0); + return reserve.postTransaction(options, values); + }) + .then((data) => { + dispatch(reserveSuccess(name)); + }).catch((err) => { + console.error(`could not reserve ${name}`); + if (err) console.error(err.stack); + dispatch(reserveFail(name)); + }); +}; + +export const dropStart = (name) => ({ type: 'names drop start', name }); + +export const dropSuccess = (name) => ({ type: 'names drop success', name }); + +export const dropFail = (name) => ({ type: 'names drop fail', name }); + +export const drop = (name) => (dispatch, getState) => { + const state = getState(); + const account = state.accounts.selected; + const contract = state.contract; + if (!contract || !account) return; + if (alreadyQueued(state.names.queue, 'drop', name)) return; + const drop = contract.functions.find((f) => f.name === 'drop'); + + name = name.toLowerCase(); + const options = { from: account.address }; + const values = [ sha3(name) ]; + + dispatch(dropStart(name)); + drop.estimateGas(options, values) + .then((gas) => { + options.gas = gas.mul(1.2).toFixed(0); + return drop.postTransaction(options, values); + }) + .then((data) => { + dispatch(dropSuccess(name)); + }).catch((err) => { + console.error(`could not drop ${name}`); + if (err) console.error(err.stack); + dispatch(reserveFail(name)); + }); +}; diff --git a/js/src/dapps/registry/Names/index.js b/js/src/dapps/registry/Names/index.js new file mode 100644 index 0000000000000000000000000000000000000000..26195de88487ef4e2ab80db80216c7c18445f2f1 --- /dev/null +++ b/js/src/dapps/registry/Names/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './names.js'; diff --git a/js/src/dapps/registry/Names/names.css b/js/src/dapps/registry/Names/names.css new file mode 100644 index 0000000000000000000000000000000000000000..a058d41ac0e62d3b7b61ff2964072ae7574d95d0 --- /dev/null +++ b/js/src/dapps/registry/Names/names.css @@ -0,0 +1,40 @@ +/* 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 . +*/ + +.names { + margin: 1em; +} + +.box { + margin: 0 1em 1em 1em; +} + +.spacing { + margin-left: 1em; +} + +.noSpacing { + margin-top: 0; +} + +.link { + color: #00BCD4; + text-decoration: none; +} +.link:hover { + text-decoration: underline; +} diff --git a/js/src/dapps/registry/Names/names.js b/js/src/dapps/registry/Names/names.js new file mode 100644 index 0000000000000000000000000000000000000000..dd7e6f772961e618bb719de465add28c19a69603 --- /dev/null +++ b/js/src/dapps/registry/Names/names.js @@ -0,0 +1,148 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { Card, CardHeader, CardText } from 'material-ui/Card'; +import TextField from 'material-ui/TextField'; +import DropDownMenu from 'material-ui/DropDownMenu'; +import MenuItem from 'material-ui/MenuItem'; +import RaisedButton from 'material-ui/RaisedButton'; +import CheckIcon from 'material-ui/svg-icons/navigation/check'; + +import { fromWei } from '../parity.js'; + +import styles from './names.css'; + +const useSignerText = (

Use the Signer to authenticate the following changes.

); + +const renderNames = (names) => { + const values = Object.values(names); + + return values + .map((name, index) => ( + + { name } + { + index < values.length - 1 + ? (, ) + : null + } + + )); +}; + +const renderQueue = (queue) => { + if (queue.length === 0) { + return null; + } + + const grouped = queue.reduce((grouped, change) => { + const last = grouped[grouped.length - 1]; + if (last && last.action === change.action) { + last.names.push(change.name); + } else { + grouped.push({ action: change.action, names: [change.name] }); + } + return grouped; + }, []); + + return ( +
    + { grouped.map(({ action, names }) => ( +
  • + { renderNames(names) } + { ' will be ' } + { action === 'reserve' ? 'reserved' : 'dropped' } +
  • + )) } +
+ ); +}; + +export default class Names extends Component { + + static propTypes = { + actions: PropTypes.object.isRequired, + fee: PropTypes.object.isRequired, + pending: PropTypes.bool.isRequired, + queue: PropTypes.array.isRequired + } + + state = { + action: 'reserve', + name: '' + }; + + render () { + const { action, name } = this.state; + const { fee, pending, queue } = this.props; + + return ( + + + + { (action === 'reserve' + ? (

+ The fee to reserve a name is { fromWei(fee).toFixed(3) }ETH. +

) + : (

To drop a name, you have to be the owner.

) + ) + } + + + + + + } + onClick={ this.onSubmitClick } + /> + { queue.length > 0 + ? (
{ useSignerText }{ renderQueue(queue) }
) + : null + } +
+
+ ); + } + + onNameChange = (e) => { + this.setState({ name: e.target.value }); + }; + onActionChange = (e, i, action) => { + this.setState({ action }); + }; + onSubmitClick = () => { + const { action, name } = this.state; + if (action === 'reserve') { + this.props.actions.reserve(name); + } else if (action === 'drop') { + this.props.actions.drop(name); + } + }; +} diff --git a/js/src/dapps/registry/Names/reducers.js b/js/src/dapps/registry/Names/reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..fcd2ce48ec2a0e6c56bfe2c61ec0e47677930a63 --- /dev/null +++ b/js/src/dapps/registry/Names/reducers.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 . + +const initialState = { + pending: false, + queue: [] +}; + +export default (state = initialState, action) => { + if (action.type === 'names reserve start') { + return { ...state, pending: true }; + } + if (action.type === 'names reserve success') { + return { + ...state, pending: false, + queue: state.queue.concat({ action: 'reserve', name: action.name }) + }; + } + if (action.type === 'names reserve fail') { + return { ...state, pending: false }; + } + + if (action.type === 'names drop start') { + return { ...state, pending: true }; + } + if (action.type === 'names drop success') { + return { + ...state, pending: false, + queue: state.queue.concat({ action: 'drop', name: action.name }) + }; + } + if (action.type === 'names drop fail') { + return { ...state, pending: false }; + } + + return state; +}; diff --git a/js/src/dapps/registry/Records/actions.js b/js/src/dapps/registry/Records/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..8b1407211906ec5eb25a44be67bc4079dd5b3119 --- /dev/null +++ b/js/src/dapps/registry/Records/actions.js @@ -0,0 +1,38 @@ +import { sha3 } from '../parity.js'; + +export const start = (name, key, value) => ({ type: 'records update start', name, key, value }); + +export const success = () => ({ type: 'records update success' }); + +export const fail = () => ({ type: 'records update error' }); + +export const update = (name, key, value) => (dispatch, getState) => { + const state = getState(); + const account = state.accounts.selected; + const contract = state.contract; + + if (!contract || !account) { + return; + } + + const fnName = key === 'A' ? 'setAddress' : 'set'; + const fn = contract.functions.find((f) => f.name === fnName); + + name = name.toLowerCase(); + const options = { from: account.address }; + const values = [ sha3(name), key, value ]; + + dispatch(start(name, key, value)); + fn.estimateGas(options, values) + .then((gas) => { + options.gas = gas.mul(1.2).toFixed(0); + return fn.postTransaction(options, values); + }) + .then((data) => { + dispatch(success()); + }).catch((err) => { + console.error(`could not update ${key} record of ${name}`); + if (err) console.error(err.stack); + dispatch(fail()); + }); +}; diff --git a/js/src/dapps/registry/Records/index.js b/js/src/dapps/registry/Records/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e2528968e5ec80aaf5ac8272102a83cace4e5608 --- /dev/null +++ b/js/src/dapps/registry/Records/index.js @@ -0,0 +1 @@ +export default from './records.js'; diff --git a/js/src/dapps/registry/Records/records.css b/js/src/dapps/registry/Records/records.css new file mode 100644 index 0000000000000000000000000000000000000000..72b62595d0ffe3aca9bc7ff7d6f7e21588f41ec3 --- /dev/null +++ b/js/src/dapps/registry/Records/records.css @@ -0,0 +1,28 @@ +/* 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 . +*/ + +.records { + margin: 1em; +} + +.noSpacing { + margin-top: 0; +} + +.spacing { + margin-left: 1em; +} diff --git a/js/src/dapps/registry/Records/records.js b/js/src/dapps/registry/Records/records.js new file mode 100644 index 0000000000000000000000000000000000000000..60640893cb5b1842da4391bf98ecddf075269328 --- /dev/null +++ b/js/src/dapps/registry/Records/records.js @@ -0,0 +1,75 @@ +import React, { Component, PropTypes } from 'react'; +import { Card, CardHeader, CardText } from 'material-ui/Card'; +import TextField from 'material-ui/TextField'; +import RaisedButton from 'material-ui/RaisedButton'; +import SaveIcon from 'material-ui/svg-icons/content/save'; + +import recordTypeSelect from '../ui/record-type-select.js'; +import styles from './records.css'; + +export default class Records extends Component { + + static propTypes = { + actions: PropTypes.object.isRequired, + pending: PropTypes.bool.isRequired, + name: PropTypes.string.isRequired, + type: PropTypes.string.isRequired, + value: PropTypes.string.isRequired + } + + state = { name: '', type: 'A', value: '' }; + + render () { + const { pending } = this.props; + const name = this.state.name || this.props.name; + const type = this.state.type || this.props.type; + const value = this.state.value || this.props.value; + + return ( + + + +

+ You can only modify entries of names that you previously registered. +

+ + + { recordTypeSelect(type, this.onTypeChange, styles.spacing) } + + } + onClick={ this.onSaveClick } + /> +
+
+ ); + } + + onNameChange = (e) => { + this.setState({ name: e.target.value }); + }; + onTypeChange = (e, i, type) => { + this.setState({ type }); + }; + onValueChange = (e) => { + this.setState({ value: e.target.value }); + }; + onSaveClick = () => { + const { name, type, value } = this.state; + this.props.actions.update(name, type, value); + }; +} diff --git a/js/src/dapps/registry/Records/reducers.js b/js/src/dapps/registry/Records/reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..7e8f0675586cf8ec65c62fd9693acf5f7fef81a3 --- /dev/null +++ b/js/src/dapps/registry/Records/reducers.js @@ -0,0 +1,24 @@ +const initialState = { + pending: false, + name: '', type: '', value: '' +}; + +export default (state = initialState, action) => { + if (action.type === 'records update start') { + return { + ...state, + pending: true, + name: action.name, type: action.entry, value: action.value + }; + } + + if (action.type === 'records update error' || action.type === 'records update success') { + return { + ...state, + pending: false, + name: initialState.name, type: initialState.type, value: initialState.value + }; + } + + return state; +}; diff --git a/js/src/dapps/registry/actions.js b/js/src/dapps/registry/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..882af036036f30fb6067849b012f6e64a0f63732 --- /dev/null +++ b/js/src/dapps/registry/actions.js @@ -0,0 +1,68 @@ +// 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 { registry as registryAbi } from '../../contracts/abi'; + +import { api } from './parity.js'; +import * as addresses from './addresses/actions.js'; +import * as accounts from './Accounts/actions.js'; +import * as lookup from './Lookup/actions.js'; +import * as events from './Events/actions.js'; +import * as names from './Names/actions.js'; +import * as records from './Records/actions.js'; + +export { addresses, accounts, lookup, events, names, records }; + +export const setContract = (contract) => ({ type: 'set contract', contract }); + +export const fetchContract = () => (dispatch) => + api.ethcore.registryAddress() + .then((address) => { + const contract = api.newContract(registryAbi, address); + dispatch(setContract(contract)); + dispatch(fetchFee()); + dispatch(fetchOwner()); + }) + .catch((err) => { + console.error('could not fetch contract'); + if (err) console.error(err.stack); + }); + +export const setFee = (fee) => ({ type: 'set fee', fee }); + +const fetchFee = () => (dispatch, getState) => { + const { contract } = getState(); + if (!contract) return; + contract.instance.fee.call() + .then((fee) => dispatch(setFee(fee))) + .catch((err) => { + console.error('could not fetch fee'); + if (err) console.error(err.stack); + }); +}; + +export const setOwner = (owner) => ({ type: 'set owner', owner }); + +export const fetchOwner = () => (dispatch, getState) => { + const { contract } = getState(); + if (!contract) return; + contract.instance.owner.call() + .then((owner) => dispatch(setOwner(owner))) + .catch((err) => { + console.error('could not fetch owner'); + if (err) console.error(err.stack); + }); +}; diff --git a/js/src/dapps/registry/addresses/accounts-reducer.js b/js/src/dapps/registry/addresses/accounts-reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..20981877d65d82789d7203edaad7c408e6668eb5 --- /dev/null +++ b/js/src/dapps/registry/addresses/accounts-reducer.js @@ -0,0 +1,38 @@ +// 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 . + +const initialState = { + all: {}, + selected: null +}; + +export default (state = initialState, action) => { + if (action.type === 'addresses set') { + const accounts = action.addresses + .filter((address) => address.isAccount) + .reduce((accounts, account) => { + accounts[account.address] = account; + return accounts; + }, {}); + return { ...state, all: accounts }; + } + + if (action.type === 'accounts select' && state.all[action.address]) { + return { ...state, selected: state.all[action.address] }; + } + + return state; +}; diff --git a/js/src/dapps/registry/addresses/actions.js b/js/src/dapps/registry/addresses/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..17975f9e659d8509d46aaf3cdd5a515434e4a2cf --- /dev/null +++ b/js/src/dapps/registry/addresses/actions.js @@ -0,0 +1,40 @@ +// 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 { api } from '../parity'; + +export const set = (addresses) => ({ type: 'addresses set', addresses }); + +export const fetch = () => (dispatch) => { + return Promise + .all([ + api.eth.accounts(), + api.personal.accountsInfo() + ]) + .then(([ accounts, data ]) => { + data = data || {}; + const addresses = Object.keys(data) + .filter((address) => data[address] && !data[address].meta.deleted) + .map((address) => ({ + ...data[address], address, + isAccount: accounts.includes(address) + })); + dispatch(set(addresses)); + }) + .catch((error) => { + console.error('could not fetch addresses', error); + }); +}; diff --git a/js/src/dapps/registry/addresses/contacts-reducer.js b/js/src/dapps/registry/addresses/contacts-reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..6b0572e5495914b8f9250c619e2c6a984d731846 --- /dev/null +++ b/js/src/dapps/registry/addresses/contacts-reducer.js @@ -0,0 +1,31 @@ +// 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 . + +const initialState = {}; + +export default (state = initialState, action) => { + if (action.type === 'addresses set') { + const contacts = action.addresses + .filter((address) => !address.isAccount) + .reduce((contacts, contact) => { + contacts[contact.address] = contact; + return contacts; + }, {}); + return contacts; + } + + return state; +}; diff --git a/js/src/dapps/registry/parity.js b/js/src/dapps/registry/parity.js new file mode 100644 index 0000000000000000000000000000000000000000..cf9819b60ebc0fdaaa8529c226cea85347906e49 --- /dev/null +++ b/js/src/dapps/registry/parity.js @@ -0,0 +1,23 @@ +// 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 . + +const api = window.parity.api; +const { bytesToHex, sha3, toWei, fromWei } = window.parity.api.util; + +export { + api, + bytesToHex, sha3, toWei, fromWei +}; diff --git a/js/src/dapps/registry/reducers.js b/js/src/dapps/registry/reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..e0f620b7084f09bfff0ef5a2a5d74821906c0092 --- /dev/null +++ b/js/src/dapps/registry/reducers.js @@ -0,0 +1,55 @@ +// 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 accountsReducer from './addresses/accounts-reducer.js'; +import contactsReducer from './addresses/contacts-reducer.js'; +import lookupReducer from './Lookup/reducers.js'; +import eventsReducer from './Events/reducers.js'; +import namesReducer from './Names/reducers.js'; +import recordsReducer from './Records/reducers.js'; + +const contractReducer = (state = null, action) => + action.type === 'set contract' ? action.contract : state; + +const feeReducer = (state = null, action) => + action.type === 'set fee' ? action.fee : state; + +const ownerReducer = (state = null, action) => + action.type === 'set owner' ? action.owner : state; + +const initialState = { + accounts: accountsReducer(undefined, { type: '' }), + contacts: contactsReducer(undefined, { type: '' }), + contract: contractReducer(undefined, { type: '' }), + fee: feeReducer(undefined, { type: '' }), + owner: ownerReducer(undefined, { type: '' }), + lookup: lookupReducer(undefined, { type: '' }), + events: eventsReducer(undefined, { type: '' }), + names: namesReducer(undefined, { type: '' }), + records: recordsReducer(undefined, { type: '' }) +}; + +export default (state = initialState, action) => ({ + accounts: accountsReducer(state.accounts, action), + contacts: contactsReducer(state.contacts, action), + contract: contractReducer(state.contract, action), + fee: feeReducer(state.fee, action), + owner: ownerReducer(state.owner, action), + lookup: lookupReducer(state.lookup, action), + events: eventsReducer(state.events, action), + names: namesReducer(state.names, action), + records: recordsReducer(state.records, action) +}); diff --git a/js/src/dapps/registry/store.js b/js/src/dapps/registry/store.js new file mode 100644 index 0000000000000000000000000000000000000000..5fb7d4b6a4e4d42c3e9e8ca61942e7f8871ca2f5 --- /dev/null +++ b/js/src/dapps/registry/store.js @@ -0,0 +1,22 @@ +// 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 { createStore, applyMiddleware } from 'redux'; +import thunk from 'redux-thunk'; + +import reducer from './reducers'; + +export default createStore(reducer, applyMiddleware(thunk)); diff --git a/js/src/dapps/registry/ui/address.js b/js/src/dapps/registry/ui/address.js new file mode 100644 index 0000000000000000000000000000000000000000..f0b9d65da0803fcb84cea68df7af50d70e9b029a --- /dev/null +++ b/js/src/dapps/registry/ui/address.js @@ -0,0 +1,47 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React from 'react'; +import renderHash from './hash'; +import IdentityIcon from '../IdentityIcon'; + +const container = { + display: 'inline-block', + verticalAlign: 'middle', + height: '24px' +}; +const align = { + display: 'inline-block', + verticalAlign: 'top', + lineHeight: '24px' +}; + +export default (address, accounts, contacts, shortenHash = true) => { + let caption; + if (accounts[address]) { + caption = ({ accounts[address].name || address }); + } else if (contacts[address]) { + caption = ({ contacts[address].name || address }); + } else { + caption = ({ shortenHash ? renderHash(address) : address }); + } + return ( +
+ + { caption } +
+ ); +}; diff --git a/js/src/dapps/registry/ui/hash.js b/js/src/dapps/registry/ui/hash.js new file mode 100644 index 0000000000000000000000000000000000000000..4035a9bbe24099f06146c4d6dd8714fd8c503533 --- /dev/null +++ b/js/src/dapps/registry/ui/hash.js @@ -0,0 +1,24 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React from 'react'; + +export default (hash) => { + const shortened = hash.length > (2 + 9 + 9) + ? hash.substr(2, 9) + '...' + hash.slice(-9) + : hash.slice(2); + return ({ shortened }); +}; diff --git a/js/src/dapps/registry/ui/image.js b/js/src/dapps/registry/ui/image.js new file mode 100644 index 0000000000000000000000000000000000000000..e0101e1f2045933ed278ac6f6a37066b1111e5bf --- /dev/null +++ b/js/src/dapps/registry/ui/image.js @@ -0,0 +1,32 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React from 'react'; + +import { parityNode } from '../../../environment'; + +const styles = { + padding: '.5em', + border: '1px solid #777' +}; + +export default (address) => ( + { +); diff --git a/js/src/dapps/registry/ui/record-type-select.js b/js/src/dapps/registry/ui/record-type-select.js new file mode 100644 index 0000000000000000000000000000000000000000..2cfbdf540679687e30a14c634de48ce9acd59966 --- /dev/null +++ b/js/src/dapps/registry/ui/record-type-select.js @@ -0,0 +1,27 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React from 'react'; +import DropDownMenu from 'material-ui/DropDownMenu'; +import MenuItem from 'material-ui/MenuItem'; + +export default (value, onSelect, className = '') => ( + + + + + +); diff --git a/js/src/dapps/signaturereg.html b/js/src/dapps/signaturereg.html new file mode 100644 index 0000000000000000000000000000000000000000..d050fe803bcb98e8d2110a90da485e31caa1aafd --- /dev/null +++ b/js/src/dapps/signaturereg.html @@ -0,0 +1,17 @@ + + + + + + + + Method Signature Registry + + +
+ + + + + + diff --git a/js/src/dapps/signaturereg.js b/js/src/dapps/signaturereg.js new file mode 100644 index 0000000000000000000000000000000000000000..72ddd0ca7921bcda2ca83f7965ffc33e6ccd5535 --- /dev/null +++ b/js/src/dapps/signaturereg.js @@ -0,0 +1,33 @@ +// 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 ReactDOM from 'react-dom'; +import React from 'react'; + +import injectTapEventPlugin from 'react-tap-event-plugin'; +injectTapEventPlugin(); + +import Application from './signaturereg/Application'; + +import '../../assets/fonts/Roboto/font.css'; +import '../../assets/fonts/RobotoMono/font.css'; +import './style.css'; +import './signaturereg.html'; + +ReactDOM.render( + , + document.querySelector('#container') +); diff --git a/js/src/dapps/signaturereg/Application/application.css b/js/src/dapps/signaturereg/Application/application.css new file mode 100644 index 0000000000000000000000000000000000000000..4675b064e08e76d2d3bef02cfd2bef17af43f48c --- /dev/null +++ b/js/src/dapps/signaturereg/Application/application.css @@ -0,0 +1,29 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.container { + background: black; + color: #eee; + font-family: 'Roboto'; + vertical-align: middle; +} + +.actions { + position: absolute; + top: 1.5em; + right: 1.5em; +} diff --git a/js/src/dapps/signaturereg/Application/application.js b/js/src/dapps/signaturereg/Application/application.js new file mode 100644 index 0000000000000000000000000000000000000000..3878af4cfb17a26abf9daea38c76ca8bf1315d0c --- /dev/null +++ b/js/src/dapps/signaturereg/Application/application.js @@ -0,0 +1,130 @@ +// 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 BigNumber from 'bignumber.js'; +import React, { Component } from 'react'; + +import { attachInterface, attachBlockNumber } from '../services'; +import Button from '../Button'; +import Events from '../Events'; +import Header from '../Header'; +import Import from '../Import'; +import Loading from '../Loading'; + +import styles from './application.css'; + +export default class Application extends Component { + state = { + accounts: {}, + address: null, + fromAddress: null, + accountsInfo: {}, + blockNumber: new BigNumber(0), + contract: null, + instance: null, + loading: true, + totalSignatures: new BigNumber(0), + showImport: false + } + + componentDidMount () { + attachInterface() + .then((state) => { + this.setState(state, () => { + this.setState({ loading: false }); + }); + + return attachBlockNumber(state.instance, (state) => { + this.setState(state); + }); + }) + .catch((error) => { + console.error('componentDidMount', error); + }); + } + + render () { + const { loading } = this.state; + + if (loading) { + return ( + + ); + } + + return ( +
+ { this.renderHeader() } + { this.renderImport() } + { this.renderEvents() } +
+ ); + } + + renderHeader () { + const { blockNumber, totalSignatures } = this.state; + + return ( +
+ ); + } + + renderImport () { + const { accounts, fromAddress, instance, showImport } = this.state; + + if (showImport) { + return ( + + ); + } + + return ( +
+ +
+ ); + } + + renderEvents () { + const { accountsInfo, contract } = this.state; + + return ( + + ); + } + + toggleImport = () => { + this.setState({ + showImport: !this.state.showImport + }); + } + + setFromAddress = (fromAddress) => { + this.setState({ + fromAddress + }); + } +} diff --git a/js/src/dapps/signaturereg/Application/index.js b/js/src/dapps/signaturereg/Application/index.js new file mode 100644 index 0000000000000000000000000000000000000000..236578226a80e822593c37acd1daad1c649950e1 --- /dev/null +++ b/js/src/dapps/signaturereg/Application/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './application'; diff --git a/js/src/dapps/signaturereg/Button/button.css b/js/src/dapps/signaturereg/Button/button.css new file mode 100644 index 0000000000000000000000000000000000000000..444359c79ea8e0bd880f2be325be42f339d92696 --- /dev/null +++ b/js/src/dapps/signaturereg/Button/button.css @@ -0,0 +1,43 @@ +/* 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 . +*/ + +.button { + background: #f80; + color: white; + border-radius: 5px; + font-size: 1em; + line-height: 24px; + height: 24px; + padding: 0.75em 1.5em; + cursor: pointer; + display: inline-block; +} + +.button.disabled { + opacity: 0.25; + cursor: default; +} + +.button.inverse { + color: #f80; + background: white; +} + +.button * { + display: inline-block; + vertical-align: top; +} diff --git a/js/src/dapps/signaturereg/Button/button.js b/js/src/dapps/signaturereg/Button/button.js new file mode 100644 index 0000000000000000000000000000000000000000..9cbbcf478ee4e23a621e95b53b1ae1dbba88e2ab --- /dev/null +++ b/js/src/dapps/signaturereg/Button/button.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 React, { Component, PropTypes } from 'react'; + +import styles from './button.css'; + +export default class Button extends Component { + static propTypes = { + children: PropTypes.node.isRequired, + className: PropTypes.string, + disabled: PropTypes.bool, + invert: PropTypes.bool, + onClick: PropTypes.func.isRequired + } + + render () { + const { children, className, disabled, invert } = this.props; + const classes = `${styles.button} ${disabled ? styles.disabled : ''} ${invert ? styles.inverse : ''} ${className}`; + + return ( +
+ { children } +
+ ); + } + + onClick = (event) => { + const { disabled, onClick } = this.props; + + if (disabled) { + return; + } + + onClick(event); + } +} diff --git a/js/src/dapps/signaturereg/Button/index.js b/js/src/dapps/signaturereg/Button/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f69a65e3d53fd0e216cb4aefcbcd551417281e09 --- /dev/null +++ b/js/src/dapps/signaturereg/Button/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './button'; diff --git a/js/src/dapps/signaturereg/Events/events.css b/js/src/dapps/signaturereg/Events/events.css new file mode 100644 index 0000000000000000000000000000000000000000..5e9960e0eed0f222552a323d0d51d96e1be9ae9c --- /dev/null +++ b/js/src/dapps/signaturereg/Events/events.css @@ -0,0 +1,76 @@ +/* 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 . +*/ + +.events { + padding: 3em; + text-align: center; +} + +.header { + font-size: 1.3em; + line-height: 1.3em; + vertical-align: middle; + text-align: center; + padding-bottom: 24px; + color: #f80; +} + +.events table { + border: none; + margin: 0 auto; + border-collapse: collapse; +} + +.events td { + padding: 0 0.5em 0.5em 0.5em; + white-space: nowrap; + text-align: left; + line-height: 24px; +} + +.events td * { + display: inline-block; + vertical-align: top; +} + +.pending { + opacity: 0.5; +} + +.mined { +} + +td.methodName { + color: #f80; +} + +td.signature { + color: #888; + text-align: right; +} + +td.timestamp { + text-align: right; +} + +td.blockNumber { + text-align: center; +} + +td.owner { + text-overflow: ellipsis; +} diff --git a/js/src/dapps/signaturereg/Events/events.js b/js/src/dapps/signaturereg/Events/events.js new file mode 100644 index 0000000000000000000000000000000000000000..302b51250417abda653c49be8427861c5fb933b4 --- /dev/null +++ b/js/src/dapps/signaturereg/Events/events.js @@ -0,0 +1,84 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { formatBlockNumber, formatBlockTimestamp, formatSignature } from '../format'; +import { attachEvents } from '../services'; +import IdentityIcon from '../IdentityIcon'; + +import styles from './events.css'; + +export default class Events extends Component { + static propTypes = { + accountsInfo: PropTypes.object.isRequired, + contract: PropTypes.object.isRequired + } + + state = { + events: [] + } + + componentDidMount () { + const { contract } = this.props; + + attachEvents(contract, (state) => { + this.setState(state); + }); + } + + render () { + const { events } = this.state; + + if (!events.length) { + return null; + } + + return ( +
+ + + { this.renderEvents() } + +
+
+ ); + } + + renderEvents () { + const { accountsInfo } = this.props; + const { events } = this.state; + + return events.map((event) => { + const name = accountsInfo[event.params.creator] + ? accountsInfo[event.params.creator].name + : event.params.creator; + + return ( + + { formatBlockTimestamp(event.block) } + { formatBlockNumber(event.blockNumber) } + + +
{ name }
+ + { formatSignature(event.params.signature) } + { event.params.method } + + ); + }); + } +} diff --git a/js/src/dapps/signaturereg/Events/index.js b/js/src/dapps/signaturereg/Events/index.js new file mode 100644 index 0000000000000000000000000000000000000000..88ad6d407c91e416ead5fef1cf8c93201cac529b --- /dev/null +++ b/js/src/dapps/signaturereg/Events/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './events'; diff --git a/js/src/dapps/signaturereg/Header/header.css b/js/src/dapps/signaturereg/Header/header.css new file mode 100644 index 0000000000000000000000000000000000000000..8d95b959c2acb10d759fc2479e7af581cf7e395b --- /dev/null +++ b/js/src/dapps/signaturereg/Header/header.css @@ -0,0 +1,67 @@ +/* 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 . +*/ + +.header { + position: relative; + height: 13.69em; + color: white; + border-bottom: 4px solid white; + overflow: hidden; +} + +.banner { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + font-size: 1.3em; + line-height: 1.3em; + padding: 24px; + background: #f80; +} + +.header img, +.content { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; +} + +.header img { + opacity: 0.2; + width: 100%; +} + +.content { + text-align: center; + padding: 3em; +} + +.hero { + font-size: 5em; + line-height: 1.2em; + vertical-align: middle; +} + +.byline { + font-size: 1.3em; + line-height: 1.3em; + vertical-align: middle; +} diff --git a/js/src/dapps/signaturereg/Header/header.js b/js/src/dapps/signaturereg/Header/header.js new file mode 100644 index 0000000000000000000000000000000000000000..8dd7cd578a5afa8cc6311b95bd8e10b7561d1b3e --- /dev/null +++ b/js/src/dapps/signaturereg/Header/header.js @@ -0,0 +1,48 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import styles from './header.css'; +import blocks from '../../../../assets/images/dapps/blocks-350.jpg'; + +export default class Header extends Component { + static propTypes = { + blockNumber: PropTypes.object.isRequired, + totalSignatures: PropTypes.object.isRequired + } + + render () { + const { totalSignatures } = this.props; + + return ( +
+
+ contract signature registry +
+ +
+
+ { totalSignatures.toFormat(0) } +
+
+ signatures registered +
+
+
+ ); + } +} diff --git a/js/src/dapps/signaturereg/Header/index.js b/js/src/dapps/signaturereg/Header/index.js new file mode 100644 index 0000000000000000000000000000000000000000..37b5835f05496ab16e2f3c472ed0a5b174838a09 --- /dev/null +++ b/js/src/dapps/signaturereg/Header/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './header.js'; diff --git a/js/src/dapps/signaturereg/IdentityIcon/identityIcon.css b/js/src/dapps/signaturereg/IdentityIcon/identityIcon.css new file mode 100644 index 0000000000000000000000000000000000000000..3fa1df99e4d29224b7dd7cc02fdaac2e68e490c7 --- /dev/null +++ b/js/src/dapps/signaturereg/IdentityIcon/identityIcon.css @@ -0,0 +1,23 @@ +/* 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 . +*/ + +.icon { + width: 24px; + height: 24px; + border-radius: 50%; + margin-right: 0.5em; +} diff --git a/js/src/dapps/signaturereg/IdentityIcon/identityIcon.js b/js/src/dapps/signaturereg/IdentityIcon/identityIcon.js new file mode 100644 index 0000000000000000000000000000000000000000..0bc86731d4544432cae2af30ee573670fff5f9f7 --- /dev/null +++ b/js/src/dapps/signaturereg/IdentityIcon/identityIcon.js @@ -0,0 +1,36 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import styles from './identityIcon.css'; + +export default class IdentityIcon extends Component { + static propTypes = { + address: PropTypes.string.isRequired + } + + render () { + const { address } = this.props; + + return ( + + ); + } +} diff --git a/js/src/dapps/signaturereg/IdentityIcon/index.js b/js/src/dapps/signaturereg/IdentityIcon/index.js new file mode 100644 index 0000000000000000000000000000000000000000..76c107bfb7540f707a9b2665aac9b52f9d7590fa --- /dev/null +++ b/js/src/dapps/signaturereg/IdentityIcon/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './identityIcon'; diff --git a/js/src/dapps/signaturereg/Import/import.css b/js/src/dapps/signaturereg/Import/import.css new file mode 100644 index 0000000000000000000000000000000000000000..8f9788c34100518c7ce3bc789447443c949939fc --- /dev/null +++ b/js/src/dapps/signaturereg/Import/import.css @@ -0,0 +1,151 @@ +/* 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 . +*/ + +.modal { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; +} + +.overlay { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: rgba(55, 55, 55, 0.75); + text-align: center; +} + +.dialog { + margin-top: 1.5em; + border-radius: 5px; + width: 750px; + background: rgba(0, 0, 0, 0.9); + display: inline-block; +} + +.close { + top: 4px; + right: 4px; + position: absolute; + background: transparent; +} + +.header { + font-size: 1.3em; + line-height: 1.3em; + padding: 16px 24px; + background: #f80; + color: white; + position: relative; + margin-bottom: 24px; + border-radius: 5px 5px 0 0; +} + +.body { + padding: 0 24px; +} + +.body div { + text-align: center; +} + +.info { + padding: 0 24px 24px 24px; + line-height: 1.618em; +} + +.info textarea { + background: rgba(80, 80, 80, 0.25); + border-radius: 5px; + resize: none; + padding: 1em; + color: #eee; + font-size: 0.75em; + font-family: 'Roboto Mono'; + width: 100%; + border: none; + box-sizing: border-box; +} + +.info textarea.error { + background: rgba(255, 0, 0, 0.25); +} + +.info .error { + color: rgba(255, 0, 0, 1); + font-size: 0.75em; + line-height: 1.5em; +} + +.buttonrow { + position: relative; + padding: 24px 0; + margin: 0; + text-align: right !important; +} + +.addressSelect { + position: absolute; + top: 24px; + left: 0; +} + +.keys { + position: absolute; + left: 24px; + top: 16px; + padding: 4px 0; +} + +.fnconstant, +.fnexists, +.fnunknown, +.fntodo { + display: inline-block; + margin: 0.25em; + padding: 0.5em 1em; + border-radius: 2px; + color: white; + line-height: 1em; + font-size: 0.8em; +} + +.fnconstant { + color: #888; + background: #333; +} + +.fnexists { + color: #f80; + background: #333; +} + +.fnunknown { + color: #eee; +} + +.fntodo { + background: #f80; +} + +.hide { + opacity: 0; +} diff --git a/js/src/dapps/signaturereg/Import/import.js b/js/src/dapps/signaturereg/Import/import.js new file mode 100644 index 0000000000000000000000000000000000000000..dcf2b3f985cf2bc37d19c7f41695e21b86742e77 --- /dev/null +++ b/js/src/dapps/signaturereg/Import/import.js @@ -0,0 +1,236 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import { callRegister, postRegister } from '../services'; +import Button from '../Button'; +import IdentityIcon from '../IdentityIcon'; + +import styles from './import.css'; + +export default class Import extends Component { + static propTypes = { + accounts: PropTypes.object.isRequired, + fromAddress: PropTypes.string.isRequired, + instance: PropTypes.object.isRequired, + visible: PropTypes.bool.isRequired, + onClose: PropTypes.func.isRequired, + onSetFromAddress: PropTypes.func.isRequired + } + + state = { + abi: null, + abiParsed: null, + abiError: 'Please add a valid ABI definition', + functions: null, + fnstate: {} + } + + render () { + const { visible, onClose } = this.props; + const { abiError } = this.state; + + if (!visible) { + return null; + } + + return ( +
+
+
+
+
abi import
+ +
+ { abiError ? this.renderCapture() : this.renderRegister() } +
+
+
+ ); + } + + renderCapture () { + const { abiError } = this.state; + + return ( +
+
+ Provide the ABI (Contract Interface) in the space provided below. Only non-constant functions (names & types) will be imported, while constant functions and existing signatures will be ignored. +
+
+ +
+ { abiError } +
+
+
+ ); + } + + renderRegister () { + const { accounts, fromAddress } = this.props; + + const account = accounts[fromAddress]; + const count = this.countFunctions(); + let buttons = null; + + if (count) { + buttons = ( +
+
+ +
+ +
+ ); + } + + return ( +
+
+ The following functions have been extracted from the ABI provided and the state has been determined from interacting with the signature contract. +
+
+
+ { this.renderFunctions() } +
+
+
+ { count || 'no' } functions available for registration +
+ { buttons } +
+ ); + } + + renderFunctions () { + const { functions, fnstate } = this.state; + + if (!functions) { + return null; + } + + return functions.map((fn) => { + if (fn.constant) { + fnstate[fn.signature] = 'fnconstant'; + } else if (!fnstate[fn.signature]) { + this.testFunction(fn); + } + + return ( +
+ { fn.id } +
+ ); + }); + } + + sortFunctions = (a, b) => { + return a.name.localeCompare(b.name); + } + + countFunctions () { + const { functions, fnstate } = this.state; + + if (!functions) { + return 0; + } + + return functions.filter((fn) => fnstate[fn.signature] === 'fntodo').length; + } + + testFunction (fn) { + const { instance } = this.props; + const { fnstate } = this.state; + + callRegister(instance, fn.id) + .then((result) => { + fnstate[fn.signature] = result ? 'fntodo' : 'fnexists'; + this.setState(fnstate); + }) + .catch((error) => { + console.error(error); + }); + } + + onAbiEdit = (event) => { + let functions = null; + let abiError = null; + let abiParsed = null; + let abi = null; + + try { + abiParsed = JSON.parse(event.target.value); + functions = api.newContract(abiParsed).functions.sort(this.sortFunctions); + abi = JSON.stringify(abiParsed); + } catch (error) { + console.error('onAbiEdit', error); + abiError = error.message; + } + + this.setState({ + functions, + abiError, + abiParsed, + abi + }); + } + + onRegister = () => { + const { instance, fromAddress, onClose } = this.props; + const { functions, fnstate } = this.state; + + Promise + .all( + functions + .filter((fn) => !fn.constant) + .filter((fn) => fnstate[fn.signature] === 'fntodo') + .map((fn) => postRegister(instance, fn.id, { from: fromAddress })) + ) + .then(() => { + onClose(); + }) + .catch((error) => { + console.error('onRegister', error); + }); + } + + onSelectFromAddress = () => { + const { accounts, fromAddress, onSetFromAddress } = this.props; + const addresses = Object.keys(accounts); + let index = 0; + + addresses.forEach((address, _index) => { + if (address === fromAddress) { + index = _index; + } + }); + + index++; + if (index >= addresses.length) { + index = 0; + } + + onSetFromAddress(addresses[index]); + } +} diff --git a/js/src/dapps/signaturereg/Import/index.js b/js/src/dapps/signaturereg/Import/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d2f352cf3dbdc50bc2c6a797fc2fc225baef6523 --- /dev/null +++ b/js/src/dapps/signaturereg/Import/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './import'; diff --git a/js/src/dapps/signaturereg/Loading/index.js b/js/src/dapps/signaturereg/Loading/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0468cab37dfd505cb0b1ef415376ca121ab9ca89 --- /dev/null +++ b/js/src/dapps/signaturereg/Loading/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './loading'; diff --git a/js/src/dapps/signaturereg/Loading/loading.css b/js/src/dapps/signaturereg/Loading/loading.css new file mode 100644 index 0000000000000000000000000000000000000000..b77d1a23725749001e0ff1e0675844afefa37aa8 --- /dev/null +++ b/js/src/dapps/signaturereg/Loading/loading.css @@ -0,0 +1,24 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.loading { + width: 100%; + text-align: center; + padding-top: 5em; + font-size: 2em; + color: #999; +} diff --git a/js/src/dapps/signaturereg/Loading/loading.js b/js/src/dapps/signaturereg/Loading/loading.js new file mode 100644 index 0000000000000000000000000000000000000000..b884597d763299230e7f956d2778783141f41feb --- /dev/null +++ b/js/src/dapps/signaturereg/Loading/loading.js @@ -0,0 +1,29 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; + +import styles from './loading.css'; + +export default class Loading extends Component { + render () { + return ( +
+ Attaching to contract ... +
+ ); + } +} diff --git a/js/src/dapps/signaturereg/format.js b/js/src/dapps/signaturereg/format.js new file mode 100644 index 0000000000000000000000000000000000000000..24b6428f48d67bb0cc99c3f6df9817f7be36c363 --- /dev/null +++ b/js/src/dapps/signaturereg/format.js @@ -0,0 +1,40 @@ +// 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 BigNumber from 'bignumber.js'; +import moment from 'moment'; + +import { api } from './parity'; + +const ZERO = new BigNumber(0); + +export function formatBlockNumber (blockNumber) { + return ZERO.eq(blockNumber || 0) + ? 'Pending' + : `${blockNumber.toFormat()}`; +} + +export function formatSignature (signature) { + return api.util.bytesToHex(signature); +} + +export function formatBlockTimestamp (block) { + if (!block || !block.timestamp) { + return null; + } + + return moment(block.timestamp).fromNow(); +} diff --git a/js/src/dapps/signaturereg/parity.js b/js/src/dapps/signaturereg/parity.js new file mode 100644 index 0000000000000000000000000000000000000000..f6d59f44d5771db93be36fa0ed8af8889d14af51 --- /dev/null +++ b/js/src/dapps/signaturereg/parity.js @@ -0,0 +1,21 @@ +// 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 . + +const { api } = window.parity; + +export { + api +}; diff --git a/js/src/dapps/signaturereg/services.js b/js/src/dapps/signaturereg/services.js new file mode 100644 index 0000000000000000000000000000000000000000..cab324f7eb4d5e0ffbb83cc3e626dc0d1265724e --- /dev/null +++ b/js/src/dapps/signaturereg/services.js @@ -0,0 +1,177 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import * as abis from '../../contracts/abi'; +import { api } from './parity'; + +const sortEvents = (a, b) => b.blockNumber.cmp(a.blockNumber) || b.logIndex.cmp(a.logIndex); + +const logToEvent = (log) => { + const key = api.util.sha3(JSON.stringify(log)); + const { blockNumber, logIndex, transactionHash, transactionIndex, params, type } = log; + + return { + type: log.event, + state: type, + blockNumber, + logIndex, + transactionHash, + transactionIndex, + params: Object.keys(params).reduce((data, name) => { + data[name] = params[name].value; + return data; + }, {}), + key + }; +}; + +export function attachInterface (callback) { + return api.ethcore + .registryAddress() + .then((registryAddress) => { + console.log(`the registry was found at ${registryAddress}`); + + const registry = api.newContract(abis.registry, registryAddress).instance; + + return Promise + .all([ + registry.getAddress.call({}, [api.util.sha3('signaturereg'), 'A']), + api.eth.accounts(), + api.personal.accountsInfo() + ]); + }) + .then(([address, addresses, accountsInfo]) => { + accountsInfo = accountsInfo || {}; + console.log(`signaturereg was found at ${address}`); + + const contract = api.newContract(abis.signaturereg, address); + const accounts = addresses.reduce((obj, address) => { + const info = accountsInfo[address] || {}; + + return Object.assign(obj, { + [address]: { + address, + name: info.name || 'Unnamed', + uuid: info.uuid + } + }); + }, {}); + const fromAddress = Object.keys(accounts)[0]; + + return { + accounts, + address, + accountsInfo, + contract, + instance: contract.instance, + fromAddress + }; + }) + .catch((error) => { + console.error('attachInterface', error); + }); +} + +export function attachBlockNumber (instance, callback) { + return api.subscribe('eth_blockNumber', (error, blockNumber) => { + if (error) { + console.error('blockNumber', error); + return; + } + + instance.totalSignatures + .call() + .then((totalSignatures) => { + callback({ + blockNumber, + totalSignatures + }); + }) + .catch((error) => { + console.error('totalSignatures', error); + }); + }); +} + +export function attachEvents (contract, callback) { + const blocks = { '0': {} }; + let mined = []; + let pending = []; + let events = []; + + const options = { + fromBlock: 0, + toBlock: 'pending', + limit: 50 + }; + + return contract.subscribe('Registered', options, (error, _logs) => { + if (error) { + console.error('events', error); + return; + } + + const logs = _logs.map(logToEvent); + + mined = logs + .filter((log) => log.state === 'mined') + .map((log) => { + const blockNumber = log.blockNumber.toString(); + + if (!blocks[blockNumber]) { + blocks[blockNumber] = {}; + getBlock(blockNumber).then((block) => { + Object.assign(blocks[blockNumber], block); + }); + } + + return Object.assign(log, { block: blocks[blockNumber] }); + }) + .reverse() + .concat(mined) + .sort(sortEvents); + + pending = logs + .filter((log) => log.state === 'pending') + .reverse() + .filter((event) => !pending.find((log) => log.params.method === event.params.method)) + .concat(pending) + .filter((event) => !mined.find((log) => log.params.method === event.params.method)) + .sort(sortEvents); + + events = pending.concat(mined); + + callback({ events }); + }); +} + +export function getBlock (blockNumber) { + return api.eth.getBlockByNumber(blockNumber); +} + +export function callRegister (instance, id, options = {}) { + return instance.register.call(options, [id]); +} + +export function postRegister (instance, id, options = {}) { + return instance.register + .estimateGas(options, [id]) + .then((gas) => { + options.gas = gas.mul(1.2).toFixed(0); + console.log('postRegister', `gas estimated at ${gas.toFormat(0)}, setting to ${gas.mul(1.2).toFormat(0)}`); + instance.register.postTransaction(options, [id]); + }); +} diff --git a/js/src/dapps/style.css b/js/src/dapps/style.css new file mode 100644 index 0000000000000000000000000000000000000000..b177a15f9264ae3f0563b51b719755d548a62a01 --- /dev/null +++ b/js/src/dapps/style.css @@ -0,0 +1,46 @@ +/* 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 . +*/ + +:root, +:root body { + background: #fff; + border: 0; + color: #333; + font-size: 16px; + font-family: 'Roboto', sans-serif; + font-weight: 300 !important; + margin: 0; + padding: 0; + vertical-align: top; +} + +:root, +:root body, +:root :global(#container) { + min-height: 100%; + width: 100%; + display: flex; + flex: 1; +} + +:root * { + font-weight: 300 !important; +} + +:root :global(#container) > div { + flex: 1; +} diff --git a/js/src/dapps/tokenreg.html b/js/src/dapps/tokenreg.html new file mode 100644 index 0000000000000000000000000000000000000000..d16d4082c19a60cd1b230b72c378dd96e9972aac --- /dev/null +++ b/js/src/dapps/tokenreg.html @@ -0,0 +1,17 @@ + + + + + + + + Token Registry + + +
+ + + + + + diff --git a/js/src/dapps/tokenreg.js b/js/src/dapps/tokenreg.js new file mode 100644 index 0000000000000000000000000000000000000000..8ca70e114f04a74630c48e58c13b99e9e4cb4aa5 --- /dev/null +++ b/js/src/dapps/tokenreg.js @@ -0,0 +1,39 @@ +// 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 ReactDOM from 'react-dom'; +import React from 'react'; +import { Provider } from 'react-redux'; + +import injectTapEventPlugin from 'react-tap-event-plugin'; +injectTapEventPlugin(); + +import store from './tokenreg/store'; +import Container from './tokenreg/Container'; + +import '../../assets/fonts/Roboto/font.css'; +import '../../assets/fonts/RobotoMono/font.css'; +import './style.css'; +import './tokenreg.html'; + +ReactDOM.render( + ( + + + + ), + document.querySelector('#container') +); diff --git a/js/src/dapps/tokenreg/Accounts/AccountSelector/account-selector.css b/js/src/dapps/tokenreg/Accounts/AccountSelector/account-selector.css new file mode 100644 index 0000000000000000000000000000000000000000..f6f8476bb3e4f31d2711fc6faeaeac1bb6ecd2cd --- /dev/null +++ b/js/src/dapps/tokenreg/Accounts/AccountSelector/account-selector.css @@ -0,0 +1,25 @@ +/* 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 . +*/ + +.account-selector { +} + +.avatar > img { + margin: 0; + width: 100%; + height: 100%; +} diff --git a/js/src/dapps/tokenreg/Accounts/AccountSelector/account-selector.js b/js/src/dapps/tokenreg/Accounts/AccountSelector/account-selector.js new file mode 100644 index 0000000000000000000000000000000000000000..4c8525d7ee8d795294966e1e317b903430480f64 --- /dev/null +++ b/js/src/dapps/tokenreg/Accounts/AccountSelector/account-selector.js @@ -0,0 +1,120 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { List, ListItem } from 'material-ui/List'; +import Subheader from 'material-ui/Subheader'; +import Avatar from 'material-ui/Avatar'; + +import IdentityIcon from '../../IdentityIcon'; + +import styles from './account-selector.css'; + +class AccountSelectorItem extends Component { + + static propTypes = { + onSelectAccount: PropTypes.func.isRequired, + account: PropTypes.object.isRequired + }; + + render () { + const account = this.props.account; + + const props = Object.assign({}, this.props); + delete props.account; + delete props.onSelectAccount; + + const icon = ( + ); + + const avatar = ( + ); + + return ( + + ); + } + + onSelectAccount = () => { + this.props.onSelectAccount(this.props.account.address); + } + +} + +export default class AccountSelector extends Component { + + static propTypes = { + list: PropTypes.array.isRequired, + selected: PropTypes.object.isRequired, + handleSetSelected: PropTypes.func.isRequired + }; + + state = { + open: false + }; + + render () { + const nestedAccounts = this.renderAccounts(this.props.list); + const selectedAccount = ( + + ); + + return ( +
+ + Select an account + { selectedAccount } + +
+ ); + } + + renderAccounts (accounts) { + return accounts + .map((account, index) => ( + + )); + } + + onToggleOpen = () => { + this.setState({ open: !this.state.open }); + } + + onSelectAccount = (address) => { + this.props.handleSetSelected(address); + this.onToggleOpen(); + } + +} diff --git a/js/src/dapps/tokenreg/Accounts/AccountSelector/container.js b/js/src/dapps/tokenreg/Accounts/AccountSelector/container.js new file mode 100644 index 0000000000000000000000000000000000000000..6438d1dff7c61f939e4598c7e4b280cdee62b1ec --- /dev/null +++ b/js/src/dapps/tokenreg/Accounts/AccountSelector/container.js @@ -0,0 +1,45 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; +import { connect } from 'react-redux'; + +import AccountSelector from './account-selector'; + +import { setSelectedAccount } from '../actions'; + +class AccountSelectorContainer extends Component { + render () { + return (); + } +} + +const mapStateToProps = (state) => { + const { accounts } = state; + return { ...accounts }; +}; + +const mapDispatchToProps = (dispatch) => { + return { + handleSetSelected: (address) => { + dispatch(setSelectedAccount(address)); + } + }; +}; + +export default connect(mapStateToProps, mapDispatchToProps)(AccountSelectorContainer); diff --git a/js/src/dapps/tokenreg/Accounts/AccountSelector/index.js b/js/src/dapps/tokenreg/Accounts/AccountSelector/index.js new file mode 100644 index 0000000000000000000000000000000000000000..87fbc567ef2f3db31a65d206720db12454dfcd7e --- /dev/null +++ b/js/src/dapps/tokenreg/Accounts/AccountSelector/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './container'; diff --git a/js/src/dapps/tokenreg/Accounts/actions.js b/js/src/dapps/tokenreg/Accounts/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..f501399c2dd624497a5ddaa3c1ce0e8fa63ffd16 --- /dev/null +++ b/js/src/dapps/tokenreg/Accounts/actions.js @@ -0,0 +1,61 @@ +// 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 . + +const { api } = window.parity; + +export const SET_ACCOUNTS = 'SET_ACCOUNTS'; +export const setAccounts = (accounts) => ({ + type: SET_ACCOUNTS, + accounts +}); + +export const SET_ACCOUNTS_INFO = 'SET_ACCOUNTS_INFO'; +export const setAccountsInfo = (accountsInfo) => ({ + type: SET_ACCOUNTS_INFO, + accountsInfo +}); + +export const SET_SELECTED_ACCOUNT = 'SET_SELECTED_ACCOUNT'; +export const setSelectedAccount = (address) => ({ + type: SET_SELECTED_ACCOUNT, + address +}); + +export const loadAccounts = () => (dispatch) => { + Promise + .all([ + api.eth.accounts(), + api.personal.accountsInfo() + ]) + .then(([ accounts, accountsInfo ]) => { + accountsInfo = accountsInfo || {}; + + const accountsList = accounts + .map(address => ({ + ...accountsInfo[address], + address + })); + + console.log('accounts', accountsList); + + dispatch(setAccounts(accountsList)); + dispatch(setAccountsInfo(accountsInfo)); + dispatch(setSelectedAccount(accountsList[0].address)); + }) + .catch(e => { + console.error('loadAccounts error', e); + }); +}; diff --git a/js/src/dapps/tokenreg/Accounts/reducer.js b/js/src/dapps/tokenreg/Accounts/reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..091df4c8a66743d9d52a8160f16b2ba27d66f336 --- /dev/null +++ b/js/src/dapps/tokenreg/Accounts/reducer.js @@ -0,0 +1,57 @@ +// 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 { + SET_ACCOUNTS, + SET_SELECTED_ACCOUNT, + SET_ACCOUNTS_INFO +} from './actions'; + +const initialState = { + list: [], + accountsInfo: {}, + selected: null +}; + +export default (state = initialState, action) => { + switch (action.type) { + case SET_ACCOUNTS: + return { + ...state, + list: [].concat(action.accounts) + }; + + case SET_ACCOUNTS_INFO: + return { + ...state, + accountsInfo: { ...action.accountsInfo } + }; + + case SET_SELECTED_ACCOUNT: { + const address = action.address; + const account = state.list.find(a => a.address === address); + + return { + ...state, + selected: account + }; + } + + default: + return state; + } +}; + diff --git a/js/src/dapps/tokenreg/Actions/Query/index.js b/js/src/dapps/tokenreg/Actions/Query/index.js new file mode 100644 index 0000000000000000000000000000000000000000..83bc6a337ca01c63b7565a611dbf847c05838e49 --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/Query/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './query'; diff --git a/js/src/dapps/tokenreg/Actions/Query/query.js b/js/src/dapps/tokenreg/Actions/Query/query.js new file mode 100644 index 0000000000000000000000000000000000000000..16d13f2f04e105e7398eba9ae2c9ba5e01a3943c --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/Query/query.js @@ -0,0 +1,207 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { Dialog, FlatButton, SelectField, MenuItem } from 'material-ui'; + +import InputText from '../../Inputs/Text'; +import Loading from '../../Loading'; +import Token from '../../Tokens/Token'; + +import { SIMPLE_TOKEN_ADDRESS_TYPE, SIMPLE_TLA_TYPE } from '../../Inputs/validation'; + +import styles from '../actions.css'; + +const initState = { + queryKey: 'tla', + form: { + valid: false, + value: '' + } +}; + +export default class QueryAction extends Component { + + static propTypes = { + show: PropTypes.bool.isRequired, + loading: PropTypes.bool.isRequired, + + onClose: PropTypes.func.isRequired, + handleQueryToken: PropTypes.func.isRequired, + handleQueryMetaLookup: PropTypes.func.isRequired, + + data: PropTypes.object, + notFound: PropTypes.bool, + metaLoading: PropTypes.bool, + metaData: PropTypes.object + } + + state = initState; + + render () { + return ( + + { this.renderContent() } + + ); + } + + renderActions () { + const { loading, data, notFound } = this.props; + + if (loading) { + return ( + + ); + } + + const complete = data || notFound; + + if (complete) { + return ([ + + ]); + } + + const isValid = this.state.form.valid; + + return ([ + , + + ]); + } + + renderContent () { + const { loading, notFound, data } = this.props; + + if (loading) { + return ( + + ); + } + + if (notFound) { + return ( +

No token has been found in the registry...

+ ); + } + + if (data) { + return this.renderData(); + } + + return this.renderForm(); + } + + renderData () { + const { data } = this.props; + + return ( + + ); + } + + renderForm () { + return ( +
+ + + + + + { + this.state.queryKey !== 'tla' + ? () + : () + } +
+ ); + } + + onQueryKeyChange = (event, index, queryKey) => { + this.setState({ + queryKey, + form: { valid: false, value: '' } + }); + } + + onChange = (valid, value) => { + this.setState({ + form: { + valid, value + } + }); + } + + onQuery = () => { + if (!this.state.form.valid) return; + + const { queryKey, form } = this.state; + + this.props.handleQueryToken(queryKey, form.value); + } + + onClose = () => { + this.setState(initState); + this.props.onClose(); + } + +} diff --git a/js/src/dapps/tokenreg/Actions/Register/index.js b/js/src/dapps/tokenreg/Actions/Register/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3099d1f42f33b844b8c9a86f23c3250a0e613b7b --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/Register/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './register'; diff --git a/js/src/dapps/tokenreg/Actions/Register/register.js b/js/src/dapps/tokenreg/Actions/Register/register.js new file mode 100644 index 0000000000000000000000000000000000000000..78d823326f26ef6bf6537fdcd6700b6fa6c98f16 --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/Register/register.js @@ -0,0 +1,217 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { Dialog, FlatButton } from 'material-ui'; + +import AccountSelector from '../../Accounts/AccountSelector'; +import InputText from '../../Inputs/Text'; + +import { TOKEN_ADDRESS_TYPE, TLA_TYPE, UINT_TYPE, STRING_TYPE } from '../../Inputs/validation'; + +import styles from '../actions.css'; + +const defaultField = { value: '', valid: false }; +const initState = { + isFormValid: false, + fields: { + address: { + ...defaultField, + type: TOKEN_ADDRESS_TYPE, + floatingLabelText: 'Token address', + hintText: 'The token address' + }, + tla: { + ...defaultField, + type: TLA_TYPE, + floatingLabelText: 'Token TLA', + hintText: 'The token short name (3 characters)' + }, + base: { + ...defaultField, + type: UINT_TYPE, + floatingLabelText: 'Token Base', + hintText: 'The token precision' + }, + name: { + ...defaultField, + type: STRING_TYPE, + floatingLabelText: 'Token name', + hintText: 'The token name' + } + } +}; + +export default class RegisterAction extends Component { + + static propTypes = { + show: PropTypes.bool.isRequired, + sending: PropTypes.bool.isRequired, + complete: PropTypes.bool.isRequired, + onClose: PropTypes.func.isRequired, + handleRegisterToken: PropTypes.func.isRequired, + + error: PropTypes.object + } + + state = initState; + + render () { + const { sending, error, complete } = this.props; + + return ( + + { this.renderContent() } + + ); + } + + renderActions () { + const { complete, sending, error } = this.props; + + if (error) { + return ( + + ); + } + + if (complete) { + return ( + + ); + } + + const isValid = this.state.isFormValid; + + return ([ + , + + ]); + } + + renderContent () { + const { error, complete } = this.props; + + if (error) return this.renderError(); + if (complete) return this.renderComplete(); + return this.renderForm(); + } + + renderError () { + const { error } = this.props; + + return (
+

{ error.toString() }

+
); + } + + renderComplete () { + return (
+

Your transaction has been posted. Please visit the Parity Signer to authenticate the transfer.

+
); + } + + renderForm () { + return ( +
+ + { this.renderInputs() } +
+ ); + } + + renderInputs () { + const { fields } = this.state; + + return Object.keys(fields).map((fieldKey, index) => { + const onChange = this.onChange.bind(this, fieldKey); + const field = fields[fieldKey]; + + return ( + + ); + }); + } + + onChange (fieldKey, valid, value) { + const { fields } = this.state; + const field = fields[fieldKey]; + + const newFields = { + ...fields, + [ fieldKey ]: { + ...field, + valid, value + } + }; + + const isFormValid = Object.keys(newFields) + .map(key => newFields[key].valid) + .reduce((current, fieldValid) => { + return current && fieldValid; + }, true); + + this.setState({ + fields: newFields, + isFormValid + }); + } + + onRegister = () => { + const { fields } = this.state; + + const data = Object.keys(fields) + .reduce((dataObject, fieldKey) => { + dataObject[fieldKey] = fields[fieldKey].value; + return dataObject; + }, {}); + + this.props.handleRegisterToken(data); + } + + onClose = () => { + this.setState(initState); + this.props.onClose(); + } + +} diff --git a/js/src/dapps/tokenreg/Actions/actions.css b/js/src/dapps/tokenreg/Actions/actions.css new file mode 100644 index 0000000000000000000000000000000000000000..d8eba57f1e513fcb0dfcf1c96ea31efc3d7f03a0 --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/actions.css @@ -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 . +*/ + +.actions { + padding-top: 2rem; +} + +.button { + margin: 0 0.5em; +} + +.button button { + background-color: #27ae60 !important; + height: 56px !important; + padding: 0 10px !important; +} + +.button button[disabled] { + background-color: rgba(50, 50, 50, 0.25) !important; +} + +.dialog { +} + +.dialog h3 { + color: rgba(50, 100, 150, 1) !important; + text-transform: uppercase; +} + +.dialogtext { + padding-top: 1em; +} + +.error { + color: red; +} diff --git a/js/src/dapps/tokenreg/Actions/actions.js b/js/src/dapps/tokenreg/Actions/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..0f3390ea4f52eed6d67b94d4cc47e22da7ee52bb --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/actions.js @@ -0,0 +1,215 @@ +// 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 { getTokenTotalSupply } from '../utils'; + +const { sha3, bytesToHex } = window.parity.api.util; + +export const SET_REGISTER_SENDING = 'SET_REGISTER_SENDING'; +export const setRegisterSending = (isSending) => ({ + type: SET_REGISTER_SENDING, + isSending +}); + +export const SET_REGISTER_ERROR = 'SET_REGISTER_ERROR'; +export const setRegisterError = (e) => ({ + type: SET_REGISTER_ERROR, + error: e +}); + +export const REGISTER_RESET = 'REGISTER_RESET'; +export const registerReset = () => ({ + type: REGISTER_RESET +}); + +export const REGISTER_COMPLETED = 'REGISTER_COMPLETED'; +export const registerCompleted = () => ({ + type: REGISTER_COMPLETED +}); + +export const registerToken = (tokenData) => (dispatch, getState) => { + console.log('registering token', tokenData); + + const state = getState(); + const contractInstance = state.status.contract.instance; + const fee = state.status.contract.fee; + + const { address, base, name, tla } = tokenData; + + dispatch(setRegisterSending(true)); + + const values = [ address, tla, base, name ]; + const options = { + from: state.accounts.selected.address, + value: fee + }; + + Promise.resolve() + .then(() => { + return contractInstance + .fromTLA.call({}, [ tla ]) + .then(([id, address, base, name, owner]) => { + if (owner !== '0x0000000000000000000000000000000000000000') { + throw new Error(`A Token has already been registered with the TLA ${tla}`); + } + }); + }) + .then(() => { + return contractInstance + .fromAddress.call({}, [ address ]) + .then(([id, tla, base, name, owner]) => { + if (owner !== '0x0000000000000000000000000000000000000000') { + throw new Error(`A Token has already been registered with the Address ${address}`); + } + }); + }) + .then(() => { + return contractInstance + .register.estimateGas(options, values); + }) + .then((gasEstimate) => { + options.gas = gasEstimate.mul(1.2).toFixed(0); + console.log(`transfer: gas estimated as ${gasEstimate.toFixed(0)} setting to ${options.gas}`); + + return contractInstance.register.postTransaction(options, values); + }) + .then((result) => { + dispatch(registerCompleted()); + }) + .catch((e) => { + console.error('registerToken error', e); + dispatch(setRegisterError(e)); + }); +}; + +export const SET_QUERY_LOADING = 'SET_QUERY_LOADING'; +export const setQueryLoading = (isLoading) => ({ + type: SET_QUERY_LOADING, + isLoading +}); + +export const SET_QUERY_RESULT = 'SET_QUERY_RESULT'; +export const setQueryResult = (data) => ({ + type: SET_QUERY_RESULT, + data +}); + +export const SET_QUERY_NOT_FOUND = 'SET_QUERY_NOT_FOUND'; +export const setQueryNotFound = () => ({ + type: SET_QUERY_NOT_FOUND +}); + +export const QUERY_RESET = 'QUERY_RESET'; +export const queryReset = () => ({ + type: QUERY_RESET +}); + +export const SET_QUERY_META_LOADING = 'SET_QUERY_META_LOADING'; +export const setQueryMetaLoading = (isLoading) => ({ + type: SET_QUERY_META_LOADING, + isLoading +}); + +export const SET_QUERY_META = 'SET_QUERY_META'; +export const setQueryMeta = (data) => ({ + type: SET_QUERY_META, + data +}); + +export const queryToken = (key, query) => (dispatch, getState) => { + const state = getState(); + const contractInstance = state.status.contract.instance; + + const contractFunc = (key === 'tla') ? 'fromTLA' : 'fromAddress'; + + dispatch(setQueryLoading(true)); + + contractInstance[contractFunc] + .call({}, [ query ]) + .then((result) => { + const data = { + index: result[0].toNumber(), + base: result[2].toNumber(), + name: result[3], + owner: result[4] + }; + + if (key === 'tla') { + data.tla = query; + data.address = result[1]; + } + + if (key === 'address') { + data.address = query; + data.tla = result[1]; + } + + return data; + }) + .then(data => { + return getTokenTotalSupply(data.address) + .then(totalSupply => { + data.totalSupply = totalSupply; + return data; + }); + }) + .then(data => { + if (data.totalSupply === null) { + dispatch(setQueryNotFound()); + dispatch(setQueryLoading(false)); + + return false; + } + + data.totalSupply = data.totalSupply.toNumber(); + dispatch(setQueryResult(data)); + dispatch(setQueryLoading(false)); + }, () => { + dispatch(setQueryNotFound()); + dispatch(setQueryLoading(false)); + }); +}; + +export const queryTokenMeta = (id, query) => (dispatch, getState) => { + console.log('loading token meta', query); + + const state = getState(); + const contractInstance = state.status.contract.instance; + + const key = sha3(query); + + const startDate = Date.now(); + dispatch(setQueryMetaLoading(true)); + + contractInstance + .meta + .call({}, [ id, key ]) + .then((value) => { + const meta = { + key, query, + value: value.find(v => v !== 0) ? bytesToHex(value) : null + }; + + dispatch(setQueryMeta(meta)); + + setTimeout(() => { + dispatch(setQueryMetaLoading(false)); + }, 500 - (Date.now() - startDate)); + }) + .catch((e) => { + console.error('load meta query error', e); + }); +}; diff --git a/js/src/dapps/tokenreg/Actions/component.js b/js/src/dapps/tokenreg/Actions/component.js new file mode 100644 index 0000000000000000000000000000000000000000..3e7ef0d6458a8e2d42c86eef629fc44e533588cb --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/component.js @@ -0,0 +1,119 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { RaisedButton } from 'material-ui'; +import ActionSearchIcon from 'material-ui/svg-icons/action/search'; +import ContentSendIcon from 'material-ui/svg-icons/content/send'; + +import Register from './Register'; +import Query from './Query'; + +import styles from './actions.css'; + +const REGISTER_ACTION = 'REGISTER_ACTION'; +const QUERY_ACTION = 'QUERY_ACTION'; + +export default class Actions extends Component { + + static propTypes = { + handleRegisterToken: PropTypes.func.isRequired, + handleRegisterClose: PropTypes.func.isRequired, + register: PropTypes.object.isRequired, + + handleQueryToken: PropTypes.func.isRequired, + handleQueryClose: PropTypes.func.isRequired, + handleQueryMetaLookup: PropTypes.func.isRequired, + query: PropTypes.object.isRequired + }; + + state = { + show: { + [ REGISTER_ACTION ]: false, + [ QUERY_ACTION ]: false + } + } + + constructor () { + super(); + + this.onShowRegister = this.onShow.bind(this, REGISTER_ACTION); + this.onShowQuery = this.onShow.bind(this, QUERY_ACTION); + } + + render () { + return ( +
+ } + label='Register Token' + primary + onTouchTap={ this.onShowRegister } /> + + } + label='Search Token' + primary + onTouchTap={ this.onShowQuery } /> + + + + +
+ ); + } + + onRegisterClose = () => { + this.onHide(REGISTER_ACTION); + this.props.handleRegisterClose(); + } + + onQueryClose = () => { + this.onHide(QUERY_ACTION); + this.props.handleQueryClose(); + } + + onShow (key) { + this.setState({ + show: { + ...this.state.show, + [ key ]: true + } + }); + } + + onHide (key) { + this.setState({ + show: { + ...this.state.show, + [ key ]: false + } + }); + } + +} diff --git a/js/src/dapps/tokenreg/Actions/container.js b/js/src/dapps/tokenreg/Actions/container.js new file mode 100644 index 0000000000000000000000000000000000000000..2c37731222ace95fdcf10b8d310d3557c880aa51 --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/container.js @@ -0,0 +1,62 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; +import { connect } from 'react-redux'; + +import Actions from './component'; + +import { registerToken, registerReset, queryToken, queryReset, queryTokenMeta } from './actions'; + +class TokensContainer extends Component { + + render () { + return (); + } +} + +const mapStateToProps = (state) => { + const { register, query } = state.actions; + + return { register, query }; +}; + +const mapDispatchToProps = (dispatch) => { + return { + handleRegisterToken: (tokenData) => { + dispatch(registerToken(tokenData)); + }, + handleRegisterClose: () => { + dispatch(registerReset()); + }, + handleQueryToken: (key, query) => { + dispatch(queryToken(key, query)); + }, + handleQueryClose: () => { + dispatch(queryReset()); + }, + handleQueryMetaLookup: (id, query) => { + dispatch(queryTokenMeta(id, query)); + } + }; +}; + +export default connect( + mapStateToProps, + mapDispatchToProps +)(TokensContainer); diff --git a/js/src/dapps/tokenreg/Actions/index.js b/js/src/dapps/tokenreg/Actions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9007217b714120bff96d4b62f9f0ad0ac69ac104 --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './container.js'; diff --git a/js/src/dapps/tokenreg/Actions/reducer.js b/js/src/dapps/tokenreg/Actions/reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..7b7f8341a32795f9de8c2a022d5a821f6a80c1f4 --- /dev/null +++ b/js/src/dapps/tokenreg/Actions/reducer.js @@ -0,0 +1,155 @@ +// 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 { + SET_REGISTER_SENDING, + SET_REGISTER_ERROR, + REGISTER_RESET, + REGISTER_COMPLETED, + + SET_QUERY_LOADING, + SET_QUERY_RESULT, + SET_QUERY_NOT_FOUND, + SET_QUERY_META_LOADING, + SET_QUERY_META, + QUERY_RESET +} from './actions'; + +const initialState = { + register: { + sending: false, + error: null, + complete: false + }, + query: { + loading: false, + data: null, + notFound: false, + metaLoading: false, + metaData: null + } +}; + +export default (state = initialState, action) => { + switch (action.type) { + case SET_REGISTER_SENDING: { + const registerState = state.register; + + return { + ...state, + register: { + ...registerState, + sending: action.isSending + } + }; + } + + case REGISTER_COMPLETED: { + const registerState = state.register; + + return { + ...state, + register: { + ...registerState, + sending: false, + complete: true + } + }; + } + + case SET_REGISTER_ERROR: { + const registerState = state.register; + + return { + ...state, + register: { + ...registerState, + sending: false, + error: action.error + } + }; + } + + case REGISTER_RESET: { + return { + ...state, + register: initialState.register + }; + } + + case SET_QUERY_LOADING: { + return { + ...state, + query: { + ...state.query, + loading: action.isLoading + } + }; + } + + case SET_QUERY_RESULT: { + return { + ...state, + query: { + ...state.query, + data: action.data + } + }; + } + + case SET_QUERY_NOT_FOUND: { + return { + ...state, + query: { + ...state.query, + notFound: true + } + }; + } + + case SET_QUERY_META_LOADING: { + return { + ...state, + query: { + ...state.query, + metaLoading: action.isLoading + } + }; + } + + case SET_QUERY_META: { + return { + ...state, + query: { + ...state.query, + metaData: action.data + } + }; + } + + case QUERY_RESET: { + return { + ...state, + query: { + ...initialState.query + } + }; + } + + default: + return state; + } +}; diff --git a/js/src/dapps/tokenreg/Application/application.css b/js/src/dapps/tokenreg/Application/application.css new file mode 100644 index 0000000000000000000000000000000000000000..07bc74b40c760c80e5848c73869fa7a0ad6ad4dd --- /dev/null +++ b/js/src/dapps/tokenreg/Application/application.css @@ -0,0 +1,22 @@ +/* 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 . +*/ + +.application { + display: flex; + flex-direction: column; + align-items: center; +} diff --git a/js/src/dapps/tokenreg/Application/application.js b/js/src/dapps/tokenreg/Application/application.js new file mode 100644 index 0000000000000000000000000000000000000000..e48922b05338b149925e119e07c71c341b1bca2c --- /dev/null +++ b/js/src/dapps/tokenreg/Application/application.js @@ -0,0 +1,72 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import getMuiTheme from 'material-ui/styles/getMuiTheme'; + +import Loading from '../Loading'; +import Status from '../Status'; +import Tokens from '../Tokens'; +import Actions from '../Actions'; + +import styles from './application.css'; + +const muiTheme = getMuiTheme({ + palette: { + primary1Color: '#27ae60' + } +}); + +export default class Application extends Component { + static childContextTypes = { + muiTheme: PropTypes.object + } + + static propTypes = { + isLoading: PropTypes.bool.isRequired, + + contract: PropTypes.object + }; + + render () { + const { isLoading, contract } = this.props; + + if (isLoading) { + return ( + + ); + } + + return ( +
+ + + + + +
+ ); + } + + getChildContext () { + return { + muiTheme + }; + } + +} diff --git a/js/src/dapps/tokenreg/Application/index.js b/js/src/dapps/tokenreg/Application/index.js new file mode 100644 index 0000000000000000000000000000000000000000..236578226a80e822593c37acd1daad1c649950e1 --- /dev/null +++ b/js/src/dapps/tokenreg/Application/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './application'; diff --git a/js/src/dapps/tokenreg/Chip/chip.css b/js/src/dapps/tokenreg/Chip/chip.css new file mode 100644 index 0000000000000000000000000000000000000000..5c28d56ce635a43b0342b320da06da0ea58e2dda --- /dev/null +++ b/js/src/dapps/tokenreg/Chip/chip.css @@ -0,0 +1,45 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.chip > span { + flex: 1; + display: flex; + flex-direction: row; +} + +.chip img { + margin-bottom: -11px; + margin-left: -11px; +} + +.value { + font-family: 'Roboto Mono', monospace; + color: rgba(255, 255, 255, 1); + -webkit-user-select: text; + cursor: text; + flex: 1; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.label { + color: rgba(255, 255, 255, 0.7); + margin-left: 1em; + margin-right: 0.5em; + text-transform: uppercase; +} diff --git a/js/src/dapps/tokenreg/Chip/chip.js b/js/src/dapps/tokenreg/Chip/chip.js new file mode 100644 index 0000000000000000000000000000000000000000..ad98860259ac664e330dec65607061a10b58a32f --- /dev/null +++ b/js/src/dapps/tokenreg/Chip/chip.js @@ -0,0 +1,68 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { Chip } from 'material-ui'; + +import IdentityIcon from '../IdentityIcon' ; + +import styles from './chip.css'; + +export default class CustomChip extends Component { + static propTypes = { + value: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + + isAddress: PropTypes.bool, + displayValue: PropTypes.string + }; + + render () { + const { isAddress, value, label } = this.props; + + const displayValue = this.props.displayValue || value; + + return ( + + { this.renderIcon(isAddress, value) } + + { displayValue } + + + { label } + + + ); + } + + renderIcon (isAddress, address) { + if (!isAddress) return; + + return ( + + ); + } +} diff --git a/js/src/dapps/tokenreg/Chip/index.js b/js/src/dapps/tokenreg/Chip/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6e1ea80fba19db63dc6973f0ead3e7de9485239e --- /dev/null +++ b/js/src/dapps/tokenreg/Chip/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './chip'; diff --git a/js/src/dapps/tokenreg/Container.js b/js/src/dapps/tokenreg/Container.js new file mode 100644 index 0000000000000000000000000000000000000000..9a8d7c63658418ce759aec4256dcdaf46f64caa0 --- /dev/null +++ b/js/src/dapps/tokenreg/Container.js @@ -0,0 +1,64 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; + +import Application from './Application'; + +import { loadContract } from './Status/actions'; +import { loadAccounts } from './Accounts/actions'; + +class Container extends Component { + static propTypes = { + isLoading: PropTypes.bool.isRequired, + contract: PropTypes.object.isRequired, + onLoad: PropTypes.func.isRequired + }; + + componentDidMount () { + this.props.onLoad(); + } + + render () { + const { isLoading, contract } = this.props; + + return (); + } +} + +const mapStateToProps = (state) => { + const { isLoading, contract } = state.status; + + return { + isLoading, + contract + }; +}; + +const mapDispatchToProps = (dispatch) => { + return { + onLoad: () => { + dispatch(loadContract()); + dispatch(loadAccounts()); + } + }; +}; + +export default connect(mapStateToProps, mapDispatchToProps)(Container); diff --git a/js/src/dapps/tokenreg/IdentityIcon/identityIcon.css b/js/src/dapps/tokenreg/IdentityIcon/identityIcon.css new file mode 100644 index 0000000000000000000000000000000000000000..2b645d8239b35335bcfb2bef2bd5f7eb64ab3bf4 --- /dev/null +++ b/js/src/dapps/tokenreg/IdentityIcon/identityIcon.css @@ -0,0 +1,23 @@ +/* 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 . +*/ + +.icon { + width: 32px; + height: 32px; + border-radius: 50%; + margin-right: 0.5em; +} diff --git a/js/src/dapps/tokenreg/IdentityIcon/identityIcon.js b/js/src/dapps/tokenreg/IdentityIcon/identityIcon.js new file mode 100644 index 0000000000000000000000000000000000000000..51f48d46ab3b54843b72899f8acea22afa947b9b --- /dev/null +++ b/js/src/dapps/tokenreg/IdentityIcon/identityIcon.js @@ -0,0 +1,36 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { api } from '../parity'; +import styles from './identityIcon.css'; + +export default class IdentityIcon extends Component { + static propTypes = { + address: PropTypes.string.isRequired + } + + render () { + const { address } = this.props; + + return ( + + ); + } +} diff --git a/js/src/dapps/tokenreg/IdentityIcon/index.js b/js/src/dapps/tokenreg/IdentityIcon/index.js new file mode 100644 index 0000000000000000000000000000000000000000..76c107bfb7540f707a9b2665aac9b52f9d7590fa --- /dev/null +++ b/js/src/dapps/tokenreg/IdentityIcon/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './identityIcon'; diff --git a/js/src/dapps/tokenreg/Inputs/Text/container.js b/js/src/dapps/tokenreg/Inputs/Text/container.js new file mode 100644 index 0000000000000000000000000000000000000000..450a2b56e54acae1f1bd10e499fd1c891a0633b5 --- /dev/null +++ b/js/src/dapps/tokenreg/Inputs/Text/container.js @@ -0,0 +1,37 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component } from 'react'; +import { connect } from 'react-redux'; + +import InputText from './input-text'; + +class InputTextContainer extends Component { + + render () { + return (); + } +} + +const mapStateToProps = (state) => { + const { contract } = state.status; + + return { contract }; +}; + +export default connect(mapStateToProps)(InputTextContainer); diff --git a/js/src/dapps/tokenreg/Inputs/Text/index.js b/js/src/dapps/tokenreg/Inputs/Text/index.js new file mode 100644 index 0000000000000000000000000000000000000000..87fbc567ef2f3db31a65d206720db12454dfcd7e --- /dev/null +++ b/js/src/dapps/tokenreg/Inputs/Text/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './container'; diff --git a/js/src/dapps/tokenreg/Inputs/Text/input-text.js b/js/src/dapps/tokenreg/Inputs/Text/input-text.js new file mode 100644 index 0000000000000000000000000000000000000000..289c8c37f38ae9a52dbafe3acdbbe9318d821435 --- /dev/null +++ b/js/src/dapps/tokenreg/Inputs/Text/input-text.js @@ -0,0 +1,141 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import { TextField } from 'material-ui'; +import CheckIcon from 'material-ui/svg-icons/navigation/check'; +import { green500 } from 'material-ui/styles/colors'; + +import Loading from '../../Loading'; + +import { validate } from '../validation'; + +import styles from '../inputs.css'; + +const initState = { + error: null, + value: '', + valid: false, + disabled: false, + loading: false +}; + +export default class InputText extends Component { + + static propTypes = { + validationType: PropTypes.string.isRequired, + onChange: PropTypes.func.isRequired, + onEnter: PropTypes.func, + + floatingLabelText: PropTypes.string, + hintText: PropTypes.string, + + contract: PropTypes.object + } + + state = initState; + + render () { + const { disabled, error } = this.state; + + return ( +
+ + + { this.renderLoading() } + { this.renderIsValid() } +
+ ); + } + + renderLoading () { + if (!this.state.loading) return; + + return ( +
+ +
+ ); + } + + renderIsValid () { + if (this.state.loading || !this.state.valid) return; + + return ( +
+ +
+ ); + } + + onChange = (event) => { + const value = event.target.value; + // So we can focus on the input after async validation + event.persist(); + + const { validationType, contract } = this.props; + + const validation = validate(value, validationType, contract); + + if (validation instanceof Promise) { + this.setState({ disabled: true, loading: true }); + + return validation + .then(validation => { + this.setValidation({ + ...validation, + disabled: false, + loading: false + }); + + event.target.focus(); + }); + } + + this.setValidation(validation); + } + + onKeyDown = (event) => { + if (!this.props.onEnter) return; + if (event.keyCode !== 13) return; + + this.props.onEnter(); + } + + setValidation = (validation) => { + const { value } = validation; + + this.setState({ ...validation }); + + if (validation.valid) { + return this.props.onChange(true, value); + } + + return this.props.onChange(false, value); + } + +} diff --git a/js/src/dapps/tokenreg/Inputs/inputs.css b/js/src/dapps/tokenreg/Inputs/inputs.css new file mode 100644 index 0000000000000000000000000000000000000000..f8bea11483dc892325e67948470e3988f4461a1b --- /dev/null +++ b/js/src/dapps/tokenreg/Inputs/inputs.css @@ -0,0 +1,33 @@ +/* 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 . +*/ + +.input-container { + width: 100%; + position: relative; +} + +.input-loading { + position: absolute; + right: -5px; + top: 20px; +} + +.input-icon { + position: absolute; + right: 5px; + bottom: 10px; +} diff --git a/js/src/dapps/tokenreg/Inputs/validation.js b/js/src/dapps/tokenreg/Inputs/validation.js new file mode 100644 index 0000000000000000000000000000000000000000..b2e0688a89f17786fa384e127da1cfd20893f95e --- /dev/null +++ b/js/src/dapps/tokenreg/Inputs/validation.js @@ -0,0 +1,212 @@ +// 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 isURL from 'validator/lib/isURL'; + +import { api } from '../parity'; + +import { getTokenTotalSupply } from '../utils'; + +const { + isHex, + isAddressValid, + toChecksumAddress +} = api.util; + +export const ADDRESS_TYPE = 'ADDRESS_TYPE'; +export const TOKEN_ADDRESS_TYPE = 'TOKEN_ADDRESS_TYPE'; +export const SIMPLE_TOKEN_ADDRESS_TYPE = 'SIMPLE_TOKEN_ADDRESS_TYPE'; +export const TLA_TYPE = 'TLA_TYPE'; +export const SIMPLE_TLA_TYPE = 'SIMPLE_TLA_TYPE'; +export const UINT_TYPE = 'UINT_TYPE'; +export const STRING_TYPE = 'STRING_TYPE'; +export const HEX_TYPE = 'HEX_TYPE'; +export const URL_TYPE = 'URL_TYPE'; + +export const ERRORS = { + invalidTLA: 'The TLA should be 3 characters long', + invalidUint: 'Please enter a non-negative integer', + invalidString: 'Please enter at least a character', + invalidAccount: 'Please select an account to transact with', + invalidRecipient: 'Please select an account to send to', + invalidAddress: 'The address is not in the correct format', + invalidTokenAddress: 'The address is not a regular token contract address', + invalidHex: 'Please enter an hexadecimal string (digits and letters from a to z)', + invalidAmount: 'Please enter a positive amount > 0', + invalidTotal: 'The amount is greater than the availale balance', + tlaAlreadyTaken: 'This TLA address is already registered', + addressAlreadyTaken: 'This Token address is already registered', + invalidURL: 'Please enter a valid URL' +}; + +const validateAddress = (address) => { + if (!isAddressValid(address)) { + return { + error: ERRORS.invalidAddress, + valid: false + }; + } + + return { + value: toChecksumAddress(address), + error: null, + valid: true + }; +}; + +const validateTokenAddress = (address, contract, simple) => { + const addressValidation = validateAddress(address); + if (!addressValidation.valid) return addressValidation; + + if (simple) return addressValidation; + + return getTokenTotalSupply(address) + .then(balance => { + if (balance === null) { + return { + error: ERRORS.invalidTokenAddress, + valid: false + }; + } + + return contract.instance + .fromAddress.call({}, [ address ]) + .then(([id, tla, base, name, owner]) => { + if (owner !== '0x0000000000000000000000000000000000000000') { + return { + error: ERRORS.addressAlreadyTaken, + valid: false + }; + } + }); + }) + .then((result) => { + if (result) return result; + return addressValidation; + }); +}; + +const validateTLA = (tla, contract, simple) => { + if (tla.toString().length !== 3) { + return { + error: ERRORS.invalidTLA, + valid: false + }; + } + + const fTLA = tla.toString().toUpperCase(); + + if (simple) { + return { + value: fTLA, + error: null, + valid: true + }; + } + + return contract.instance + .fromTLA.call({}, [ fTLA ]) + .then(([id, address, base, name, owner]) => { + if (owner !== '0x0000000000000000000000000000000000000000') { + return { + error: ERRORS.tlaAlreadyTaken, + valid: false + }; + } + }) + .then((result) => { + if (result) return result; + return { + value: fTLA, + error: null, + valid: true + }; + }); +}; + +const validateUint = (uint) => { + if (!/^\d+$/.test(uint) || parseInt(uint) <= 0) { + return { + error: ERRORS.invalidUint, + valid: false + }; + } + + return { + value: parseInt(uint), + error: null, + valid: true + }; +}; + +const validateString = (string) => { + if (string.toString().length === 0) { + return { + error: ERRORS.invalidString, + valid: false + }; + } + + return { + value: string.toString(), + error: null, + valid: true + }; +}; + +const validateHex = (string) => { + if (!isHex(string.toString())) { + return { + error: ERRORS.invalidHex, + valid: false + }; + } + + return { + value: string.toString(), + error: null, + valid: true + }; +}; + +const validateURL = (string) => { + if (!isURL(string.toString())) { + return { + error: ERRORS.invalidURL, + valid: false + }; + } + + return { + value: string.toString(), + error: null, + valid: true + }; +}; + +export const validate = (value, type, contract) => { + if (type === ADDRESS_TYPE) return validateAddress(value); + if (type === TOKEN_ADDRESS_TYPE) return validateTokenAddress(value, contract); + if (type === SIMPLE_TOKEN_ADDRESS_TYPE) return validateTokenAddress(value, contract, true); + if (type === TLA_TYPE) return validateTLA(value, contract); + if (type === SIMPLE_TLA_TYPE) return validateTLA(value, contract, true); + if (type === UINT_TYPE) return validateUint(value); + if (type === STRING_TYPE) return validateString(value); + if (type === HEX_TYPE) return validateHex(value); + if (type === URL_TYPE) return validateURL(value); + + return { valid: true, error: null }; +}; diff --git a/js/src/dapps/tokenreg/Loading/index.js b/js/src/dapps/tokenreg/Loading/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0468cab37dfd505cb0b1ef415376ca121ab9ca89 --- /dev/null +++ b/js/src/dapps/tokenreg/Loading/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './loading'; diff --git a/js/src/dapps/tokenreg/Loading/loading.css b/js/src/dapps/tokenreg/Loading/loading.css new file mode 100644 index 0000000000000000000000000000000000000000..dbdb98e42254917684a63e20b6f6644371dff060 --- /dev/null +++ b/js/src/dapps/tokenreg/Loading/loading.css @@ -0,0 +1,23 @@ +/* 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 . +*/ + +.loading { + flex: 1; + display: flex; + align-items: center; + justify-content: center; +} diff --git a/js/src/dapps/tokenreg/Loading/loading.js b/js/src/dapps/tokenreg/Loading/loading.js new file mode 100644 index 0000000000000000000000000000000000000000..bdcc98df679ce7ffb71615348b4075b091e34529 --- /dev/null +++ b/js/src/dapps/tokenreg/Loading/loading.js @@ -0,0 +1,36 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import CircularProgress from 'material-ui/CircularProgress'; + +import styles from './loading.css'; + +export default class Loading extends Component { + static propTypes = { + size: PropTypes.number + }; + + render () { + const size = (this.props.size || 2) * 60; + + return ( +
+ +
+ ); + } +} diff --git a/js/src/dapps/tokenreg/Status/actions.js b/js/src/dapps/tokenreg/Status/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..b7de9c1081f53ef1c485c746295d804aef87a309 --- /dev/null +++ b/js/src/dapps/tokenreg/Status/actions.js @@ -0,0 +1,202 @@ +// 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 { + registry as registryAbi, + tokenreg as tokenregAbi, + githubhint as githubhintAbi +} from '../../../contracts/abi'; + +import { loadToken, setTokenPending, deleteToken, setTokenData } from '../Tokens/actions'; + +const { api } = window.parity; + +export const SET_LOADING = 'SET_LOADING'; +export const setLoading = (isLoading) => ({ + type: SET_LOADING, + isLoading +}); + +export const FIND_CONTRACT = 'FIND_CONTRACT'; +export const loadContract = () => (dispatch) => { + dispatch(setLoading(true)); + + api.ethcore + .registryAddress() + .then((registryAddress) => { + console.log(`registry found at ${registryAddress}`); + const registry = api.newContract(registryAbi, registryAddress).instance; + + return Promise.all([ + registry.getAddress.call({}, [api.util.sha3('tokenreg'), 'A']), + registry.getAddress.call({}, [api.util.sha3('githubhint'), 'A']) + ]); + }) + .then(([ tokenregAddress, githubhintAddress ]) => { + console.log(`tokenreg was found at ${tokenregAddress}`); + + const tokenregContract = api + .newContract(tokenregAbi, tokenregAddress); + + const githubhintContract = api + .newContract(githubhintAbi, githubhintAddress); + + dispatch(setContractDetails({ + address: tokenregAddress, + instance: tokenregContract.instance, + raw: tokenregContract + })); + + dispatch(setGithubhintDetails({ + address: githubhintAddress, + instance: githubhintContract.instance, + raw: githubhintContract + })); + + dispatch(loadContractDetails()); + dispatch(subscribeEvents()); + }) + .catch((error) => { + console.error('loadContract error', error); + }); +}; + +export const LOAD_CONTRACT_DETAILS = 'LOAD_CONTRACT_DETAILS'; +export const loadContractDetails = () => (dispatch, getState) => { + const state = getState(); + + const instance = state.status.contract.instance; + + Promise + .all([ + api.eth.accounts(), + instance.owner.call(), + instance.fee.call() + ]) + .then(([accounts, owner, fee]) => { + console.log(`owner as ${owner}, fee set at ${fee.toFormat()}`); + + const isOwner = accounts.filter(a => a === owner).length > 0; + + dispatch(setContractDetails({ + fee, + owner, + isOwner + })); + + dispatch(setLoading(false)); + }) + .catch((error) => { + console.error('loadContractDetails error', error); + }); +}; + +export const SET_CONTRACT_DETAILS = 'SET_CONTRACT_DETAILS'; +export const setContractDetails = (details) => ({ + type: SET_CONTRACT_DETAILS, + details +}); + +export const SET_GITHUBHINT_CONTRACT = 'SET_GITHUBHINT_CONTRACT'; +export const setGithubhintDetails = (details) => ({ + type: SET_GITHUBHINT_CONTRACT, + details +}); + +export const subscribeEvents = () => (dispatch, getState) => { + const state = getState(); + + const contract = state.status.contract.raw; + const previousSubscriptionId = state.status.subscriptionId; + + if (previousSubscriptionId) { + contract.unsubscribe(previousSubscriptionId); + } + + contract + .subscribe(null, { + fromBlock: 'latest', + toBlock: 'pending', + limit: 50 + }, (error, logs) => { + if (error) { + console.error('setupFilters', error); + return; + } + + if (!logs || logs.length === 0) return; + + logs.forEach(log => { + const event = log.event; + const type = log.type; + const params = log.params; + + if (event === 'Registered' && type === 'pending') { + return dispatch(setTokenData(params.id.toNumber(), { + tla: '...', + base: -1, + address: params.addr.value, + name: params.name.value, + isPending: true + })); + } + + if (event === 'Registered' && type === 'mined') { + return dispatch(loadToken(params.id.value.toNumber())); + } + + if (event === 'Unregistered' && type === 'pending') { + return dispatch(setTokenPending(params.id.value.toNumber(), true)); + } + + if (event === 'Unregistered' && type === 'mined') { + return dispatch(deleteToken(params.id.value.toNumber())); + } + + if (event === 'MetaChanged' && type === 'pending') { + return dispatch(setTokenData( + params.id.value.toNumber(), + { metaPending: true, metaMined: false } + )); + } + + if (event === 'MetaChanged' && type === 'mined') { + setTimeout(() => { + dispatch(setTokenData( + params.id.value.toNumber(), + { metaPending: false, metaMined: false } + )); + }, 5000); + + return dispatch(setTokenData( + params.id.value.toNumber(), + { metaPending: false, metaMined: true } + )); + } + + console.log('new log event', log); + }); + }) + .then((subscriptionId) => { + dispatch(setSubscriptionId(subscriptionId)); + }); +}; + +export const SET_SUBSCRIPTION_ID = 'SET_SUBSCRIPTION_ID'; +export const setSubscriptionId = subscriptionId => ({ + type: SET_SUBSCRIPTION_ID, + subscriptionId +}); diff --git a/js/src/dapps/tokenreg/Status/index.js b/js/src/dapps/tokenreg/Status/index.js new file mode 100644 index 0000000000000000000000000000000000000000..44079b22485b96c83d7ed82e2491caf9e1c8c7b5 --- /dev/null +++ b/js/src/dapps/tokenreg/Status/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './status'; diff --git a/js/src/dapps/tokenreg/Status/reducer.js b/js/src/dapps/tokenreg/Status/reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..7b018bd85e32222a846be55b5ab31ccddbee9f08 --- /dev/null +++ b/js/src/dapps/tokenreg/Status/reducer.js @@ -0,0 +1,65 @@ +// 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 { + SET_LOADING, + SET_CONTRACT_DETAILS, + SET_GITHUBHINT_CONTRACT, + SET_SUBSCRIPTION_ID +} from './actions'; + +const initialState = { + isLoading: true, + subscriptionId: null, + contract: { + addres: null, + instance: null, + raw: null, + owner: null, + isOwner: false, + fee: null + }, + githubhint: { + address: null, + instance: null, + raw: null + } +}; + +export default (state = initialState, action) => { + switch (action.type) { + case SET_LOADING: + return { ...state, isLoading: action.isLoading }; + + case SET_SUBSCRIPTION_ID: + return { ...state, subscriptionId: action.subscriptionId }; + + case SET_CONTRACT_DETAILS: + return { ...state, contract: { + ...state.contract, + ...action.details + } }; + + case SET_GITHUBHINT_CONTRACT: + return { ...state, githubhint: { + ...state.githubhint, + ...action.details + } }; + + default: + return state; + } +}; diff --git a/js/src/dapps/tokenreg/Status/status.css b/js/src/dapps/tokenreg/Status/status.css new file mode 100644 index 0000000000000000000000000000000000000000..27ef53607ef7b0afc8407a9230819b01f078cf84 --- /dev/null +++ b/js/src/dapps/tokenreg/Status/status.css @@ -0,0 +1,36 @@ +/* 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 . +*/ + +.status { + background: rgba(46, 204, 113, 0.85); + color: rgba(255, 255, 255, 1); + padding: 4em 0 2em 0; + + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + + width: 100%; +} + +.title { + font-size: 3rem; + font-weight: 300; + margin-top: 0; + text-transform: uppercase; +} diff --git a/js/src/dapps/tokenreg/Status/status.js b/js/src/dapps/tokenreg/Status/status.js new file mode 100644 index 0000000000000000000000000000000000000000..f8c7b347a4b7b062ce45e56bc61fd99e9164342a --- /dev/null +++ b/js/src/dapps/tokenreg/Status/status.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 React, { Component, PropTypes } from 'react'; + +import Chip from '../Chip'; + +import styles from './status.css'; + +const { api } = window.parity; + +export default class Status extends Component { + static propTypes = { + address: PropTypes.string.isRequired, + fee: PropTypes.object.isRequired + }; + + render () { + const { address, fee } = this.props; + + return ( +
+

Token Registry

+ + + + +
+ ); + } +} diff --git a/js/src/dapps/tokenreg/Tokens/Token/add-meta.js b/js/src/dapps/tokenreg/Tokens/Token/add-meta.js new file mode 100644 index 0000000000000000000000000000000000000000..09e65954d2545663a855302cd6174c51aea435e3 --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/Token/add-meta.js @@ -0,0 +1,193 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { Dialog, RaisedButton, FlatButton, SelectField, MenuItem } from 'material-ui'; +import AddIcon from 'material-ui/svg-icons/content/add'; + +import InputText from '../../Inputs/Text'; +import { ADDRESS_TYPE } from '../../Inputs/validation'; + +import styles from './token.css'; + +import { metaDataKeys } from '../../constants'; + +const initState = { + showDialog: false, + complete: false, + metaKeyIndex: 0, + + form: { + valid: false, + value: '' + } +}; + +export default class AddMeta extends Component { + static propTypes = { + isTokenOwner: PropTypes.bool, + handleAddMeta: PropTypes.func, + index: PropTypes.number + }; + + state = initState; + + render () { + if (!this.props.isTokenOwner) return null; + + return (
+ } + primary + fullWidth + onTouchTap={ this.onShowDialog } /> + + + { this.renderContent() } + +
); + } + + renderActions () { + const { complete } = this.state; + + if (complete) { + return ( + + ); + } + + const isValid = this.state.form.valid; + + return ([ + , + + ]); + } + + renderContent () { + const { complete } = this.state; + + if (complete) return this.renderComplete(); + return this.renderForm(); + } + + renderComplete () { + if (metaDataKeys[this.state.metaKeyIndex].value === 'IMG') { + return (
+

+ Your transactions has been posted. + Two transactions are needed to add an Image. + Please visit the Parity Signer to authenticate the transfer.

+
); + } + return (
+

Your transaction has been posted. Please visit the Parity Signer to authenticate the transfer.

+
); + } + + renderForm () { + const selectedMeta = metaDataKeys[this.state.metaKeyIndex]; + + return ( +
+ + + { this.renderMetaKeyItems() } + + + + +
+ ); + } + + renderMetaKeyItems () { + return metaDataKeys.map((key, index) => ( + + )); + } + + onShowDialog = () => { + this.setState({ showDialog: true }); + } + + onClose = () => { + this.setState(initState); + } + + onAdd = () => { + const { index } = this.props; + + const keyIndex = this.state.metaKeyIndex; + const key = metaDataKeys[keyIndex].value; + + this.props.handleAddMeta( + index, + key, + this.state.form.value + ); + + this.setState({ complete: true }); + } + + onChange = (valid, value) => { + this.setState({ + form: { + valid, value + } + }); + } + + onMetaKeyChange = (event, metaKeyIndex) => { + this.setState({ metaKeyIndex, form: { + ...[this.state.form], + valid: false, + value: '' + } }); + } + +} diff --git a/js/src/dapps/tokenreg/Tokens/Token/index.js b/js/src/dapps/tokenreg/Tokens/Token/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b822b4bdf7c1d731ef6e68055be06e6cc85d0ec --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/Token/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './token'; diff --git a/js/src/dapps/tokenreg/Tokens/Token/token.css b/js/src/dapps/tokenreg/Tokens/Token/token.css new file mode 100644 index 0000000000000000000000000000000000000000..cfd01e3d630f26d22ebaba26c6a373e6b1cd23ea --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/Token/token.css @@ -0,0 +1,140 @@ +/* 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 . +*/ + +.token{ + position: relative; + display: flex; + + width: 20rem; + margin: 1rem; + padding: 1rem; + padding-bottom: 1.5rem; +} + +.token-container, .token-content, .token-meta { + width: 100%; + + display: flex; + flex-direction: column; + align-items: center; +} + +.token-content, .token-meta { + z-index: 50; +} + +.token-bg { + position: absolute; + top: 0; + bottom: 0; + right: 0; + left: 0; + -webkit-filter: blur(5px); + filter: blur(5px); + background-color: rgba(255, 255, 255, 0.85); +} + +.token-container { + flex: 1; +} + +.full-width .token-container { + flex-direction: row; + align-items: flex-start; +} + +.full-width .token-content { + width: 20rem; + margin-right: 1rem; +} + +.token-content > div, .token-meta > div { + max-width: 100%; +} + +.loading { + margin: 1rem 0; +} + +.name { + padding-bottom: 0.75rem; +} + +.title { + font-size: 2rem; + padding: 0 0 0.5rem; +} + +.meta-query { + font-size: 0.9rem; + margin-top: 1.5rem; + margin-bottom: 0; +} + +.meta-key { + font-weight: bold; +} + +.meta-value { + margin-top: 0.5rem; + max-width: 100%; + overflow-wrap: break-word; +} + +.meta-info { + margin-top: 1.5rem; + margin-bottom: -0.5rem; + font-size: 0.9rem; + color: gray; +} + +.meta-image { + width: 100%; + margin-top: 1rem; +} + +.meta-image img { + width: 100%; +} + +.meta-form { + width: 100%; +} + +.unregister { + margin-top: 1rem; +} + +.add-meta { + margin-top: 1rem; + width: 100%; +} + +.pending { + position: absolute; + top: 0; + bottom: 0; + right: 0; + left: 0; + z-index: 100; + background-color: rgba(0, 0, 0, 0.35); +} + +.dialog h3 { + color: rgba(50, 100, 150, 1) !important; + text-transform: uppercase; +} diff --git a/js/src/dapps/tokenreg/Tokens/Token/token.js b/js/src/dapps/tokenreg/Tokens/Token/token.js new file mode 100644 index 0000000000000000000000000000000000000000..18942b085a622df28c04d57357175fb4a4a13b80 --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/Token/token.js @@ -0,0 +1,339 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import Paper from 'material-ui/Paper'; +import { RaisedButton, SelectField, MenuItem } from 'material-ui'; + +import FindIcon from 'material-ui/svg-icons/action/find-in-page'; +import DeleteIcon from 'material-ui/svg-icons/action/delete'; + +import Loading from '../../Loading'; +import Chip from '../../Chip'; +import AddMeta from './add-meta'; + +import styles from './token.css'; + +import { metaDataKeys } from '../../constants'; + +import { api } from '../../parity'; +import { parityNode } from '../../../../environment'; + +export default class Token extends Component { + static propTypes = { + handleMetaLookup: PropTypes.func.isRequired, + address: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + index: PropTypes.number.isRequired, + owner: PropTypes.string.isRequired, + + handleAddMeta: PropTypes.func, + handleUnregister: PropTypes.func, + + tla: PropTypes.string, + base: PropTypes.number, + totalSupply: PropTypes.number, + meta: PropTypes.object, + isMetaLoading: PropTypes.bool, + ownerAccountInfo: PropTypes.shape({ + name: PropTypes.string, + meta: PropTypes.object + }), + metaPending: PropTypes.bool, + metaMined: PropTypes.bool, + isLoading: PropTypes.bool, + isPending: PropTypes.bool, + isTokenOwner: PropTypes.bool.isRequired, + + fullWidth: PropTypes.bool + }; + + state = { + metaKeyIndex: 0 + }; + + render () { + const { isLoading, fullWidth } = this.props; + + if (isLoading) { + return ( +
+ +
+ ); + } + + if (fullWidth) { + return (
+ { this.renderContent() } +
); + } + + return (
+ +
+ { this.renderContent() } + +
); + } + + renderContent () { + const { address, tla, base, name, meta, owner, totalSupply } = this.props; + + return (
+ { this.renderIsPending() } + +
+
{ tla }
+
"{ name }"
+ + { this.renderBase(base) } + { this.renderTotalSupply(totalSupply, base, tla) } + { this.renderAddress(address) } + { this.renderOwner(owner) } +
+ +
+
+ + + { this.renderMetaKeyItems() } + + + + } + primary + fullWidth + onTouchTap={ this.onMetaLookup } /> +
+ + { this.renderMeta(meta) } + { this.renderAddMeta() } + { this.renderUnregister() } +
+ + { this.renderMetaPending() } + { this.renderMetaMined() } +
); + } + + renderMetaKeyItems () { + return metaDataKeys.map((key, index) => ( + + )); + } + + renderBase (base) { + if (!base || base < 0) return null; + return ( + + ); + } + + renderAddress (address) { + if (!address) return null; + return ( + + ); + } + + renderTotalSupply (totalSupply, base, tla) { + const balance = Math.round((totalSupply / base) * 100) / 100; + + return ( + + ); + } + + renderOwner (owner) { + if (!owner) return null; + + const ownerInfo = this.props.ownerAccountInfo; + + const displayValue = (ownerInfo && ownerInfo.name) + ? ownerInfo.name + : owner; + + return ( + + ); + } + + renderIsPending () { + const { isPending } = this.props; + + if (!isPending) { + return null; + } + + return ( +
+ ); + } + + renderAddMeta () { + if (!this.props.isTokenOwner) { + return null; + } + + return ( + + ); + } + + renderUnregister () { + if (!this.props.isTokenOwner) { + return null; + } + + return ( + } + secondary + fullWidth + onTouchTap={ this.onUnregister } /> + ); + } + + renderMeta (meta) { + const isMetaLoading = this.props.isMetaLoading; + + if (isMetaLoading) { + return (
+ +
); + } + + if (!meta) return; + + const metaData = metaDataKeys.find(m => m.value === meta.query); + + if (!meta.value) { + return (
+

+ No + { metaData.label.toLowerCase() } + meta-data... +

+
); + } + + if (meta.query === 'IMG') { + const imageHash = meta.value.replace(/^0x/, ''); + + return (
+

+ + { metaData.label } + meta-data: +

+
+ +
+
); + } + + if (meta.query === 'A') { + const address = meta.value.slice(0, 42); + + return (
+

+ + { metaData.label } + meta-data: +

+

+ { api.util.toChecksumAddress(address) } +

+
); + } + + return (
+

+ + { metaData.label } + meta-data: +

+

{ meta.value }

+
); + } + + renderMetaPending () { + const isMetaPending = this.props.metaPending; + if (!isMetaPending) return; + + return (
+

+ Meta-Data pending... +

+
); + } + + renderMetaMined () { + const isMetaMined = this.props.metaMined; + if (!isMetaMined) return; + + return (
+

+ Meta-Data saved on the blockchain! +

+
); + } + + onUnregister = () => { + const index = this.props.index; + this.props.handleUnregister(index); + } + + onMetaLookup = () => { + const keyIndex = this.state.metaKeyIndex; + const key = metaDataKeys[keyIndex].value; + const index = this.props.index; + + this.props.handleMetaLookup(index, key); + } + + onMetaKeyChange = (event, metaKeyIndex) => { + this.setState({ metaKeyIndex }); + } +} diff --git a/js/src/dapps/tokenreg/Tokens/actions.js b/js/src/dapps/tokenreg/Tokens/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..7953bb241c7af75b5c84e563ed1288d7b1be5078 --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/actions.js @@ -0,0 +1,262 @@ +// 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 { getTokenTotalSupply } from '../utils'; + +const { bytesToHex } = window.parity.api.util; + +export const SET_TOKENS_LOADING = 'SET_TOKENS_LOADING'; +export const setTokensLoading = (isLoading) => ({ + type: SET_TOKENS_LOADING, + isLoading +}); + +export const SET_TOKEN_COUNT = 'SET_TOKEN_COUNT'; +export const setTokenCount = (tokenCount) => ({ + type: SET_TOKEN_COUNT, + tokenCount +}); + +export const SET_TOKEN_DATA = 'SET_TOKEN_DATA'; +export const setTokenData = (index, tokenData) => ({ + type: SET_TOKEN_DATA, + index, tokenData +}); + +export const SET_TOKEN_META = 'SET_TOKEN_META'; +export const setTokenMeta = (index, meta) => ({ + type: SET_TOKEN_META, + index, meta +}); + +export const SET_TOKEN_LOADING = 'SET_TOKEN_LOADING'; +export const setTokenLoading = (index, isLoading) => ({ + type: SET_TOKEN_LOADING, + index, isLoading +}); + +export const SET_TOKEN_META_LOADING = 'SET_TOKEN_META_LOADING'; +export const setTokenMetaLoading = (index, isMetaLoading) => ({ + type: SET_TOKEN_META_LOADING, + index, isMetaLoading +}); + +export const SET_TOKEN_PENDING = 'SET_TOKEN_PENDING'; +export const setTokenPending = (index, isPending) => ({ + type: SET_TOKEN_PENDING, + index, isPending +}); + +export const DELETE_TOKEN = 'DELETE_TOKEN'; +export const deleteToken = (index) => ({ + type: DELETE_TOKEN, + index +}); + +export const loadTokens = () => (dispatch, getState) => { + console.log('loading tokens...'); + + const state = getState(); + const contractInstance = state.status.contract.instance; + + dispatch(setTokensLoading(true)); + + contractInstance + .tokenCount + .call() + .then((count) => { + const tokenCount = parseInt(count); + console.log(`token count: ${tokenCount}`); + dispatch(setTokenCount(tokenCount)); + + for (let i = 0; i < tokenCount; i++) { + dispatch(loadToken(i)); + } + + dispatch(setTokensLoading(false)); + }) + .catch((e) => { + console.error('loadTokens error', e); + }); +}; + +export const loadToken = (index) => (dispatch, getState) => { + console.log('loading token', index); + + const state = getState(); + const contractInstance = state.status.contract.instance; + + const userAccounts = state.accounts.list; + const accountsInfo = state.accounts.accountsInfo; + + dispatch(setTokenLoading(index, true)); + + contractInstance + .token + .call({}, [ parseInt(index) ]) + .then((result) => { + const tokenOwner = result[4]; + + const isTokenOwner = userAccounts + .filter(a => a.address === tokenOwner) + .length > 0; + + const data = { + index: parseInt(index), + address: result[0], + tla: result[1], + base: result[2].toNumber(), + name: result[3], + owner: tokenOwner, + ownerAccountInfo: accountsInfo[tokenOwner], + isPending: false, + isTokenOwner + }; + + return data; + }) + .then(data => { + return getTokenTotalSupply(data.address) + .then(totalSupply => { + data.totalSupply = totalSupply; + return data; + }); + }) + .then(data => { + // If no total supply, must not be a proper token + if (data.totalSupply === null) { + dispatch(setTokenData(index, null)); + dispatch(setTokenLoading(index, false)); + return; + } + + data.totalSupply = data.totalSupply.toNumber(); + console.log(`token loaded: #${index}`, data); + dispatch(setTokenData(index, data)); + dispatch(setTokenLoading(index, false)); + }) + .catch((e) => { + dispatch(setTokenData(index, null)); + dispatch(setTokenLoading(index, false)); + + if (!e instanceof TypeError) { + console.error(`loadToken #${index} error`, e); + } + }); +}; + +export const queryTokenMeta = (index, query) => (dispatch, getState) => { + console.log('loading token meta', index, query); + + const state = getState(); + const contractInstance = state.status.contract.instance; + + const startDate = Date.now(); + dispatch(setTokenMetaLoading(index, true)); + + contractInstance + .meta + .call({}, [ index, query ]) + .then((value) => { + const meta = { + query, + value: value.find(v => v !== 0) ? bytesToHex(value) : null + }; + + console.log(`token meta loaded: #${index}`, value); + dispatch(setTokenMeta(index, meta)); + + setTimeout(() => { + dispatch(setTokenMetaLoading(index, false)); + }, 500 - (Date.now() - startDate)); + }) + .catch((e) => { + console.error(`loadToken #${index} error`, e); + }); +}; + +export const addTokenMeta = (index, key, value) => (dispatch, getState) => { + console.log('add token meta', index, key, value); + + const state = getState(); + const contractInstance = state.status.contract.instance; + const token = state.tokens.tokens.find(t => t.index === index); + + const options = { from: token.owner }; + const values = [ index, key, value ]; + + contractInstance + .setMeta + .estimateGas(options, values) + .then((gasEstimate) => { + options.gas = gasEstimate.mul(1.2).toFixed(0); + console.log(`addTokenMeta: gas estimated as ${gasEstimate.toFixed(0)} setting to ${options.gas}`); + + return contractInstance.setMeta.postTransaction(options, values); + }) + .catch((e) => { + console.error(`addTokenMeta: #${index} error`, e); + }); +}; + +export const addGithubhintURL = (from, key, url) => (dispatch, getState) => { + console.log('add githubhint url', key, url); + + const state = getState(); + const contractInstance = state.status.githubhint.instance; + + const options = { from }; + + const values = [ key, url ]; + + contractInstance + .hintURL + .estimateGas(options, values) + .then((gasEstimate) => { + options.gas = gasEstimate.mul(1.2).toFixed(0); + console.log(`transfer: gas estimated as ${gasEstimate.toFixed(0)} setting to ${options.gas}`); + + return contractInstance.hintURL.postTransaction(options, values); + }) + .catch((e) => { + console.error('addGithubhintURL error', e); + }); +}; + +export const unregisterToken = (index) => (dispatch, getState) => { + console.log('unregistering token', index); + + const state = getState(); + const contractInstance = state.status.contract.instance; + + const values = [ index ]; + const options = { + from: state.accounts.selected.address + }; + + contractInstance + .unregister + .estimateGas(options, values) + .then((gasEstimate) => { + options.gas = gasEstimate.mul(1.2).toFixed(0); + console.log(`transfer: gas estimated as ${gasEstimate.toFixed(0)} setting to ${options.gas}`); + + return contractInstance.unregister.postTransaction(options, values); + }) + .catch((e) => { + console.error(`unregisterToken #${index} error`, e); + }); +}; diff --git a/js/src/dapps/tokenreg/Tokens/container.js b/js/src/dapps/tokenreg/Tokens/container.js new file mode 100644 index 0000000000000000000000000000000000000000..b6171c2cc1d3eed386044efcdd7d196790e0084e --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/container.js @@ -0,0 +1,80 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; + +import Tokens from './tokens'; + +import { loadTokens, queryTokenMeta, unregisterToken, addTokenMeta } from './actions'; + +class TokensContainer extends Component { + static propTypes = { + isOwner: PropTypes.bool, + isLoading: PropTypes.bool, + tokens: PropTypes.array, + tokenCount: PropTypes.number, + onLoadTokens: PropTypes.func, + accounts: PropTypes.array + }; + + componentDidMount () { + this.props.onLoadTokens(); + } + + render () { + console.log(this.props); + return ( + + ); + } +} + +const mapStateToProps = (state) => { + const { list } = state.accounts; + const { isLoading, tokens, tokenCount } = state.tokens; + + const { isOwner } = state.status.contract; + + return { isLoading, tokens, tokenCount, isOwner, accounts: list }; +}; + +const mapDispatchToProps = (dispatch) => { + return { + onLoadTokens: () => { + dispatch(loadTokens()); + }, + + handleMetaLookup: (index, query) => { + dispatch(queryTokenMeta(index, query)); + }, + + handleUnregister: (index) => { + dispatch(unregisterToken(index)); + }, + + handleAddMeta: (index, key, value) => { + dispatch(addTokenMeta(index, key, value)); + } + }; +}; + +export default connect( + mapStateToProps, + mapDispatchToProps +)(TokensContainer); diff --git a/js/src/dapps/tokenreg/Tokens/index.js b/js/src/dapps/tokenreg/Tokens/index.js new file mode 100644 index 0000000000000000000000000000000000000000..87fbc567ef2f3db31a65d206720db12454dfcd7e --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './container'; diff --git a/js/src/dapps/tokenreg/Tokens/reducer.js b/js/src/dapps/tokenreg/Tokens/reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..21952105c4d30bf9cfa74a4ab3ff296dddfca9f4 --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/reducer.js @@ -0,0 +1,114 @@ +// 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 { + SET_TOKENS_LOADING, + SET_TOKEN_COUNT, + SET_TOKEN_DATA, + SET_TOKEN_META, + SET_TOKEN_LOADING, + SET_TOKEN_META_LOADING, + SET_TOKEN_PENDING, + DELETE_TOKEN +} from './actions'; + +const initialState = { + isLoading: true, + tokens: [], + tokenCount: 0 +}; + +export default (state = initialState, action) => { + switch (action.type) { + case SET_TOKENS_LOADING: + return { ...state, isLoading: action.isLoading }; + + case SET_TOKEN_COUNT: + return { ...state, tokenCount: action.tokenCount }; + + case SET_TOKEN_DATA: { + const index = action.index; + const tokens = [].concat(state.tokens); + + tokens[index] = { + ...tokens[index], + ...action.tokenData + }; + + return { ...state, tokens: tokens }; + } + + case SET_TOKEN_META: { + const index = action.index; + const tokens = [].concat(state.tokens); + + tokens[index] = { + ...tokens[index], + meta: action.meta + }; + + return { ...state, tokens: tokens }; + } + + case SET_TOKEN_LOADING: { + const index = action.index; + const tokens = [].concat(state.tokens); + + tokens[index] = { + ...tokens[index], + isLoading: action.isLoading + }; + + return { ...state, tokens: tokens }; + } + + case SET_TOKEN_META_LOADING: { + const index = action.index; + const tokens = [].concat(state.tokens); + + tokens[index] = { + ...tokens[index], + isMetaLoading: action.isMetaLoading + }; + + return { ...state, tokens: tokens }; + } + + case SET_TOKEN_PENDING: { + const index = action.index; + const tokens = [].concat(state.tokens); + + tokens[index] = { + ...tokens[index], + isPending: action.isPending + }; + + return { ...state, tokens: tokens }; + } + + case DELETE_TOKEN: { + const index = action.index; + const tokens = [].concat(state.tokens); + + delete tokens[index]; + + return { ...state, tokens: tokens }; + } + + default: + return state; + } +}; diff --git a/js/src/dapps/tokenreg/Tokens/tokens.css b/js/src/dapps/tokenreg/Tokens/tokens.css new file mode 100644 index 0000000000000000000000000000000000000000..20aaecef4eeefb97ec57576d0a0009ad0c4cfc37 --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/tokens.css @@ -0,0 +1,24 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.tokens { + width: 90%; + padding-top: 2rem; + display: flex; + flex-wrap: wrap; + justify-content: space-around; +} diff --git a/js/src/dapps/tokenreg/Tokens/tokens.js b/js/src/dapps/tokenreg/Tokens/tokens.js new file mode 100644 index 0000000000000000000000000000000000000000..57c2a2a9138d081a0789f630d9bc85ed072bc1a1 --- /dev/null +++ b/js/src/dapps/tokenreg/Tokens/tokens.js @@ -0,0 +1,68 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import Token from './Token'; +import Loading from '../Loading'; + +import styles from './tokens.css'; + +export default class Tokens extends Component { + static propTypes = { + handleAddMeta: PropTypes.func.isRequired, + handleUnregister: PropTypes.func.isRequired, + handleMetaLookup: PropTypes.func.isRequired, + isOwner: PropTypes.bool.isRequired, + isLoading: PropTypes.bool.isRequired, + tokens: PropTypes.array, + accounts: PropTypes.array + }; + + render () { + const { isLoading, tokens } = this.props; + const loading = isLoading ? () : null; + + return ( +
+ { this.renderTokens(tokens) } + { loading } +
+ ); + } + + renderTokens (tokens) { + const { accounts } = this.props; + + return tokens.map((token, index) => { + if (!token || !token.tla) { + return null; + } + + const isTokenOwner = !!accounts.find((account) => account.address === token.owner); + + return ( + + ); + }); + } +} diff --git a/js/src/dapps/tokenreg/constants.js b/js/src/dapps/tokenreg/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..e9e7bebcab84e261fd03f6a9af8aa12a02a77203 --- /dev/null +++ b/js/src/dapps/tokenreg/constants.js @@ -0,0 +1,30 @@ +// 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 { HEX_TYPE, ADDRESS_TYPE } from './Inputs/validation'; + +export const metaDataKeys = [ + { + label: 'Image', + value: 'IMG', + validation: HEX_TYPE + }, + { + label: 'Address', + value: 'A', + validation: ADDRESS_TYPE + } +]; diff --git a/js/src/dapps/tokenreg/parity.js b/js/src/dapps/tokenreg/parity.js new file mode 100644 index 0000000000000000000000000000000000000000..f6d59f44d5771db93be36fa0ed8af8889d14af51 --- /dev/null +++ b/js/src/dapps/tokenreg/parity.js @@ -0,0 +1,21 @@ +// 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 . + +const { api } = window.parity; + +export { + api +}; diff --git a/js/src/dapps/tokenreg/reducers.js b/js/src/dapps/tokenreg/reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..cf533432fd4409af5aa057dc78a4fee01b669609 --- /dev/null +++ b/js/src/dapps/tokenreg/reducers.js @@ -0,0 +1,28 @@ +// 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 { combineReducers } from 'redux'; + +import status from './Status/reducer'; +import tokens from './Tokens/reducer'; +import actions from './Actions/reducer'; +import accounts from './Accounts/reducer'; + +const rootReducer = combineReducers({ + status, tokens, actions, accounts +}); + +export default rootReducer; diff --git a/js/src/dapps/tokenreg/store.js b/js/src/dapps/tokenreg/store.js new file mode 100644 index 0000000000000000000000000000000000000000..5fb7d4b6a4e4d42c3e9e8ca61942e7f8871ca2f5 --- /dev/null +++ b/js/src/dapps/tokenreg/store.js @@ -0,0 +1,22 @@ +// 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 { createStore, applyMiddleware } from 'redux'; +import thunk from 'redux-thunk'; + +import reducer from './reducers'; + +export default createStore(reducer, applyMiddleware(thunk)); diff --git a/js/src/dapps/tokenreg/utils.js b/js/src/dapps/tokenreg/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..0f4e192f085a5e337e3917dfd63b160c75c25893 --- /dev/null +++ b/js/src/dapps/tokenreg/utils.js @@ -0,0 +1,37 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import { api } from './parity'; + +import { eip20 as eip20Abi } from '../../contracts/abi'; + +export const getTokenTotalSupply = (tokenAddress) => { + return api + .eth + .getCode(tokenAddress) + .then(code => { + if (!code || /^(0x)?0?$/.test(code)) { + return null; + } + + const contract = api.newContract(eip20Abi, tokenAddress); + + return contract + .instance + .totalSupply + .call({}, []); + }); +}; diff --git a/js/src/dev.parity.html b/js/src/dev.parity.html new file mode 100644 index 0000000000000000000000000000000000000000..9cfe5ac18ef2f244a9d3bb3b2c90f23d715a8d4e --- /dev/null +++ b/js/src/dev.parity.html @@ -0,0 +1,13 @@ + + + + + + + + dev::Parity.js + + + + + diff --git a/js/src/dev.web3.html b/js/src/dev.web3.html new file mode 100644 index 0000000000000000000000000000000000000000..93faba8e55a5ac80f39b3fc6a5841cf3d4a85fc3 --- /dev/null +++ b/js/src/dev.web3.html @@ -0,0 +1,13 @@ + + + + + + + + dev::Web3 + + + + + diff --git a/js/src/environment/empty.js b/js/src/environment/empty.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/js/src/environment/index.js b/js/src/environment/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9b95bb0dada43fd3bb2a97cc3a9aadb6513b358e --- /dev/null +++ b/js/src/environment/index.js @@ -0,0 +1,32 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +// import './integration-tests'; +// import './perf-debug'; + +import './tests'; + +const parityNode = ( + process.env.PARITY_URL && `http://${process.env.PARITY_URL}` + ) || ( + process.env.NODE_ENV === 'production' + ? 'http://127.0.0.1:8080' + : '' + ); + +export { + parityNode +}; diff --git a/js/src/environment/integration-tests/fake-backend.js b/js/src/environment/integration-tests/fake-backend.js new file mode 100644 index 0000000000000000000000000000000000000000..16fcae3adc515a4ce8412f014acb8fb8228b4477 --- /dev/null +++ b/js/src/environment/integration-tests/fake-backend.js @@ -0,0 +1,84 @@ +// 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 sinon from 'sinon/pkg/sinon'; +import mockedResponses from '../../../test/mocked-responses.json'; + +class FakeRpcServer { + constructor () { + this.xhr = null; + this.middlewares = []; + } + + start () { + this.xhr = sinon.useFakeXMLHttpRequest(); + this.xhr.onCreate = this.handleRequest; + return () => this.xhr.restore(); + } + + simpleRpc (rpcMethod, result) { + this.rpc(rpcMethod, req => result); + } + + rpc (rpcMethod, middleware) { + this.middlewares.unshift({ + rpcMethod, middleware + }); + } + + handleRequest = req => { + setTimeout(() => { + req.body = JSON.parse(req.requestBody); + const middlewaresForMethod = this.middlewares + .filter(m => m.rpcMethod === req.body.method); + + const response = middlewaresForMethod + .map(m => m.middleware) + .reduce((replied, middleware) => { + if (replied) { + return replied; + } + + return middleware(req); + }, false); + + if (!response) { + return req.respond(405, { + 'Content-Type': 'application/json' + }, JSON.stringify({ + jsonrpc: '2.0', + id: req.body.id, + result: null + })); + } + + return req.respond(200, { + 'Content-Type': 'application/json' + }, JSON.stringify({ + jsonrpc: '2.0', + id: req.body.id, + result: response + })); + }); + } +} + +const fakeRpc = new FakeRpcServer(); +fakeRpc.start(); +mockedResponses.rpc.forEach(method => fakeRpc.simpleRpc(method.name, method.response)); + +// export fakeRpc to mock stuff in tests +window.fakeRpc = fakeRpc; diff --git a/js/src/environment/integration-tests/index.js b/js/src/environment/integration-tests/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d62acaa324beddb79497de60c702541139d1c1ef --- /dev/null +++ b/js/src/environment/integration-tests/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import './fake-backend'; diff --git a/js/src/environment/perf-debug/index.js b/js/src/environment/perf-debug/index.js new file mode 100644 index 0000000000000000000000000000000000000000..29f84f50fb0799d68c028459fc03aa04d3cedab6 --- /dev/null +++ b/js/src/environment/perf-debug/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import './why-update'; diff --git a/js/src/environment/perf-debug/why-update.js b/js/src/environment/perf-debug/why-update.js new file mode 100644 index 0000000000000000000000000000000000000000..35eef2edc3639c528c8c58f4db3e1efacf65f77f --- /dev/null +++ b/js/src/environment/perf-debug/why-update.js @@ -0,0 +1,20 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React from 'react'; +import { whyDidYouUpdate } from 'why-did-you-update'; + +whyDidYouUpdate(React); diff --git a/js/src/environment/tests/index.js b/js/src/environment/tests/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3e6241fb1144fe9dc62d1809c51822d9e64cc799 --- /dev/null +++ b/js/src/environment/tests/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import './test-utils'; diff --git a/js/src/environment/tests/test-utils.js b/js/src/environment/tests/test-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..785a6f3ad8ee97e366aaae9bf0ec85a5441cb6d5 --- /dev/null +++ b/js/src/environment/tests/test-utils.js @@ -0,0 +1,46 @@ +// 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 { Component } from 'react'; + +const isProd = process.env.NODE_ENV === 'production'; + +// Component utils for integration tests hooks. +const TEST_HOOK = 'data-test'; +Component.prototype._test = isProd ? noop : testHook; +Component.prototype._testInherit = isProd ? noop : testHookInherit; + +function noop (name) {} + +function testHookInherit (name) { + let hook = this.props[TEST_HOOK]; + if (name) { + hook += `-${name}`; + } + return { + [TEST_HOOK]: hook + }; +} + +function testHook (name) { + let hook = this.constructor.name; + if (name) { + hook += `-${name}`; + } + return { + [TEST_HOOK]: hook + }; +} diff --git a/js/src/error_pages.css b/js/src/error_pages.css new file mode 100644 index 0000000000000000000000000000000000000000..0b098d29ade714976a3764ffd985b39597d36d7c --- /dev/null +++ b/js/src/error_pages.css @@ -0,0 +1,113 @@ +/* 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 . +*/ + +@font-face { + font-family: "Roboto"; + src: url('~roboto-font/fonts/Roboto/roboto-light-webfont.eot'); + src: url('~roboto-font/fonts/Roboto/roboto-light-webfont.eot?#iefix') format('embedded-opentype'), url('~roboto-font/fonts/Roboto/roboto-light-webfont.woff') format('woff'), url('~roboto-font/fonts/Roboto/roboto-light-webfont.ttf') format('truetype'); + font-weight: 300; + font-style: normal; +} + +@font-face { + font-family: 'Roboto Mono'; + src: url('~roboto-mono-webfont/fonts/RobotoMono-Light.ttf') format('truetype'); + font-style: normal; + font-weight: 300; + text-rendering: optimizeLegibility; +} + +:root, :root body { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; + background: rgb(95, 95, 95); + color: rgba(255, 255, 255, 0.75); + font-size: 16px; + font-family: 'Roboto', sans-serif; + font-weight: 300; +} + +:root a, :root a:visited { + text-decoration: none; + cursor: pointer; + color: rgb(0, 151, 167); /* #f80 */ +} + +:root a:hover { + color: rgb(0, 174, 193); +} + +h1,h2,h3,h4,h5,h6 { + font-weight: 300; + text-transform: uppercase; + text-decoration: none; +} + +h1 { + font-size: 24px; + line-height: 36px; + color: rgb(0, 151, 167); +} + +h2 { + font-size: 20px; + line-height: 34px; +} + +code,kbd,pre,samp { + font-family: 'Roboto Mono', monospace; +} + +.parity-navbar { + background: rgb(65, 65, 65); + height: 72px; + padding: 0 1rem; + display: flex; + justify-content: space-between; +} + +.parity-status { + clear: both; + padding: 1rem; + margin: 1rem 0; + text-align: right; + opacity: 0.75; +} + +.parity-box { + margin: 1rem; + padding: 1rem; + background-color: rgb(48, 48, 48); + box-sizing: border-box; + box-shadow: rgba(0, 0, 0, 0.117647) 0px 1px 6px, rgba(0, 0, 0, 0.117647) 0px 1px 4px; + border-radius: 2px; + z-index: 1; + color: #aaa; +} + +.parity-box h1, +.parity-box h2, +.parity-box h3, +.parity-box h4, +.parity-box h5, +.parity-box h6 { + margin: 0; +} diff --git a/js/src/index.html b/js/src/index.html new file mode 100644 index 0000000000000000000000000000000000000000..78001343290f67523489c216ab31a82f937d6dc0 --- /dev/null +++ b/js/src/index.html @@ -0,0 +1,21 @@ + + + + + + + + Parity + + + +
+ + + + + diff --git a/js/src/index.js b/js/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2321b5cf64d4a1e3114b45645d27d643b019c802 --- /dev/null +++ b/js/src/index.js @@ -0,0 +1,90 @@ +// 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 'babel-polyfill'; +import 'whatwg-fetch'; + +import es6Promise from 'es6-promise'; +es6Promise.polyfill(); + +import React from 'react'; +import ReactDOM from 'react-dom'; +import injectTapEventPlugin from 'react-tap-event-plugin'; +import { createHashHistory } from 'history'; +import { Redirect, Router, Route, useRouterHistory } from 'react-router'; + +import SecureApi from './secureApi'; +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 { setApi } from './redux/providers/apiActions'; + +import './environment'; + +import '../assets/fonts/Roboto/font.css'; +import '../assets/fonts/RobotoMono/font.css'; + +import styles from './reset.css'; +import './index.html'; + +injectTapEventPlugin(); + +const parityUrl = process.env.PARITY_URL || + ( + process.env.NODE_ENV === 'production' + ? window.location.host + : '127.0.0.1:8180' + ); + +const api = new SecureApi(`ws://${parityUrl}`); +ContractInstances.create(api); + +const store = initStore(api); +store.dispatch({ type: 'initAll', api }); +store.dispatch(setApi(api)); + +const routerHistory = useRouterHistory(createHashHistory)({}); + +ReactDOM.render( + + + + + + + + + + + + + + + + + + + + + + + + , + document.querySelector('#container') +); diff --git a/js/src/jsonrpc/README.md b/js/src/jsonrpc/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8f16ec3ca77a3caf39263afb1306ca92e4af8a1d --- /dev/null +++ b/js/src/jsonrpc/README.md @@ -0,0 +1,20 @@ +# jsonrpc + +JSON file of all ethereum's rpc methods supported by parity + +## interfaces + +[interfaces.md](release/interfaces.md) contains the auto-generated list of interfaces exposed, along with their relevant documentation + +## contributing + +0. Clone the repo +0. Branch +0. Add the missing interfaces only into `src/interfaces/*.js` +0. Parameters (array) & Returns take objects of type + - `{ type: [Array|Boolean|Object|String|...], desc: 'some description' }` + - Types are built-in JS types or those defined in `src/types.js` (e.g. `BlockNumber`, `Quantity`, etc.) + - If a formatter is required, add it as `format: 'string-type'` +0. Run the lint & tests, `npm run lint && npm run testOnce` +0. Generate via `npm run build` which outputs `index.js`, `index.json` & `interfaces.md` (Only required until Travis is fully in-place) +0. Check-in and make a PR diff --git a/js/src/jsonrpc/generator/build-json.js b/js/src/jsonrpc/generator/build-json.js new file mode 100644 index 0000000000000000000000000000000000000000..362df7bf5fe9305c5231f7c30fefccf320a5a6f6 --- /dev/null +++ b/js/src/jsonrpc/generator/build-json.js @@ -0,0 +1,67 @@ +// 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 fs from 'fs'; +import path from 'path'; + +import interfaces from '../'; + +const INDEX_JSON = path.join(__dirname, '../../release/index.json'); +const methods = []; + +function formatDescription (obj) { + const optional = obj.optional ? '(optional) ' : ''; + const defaults = obj.default ? `(default: ${obj.default}) ` : ''; + + return `${obj.type.name} - ${optional}${defaults}${obj.desc}`; +} + +function formatType (obj) { + if (obj.type === Object && obj.details) { + const formatted = {}; + + Object.keys(obj.details).sort().forEach((key) => { + formatted[key] = formatType(obj.details[key]); + }); + + return { + desc: formatDescription(obj), + details: formatted + }; + } else if (obj.type && obj.type.name) { + return formatDescription(obj); + } + + return obj; +} + +Object.keys(interfaces).sort().forEach((group) => { + Object.keys(interfaces[group]).sort().forEach((name) => { + const method = interfaces[group][name]; + const deprecated = method.deprecated ? ' (Deprecated and not supported, to be removed in a future version)' : ''; + + methods.push({ + name: `${group}_${name}`, + desc: `${method.desc}${deprecated}`, + params: method.params.map(formatType), + returns: formatType(method.returns), + inputFormatters: method.params.map((param) => param.format || null), + outputFormatter: method.returns.format || null + }); + }); +}); + +fs.writeFileSync(INDEX_JSON, JSON.stringify({ methods: methods }, null, 2), 'utf8'); diff --git a/js/src/jsonrpc/generator/build-markdown.js b/js/src/jsonrpc/generator/build-markdown.js new file mode 100644 index 0000000000000000000000000000000000000000..278138d545ef2a72ce917735b1d6ae6fe44c1dbd --- /dev/null +++ b/js/src/jsonrpc/generator/build-markdown.js @@ -0,0 +1,69 @@ +// 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 fs from 'fs'; +import path from 'path'; + +import interfaces from '../'; + +const MARKDOWN = path.join(__dirname, '../../release/interfaces.md'); + +let preamble = '# interfaces\n'; +let markdown = ''; + +function formatDescription (obj, prefix = '', indent = '') { + const optional = obj.optional ? '(optional) ' : ''; + const defaults = obj.default ? `(default: ${obj.default}) ` : ''; + + return `${indent}- ${prefix}\`${obj.type.name}\` - ${optional}${defaults}${obj.desc}`; +} + +function formatType (obj) { + if (obj.type === Object && obj.details) { + const sub = Object.keys(obj.details).sort().map((key) => { + return formatDescription(obj.details[key], `\`${key}\`/`, ' '); + }).join('\n'); + + return `${formatDescription(obj)}\n${sub}`; + } else if (obj.type && obj.type.name) { + return formatDescription(obj); + } + + return obj; +} + +Object.keys(interfaces).sort().forEach((group) => { + let content = ''; + + preamble = `${preamble}\n- [${group}](#${group})`; + markdown = `${markdown}\n## ${group}\n`; + + Object.keys(interfaces[group]).sort().forEach((iname) => { + const method = interfaces[group][iname]; + const name = `${group}_${iname}`; + const deprecated = method.deprecated ? ' (Deprecated and not supported, to be removed in a future version)' : ''; + const desc = `${method.desc}${deprecated}`; + const params = method.params.map(formatType).join('\n'); + const returns = formatType(method.returns); + + markdown = `${markdown}\n- [${name}](#${name})`; + content = `${content}### ${name}\n\n${desc}\n\n#### parameters\n\n${params || 'none'}\n\n#### returns\n\n${returns || 'none'}\n\n`; + }); + + markdown = `${markdown}\n\n${content}`; +}); + +fs.writeFileSync(MARKDOWN, `${preamble}\n\n${markdown}`, 'utf8'); diff --git a/js/src/jsonrpc/index.js b/js/src/jsonrpc/index.js new file mode 100644 index 0000000000000000000000000000000000000000..18bd4302df938610835f01fc276c073a2827c44c --- /dev/null +++ b/js/src/jsonrpc/index.js @@ -0,0 +1,35 @@ +// 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 db from './interfaces/db'; +import eth from './interfaces/eth'; +import ethcore from './interfaces/ethcore'; +import net from './interfaces/net'; +import personal from './interfaces/personal'; +import shh from './interfaces/shh'; +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 +}; diff --git a/js/src/jsonrpc/index.spec.js b/js/src/jsonrpc/index.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..0f124747743b78f4c9988fefb22d7b12d2c10fa9 --- /dev/null +++ b/js/src/jsonrpc/index.spec.js @@ -0,0 +1,62 @@ +// 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 interfaces from './'; +import { Address, BlockNumber, Data, Hash, Integer, Quantity } from './types'; + +const flatlist = {}; + +function verifyType (obj) { + if (typeof obj !== 'string') { + expect(obj).to.satisfy(() => { + return obj.type === Array || + obj.type === Boolean || + obj.type === Object || + obj.type === String || + obj.type === Address || + obj.type === BlockNumber || + obj.type === Data || + obj.type === Hash || + obj.type === Integer || + obj.type === Quantity; + }); + } +} + +describe('jsonrpc/interfaces', () => { + Object.keys(interfaces).forEach((group) => { + describe(group, () => { + Object.keys(interfaces[group]).forEach((name) => { + const method = interfaces[group][name]; + + flatlist[`${group}_${name}`] = true; + + describe(name, () => { + it('has the correct interface', () => { + expect(method.desc).to.be.a('string'); + expect(method.params).to.be.an('array'); + expect(method.returns).to.satisfy((returns) => { + return typeof returns === 'string' || typeof returns === 'object'; + }); + + method.params.forEach(verifyType); + verifyType(method.returns); + }); + }); + }); + }); + }); +}); diff --git a/js/src/jsonrpc/interfaces/db.js b/js/src/jsonrpc/interfaces/db.js new file mode 100644 index 0000000000000000000000000000000000000000..ab4d35b34a7087aac66f6825dc2d9d061fcb230c --- /dev/null +++ b/js/src/jsonrpc/interfaces/db.js @@ -0,0 +1,103 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import { Data } from '../types'; + +export default { + getHex: { + desc: 'Returns binary data from the local database.', + params: [ + { + type: String, + desc: 'Database name' + }, + { + type: String, + desc: 'Key name' + } + ], + returns: { + type: Data, + desc: 'The previously stored data' + }, + deprecated: true + }, + + getString: { + desc: 'Returns string from the local database.', + params: [ + { + type: String, + desc: 'Database name' + }, + { + type: String, + desc: 'Key name' + } + ], + returns: { + type: String, + desc: 'The previously stored string' + }, + deprecated: true + }, + + putHex: { + desc: 'Stores binary data in the local database.', + params: [ + { + type: String, + desc: 'Database name' + }, + { + type: String, + desc: 'Key name' + }, + { + type: Data, + desc: 'The data to store' + } + ], + returns: { + type: Boolean, + desc: '`true` if the value was stored, otherwise `false`' + }, + deprecated: true + }, + + putString: { + desc: 'Stores a string in the local database.', + params: [ + { + type: String, + desc: 'Database name' + }, + { + type: String, + desc: 'Key name' + }, + { + type: String, + desc: 'The string to store' + } + ], + returns: { + type: Boolean, + desc: '`true` if the value was stored, otherwise `false`' + }, + deprecated: true + } +}; diff --git a/js/src/jsonrpc/interfaces/eth.js b/js/src/jsonrpc/interfaces/eth.js new file mode 100644 index 0000000000000000000000000000000000000000..f1c8fb86f656bab616ee0f6c1431454ff379a588 --- /dev/null +++ b/js/src/jsonrpc/interfaces/eth.js @@ -0,0 +1,1056 @@ +// 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 { Address, BlockNumber, Data, Hash, Quantity } from '../types'; + +export default { + accounts: { + desc: 'Returns a list of addresses owned by client.', + params: [], + returns: { + type: Array, + desc: '20 Bytes - addresses owned by the client' + } + }, + + blockNumber: { + desc: 'Returns the number of most recent block.', + params: [], + returns: { + type: Quantity, + desc: 'integer of the current block number the client is on' + } + }, + + call: { + desc: 'Executes a new message call immediately without creating a transaction on the block chain.', + params: [ + { + type: Object, + desc: 'The transaction call object', + format: 'inputCallFormatter', + details: { + from: { + type: Address, + desc: '20 Bytes - The address the transaction is send from', + optional: true + }, + to: { + type: Address, + desc: '20 Bytes - The address the transaction is directed to' + }, + gas: { + type: Quantity, + desc: 'Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions', + optional: true + }, + gasPrice: { + type: Quantity, + desc: 'Integer of the gasPrice used for each paid gas', + optional: true + }, + value: { + type: Quantity, + desc: 'Integer of the value send with this transaction', + optional: true + }, + data: { + type: Data, + desc: 'Hash of the method signature and encoded parameters. For details see [Ethereum Contract ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI)', + optional: true + } + } + }, + { + type: BlockNumber, + desc: 'integer block number, or the string `\'latest\'`, `\'earliest\'` or `\'pending\'`, see the [default block parameter](#the-default-block-parameter)', + format: 'inputDefaultBlockNumberFormatter' + } + ], + returns: { + type: Data, + desc: 'the return value of executed contract' + } + }, + + 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: [], + returns: { + type: Address, + desc: 'The current coinbase address' + } + }, + + compileSerpent: { + desc: 'Returns compiled serpent code.', + params: [ + { + type: String, + desc: 'The source code' + } + ], + returns: { + type: Data, + desc: 'The compiled source code' + } + }, + + compileSolidity: { + desc: 'Returns compiled solidity code.', + params: [ + { + type: String, + desc: 'The source code' + } + ], + returns: { + type: Data, + desc: 'The compiled source code' + } + }, + + compileLLL: { + desc: 'Returns compiled LLL code.', + params: [ + { + type: String, + desc: 'The source code' + } + ], + returns: { + type: Data, + desc: 'The compiled source code' + } + }, + + estimateGas: { + desc: 'Makes a call or transaction, which won\'t be added to the blockchain and returns the used gas, which can be used for estimating the used gas.', + params: [ + { + type: Object, + desc: 'see [eth_sendTransaction](#eth_sendTransaction)', + format: 'inputCallFormatter' + } + ], + returns: { + type: Quantity, + desc: 'The amount of gas used', + format: 'utils.toDecimal' + } + }, + + fetchQueuedTransactions: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + flush: { + desc: '?', + params: [], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + gasPrice: { + desc: 'Returns the current price per gas in wei.', + params: [], + returns: { + type: Quantity, + desc: 'integer of the current gas price in wei' + } + }, + + getBalance: { + desc: 'Returns the balance of the account of given address.', + params: [ + { + type: Address, + desc: '20 Bytes - address to check for balance', + format: 'inputAddressFormatter' + }, + { + type: BlockNumber, + desc: 'integer block number, or the string `\'latest\'`, `\'earliest\'` or `\'pending\'`, see the [default block parameter](#the-default-block-parameter)', + format: 'inputDefaultBlockNumberFormatter' + } + ], + returns: { + type: Quantity, + desc: 'integer of the current balance in wei', + format: 'outputBigNumberFormatter' + } + }, + + getBlockByHash: { + desc: 'Returns information about a block by hash.', + params: [ + { + type: Hash, + desc: 'Hash of a block' + }, + { + type: Boolean, + desc: 'If `true` it returns the full transaction objects, if `false` only the hashes of the transactions' + } + ], + returns: { + type: Object, + desc: 'A block object, or `null` when no block was found', + details: { + number: { + type: Quantity, + desc: 'The block number. `null` when its pending block' + }, + hash: { + type: Hash, + desc: '32 Bytes - hash of the block. `null` when its pending block' + }, + parentHash: { + type: Hash, + desc: '32 Bytes - hash of the parent block' + }, + nonce: { + type: Data, + desc: '8 Bytes - hash of the generated proof-of-work. `null` when its pending block' + }, + sha3Uncles: { + type: Data, + desc: '32 Bytes - SHA3 of the uncles data in the block' + }, + logsBloom: { + type: Data, + desc: '256 Bytes - the bloom filter for the logs of the block. `null` when its pending block' + }, + transactionsRoot: { + type: Data, + desc: '32 Bytes - the root of the transaction trie of the block' + }, + stateRoot: { + type: Data, + desc: '32 Bytes - the root of the final state trie of the block' + }, + receiptsRoot: { + type: Data, desc: '32 Bytes - the root of the receipts trie of the block' + }, + miner: { + type: Address, + desc: '20 Bytes - the address of the beneficiary to whom the mining rewards were given' + }, + difficulty: { + type: Quantity, + desc: 'integer of the difficulty for this block' + }, + totalDifficulty: { + type: Quantity, + desc: 'integer of the total difficulty of the chain until this block' + }, + extraData: { + type: Data, + desc: 'the \'extra data\' field of this block' + }, + size: { + type: Quantity, + desc: 'integer the size of this block in bytes' + }, + gasLimit: { + type: Quantity, + desc: 'the maximum gas allowed in this block' + }, + gasUsed: { + type: Quantity, + desc: 'the total used gas by all transactions in this block' + }, + timestamp: { + type: Quantity, + desc: 'the unix timestamp for when the block was collated' + }, + transactions: { + type: Array, + desc: 'Array of transaction objects, or 32 Bytes transaction hashes depending on the last given parameter' + }, + uncles: { + type: Array, + desc: 'Array of uncle hashes' + } + } + } + }, + + getBlockByNumber: { + desc: 'Returns information about a block by block number.', + params: [ + { + type: BlockNumber, + desc: 'integer of a block number, or the string `\'earliest\'`, `\'latest\'` or `\'pending\'`, as in the [default block parameter](#the-default-block-parameter)' + }, + { + type: Boolean, + desc: 'If `true` it returns the full transaction objects, if `false` only the hashes of the transactions' + } + ], + returns: 'See [eth_getBlockByHash](#eth_getblockbyhash)' + }, + + getBlockTransactionCountByHash: { + desc: 'Returns the number of transactions in a block from a block matching the given block hash.', + params: [ + { + type: Hash, + desc: '32 Bytes - hash of a block' + } + ], + returns: { + type: Quantity, + desc: 'integer of the number of transactions in this block' + } + }, + + getBlockTransactionCountByNumber: { + desc: 'Returns the number of transactions in a block from a block matching the given block number.', + params: [ + { + type: BlockNumber, + desc: 'integer of a block number, or the string `\'earliest\'`, `\'latest\'` or `\'pending\'`, as in the [default block parameter](#the-default-block-parameter)' + } + ], + returns: { + type: Quantity, + desc: 'integer of the number of transactions in this block' + } + }, + + getCode: { + desc: 'Returns code at a given address.', + params: [ + { + type: Address, + desc: '20 Bytes - address', + format: 'inputAddressFormatter' + }, + { + type: BlockNumber, + desc: 'integer block number, or the string `\'latest\'`, `\'earliest\'` or `\'pending\'`, see the [default block parameter](#the-default-block-parameter)', + format: 'inputDefaultBlockNumberFormatter' + } + ], + returns: { + type: Data, + desc: 'the code from the given address' + } + }, + + getCompilers: { + desc: 'Returns a list of available compilers in the client.', + params: [], + returns: { + type: Array, + desc: 'Array of available compilers' + } + }, + + getFilterChanges: { + desc: 'Polling method for a filter, which returns an array of logs which occurred since last poll.', + params: [ + { + type: Quantity, + desc: 'The filter id' + } + ], + returns: { + type: Array, + desc: 'Array of log objects, or an empty array if nothing has changed since last poll' + } + }, + + getFilterChangesEx: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + getFilterLogs: { + desc: 'Returns an array of all logs matching filter with given id.', + params: [ + { + type: Quantity, + desc: 'The filter id' + } + ], + returns: 'See [eth_getFilterChanges](#eth_getfilterchanges)' + }, + + getFilterLogsEx: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + getLogs: { + desc: 'Returns an array of all logs matching a given filter object.', + params: [ + { + type: Object, + desc: 'The filter object, see [eth_newFilter parameters](#eth_newfilter)' + } + ], + returns: 'See [eth_getFilterChanges](#eth_getfilterchanges)' + }, + + getLogsEx: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + getStorageAt: { + desc: 'Returns the value from a storage position at a given address.', + params: [ + { + type: Address, + desc: '20 Bytes - address of the storage' + }, + { + type: Quantity, + desc: 'integer of the position in the storage', + format: 'utils.toHex' + }, + { + type: BlockNumber, + desc: 'integer block number, or the string `\'latest\'`, `\'earliest\'` or `\'pending\'`, see the [default block parameter](#the-default-block-parameter)', + format: 'inputDefaultBlockNumberFormatter' + } + ], + returns: { + type: Data, + desc: 'the value at this storage position' + } + }, + + getTransactionByHash: { + desc: 'Returns the information about a transaction requested by transaction hash.', + params: [ + { + type: Hash, + desc: '32 Bytes - hash of a transaction' + } + ], + returns: { + type: Object, + desc: 'A transaction object, or `null` when no transaction was found:', + format: 'outputTransactionFormatter', + details: { + hash: { + type: Hash, + desc: '32 Bytes - hash of the transaction.' + }, + nonce: { + type: Quantity, + desc: 'the number of transactions made by the sender prior to this one.' + }, + blockHash: { + type: Hash, + desc: '32 Bytes - hash of the block where this transaction was in. `null` when its pending.' + }, + blockNumber: { + type: BlockNumber, + desc: 'block number where this transaction was in. `null` when its pending.' + }, + transactionIndex: { + type: Quantity, + desc: 'integer of the transactions index position in the block. `null` when its pending.' + }, + from: { + type: Address, + desc: '20 Bytes - address of the sender.' + }, + to: { + type: Address, + desc: '20 Bytes - address of the receiver. `null` when its a contract creation transaction.' + }, + value: { + type: Quantity, + desc: 'value transferred in Wei.' + }, + gasPrice: { + type: Quantity, + desc: 'gas price provided by the sender in Wei.' + }, + gas: { + type: Quantity, + desc: 'gas provided by the sender.' + }, + input: { + type: Data, + desc: 'the data send along with the transaction.' + } + } + } + }, + + getTransactionByBlockHashAndIndex: { + desc: 'Returns information about a transaction by block hash and transaction index position.', + params: [ + { + type: Hash, + desc: 'hash of a block' + }, + { + type: Quantity, + desc: 'integer of the transaction index position' + } + ], + returns: 'See [eth_getBlockByHash](#eth_gettransactionbyhash)' + }, + + getTransactionByBlockNumberAndIndex: { + desc: 'Returns information about a transaction by block number and transaction index position.', + params: [ + { + type: BlockNumber, + desc: 'a block number, or the string `\'earliest\'`, `\'latest\'` or `\'pending\'`, as in the [default block parameter](#the-default-block-parameter)' + }, + { + type: Quantity, + desc: 'The transaction index position' + } + ], + returns: 'See [eth_getBlockByHash](#eth_gettransactionbyhash)' + }, + + getTransactionCount: { + desc: 'Returns the number of transactions *sent* from an address.', + params: [ + { + type: Address, + desc: '20 Bytes - address' + }, + { + type: BlockNumber, + desc: 'integer block number, or the string `\'latest\'`, `\'earliest\'` or `\'pending\'`, see the [default block parameter](#the-default-block-parameter)', + format: 'inputDefaultBlockNumberFormatter' + } + ], + returns: { + type: Quantity, + desc: 'integer of the number of transactions send from this address', + format: 'utils.toDecimal' + } + }, + + getTransactionReceipt: { + desc: 'Returns the receipt of a transaction by transaction hash.\n**Note** That the receipt is not available for pending transactions.', + params: [ + { + type: Hash, + desc: 'hash of a transaction' + } + ], + returns: { + type: Object, + desc: 'A transaction receipt object, or `null` when no receipt was found:', + format: 'outputTransactionReceiptFormatter', + details: { + transactionHash: { + type: Hash, + desc: '32 Bytes - hash of the transaction.' + }, + transactionIndex: { + type: Quantity, + desc: 'integer of the transactions index position in the block.' + }, + blockHash: { + type: Hash, + desc: '32 Bytes - hash of the block where this transaction was in.' + }, + blockNumber: { + type: BlockNumber, + desc: 'block number where this transaction was in.' + }, + cumulativeGasUsed: { + type: Quantity, + desc: 'The total amount of gas used when this transaction was executed in the block.' + }, + gasUsed: { + type: Quantity, + desc: 'The amount of gas used by this specific transaction alone.' + }, + contractAddress: { + type: Address, + desc: '20 Bytes - The contract address created, if the transaction was a contract creation, otherwise `null`.' + }, + logs: { + type: Array, + desc: 'Array of log objects, which this transaction generated.' + } + } + } + }, + + getUncleByBlockHashAndIndex: { + desc: 'Returns information about a uncle of a block by hash and uncle index position.', + params: [ + { + type: Hash, + desc: 'Hash a block' + }, + { + type: Quantity, + desc: 'The uncle\'s index position' + } + ], + returns: 'See [eth_getBlockByHash](#eth_getblockbyhash)' + }, + + getUncleByBlockNumberAndIndex: { + desc: 'Returns information about a uncle of a block by number and uncle index position.', + params: [ + { + type: BlockNumber, + desc: 'a block number, or the string `\'earliest\'`, `\'latest\'` or `\'pending\'`, as in the [default block parameter](#the-default-block-parameter)' + }, + { + type: Quantity, + desc: 'The uncle\'s index position' + } + ], + returns: 'See [eth_getBlockByHash](#eth_getblockbyhash)' + }, + + getUncleCountByBlockHash: { + desc: 'Returns the number of uncles in a block from a block matching the given block hash.', + params: [ + { + type: Hash, + desc: '32 Bytes - hash of a block' + } + ], + returns: { + type: Quantity, + desc: 'integer of the number of uncles in this block' + } + }, + + getUncleCountByBlockNumber: { + desc: 'Returns the number of uncles in a block from a block matching the given block number.', + params: [ + { + type: BlockNumber, + desc: 'integer of a block number, or the string \'latest\', \'earliest\' or \'pending\', see the [default block parameter](#the-default-block-parameter)' + } + ], + returns: { + type: Quantity, + desc: 'integer of the number of uncles in this block' + } + }, + + getWork: { + desc: 'Returns the hash of the current block, the seedHash, and the boundary condition to be met (\'target\').', + params: [], + returns: { + type: Array, + desc: 'Array with the following properties:' + } + }, + + hashrate: { + desc: 'Returns the number of hashes per second that the node is mining with.', + params: [], + returns: { + type: Quantity, + desc: 'number of hashes per second' + } + }, + + inspectTransaction: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + mining: { + desc: 'Returns `true` if client is actively mining new blocks.', + params: [], + returns: { + type: Boolean, + desc: '`true` of the client is mining, otherwise `false`' + } + }, + + newBlockFilter: { + desc: 'Creates a filter in the node, to notify when a new block arrives.\nTo check if the state has changed, call [eth_getFilterChanges](#eth_getfilterchanges).', + params: [], + returns: { + type: Quantity, + desc: 'A filter id' + } + }, + + newFilter: { + desc: 'Creates a filter object, based on filter options, to notify when the state changes (logs).\nTo check if the state has changed, call [eth_getFilterChanges](#eth_getfilterchanges).', + params: [{ + type: Object, + desc: 'The filter options:', + details: { + fromBlock: { + type: BlockNumber, + desc: 'Integer block number, or `\'latest\'` for the last mined block or `\'pending\'`, `\'earliest\'` for not yet mined transactions.', + optional: true, + default: 'latest' + }, + toBlock: { + type: BlockNumber, + desc: 'Integer block number, or `\'latest\'` for the last mined block or `\'pending\'`, `\'earliest\'` for not yet mined transactions.', + optional: true, + default: 'latest' + }, + address: { + type: Address, + desc: '20 Bytes - Contract address or a list of addresses from which logs should originate.', + optional: true + }, + topics: { + type: Array, + desc: 'Array of 32 Bytes `DATA` topics. Topics are order-dependent. Each topic can also be an array of DATA with \'or\' options.', + optional: true + }, + limit: { + type: Number, + desc: 'The maximum number of entries to retrieve (latest first)', + optional: true + } + } + }], + returns: { + type: Quantity, + desc: 'The filter id' + } + }, + + newFilterEx: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + newPendingTransactionFilter: { + desc: 'Creates a filter in the node, to notify when new pending transactions arrive.\nTo check if the state has changed, call [eth_getFilterChanges](#eth_getfilterchanges).', + params: [], + returns: { + type: Quantity, + desc: 'A filter id' + } + }, + + notePassword: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + pendingTransactions: { + desc: '?', + params: [], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + 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: [], + returns: { + type: String, + desc: 'The current ethereum protocol version' + } + }, + + register: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + sendRawTransaction: { + desc: 'Creates new message call transaction or a contract creation for signed transactions.', + params: [ + { + type: Data, + desc: 'The signed transaction data' + } + ], + returns: { + type: Hash, + desc: '32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available' + } + }, + + sendTransaction: { + desc: 'Creates new message call transaction or a contract creation, if the data field contains code.', + params: [ + { + type: Object, desc: 'The transaction object', + format: 'inputTransactionFormatter', + details: { + from: { + type: Address, + desc: '20 Bytes - The address the transaction is send from' + }, + to: { + type: Address, + desc: '20 Bytes - (optional when creating new contract) The address the transaction is directed to' + }, + gas: { + type: Quantity, + desc: 'Integer of the gas provided for the transaction execution. It will return unused gas.', + optional: true, + default: 90000 + }, + gasPrice: { + type: Quantity, + desc: 'Integer of the gasPrice used for each paid gas', + optional: true, + default: 'To-Be-Determined' + }, + value: { + type: Quantity, + desc: 'Integer of the value send with this transaction', + optional: true + }, + data: { + type: Data, + desc: 'The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see [Ethereum Contract ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI)' + }, + nonce: { + type: Quantity, + desc: 'Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.', + optional: true + } + } + } + ], + returns: { + type: Hash, + desc: '32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available' + } + }, + + sign: { + desc: 'Signs transaction hash with a given address.', + params: [ + { + type: Address, + desc: '20 Bytes - address', + format: 'inputAddressFormatter' + }, + { + type: Data, + desc: 'Transaction hash to sign' + } + ], + returns: { + type: Data, + desc: 'Signed data' + } + }, + + signTransaction: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + submitWork: { + desc: 'Used for submitting a proof-of-work solution.', + params: [ + { + type: Data, + desc: '8 Bytes - The nonce found (64 bits)' + }, + { + type: Data, + desc: '32 Bytes - The header\'s pow-hash (256 bits)' + }, + { + type: Data, + desc: '32 Bytes - The mix digest (256 bits)' + } + ], + returns: { + type: Boolean, + desc: '`true` if the provided solution is valid, otherwise `false`' + } + }, + + submitHashrate: { + desc: 'Used for submitting mining hashrate.', + params: [ + { + type: Data, + desc: 'a hexadecimal string representation (32 bytes) of the hash rate' + }, + { + type: String, + desc: 'A random hexadecimal(32 bytes) ID identifying the client' + } + ], + returns: { + type: Boolean, + desc: '`true` if submitting went through succesfully and `false` otherwise' + } + }, + + syncing: { + desc: 'Returns an object with data about the sync status or `false`.', + params: [], + returns: { + type: Object, + desc: 'An object with sync status data or `FALSE`, when not syncing', + format: 'outputSyncingFormatter', + details: { + startingBlock: { + type: Quantity, + desc: 'The block at which the import started (will only be reset, after the sync reached this head)' + }, + currentBlock: { + type: Quantity, + desc: 'The current block, same as eth_blockNumber' + }, + highestBlock: { + type: Quantity, + desc: 'The estimated highest block' + }, + blockGap: { + type: Array, + desc: 'Array of "first", "last", such that [first, last) are all missing from the chain' + }, + warpChunksAmount: { + type: Quantity, + desc: 'Total amount of snapshot chunks' + }, + warpChunksProcessed: { + type: Quantity, + desc: 'Total amount of snapshot chunks processed' + } + } + } + }, + + uninstallFilter: { + desc: 'Uninstalls a filter with given id. Should always be called when watch is no longer needed.\nAdditonally Filters timeout when they aren\'t requested with [eth_getFilterChanges](#eth_getfilterchanges) for a period of time.', + params: [ + { + type: Quantity, + desc: 'The filter id' + } + ], + returns: { + type: Boolean, + desc: '`true` if the filter was successfully uninstalled, otherwise `false`' + } + }, + + unregister: { + desc: '?', + params: [ + '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + } +}; diff --git a/js/src/jsonrpc/interfaces/ethcore.js b/js/src/jsonrpc/interfaces/ethcore.js new file mode 100644 index 0000000000000000000000000000000000000000..c81a82f76ddc386af0e39ee03d34487febd4620b --- /dev/null +++ b/js/src/jsonrpc/interfaces/ethcore.js @@ -0,0 +1,375 @@ +// 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 { Address, Data, Hash, Quantity } from '../types'; + +export default { + acceptNonReservedPeers: { + desc: '?', + params: [], + returns: { + type: Boolean, + desc: '?' + } + }, + + addReservedPeer: { + desc: '?', + params: [ + { + type: String, + desc: 'Enode' + } + ], + returns: { + type: Boolean, + desc: '?' + } + }, + + dappsPort: { + desc: 'Returns the port the dapps are running on, error if not enabled', + params: [], + returns: { + type: Quantity, + desc: 'The port number' + } + }, + + defaultExtraData: { + desc: 'Returns the default extra data', + params: [], + returns: { + type: Data, + desc: 'Extra data' + } + }, + + devLogs: { + desc: 'Returns latest logs of your node', + params: [], + returns: { + type: Array, + desc: 'Development logs' + } + }, + + devLogsLevels: { + desc: 'Returns current log level settings', + params: [], + returns: { + type: String, + decs: 'Current log level' + } + }, + + dropNonReservedPeers: { + desc: '?', + params: [], + returns: { + type: Boolean, + desc: '?' + } + }, + + extraData: { + desc: 'Returns currently set extra data', + params: [], + returns: { + type: Data, + desc: 'Extra data' + } + }, + + gasFloorTarget: { + desc: 'Returns current target for gas floor', + params: [], + returns: { + type: Quantity, + desc: 'Gas Floor Target', + format: 'outputBigNumberFormatter' + } + }, + + gasPriceHistogram: { + desc: 'Returns a snapshot of the historic gas prices', + params: [], + returns: { + type: Object, + desc: 'Historic values', + details: { + bucketBounds: { + type: Array, + desc: 'Array of U256 bound values' + }, + count: { + type: Array, + desc: 'Array of U64 counts' + } + } + } + }, + + generateSecretPhrase: { + desc: 'Creates a secret phrase that can be associated with an account', + params: [], + returns: { + type: String, + desc: 'The secret phrase' + } + }, + + hashContent: { + desc: 'Creates a hash of the file as retrieved', + params: [ + { + type: String, + desc: 'The url of the content' + } + ], + returns: { + type: Hash, + desc: 'The hash of the content' + } + }, + + minGasPrice: { + desc: 'Returns currently set minimal gas price', + params: [], + returns: { + type: Quantity, + desc: 'Minimal Gas Price', + format: 'outputBigNumberFormatter' + } + }, + + mode: { + desc: 'Get the mode. Results one of: "active", "passive", "dark", "off".', + params: [], + returns: { + type: String, + desc: 'The mode' + } + }, + + netChain: { + desc: 'Returns the name of the connected chain.', + params: [], + returns: { + type: String, + desc: 'chain name' + } + }, + + netPeers: { + desc: 'Returns number of peers.', + params: [], + returns: { + type: Quantity, + desc: 'Number of peers' + } + }, + + netMaxPeers: { + desc: 'Returns maximal number of peers.', + params: [], + returns: { + type: Quantity, + desc: 'Maximal number of peers' + } + }, + + netPort: { + desc: 'Returns network port the node is listening on.', + params: [], + returns: { + type: Quantity, + desc: 'Port Number' + } + }, + + nodeName: { + desc: 'Returns node name (identity)', + params: [], + returns: { + type: String, + desc: 'Node name' + } + }, + + phraseToAddress: { + desc: 'Converts a secret phrase into the corresponting address', + params: [ + { + type: String, + desc: 'The secret' + } + ], + returns: { + type: Address, + desc: 'Corresponding address' + } + }, + + removeReservedPeer: { + desc: '?', + params: [ + { + type: String, + desc: 'Encode' + } + ], + returns: { + type: Boolean, + desc: '?' + } + }, + + registryAddress: { + desc: 'The address for the global registry', + params: [], + returns: { + type: Address, + desc: 'The registry address' + } + }, + + rpcSettings: { + desc: 'Returns basic settings of rpc (enabled, port, interface).', + params: [], + returns: { + type: Object, + desc: 'JSON object containing rpc settings' + } + }, + + setAuthor: { + desc: 'Changes author (coinbase) for mined blocks.', + params: [ + { + type: Address, + desc: '20 Bytes - Address', + format: 'inputAddressFormatter' + } + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + setExtraData: { + desc: 'Changes extra data for newly mined blocks', + params: [ + { + type: Data, + desc: 'Extra Data', + format: 'utils.toHex' + } + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + setGasFloorTarget: { + desc: 'Changes current gas floor target.', + params: [ + { + type: Quantity, + desc: 'Gas Floor Target', + format: 'utils.toHex' + } + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + setMinGasPrice: { + desc: 'Changes minimal gas price for transaction to be accepted to the queue.', + params: [ + { + type: Quantity, + desc: 'Minimal gas price', + format: 'utils.toHex' + } + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + setMode: { + desc: 'Changes the mode', + params: [ + { + type: String, + desc: 'The mode to set, one of "active", "passive", "dark", "off"' + } + ], + returns: { + type: Boolean, + desc: 'True if the call succeeded' + } + }, + + setTransactionsLimit: { + desc: 'Changes limit for transactions in queue.', + params: [ + { + type: Quantity, + desc: 'New Limit', + format: 'utils.toHex' + } + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + }, + + signerPort: { + desc: 'Returns the port the signer is running on, error if not enabled', + params: [], + returns: { + type: Quantity, + desc: 'The port number' + } + }, + + transactionsLimit: { + desc: 'Changes limit for transactions in queue.', + params: [], + returns: { + type: Quantity, + desc: 'Current max number of transactions in queue', + format: 'outputBigNumberFormatter' + } + }, + + unsignedTransactionsCount: { + desc: 'Returns number of unsigned transactions when running with Trusted Signer. Error otherwise', + params: [], + returns: { + type: Quantity, + desc: 'Number of unsigned transactions' + } + } +}; diff --git a/js/src/jsonrpc/interfaces/net.js b/js/src/jsonrpc/interfaces/net.js new file mode 100644 index 0000000000000000000000000000000000000000..9cc3bc0766665d115f4a98a8e8412f9c7e383fa0 --- /dev/null +++ b/js/src/jsonrpc/interfaces/net.js @@ -0,0 +1,47 @@ +// 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 { + listening: { + desc: 'Returns `true` if client is actively listening for network connections.', + params: [], + returns: { + type: Boolean, + desc: '`true` when listening, otherwise `false`.' + } + }, + + peerCount: { + desc: 'Returns number of peers currenly connected to the client.', + params: [], + returns: { + type: Quantity, + desc: 'Integer of the number of connected peers', + format: 'utils.toDecimal' + } + }, + + version: { + desc: 'Returns the current network protocol version.', + params: [], + returns: { + type: String, + desc: 'The current network protocol version' + } + } +}; diff --git a/js/src/jsonrpc/interfaces/personal.js b/js/src/jsonrpc/interfaces/personal.js new file mode 100644 index 0000000000000000000000000000000000000000..2a9ce7c192ee9555bc15118cf467ec543c7adf5b --- /dev/null +++ b/js/src/jsonrpc/interfaces/personal.js @@ -0,0 +1,306 @@ +// 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 { 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: [], + returns: { + type: Array, + desc: '20 Bytes addresses owned by the client.' + } + }, + + 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: [ + { + type: String, + desc: 'Password' + } + ], + returns: { + type: Address, + desc: 'The created address' + } + }, + + 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: [ + { + type: Object, + desc: 'The transaction object', + details: { + from: { + type: Address, + desc: '20 Bytes - The address the transaction is send from' + }, + to: { + type: Address, + desc: '20 Bytes - (optional when creating new contract) The address the transaction is directed to' + }, + gas: { + type: Quantity, + desc: 'Integer of the gas provided for the transaction execution. It will return unused gas', + optional: true, + default: 90000 + }, + gasPrice: { + type: Quantity, + desc: 'Integer of the gasPrice used for each paid gas', + optional: true, + default: 'To-Be-Determined' + }, + value: { + type: Quantity, + desc: 'Integer of the value send with this transaction', + optional: true + }, + data: { + type: Data, + desc: 'The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see [Ethereum Contract ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI)' + }, + nonce: { + type: Quantity, + desc: 'Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.', + optional: true + } + } + }, + { + type: String, + desc: 'Passphrase to unlock `from` account.' + } + ], + returns: { + type: Data, + desc: '32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available' + } + }, + + signerEnabled: { + desc: 'Returns whether signer is enabled/disabled.', + params: [], + returns: { + type: Boolean, + desc: 'true when enabled, false when disabled' + } + }, + + unlockAccount: { + desc: '?', + params: [ + '?', '?', '?' + ], + returns: { + type: Boolean, + desc: 'whether the call was successful' + } + } +}; diff --git a/js/src/jsonrpc/interfaces/shh.js b/js/src/jsonrpc/interfaces/shh.js new file mode 100644 index 0000000000000000000000000000000000000000..e9f727dacc4cb010942d7c3cb54d2d2dca2ffb81 --- /dev/null +++ b/js/src/jsonrpc/interfaces/shh.js @@ -0,0 +1,169 @@ +// 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 { Data, Quantity } from '../types'; + +export default { + version: { + desc: 'Returns the current whisper protocol version.', + params: [], + returns: { + type: String, + desc: 'The current whisper protocol version' + } + }, + + post: { + desc: 'Sends a whisper message.', + params: [ + { + type: Object, desc: 'The whisper post object:', format: 'inputPostFormatter', + details: { + from: { + type: Data, desc: '60 Bytes - The identity of the sender', + optional: true + }, + to: { + type: Data, desc: '60 Bytes - The identity of the receiver. When present whisper will encrypt the message so that only the receiver can decrypt it', + optional: true + }, + topics: { + type: Array, desc: 'Array of `DATA` topics, for the receiver to identify messages' + }, + payload: { + type: Data, desc: 'The payload of the message' + }, + priority: { + type: Quantity, desc: 'The integer of the priority in a rang from ... (?)' + }, + ttl: { + type: Quantity, desc: 'Integer of the time to live in seconds.' + } + } + } + ], + returns: { + type: Boolean, + desc: '`true` if the message was send, otherwise `false`' + } + }, + + newIdentity: { + desc: 'Creates new whisper identity in the client.', + params: [], + returns: { + type: Data, + desc: '60 Bytes - the address of the new identiy' + } + }, + + hasIdentity: { + desc: 'Checks if the client hold the private keys for a given identity.', + params: [ + { + type: Data, + desc: '60 Bytes - The identity address to check' + } + ], + returns: { + type: Boolean, + desc: '`true` if the client holds the privatekey for that identity, otherwise `false`' + } + }, + + newGroup: { + desc: '(?)', + params: [], + returns: { + type: Data, desc: '60 Bytes - the address of the new group. (?)' + } + }, + + addToGroup: { + desc: '(?)', + params: [ + { + type: Data, + desc: '60 Bytes - The identity address to add to a group (?)' + } + ], + returns: { + type: Boolean, + desc: '`true` if the identity was successfully added to the group, otherwise `false` (?)' + } + }, + + newFilter: { + desc: 'Creates filter to notify, when client receives whisper message matching the filter options.', + params: [ + { + type: Object, desc: 'The filter options:', + details: { + to: { + type: Data, desc: '60 Bytes - Identity of the receiver. *When present it will try to decrypt any incoming message if the client holds the private key to this identity.*', + optional: true + }, + topics: { + type: Array, desc: 'Array of `DATA` topics which the incoming message\'s topics should match. You can use the following combinations' + } + } + } + ], + returns: { + type: Quantity, + desc: 'The newly created filter' + } + }, + + uninstallFilter: { + desc: 'Uninstalls a filter with given id. Should always be called when watch is no longer needed.\nAdditonally Filters timeout when they aren\'t requested with [shh_getFilterChanges](#shh_getfilterchanges) for a period of time.', + params: [ + { + type: Quantity, + desc: 'The filter id' + } + ], + returns: { + type: Boolean, + desc: '`true` if the filter was successfully uninstalled, otherwise `false`' + } + }, + + getFilterChanges: { + desc: 'Polling method for whisper filters. Returns new messages since the last call of this method.\n**Note** calling the [shh_getMessages](#shh_getmessages) method, will reset the buffer for this method, so that you won\'t receive duplicate messages.', + params: [ + { + type: Quantity, + desc: 'The filter id' + } + ], + returns: { + type: Array, + desc: 'Array of messages received since last poll' + } + }, + + getMessages: { + desc: 'Get all messages matching a filter. Unlike `shh_getFilterChanges` this returns all messages.', + params: [ + { + type: Quantity, + desc: 'The filter id' + } + ], + returns: 'See [shh_getFilterChanges](#shh_getfilterchanges)' + } +}; diff --git a/js/src/jsonrpc/interfaces/trace.js b/js/src/jsonrpc/interfaces/trace.js new file mode 100644 index 0000000000000000000000000000000000000000..3dc4451f006369de574c536fb2033467642d36d8 --- /dev/null +++ b/js/src/jsonrpc/interfaces/trace.js @@ -0,0 +1,79 @@ +// 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 { BlockNumber, Hash, Integer } from '../types'; + +export default { + filter: { + desc: 'Returns traces matching given filter', + params: [ + { + type: Object, + desc: 'The filter object' + } + ], + returns: { + type: Array, + desc: 'Traces matching given filter' + } + }, + + get: { + desc: 'Returns trace at given position.', + params: [ + { + type: Hash, + desc: 'Transaction hash' + }, + { + type: Integer, + desc: 'Trace position witing transaction' + } + ], + returns: { + type: Object, + desc: 'Trace object' + } + }, + + transaction: { + desc: 'Returns all traces of given transaction', + params: [ + { + type: Hash, + desc: 'Transaction hash' + } + ], + returns: { + type: Array, + desc: 'Traces of given transaction' + } + }, + + block: { + desc: 'Returns traces created at given block', + params: [ + { + type: BlockNumber, + desc: 'Integer block number, or \'latest\' for the last mined block or \'pending\', \'earliest\' for not yet mined transactions' + } + ], + returns: { + type: Array, + desc: 'Block traces' + } + } +}; diff --git a/js/src/jsonrpc/interfaces/web3.js b/js/src/jsonrpc/interfaces/web3.js new file mode 100644 index 0000000000000000000000000000000000000000..783663716ab354b7fddb133ae9edf4281e51a9ea --- /dev/null +++ b/js/src/jsonrpc/interfaces/web3.js @@ -0,0 +1,42 @@ +// 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 { Data } from '../types'; + +export default { + clientVersion: { + desc: 'Returns the current client version.', + params: [], + returns: { + type: String, + desc: 'The current client version' + } + }, + + sha3: { + desc: 'Returns Keccak-256 (*not* the standardized SHA3-256) of the given data.', + params: [ + { + type: String, + desc: 'The data to convert into a SHA3 hash' + } + ], + returns: { + type: Data, + desc: 'The SHA3 result of the given string' + } + } +}; diff --git a/js/src/jsonrpc/rollup.config.js b/js/src/jsonrpc/rollup.config.js new file mode 100644 index 0000000000000000000000000000000000000000..cc4f8c9314c4fcab0743efe67f38821413fa9369 --- /dev/null +++ b/js/src/jsonrpc/rollup.config.js @@ -0,0 +1,12 @@ +import babel from 'rollup-plugin-babel'; + +export default { + entry: 'src/index.js', + dest: 'release/index.js', + format: 'cjs', + plugins: [babel({ + babelrc: false, + presets: ['es2015-rollup', 'stage-0'], + runtimeHelpers: true + })] +}; diff --git a/js/src/jsonrpc/types.js b/js/src/jsonrpc/types.js new file mode 100644 index 0000000000000000000000000000000000000000..026e010ed9655cfa26cf83d715b935fec9980ccc --- /dev/null +++ b/js/src/jsonrpc/types.js @@ -0,0 +1,27 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export class Address {} + +export class BlockNumber {} + +export class Data {} + +export class Hash {} + +export class Integer {} + +export class Quantity {} diff --git a/js/src/lib.rs b/js/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..25d336fabe9d5e934074e8759f26c5c16a3f48a9 --- /dev/null +++ b/js/src/lib.rs @@ -0,0 +1,22 @@ +// 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 . + +#[cfg(feature = "with-syntex")] +include!(concat!(env!("OUT_DIR"), "/lib.rs")); + +#[cfg(not(feature = "with-syntex"))] +include!("lib.rs.in"); + diff --git a/js/src/lib.rs.in b/js/src/lib.rs.in new file mode 100644 index 0000000000000000000000000000000000000000..b3f09556a2bbd407ccd894c5168218ecf128b0b2 --- /dev/null +++ b/js/src/lib.rs.in @@ -0,0 +1,55 @@ +// 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 . + +extern crate parity_dapps_glue; + +use std::collections::HashMap; +use parity_dapps_glue::{WebApp, File, Info}; + +#[derive(WebAppFiles)] +#[webapp(path = "../build")] +pub struct App { + pub files: HashMap<&'static str, File>, +} + +impl Default for App { + fn default() -> App { + App { + files: Self::files(), + } + } +} + +impl WebApp for App { + fn file(&self, path: &str) -> Option<&File> { + self.files.get(path) + } + + fn info(&self) -> Info { + Info { + name: "Parity UI", + version: env!("CARGO_PKG_VERSION"), + author: "Ethcore ", + description: "New UI for Parity.", + icon_url: "icon.png", + } + } +} + +#[test] +fn test_js() { + parity_dapps_glue::js::build(env!("CARGO_MANIFEST_DIR")); +} diff --git a/js/src/library.js b/js/src/library.js new file mode 100644 index 0000000000000000000000000000000000000000..fbbab22862be8893a9cb074d48490aed5acb8351 --- /dev/null +++ b/js/src/library.js @@ -0,0 +1,23 @@ +// 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 Abi from './abi'; +import Api from './api'; + +export { + Abi, + Api +}; diff --git a/js/src/modals/AddAddress/addAddress.js b/js/src/modals/AddAddress/addAddress.js new file mode 100644 index 0000000000000000000000000000000000000000..5ab8bbe80f6bdf4e7e3e742ffe9da19b9fd533d0 --- /dev/null +++ b/js/src/modals/AddAddress/addAddress.js @@ -0,0 +1,151 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import ContentAdd from 'material-ui/svg-icons/content/add'; +import ContentClear from 'material-ui/svg-icons/content/clear'; + +import { Button, Modal, Form, Input, InputAddress } from '../../ui'; +import { ERRORS, validateAddress, validateName } from '../../util/validation'; + +export default class AddAddress extends Component { + static contextTypes = { + api: PropTypes.object.isRequired + } + + static propTypes = { + contacts: PropTypes.object.isRequired, + onClose: PropTypes.func + }; + + state = { + address: '', + addressError: ERRORS.invalidAddress, + name: '', + nameError: ERRORS.invalidName, + description: '' + }; + + render () { + return ( + + { this.renderFields() } + + ); + } + + renderDialogActions () { + const { addressError, nameError } = this.state; + const hasError = !!(addressError || nameError); + + return ([ +
+ ); + } + + handleTokensChange = (tokens) => { + this.handleSearchChange(tokens); + } + + handleInputChange = (inputValue) => { + this.setState({ inputValue }, () => { + this.handleSearchChange(); + }); + } + + handleSearchChange = (searchTokens) => { + const { onChange, tokens } = this.props; + const { inputValue } = this.state; + + const newSearchTokens = [] + .concat(searchTokens || tokens); + + const newSearchValues = [] + .concat(searchTokens || tokens, inputValue); + + onChange(newSearchTokens, newSearchValues); + } + + handleSearchClick = () => { + const { showSearch } = this.state; + + this.handleOpenSearch(!showSearch); + } + + handleSearchBlur = () => { + const timeoutId = window.setTimeout(() => { + const { inputValue } = this.state; + const { tokens } = this.props; + + if (tokens.length === 0 && inputValue.length === 0) { + this.handleOpenSearch(false); + } + }, 250); + + this.setState({ + timeoutIds: [].concat(this.state.timeoutIds, timeoutId) + }); + } + + handleOpenSearch = (showSearch, force) => { + if (this.state.stateChanging && !force) { + return false; + } + + this.setState({ + showSearch: showSearch, + stateChanging: true + }); + + const timeoutId = window.setTimeout(() => { + this.setState({ stateChanging: false }); + }, 450); + + this.setState({ + timeoutIds: [].concat(this.state.timeoutIds, timeoutId) + }); + } +} diff --git a/js/src/ui/Actionbar/Sort/index.js b/js/src/ui/Actionbar/Sort/index.js new file mode 100644 index 0000000000000000000000000000000000000000..82855931c74d33e76800c73d93105ab7aabf1e8d --- /dev/null +++ b/js/src/ui/Actionbar/Sort/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './sort'; diff --git a/js/src/ui/Actionbar/Sort/sort.css b/js/src/ui/Actionbar/Sort/sort.css new file mode 100644 index 0000000000000000000000000000000000000000..ff592ca2f3f407fabb81137beaf0ea95402649df --- /dev/null +++ b/js/src/ui/Actionbar/Sort/sort.css @@ -0,0 +1,20 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.sortButton { + min-width: 50px !important; +} diff --git a/js/src/ui/Actionbar/Sort/sort.js b/js/src/ui/Actionbar/Sort/sort.js new file mode 100644 index 0000000000000000000000000000000000000000..35c51e5a1dd198d3ad36016496417fa47ecb7ffb --- /dev/null +++ b/js/src/ui/Actionbar/Sort/sort.js @@ -0,0 +1,73 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import IconMenu from 'material-ui/IconMenu'; +import MenuItem from 'material-ui/MenuItem'; + +import SortIcon from 'material-ui/svg-icons/content/sort'; + +import { Button } from '../../'; + +import styles from './sort.css'; + +export default class ActionbarSort extends Component { + static propTypes = { + onChange: PropTypes.func.isRequired, + order: PropTypes.string + }; + + state = { + menuOpen: false + } + + render () { + return ( + } + onClick={ this.handleMenuOpen } + /> + } + open={ this.state.menuOpen } + onRequestChange={ this.handleMenuChange } + onItemTouchTap={ this.handleSortChange } + targetOrigin={ { horizontal: 'right', vertical: 'top' } } + anchorOrigin={ { horizontal: 'right', vertical: 'top' } } + > + + + + + ); + } + + handleSortChange = (event, child) => { + const order = child.props.value; + this.props.onChange(order); + } + + handleMenuOpen = () => { + this.setState({ menuOpen: true }); + } + + handleMenuChange = (open) => { + this.setState({ menuOpen: open }); + } +} diff --git a/js/src/ui/Actionbar/actionbar.css b/js/src/ui/Actionbar/actionbar.css new file mode 100644 index 0000000000000000000000000000000000000000..73c5687f434a29c16a96a0b975e17f288d4b4a94 --- /dev/null +++ b/js/src/ui/Actionbar/actionbar.css @@ -0,0 +1,39 @@ +/* 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 . +*/ +.actionbar { + padding: 0 24px !important; + margin-bottom: 0; + height: auto !important; + background: rgba(0, 0, 0, 0.25) !important; +} + +.tooltitle { + text-transform: uppercase; + color: white; +} + +.toolbuttons { +} + +.toolbuttons button { + margin: 10px 0 10px 16px !important; + color: white !important; +} + +.toolbuttons svg { + fill: white !important; +} diff --git a/js/src/ui/Actionbar/actionbar.js b/js/src/ui/Actionbar/actionbar.js new file mode 100644 index 0000000000000000000000000000000000000000..c3fbe6a189809b37ad65fdfc2a843487bf345837 --- /dev/null +++ b/js/src/ui/Actionbar/actionbar.js @@ -0,0 +1,67 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { Toolbar, ToolbarGroup } from 'material-ui/Toolbar'; + +import styles from './actionbar.css'; + +export default class Actionbar extends Component { + static propTypes = { + title: PropTypes.string, + buttons: PropTypes.array, + children: PropTypes.node, + className: PropTypes.string + }; + + render () { + const { children, className } = this.props; + const classes = `${styles.actionbar} ${className}`; + + return ( + + { this.renderTitle() } + { this.renderButtons() } + { children } + + ); + } + + renderButtons () { + const { buttons } = this.props; + + if (!buttons || !buttons.length) { + return null; + } + + return ( + + { buttons } + + ); + } + + renderTitle () { + const { title } = this.props; + + return ( +

+ { title } +

+ ); + } +} diff --git a/js/src/ui/Actionbar/index.js b/js/src/ui/Actionbar/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5955440799df0a74a56ce38fb41569f1559130d9 --- /dev/null +++ b/js/src/ui/Actionbar/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './actionbar'; diff --git a/js/src/ui/Badge/badge.css b/js/src/ui/Badge/badge.css new file mode 100644 index 0000000000000000000000000000000000000000..3653bdae86edfa3381019ab6b99b5a719ddc3c29 --- /dev/null +++ b/js/src/ui/Badge/badge.css @@ -0,0 +1,35 @@ +/* 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 . +*/ +.bubble { + border-radius: 50%; + padding: 3px 5px; + color: white; + font-size: 0.7em; + line-height: 1em; +} + +.default { + background: #555; +} + +.red { + background: red; +} + +.green { + background: green; +} diff --git a/js/src/ui/Badge/badge.js b/js/src/ui/Badge/badge.js new file mode 100644 index 0000000000000000000000000000000000000000..1ffd4d83ca0de3b0d5c750a88859ddee0799b2e8 --- /dev/null +++ b/js/src/ui/Badge/badge.js @@ -0,0 +1,38 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import styles from './badge.css'; + +export default class Badge extends Component { + static propTypes = { + className: PropTypes.string, + color: PropTypes.string, + value: PropTypes.any + }; + + render () { + const { className, color, value } = this.props; + const classes = `${styles.bubble} ${styles[color || 'default']} ${className}`; + + return ( +
+ { value } +
+ ); + } +} diff --git a/js/src/ui/Badge/index.js b/js/src/ui/Badge/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8dc0c9ef0fb9af3e93db0fcd975a1da3d51b3993 --- /dev/null +++ b/js/src/ui/Badge/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './badge'; diff --git a/js/src/ui/Balance/balance.css b/js/src/ui/Balance/balance.css new file mode 100644 index 0000000000000000000000000000000000000000..6fe1b2a5151d923b625c884e1192af79fafecd95 --- /dev/null +++ b/js/src/ui/Balance/balance.css @@ -0,0 +1,56 @@ +/* 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 . +*/ +.balances { + display: flex; + flex-wrap: wrap; + margin: 1em 0 0 0; + vertical-align: top; +} + +.empty { + line-height: 24px; + margin: 0.75em 0.5em 0 0; + opacity: 0.25; +} + +.balance { + background: rgba(255, 255, 255, 0.07); + border-radius: 16px; + margin: 0.75em 0.5em 0 0; + max-height: 24px; + max-width: 100%; + display: flex; + align-items: center; +} + +.balance img { + height: 32px; + margin: -4px 1em 0 0; + width: 32px; +} + +.balanceValue { + margin: 0 1em 0 0; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} + +.balanceTag { + font-size: 0.85em; + padding-right: 0.75rem; +} diff --git a/js/src/ui/Balance/balance.js b/js/src/ui/Balance/balance.js new file mode 100644 index 0000000000000000000000000000000000000000..b6f78664806a13215364c0d0a36e89f98027501b --- /dev/null +++ b/js/src/ui/Balance/balance.js @@ -0,0 +1,96 @@ +// 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 BigNumber from 'bignumber.js'; +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; + +import unknownImage from '../../../assets/images/contracts/unknown-64x64.png'; +import styles from './balance.css'; + +class Balance extends Component { + static contextTypes = { + api: PropTypes.object + } + + static propTypes = { + balance: PropTypes.object, + images: PropTypes.object.isRequired + } + + render () { + const { api } = this.context; + const { balance, images } = this.props; + + if (!balance) { + return null; + } + + let body = (balance.tokens || []) + .filter((balance) => new BigNumber(balance.value).gt(0)) + .map((balance) => { + const token = balance.token; + const value = token.format + ? new BigNumber(balance.value).div(new BigNumber(token.format)).toFormat(3) + : api.util.fromWei(balance.value).toFormat(3); + const imagesrc = token.image || images[token.address] || unknownImage; + + return ( +
+ { +
+ { value } +
+
{ token.tag }
+
+ ); + }); + + if (!body.length) { + body = ( +
+ There are no balances associated with this account +
+ ); + } + + return ( +
+ { body } +
+ ); + } +} + +function mapStateToProps (state) { + const { images } = state; + + return { images }; +} + +function mapDispatchToProps (dispatch) { + return bindActionCreators({}, dispatch); +} + +export default connect( + mapStateToProps, + mapDispatchToProps +)(Balance); diff --git a/js/src/ui/Balance/index.js b/js/src/ui/Balance/index.js new file mode 100644 index 0000000000000000000000000000000000000000..24ed7c44e1a891c57a52d372d1db72738561c89d --- /dev/null +++ b/js/src/ui/Balance/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './balance'; diff --git a/js/src/ui/BlockStatus/blockStatus.css b/js/src/ui/BlockStatus/blockStatus.css new file mode 100644 index 0000000000000000000000000000000000000000..ed86646f098b40ed6ac55833302b8898d9732106 --- /dev/null +++ b/js/src/ui/BlockStatus/blockStatus.css @@ -0,0 +1,22 @@ +/* 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 . +*/ + +.blockNumber { +} + +.syncStatus { +} diff --git a/js/src/ui/BlockStatus/blockStatus.js b/js/src/ui/BlockStatus/blockStatus.js new file mode 100644 index 0000000000000000000000000000000000000000..98e10f50472826db0d77cb4365e10aac3fa790ae --- /dev/null +++ b/js/src/ui/BlockStatus/blockStatus.js @@ -0,0 +1,90 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; + +import styles from './blockStatus.css'; + +class BlockStatus extends Component { + static propTypes = { + blockNumber: PropTypes.object, + syncing: PropTypes.oneOfType([ + PropTypes.bool, + PropTypes.object + ]) + } + + render () { + const { blockNumber, syncing } = this.props; + + if (!blockNumber) { + return null; + } + + if (!syncing) { + return ( +
+ { blockNumber.toFormat() } best block +
+ ); + } + + if (!syncing.warpChunksAmount.eq(syncing.warpChunksProcessed)) { + return ( +
+ { syncing.warpChunksProcessed.mul(100).div(syncing.warpChunksAmount).toFormat(2) }% warp restore +
+ ); + } + + let warpStatus = null; + + if (syncing.blockGap) { + const [first, last] = syncing.blockGap; + + warpStatus = ( + , { first.mul(100).div(last).toFormat(2) }% historic + ); + } + + return ( +
+ { syncing.currentBlock.toFormat() }/{ syncing.highestBlock.toFormat() } syncing + { warpStatus } +
+ ); + } +} + +function mapStateToProps (state) { + const { blockNumber, syncing } = state.nodeStatus; + + return { + blockNumber, + syncing + }; +} + +function mapDispatchToProps (dispatch) { + return bindActionCreators({}, dispatch); +} + +export default connect( + mapStateToProps, + mapDispatchToProps +)(BlockStatus); diff --git a/js/src/ui/BlockStatus/index.js b/js/src/ui/BlockStatus/index.js new file mode 100644 index 0000000000000000000000000000000000000000..af5761fad3ecac39dbd9c197d1b5a1f329971a12 --- /dev/null +++ b/js/src/ui/BlockStatus/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './blockStatus'; diff --git a/js/src/ui/Button/button.js b/js/src/ui/Button/button.js new file mode 100644 index 0000000000000000000000000000000000000000..ef4c7d7fec7c88ab81a9645b54fe3d17e760e458 --- /dev/null +++ b/js/src/ui/Button/button.js @@ -0,0 +1,45 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; +import { FlatButton } from 'material-ui'; + +export default class Button extends Component { + static propTypes = { + className: PropTypes.string, + disabled: PropTypes.bool, + icon: PropTypes.node, + label: PropTypes.oneOfType([ + React.PropTypes.string, + React.PropTypes.object + ]), + onClick: PropTypes.func + } + + render () { + const { className, disabled, icon, label, onClick } = this.props; + + return ( + + ); + } +} diff --git a/js/src/ui/Button/index.js b/js/src/ui/Button/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f69a65e3d53fd0e216cb4aefcbcd551417281e09 --- /dev/null +++ b/js/src/ui/Button/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './button'; diff --git a/js/src/ui/ConfirmDialog/confirmDialog.css b/js/src/ui/ConfirmDialog/confirmDialog.css new file mode 100644 index 0000000000000000000000000000000000000000..6bb860bd342eb299c3d717d6e5d0b329edbe2348 --- /dev/null +++ b/js/src/ui/ConfirmDialog/confirmDialog.css @@ -0,0 +1,19 @@ +/* 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 . +*/ +.body { + text-align: center; +} diff --git a/js/src/ui/ConfirmDialog/confirmDialog.js b/js/src/ui/ConfirmDialog/confirmDialog.js new file mode 100644 index 0000000000000000000000000000000000000000..7a0be650a1c5e07c8e9c05cdc31aac299961c4c7 --- /dev/null +++ b/js/src/ui/ConfirmDialog/confirmDialog.js @@ -0,0 +1,56 @@ +import React, { Component, PropTypes } from 'react'; +import ActionDone from 'material-ui/svg-icons/action/done'; +import ContentClear from 'material-ui/svg-icons/content/clear'; + +import Button from '../Button'; +import Modal from '../Modal'; + +import styles from './confirmDialog.css'; + +export default class ConfirmDialog extends Component { + static propTypes = { + children: PropTypes.node.isRequired, + className: PropTypes.string, + iconConfirm: PropTypes.node, + iconDeny: PropTypes.node, + labelConfirm: PropTypes.string, + labelDeny: PropTypes.string, + title: PropTypes.oneOfType([ + PropTypes.node, PropTypes.string + ]).isRequired, + visible: PropTypes.bool.isRequired, + onConfirm: PropTypes.func.isRequired, + onDeny: PropTypes.func.isRequired + } + + render () { + const { children, className, title, visible } = this.props; + + return ( + +
+ { children } +
+
+ ); + } + + renderActions () { + const { iconConfirm, iconDeny, labelConfirm, labelDeny, onConfirm, onDeny } = this.props; + + return [ +