├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ ├── docker.yml │ ├── pip-audit.yml │ └── pythonpublish.yml ├── .gitignore ├── CHANGELOG.md ├── Dockerfile ├── LICENSE ├── README.md ├── etheno ├── __init__.py ├── __main__.py ├── ascii_escapes.py ├── client.py ├── contracts.py ├── differentials.py ├── etheno.py ├── ganache.py ├── genesis.py ├── geth.py ├── jsonrpc.py ├── jsonrpcclient.py ├── keyfile.py ├── logger.py ├── parity.py ├── signals.py ├── synchronization.py ├── threadwrapper.py ├── truffle.py └── utils.py ├── logo ├── etheno.png └── etheno.svg ├── setup.py └── tests └── drizzle ├── contracts ├── ComplexStorage.sol ├── Migrations.sol ├── SimpleStorage.sol └── TutorialToken.sol ├── hardhat.config.js ├── package.json └── test ├── TestSimpleStorage.sol └── simplestorage.js /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: github-actions 5 | directory: / 6 | schedule: 7 | interval: daily 8 | -------------------------------------------------------------------------------- /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docker 2 | on: 3 | push: 4 | branches: [master] 5 | tags: 6 | - '*' 7 | jobs: 8 | docker: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Set up QEMU 12 | uses: docker/setup-qemu-action@v2 13 | 14 | - name: Set up Docker Buildx 15 | uses: docker/setup-buildx-action@v2 16 | id: buildx 17 | with: 18 | install: true 19 | 20 | - name: DockerHub Login 21 | uses: docker/login-action@v2 22 | with: 23 | username: ${{ secrets.DOCKERHUB_USERNAME }} 24 | password: ${{ secrets.DOCKERHUB_ACCESS_TOKEN }} 25 | 26 | - name: GitHub Container Registry Login 27 | uses: docker/login-action@v2 28 | with: 29 | registry: ghcr.io 30 | username: ${{ github.actor }} 31 | password: ${{ secrets.GITHUB_TOKEN }} 32 | 33 | - name: Set Docker Package and Version 34 | id: version 35 | run: | 36 | set +e 37 | _=$(echo "$GITHUB_REF" | grep "^refs/heads/") 38 | if [ $? -eq 0 ]; then 39 | # branch 40 | if [ "$GITHUB_REF" = "refs/heads/master" ]; then 41 | VER=latest 42 | PKG=etheno 43 | else 44 | VER=testing 45 | PKG=etheno 46 | fi 47 | fi 48 | _=$(echo "$GITHUB_REF" | grep "^refs/tags/") 49 | if [ $? -eq 0 ]; then 50 | # tag 51 | # refs/tags/v1.X => v1.X 52 | VER=$(echo "$GITHUB_REF" | sed -e 's/.*\///') 53 | PKG=etheno 54 | fi 55 | set -e 56 | echo "::set-output name=PKG::$PKG" 57 | echo "::set-output name=VER::$VER" 58 | 59 | 60 | - name: Docker build and push 61 | uses: docker/build-push-action@v3 62 | with: 63 | push: true 64 | target: final 65 | platforms: | 66 | linux/arm64/v8 67 | linux/amd64 68 | tags: | 69 | trailofbits/${{ steps.version.outputs.PKG }}:${{ steps.version.outputs.VER }} 70 | ghcr.io/${{ github.repository }}/${{ steps.version.outputs.PKG }}:${{ steps.version.outputs.VER }} 71 | -------------------------------------------------------------------------------- /.github/workflows/pip-audit.yml: -------------------------------------------------------------------------------- 1 | name: Scan dependencies for vulnerabilities with pip-audit 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | schedule: 9 | - cron: "0 12 * * *" 10 | 11 | jobs: 12 | pip-audit: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout repository 17 | uses: actions/checkout@v3 18 | 19 | - name: Install Python 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: "3.x" 23 | 24 | - name: Install project 25 | run: | 26 | python -m venv /tmp/pip-audit-env 27 | source /tmp/pip-audit-env/bin/activate 28 | 29 | python -m pip install --upgrade pip 30 | python -m pip install . 31 | 32 | 33 | - name: Run pip-audit 34 | uses: pypa/gh-action-pip-audit@v1.0.0 35 | with: 36 | virtual-environment: /tmp/pip-audit-env 37 | 38 | -------------------------------------------------------------------------------- /.github/workflows/pythonpublish.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [published] 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Set up Python 18 | uses: actions/setup-python@v4 19 | with: 20 | python-version: '3.x' 21 | - name: Install and upgrade dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install setuptools wheel twine 25 | pip install --upgrade setuptools wheel twine 26 | - name: Build and publish 27 | env: 28 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 29 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 30 | run: | 31 | python setup.py sdist bdist_wheel 32 | twine upload dist/* 33 | 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.pyc 3 | build 4 | dist 5 | venv/ 6 | *egg* 7 | init.json 8 | tests/drizzle/node_modules/ 9 | tests/drizzle/artifacts/ 10 | tests/drizzle/yarn.lock 11 | tests/drizzle/cache/ -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | The format is based on [Keep a Changelog](http://keepachangelog.com/). 4 | 5 | ## [Unreleased](https://github.com/trailofbits/etheno/compare/v0.3.2...HEAD) 6 | 7 | ## 0.3.2 - 2022-11-01 8 | 9 | ### Fixed 10 | - Dropped `rusty-rlp` dependency so that ARM Docker builds work as expected during QEMU emulation 11 | 12 | ## 0.3.1 - 2022-11-01 13 | 14 | ### Changed 15 | - We are now using `ganache` instead of `ganache-cli` for running Ganache 16 | - Using the latest Flask version 17 | - Python 3.7.x is now the lowest allowed version 18 | 19 | ### Fixed 20 | - Fixed a bug that occurred when a `JSONRPCError` was being logged 21 | - Fixed a bug that occurred when using non-hex strings during Ganache initialization 22 | - Fixed a bug that prevented Ganache from being used from within a Docker container 23 | 24 | ### Removed 25 | - Removed Manticore integration and all associated command-line parameters 26 | - Removed Echidna integration and all associated command-line parameters 27 | - Removed `examples/` folder since it is outdated and uses deprecated features 28 | ## 0.2.3 — 2019-06-27 29 | 30 | ### Added 31 | 32 | - Support for the latest version of Manticore (v0.3.0) 33 | 34 | ### Fixed 35 | 36 | - Fixes a bug due to a change in the way the latest version of Truffle handles its config files 37 | - Fixes a bug that would erroneously print a warning that the version of Manticore is too old 38 | 39 | ## 0.2.2 — 2019-04-11 40 | 41 | ### Added 42 | 43 | - Updated to support a [newer version of Echidna](https://github.com/crytic/echidna/tree/dev-etheno) 44 | - We are almost at feature parity with Echidna master, which we expect to happen at the next release 45 | - Two new commandline options to export raw transactions as a JSON file 46 | - New `--truffle-cmd` argument to specify the build command 47 | 48 | ### Changed 49 | 50 | - The [`BrokenMetaCoin` example](examples/BrokenMetaCoin) was updated to a newer version of Solidity 51 | 52 | ### Fixed 53 | 54 | - Fixes a bug in honoring the `--ganache-args` option 55 | 56 | ## 0.2.1 — 2019-02-07 57 | 58 | Bugfix release. 59 | 60 | - Manticore is now an optional requirement 61 | - Improvements and bugfixes to the logger integration with Manticore 62 | - Added a workaround to the examples for a bug in Truffle 63 | 64 | ## 0.2.0 — 2018-11-02 65 | 66 | First formal release of Etheno. 67 | 68 | ### Added 69 | 70 | - An [example](examples/ConstantinopleGasUsage) that can automatically reproduce [the Constantinople gas usage discrepancy](https://github.com/paritytech/parity-ethereum/pull/9746) that caused a hard-fork on Ropsten in October of 2018 71 | - More client integrations and support 72 | - Support for JSON RPC clients that have no local accounts and only accept signed raw transactions 73 | - Support for saving and loading genesis files 74 | - Support for Geth with either an autogenerated or user-provided genesis 75 | - Support for Parity with either an autogenerated or user-provided genesis 76 | - Automated transaction synchronization between chains (_e.g._, if clients are running with different genesis blocks) 77 | - Improved automated testing 78 | - Automated differential testing that reports differences between clients 79 | - Integration with the [Echidna](https://github.com/trailofbits/echidna) EVM fuzzer 80 | - Improved extensibility and user friendliness 81 | - Client and Plugin API 82 | - Logging framework with ANSI color on the terminal 83 | - Optional log directory with client- and plugin-specific log files, including auto-generated scripts to re-run the clients 84 | 85 | ### Changed 86 | 87 | - The [`BrokenMetaCoin` example](examples/BrokenMetaCoin) was improved by adding various utilities for interacting with Manticore 88 | 89 | ## 0.0.1 — 2018-10-07 90 | 91 | Prerelease at TruffleCon, 2018. 92 | 93 | Initial Features: 94 | 95 | - Manticore Integration 96 | - Truffle Integration 97 | - Ganache Integration 98 | - JSON RPC Multiplexing 99 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1.3 2 | FROM ubuntu:focal AS python-wheels 3 | RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ 4 | build-essential \ 5 | ca-certificates \ 6 | cmake \ 7 | curl \ 8 | python3-dev \ 9 | python3-pip \ 10 | python3-setuptools 11 | 12 | RUN --mount=type=bind,target=/etheno \ 13 | cd /etheno && \ 14 | pip3 install --no-cache-dir --upgrade pip setuptools && \ 15 | pip3 wheel --no-cache-dir -w /wheels \ 16 | . 17 | 18 | 19 | FROM ubuntu:focal AS ganache 20 | RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ 21 | build-essential \ 22 | ca-certificates \ 23 | curl \ 24 | gnupg \ 25 | lsb-release 26 | RUN curl -fsSL https://deb.nodesource.com/setup_16.x | bash && \ 27 | DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends nodejs 28 | RUN npm install --omit=dev --location=global --prefix /opt/node ganache truffle 29 | 30 | 31 | FROM ubuntu:focal AS final 32 | LABEL org.opencontainers.image.authors="Evan Sultanik" 33 | 34 | RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ 35 | bash-completion \ 36 | ca-certificates \ 37 | curl \ 38 | gpg-agent \ 39 | libudev-dev \ 40 | locales \ 41 | python3 \ 42 | python3-pip \ 43 | software-properties-common \ 44 | sudo \ 45 | && rm -rf /var/lib/apt/lists/* 46 | 47 | # NOTE: solc was removed from the below command since the echidna integration is being removed 48 | # If the solc option is added back, --platform linux-amd64 needs to be added to the `docker build` command for M1 machines 49 | RUN add-apt-repository -y ppa:ethereum/ethereum && \ 50 | apt-get update && apt-get install -y --no-install-recommends \ 51 | ethereum \ 52 | && rm -rf /var/lib/apt/lists/* 53 | 54 | RUN curl -fsSL https://deb.nodesource.com/setup_16.x | bash && \ 55 | apt-get install -y --no-install-recommends nodejs \ 56 | && rm -rf /var/lib/apt/lists/* 57 | 58 | COPY --from=ganache /opt/node /usr/local/ 59 | 60 | # BEGIN Install Etheno 61 | RUN --mount=type=bind,target=/mnt/etheno \ 62 | --mount=type=bind,target=/mnt/wheels,source=/wheels,from=python-wheels \ 63 | cd /mnt/etheno && \ 64 | pip3 install --no-cache-dir --upgrade pip setuptools && \ 65 | pip3 install --no-cache-dir --no-index --find-links /mnt/wheels . 66 | 67 | RUN useradd -m -G sudo etheno 68 | 69 | # Allow passwordless sudo for etheno 70 | RUN echo 'etheno ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers 71 | 72 | USER etheno 73 | ENV HOME=/home/etheno 74 | 75 | # Use the DOCKER env variable to set hostname accordingly 76 | ENV DOCKER=1 77 | WORKDIR /home/etheno 78 | 79 | CMD ["/bin/bash"] 80 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | The repo is now archived. Use [medusa](https://github.com/crytic/medusa) for fuzzing. To learn more: https://secure-contracts.com/ 2 | 3 | 4 | # Etheno 5 | [![Slack Status](https://slack.empirehacking.nyc/badge.svg)](https://slack.empirehacking.nyc) 6 | [![PyPI version](https://badge.fury.io/py/etheno.svg)](https://badge.fury.io/py/etheno) 7 |

8 | 9 |

10 |
11 | 12 | 13 | Etheno is the Ethereum testing Swiss Army knife. It’s a JSON RPC multiplexer, analysis tool wrapper, and test integration tool. It eliminates the complexity of setting up analysis tools like [Echidna](https://github.com/trailofbits/echidna) on large, multi-contract projects. 14 | 15 | If you are a smart contract developer, you should use Etheno to test your contracts. If you are an Ethereum client developer, you should use Etheno to perform differential testing on your implementation. 16 | 17 | Etheno is named after the Greek goddess [Stheno](https://en.wikipedia.org/wiki/Stheno), sister of Medusa, and mother of Echidna—which also happens to be the name of [our EVM property-based fuzz tester](https://github.com/trailofbits/echidna). 18 | 19 | ## Features 20 | 21 | * **JSON RPC Multiplexing**: Etheno runs a JSON RPC server that can multiplex calls to one or more clients 22 | * API for filtering and modifying JSON RPC calls 23 | * Enables differential testing by sending JSON RPC sequences to multiple Ethereum clients 24 | * Deploy to and interact with multiple networks at the same time 25 | * **Integration with Test Frameworks** like Ganache and Truffle 26 | * Run a local test network with a single command 27 | 28 | ## Quickstart 29 | 30 | Use our prebuilt Docker container to quickly install and try Etheno: 31 | 32 | ``` 33 | docker pull trailofbits/etheno 34 | docker run -it trailofbits/etheno 35 | ``` 36 | 37 | **NOTE:** Many of Etheno's capabilities will require publishing one or more ports and persisting data using volumes as part of the `docker run` command. 38 | - To learn about publishing ports, click [here](https://docs.docker.com/storage/volumes/) 39 | - To learn more about persisting data using volumes, click [here](https://docs.docker.com/storage/volumes/) 40 | 41 | 42 | Alternatively, natively install Etheno in a few shell commands: 43 | 44 | ``` 45 | # Install system dependencies 46 | sudo apt-get update && sudo apt-get install python3 python3-pip -y 47 | 48 | # Install Etheno 49 | pip3 install --user etheno 50 | 51 | # Use the Etheno CLI 52 | cd /path/to/a/truffle/project 53 | etheno --ganache --truffle 54 | ``` 55 | 56 | ## Usage 57 | 58 | Etheno can be used in many different ways and therefore has numerous command-line argument combinations. 59 | 60 | ### Ganache Integration 61 | 62 | A Ganache instance can automatically be run within Etheno: 63 | ``` 64 | etheno --ganache 65 | ``` 66 | 67 | * `--ganache-port` will set the port on which Ganache is run; if omitted, Etheno will choose the lowest port higher than the port on which Etheno’s JSON RPC server is running 68 | * `--ganache-args` lets you pass additional arguments to Ganache 69 | * `--accounts` or `-a` sets the number of accounts to create in Ganache (default is 10) 70 | * `--balance` or `-b` sets the default balance (in Ether) to seed to each Ganache account (default is 1000.0) 71 | * `--gas-price` or `-c` sets the default gas price in wei for Ganache (default is 20_000_000_000) 72 | 73 | Running a Ganache instance via Etheno can be used to deploy large, multi-contract projects in tandem with Echidna. To learn more on how to use Echidna and Ganache together, click [here](https://github.com/crytic/building-secure-contracts/blob/master/program-analysis/echidna/end-to-end-testing.md). 74 | 75 | 76 | **NOTE:** We recommend using the latest version of Ganache (v7.3.2) and Node 16.x. After the upstream bug (see below) is fixed, the Ganache package should be upgraded. 77 | 78 | 79 | **NOTE:** Currently, there is an upstream bug in the latest version of Ganache (v7.3.2) that prevents the Etheno integration from working if the contract size that is being tested is very large (https://github.com/trufflesuite/ganache/issues/3332). 80 | 81 | 82 | ### JSON RPC Server and Multiplexing 83 | 84 | This command starts a JSON RPC server and forwards all messages to the given clients: 85 | 86 | ``` 87 | etheno https://client1.url.com:1234/ https://client2.url.com:8545/ http://client3.url.com:8888/ 88 | ``` 89 | 90 | * `--port` or `-p` allows you to specify a port on which to run Etheno’s JSON RPC server (default is 8545) 91 | * `--run-publicly` allows incoming JSON RPC connections from external computers on the network 92 | * `--debug` will run a web-based interactive debugger in the event that an internal Etheno client throws an exception while processing a JSON RPC call; this should _never_ be used in conjunction with `--run-publicly` 93 | * `--master` or `-s` will set the “master” client, which will be used for synchronizing with Etheno clients. If a master is not explicitly provided, it defaults to the first client listed. 94 | * `--raw`, when prefixed before a client URL, will cause Etheno to auto-sign all transactions and submit them to the client as raw transactions 95 | 96 | ### Geth and Parity Integration 97 | 98 | A Geth and/or Parity instance can be run as a private chain with 99 | * `--geth` or `-go` for Geth 100 | * `--parity` or `-pa` for Parity 101 | 102 | Each will be instantiated with an autogenerated genesis block. You may provide a custom `genesis.json` file in Geth format using the `--genesis` or `-j` argument. The genesis used for each run will automatically be saved to the log directory (if one is provided using the `--log-dir` option), or it can be manually saved to a location provided with the `--save-genesis` option. 103 | 104 | The network ID of each client will default to 0x657468656E6F (equal to the string `etheno` in ASCII). This can be overridden with the `--network-id` or `-i` option. 105 | 106 | EIP and hard fork block numbers can be set within a custom genesis.json as usual, or they may be specified as command-line options such as `--constantinople`. 107 | 108 | ### Differential Testing 109 | 110 | Whenever two or more clients are run within Etheno, the differential 111 | testing plugin will automatically be loaded. This plugin checks for a 112 | variety of different discrepancies between the clients, such as gas 113 | usage differences. A report is printed when Etheno exits. 114 | 115 | This plugin can be disabled with the `--no-differential-testing` option. 116 | 117 | ### Truffle Integration 118 | 119 | Truffle migrations can automatically be run within a Truffle project: 120 | ``` 121 | etheno --truffle 122 | ``` 123 | 124 | Additional arguments can be passed to Truffle using `--truffle-args`. 125 | 126 | ### Logging 127 | 128 | By default, Etheno only prints log messages to the console with a log 129 | level defaulting to `INFO`. An alternative log level can be specified 130 | with `--log-level` or `-l`. You can specify a log file with the 131 | `--log-file` option. In addition, you can provide the path to a 132 | logging directory with `--log-dir` in which the following will be 133 | saved: 134 | * a complete log file including log messages at all log levels; 135 | * separate log files for each Etheno client and plugin; 136 | * the genesis file used to instantiate clients; 137 | * a subdirectory in which each client and plugin can store additional files such as test results; 138 | * a script to re-run Geth and/or Parity using the same genesis and chain data that Etheno used. 139 | 140 | ## Requirements 141 | 142 | * Python 3.7 or newer 143 | 144 | ### Optional Requirements 145 | * [Node](https://nodejs.org/en/) 16.x or newer to install various integrations 146 | * [Ganache](https://www.npmjs.com/package/ganache) 7.3.2 or newer for its associated integrations 147 | * [Truffle](https://www.npmjs.com/package/truffle) for its associated integrations 148 | * [Geth](https://github.com/ethereum/go-ethereum) and/or [Parity](https://github.com/paritytech/parity-ethereum), if you would like to have Etheno run them 149 | 150 | ## Getting Help 151 | 152 | Feel free to stop by our [Slack channel](https://empirehacking.slack.com/) for help on using or extending Etheno. 153 | 154 | ## License 155 | 156 | Etheno is licensed and distributed under the [AGPLv3](LICENSE) license. [Contact us](mailto:opensource@trailofbits.com) if you’re looking for an exception to the terms. 157 | -------------------------------------------------------------------------------- /etheno/__init__.py: -------------------------------------------------------------------------------- 1 | from .etheno import Etheno, EthenoPlugin 2 | from .client import EthenoClient, SelfPostingClient, RpcProxyClient, DATA, QUANTITY 3 | -------------------------------------------------------------------------------- /etheno/__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import os 4 | import shlex 5 | import sys 6 | from threading import Thread 7 | 8 | from .client import RpcProxyClient 9 | from .differentials import DifferentialTester 10 | from .etheno import app, EthenoView, GETH_DEFAULT_RPC_PORT, ETHENO, VERSION_NAME 11 | from .genesis import Account, make_accounts, make_genesis 12 | from .jsonrpc import EventSummaryExportPlugin, JSONRPCExportPlugin 13 | from .synchronization import AddressSynchronizingClient, RawTransactionClient 14 | from .utils import ( 15 | clear_directory, 16 | decode_value, 17 | find_open_port, 18 | format_hex_address, 19 | ynprompt, 20 | ) 21 | from . import ganache 22 | from . import geth 23 | from . import logger 24 | from . import parity 25 | from . import truffle 26 | 27 | # Constant for converting whole units to wei 28 | ETHER = 1e18 29 | 30 | 31 | def main(argv=None): 32 | parser = argparse.ArgumentParser( 33 | description="An Ethereum JSON RPC multiplexer, differential fuzzer, and test framework integration tool." 34 | ) 35 | parser.add_argument( 36 | "--debug", 37 | action="store_true", 38 | default=False, 39 | help="Enable debugging from within the web server", 40 | ) 41 | parser.add_argument( 42 | "--run-publicly", 43 | action="store_true", 44 | default=False, 45 | help="Allow the web server to accept external connections", 46 | ) 47 | parser.add_argument( 48 | "-p", 49 | "--port", 50 | type=int, 51 | default=GETH_DEFAULT_RPC_PORT, 52 | help="Port on which to run the JSON RPC webserver (default=%d)" 53 | % GETH_DEFAULT_RPC_PORT, 54 | ) 55 | parser.add_argument( 56 | "-a", 57 | "--accounts", 58 | type=int, 59 | default=10, 60 | help="Number of accounts to create in the client (default=10)", 61 | ) 62 | parser.add_argument( 63 | "-b", 64 | "--balance", 65 | type=float, 66 | default=1000.0, 67 | help="Default balance (in Ether) to seed to each account (default=100.0)", 68 | ) 69 | # TODO: do we really need a gas price specified for ganache? is there a use case here? 70 | parser.add_argument( 71 | "-c", 72 | "--gas-price", 73 | type=int, 74 | default=20000000000, 75 | help="Default gas price (default=20000000000)", 76 | ) 77 | # TODO: networkID can have a default value it seems like 78 | parser.add_argument( 79 | "-i", 80 | "--network-id", 81 | type=int, 82 | default=None, 83 | help="Specify a network ID (default is the network ID of the master client)", 84 | ) 85 | parser.add_argument( 86 | "-t", 87 | "--truffle", 88 | action="store_true", 89 | default=False, 90 | help="Run the truffle migrations in the current directory and exit", 91 | ) 92 | parser.add_argument( 93 | "--truffle-cmd", 94 | type=str, 95 | default="truffle", 96 | help="Command to run truffle (default=truffle)", 97 | ) 98 | parser.add_argument( 99 | "--truffle-args", 100 | type=str, 101 | default="migrate", 102 | help="Arguments to pass to truffle (default=migrate)", 103 | ) 104 | parser.add_argument( 105 | "-g", 106 | "--ganache", 107 | action="store_true", 108 | default=False, 109 | help="Run Ganache as a master JSON RPC client (cannot be used in conjunction with --master)", 110 | ) 111 | # TODO: This cmd-line argument is error-prone and should probably be removed. Commenting it out for now 112 | """ 113 | parser.add_argument('--ganache-cmd', type=str, default=None, help='Specify a command that runs Ganache ' 114 | '(default="/usr/bin/env ganache")') 115 | """ 116 | parser.add_argument( 117 | "--ganache-args", 118 | type=str, 119 | default=None, 120 | help="Additional arguments to pass to Ganache", 121 | ) 122 | parser.add_argument( 123 | "--ganache-port", 124 | type=int, 125 | default=None, 126 | help="Port on which to run Ganache (defaults to the closest available port to the port " 127 | "specified with --port plus one)", 128 | ) 129 | parser.add_argument( 130 | "-go", 131 | "--geth", 132 | action="store_true", 133 | default=False, 134 | help="Run Geth as a JSON RPC client", 135 | ) 136 | parser.add_argument( 137 | "--geth-port", 138 | type=int, 139 | default=None, 140 | help="Port on which to run Geth (defaults to the closest available port to the port specified " 141 | "with --port plus one)", 142 | ) 143 | parser.add_argument( 144 | "-pa", 145 | "--parity", 146 | action="store_true", 147 | default=False, 148 | help="Run Parity as a JSON RPC client", 149 | ) 150 | parser.add_argument( 151 | "--parity-port", 152 | type=int, 153 | default=None, 154 | help="Port on which to run Parity (defaults to the closest available port to the port " 155 | "specified with --port plus one)", 156 | ) 157 | parser.add_argument( 158 | "-j", 159 | "--genesis", 160 | type=str, 161 | default=None, 162 | help="Path to a genesis.json file to use for initializing clients. Any genesis-related options " 163 | "like --network-id will override the values in this file. If --accounts is greater than " 164 | "zero, that many new accounts will be appended to the accounts in the genesis file.", 165 | ) 166 | parser.add_argument( 167 | "--save-genesis", 168 | type=str, 169 | default=None, 170 | help="Save a genesis.json file to reproduce the state of this run. Note that this genesis file " 171 | "will include all known private keys for the genesis accounts, so use this with caution.", 172 | ) 173 | parser.add_argument( 174 | "--constantinople-block", 175 | type=int, 176 | default=None, 177 | help="The block in which to enable Constantinople EIPs (default=do not enable Constantinople)", 178 | ) 179 | parser.add_argument( 180 | "--constantinople", 181 | action="store_true", 182 | default=False, 183 | help="Enables Constantinople EIPs; equivalent to `--constantinople-block 0`", 184 | ) 185 | parser.add_argument( 186 | "--no-differential-testing", 187 | action="store_false", 188 | dest="run_differential", 189 | default=True, 190 | help="Do not run differential testing, which is run by default", 191 | ) 192 | parser.add_argument( 193 | "-l", 194 | "--log-level", 195 | type=str.upper, 196 | choices={"CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"}, 197 | default="INFO", 198 | help="Set Etheno's log level (default=INFO)", 199 | ) 200 | parser.add_argument( 201 | "--log-file", 202 | type=str, 203 | default=None, 204 | help="Path to save all log output to a single file", 205 | ) 206 | parser.add_argument( 207 | "--log-dir", 208 | type=str, 209 | default=None, 210 | help="Path to a directory in which to save all log output, divided by logging source", 211 | ) 212 | parser.add_argument( 213 | "-d", 214 | "--dump-jsonrpc", 215 | type=str, 216 | default=None, 217 | help="Path to a JSON file in which to dump all raw JSON RPC calls; if `--log-dir` is provided, " 218 | "the raw JSON RPC calls will additionally be dumped to `rpc.json` in the log directory.", 219 | ) 220 | parser.add_argument( 221 | "-x", 222 | "--export-summary", 223 | type=str, 224 | default=None, 225 | help="Path to a JSON file in which to export an event summary", 226 | ) 227 | parser.add_argument( 228 | "-v", 229 | "--version", 230 | action="store_true", 231 | default=False, 232 | help="Print version information and exit", 233 | ) 234 | parser.add_argument( 235 | "client", 236 | type=str, 237 | nargs="*", 238 | help="JSON RPC client URLs to multiplex; if no client is specified for --master, the first " 239 | 'client in this list will default to the master (format="http://foo.com:8545/")', 240 | ) 241 | parser.add_argument( 242 | "-s", 243 | "--master", 244 | type=str, 245 | default=None, 246 | help="A JSON RPC client to use as the master " 247 | '(format="http://foo.com:8545/")', 248 | ) 249 | parser.add_argument( 250 | "--raw", 251 | type=str, 252 | nargs="*", 253 | action="append", 254 | help="JSON RPC client URLs to multiplex that do not have any local accounts; Etheno will " 255 | "automatically use auto-generated accounts with known private keys, pre-sign all " 256 | "transactions, and only use eth_sendRawTransaction", 257 | ) 258 | 259 | if argv is None: 260 | argv = sys.argv 261 | 262 | args = parser.parse_args(argv[1:]) 263 | 264 | if args.version: 265 | print(VERSION_NAME) 266 | sys.exit(0) 267 | 268 | if args.constantinople and args.constantinople_block is None: 269 | args.constantinople_block = 0 270 | 271 | ETHENO.log_level = args.log_level 272 | 273 | if args.log_file: 274 | ETHENO.logger.save_to_file(args.log_file) 275 | 276 | if args.log_dir: 277 | if os.path.exists(args.log_dir): 278 | if not ynprompt( 279 | "Logging path `%s` already exists! Would you like to overwrite it? [yN] " 280 | % args.log_dir 281 | ): 282 | sys.exit(1) 283 | elif os.path.isfile(args.log_dir): 284 | os.remove(args.log_dir) 285 | else: 286 | # don't delete the directory, just its contents 287 | # we can't use shutil.rmtree here, because that deletes the directory and also it doesn't work on 288 | # symlinks 289 | if not ynprompt( 290 | "We are about to delete the contents of `%s`. Are you sure? [yN] " 291 | % args.log_dir 292 | ): 293 | sys.exit(1) 294 | abspath = os.path.abspath(args.log_dir) 295 | if ( 296 | abspath == "" 297 | or abspath == "/" 298 | or abspath.endswith("://") 299 | or abspath.endswith(":\\\\") 300 | ): 301 | print( 302 | "Wait a sec, you want me to delete `%s`?!\nThat looks too dangerous.\nIf I were to do that, " 303 | "you'd file an angry GitHub issue complaining that I deleted your hard drive.\nYou're on " 304 | "your own deleting this directory!" % abspath 305 | ) 306 | sys.exit(1) 307 | clear_directory(args.log_dir) 308 | 309 | ETHENO.logger.save_to_directory(args.log_dir) 310 | if not args.log_file: 311 | # Also create a unified log in the log dir: 312 | ETHENO.logger.save_to_file(os.path.join(args.log_dir, "Complete.log")) 313 | 314 | ETHENO.add_plugin(JSONRPCExportPlugin(os.path.join(args.log_dir, "rpc.json"))) 315 | 316 | if args.dump_jsonrpc is not None: 317 | ETHENO.add_plugin(JSONRPCExportPlugin(args.dump_jsonrpc)) 318 | 319 | if args.export_summary is not None: 320 | ETHENO.add_plugin(EventSummaryExportPlugin(args.export_summary)) 321 | 322 | if args.genesis is None: 323 | # Set defaults since no genesis was supplied 324 | if args.accounts is None: 325 | args.accounts = 10 326 | if args.gas_price is None: 327 | args.gas_price = 20000000000 328 | 329 | accounts = [] 330 | 331 | # TODO: args.gas_price is not set if a genesis file is provided 332 | if args.genesis: 333 | with open(args.genesis, "rb") as f: 334 | genesis = json.load(f) 335 | if "config" not in genesis: 336 | genesis["config"] = {} 337 | if "alloc" not in genesis: 338 | genesis["alloc"] = {} 339 | if args.network_id is None: 340 | args.network_id = genesis["config"].get("chainId", None) 341 | if args.constantinople_block is None: 342 | args.constantinople_block = genesis["config"].get( 343 | "constantinopleBlock", None 344 | ) 345 | args.constantinople = args.constantinople_block is not None 346 | for addr, bal in genesis["alloc"].items(): 347 | pkey = None 348 | if "privateKey" in bal: 349 | pkey = bal["privateKey"] 350 | accounts.append( 351 | Account( 352 | address=int(addr, 16), 353 | balance=decode_value(bal["balance"]), 354 | private_key=decode_value(pkey), 355 | ) 356 | ) 357 | else: 358 | # We will generate it further below once we've resolved all of the parameters 359 | genesis = None 360 | 361 | accounts += make_accounts(args.accounts, default_balance=int(args.balance * ETHER)) 362 | 363 | if genesis is not None: 364 | # add the new accounts to the genesis 365 | for account in accounts[len(genesis["alloc"]) :]: 366 | genesis["alloc"][format_hex_address(account.address)] = { 367 | "balance": "%d" % account.balance, 368 | "privateKey": format_hex_address(account.private_key), 369 | "comment": "`privateKey` and `comment` are ignored. In a real chain, the private key should _not_ be " 370 | "stored!", 371 | } 372 | 373 | if args.raw is None: 374 | args.raw = [] 375 | else: 376 | args.raw = [r[0] for r in args.raw] 377 | 378 | # TODO: This if/elif/else logic is flawed - needs rework 379 | if args.ganache and args.master: 380 | parser.print_help() 381 | sys.stderr.write( 382 | "\nError: You cannot specify both --ganache and --master at the same time!\n" 383 | ) 384 | sys.exit(1) 385 | elif args.ganache: 386 | if args.ganache_port is None: 387 | args.ganache_port = find_open_port(args.port + 1) 388 | 389 | if args.network_id is None: 390 | args.network_id = 0x657468656E6F # 'etheno' in hex 391 | 392 | # Have to use hex() so that string is hex-encoded (prefixed with 0x) that is necessary for Ganache v7.0+ 393 | # https://github.com/trufflesuite/ganache/discussions/1075 394 | ganache_accounts = [ 395 | "--account=%s,0x%x" % (hex(acct.private_key), acct.balance) 396 | for acct in accounts 397 | ] 398 | 399 | ganache_args = ganache_accounts + [ 400 | "-g", 401 | str(args.gas_price), 402 | "-i", 403 | str(args.network_id), 404 | ] 405 | 406 | if args.ganache_args is not None: 407 | ganache_args += shlex.split(args.ganache_args) 408 | # Removed cmd argument 409 | ganache_instance = ganache.Ganache(args=ganache_args, port=args.ganache_port) 410 | 411 | ETHENO.master_client = ganache.GanacheClient(ganache_instance) 412 | 413 | ganache_instance.start() 414 | elif args.master: 415 | ETHENO.master_client = AddressSynchronizingClient(RpcProxyClient(args.master)) 416 | elif args.client and not args.geth and not args.parity: 417 | ETHENO.master_client = AddressSynchronizingClient( 418 | RpcProxyClient(args.client[0]) 419 | ) 420 | args.client = args.client[1:] 421 | elif args.raw and not args.geth and not args.parity: 422 | ETHENO.master_client = RawTransactionClient( 423 | RpcProxyClient(args.raw[0]), accounts 424 | ) 425 | args.raw = args.raw[1:] 426 | 427 | if args.network_id is None: 428 | if ETHENO.master_client: 429 | args.network_id = int( 430 | ETHENO.master_client.post( 431 | {"id": 1, "jsonrpc": "2.0", "method": "net_version"} 432 | )["result"], 433 | 16, 434 | ) 435 | else: 436 | args.network_id = 0x657468656E6F # 'etheno' in hex 437 | 438 | if genesis is None: 439 | genesis = make_genesis( 440 | network_id=args.network_id, 441 | accounts=accounts, 442 | constantinople_block=args.constantinople_block, 443 | ) 444 | else: 445 | # Update the genesis with any overridden values 446 | genesis["config"]["chainId"] = args.network_id 447 | 448 | if args.save_genesis: 449 | with open(args.save_genesis, "wb") as f: 450 | f.write(json.dumps(genesis).encode("utf-8")) 451 | ETHENO.logger.info("Saved genesis to %s" % args.save_genesis) 452 | 453 | if args.geth: 454 | if args.geth_port is None: 455 | args.geth_port = find_open_port(args.port + 1) 456 | 457 | geth_instance = geth.GethClient(genesis=genesis, port=args.geth_port) 458 | geth_instance.etheno = ETHENO 459 | for account in accounts: 460 | # TODO: Make some sort of progress bar here 461 | geth_instance.logger.info( 462 | "Unlocking Geth account %s" % format_hex_address(account.address, True) 463 | ) 464 | geth_instance.import_account(account.private_key) 465 | geth_instance.start(unlock_accounts=True) 466 | if ETHENO.master_client is None: 467 | ETHENO.master_client = geth_instance 468 | else: 469 | ETHENO.add_client(AddressSynchronizingClient(geth_instance)) 470 | 471 | if args.parity: 472 | if args.parity_port is None: 473 | if args.geth_port is not None: 474 | args.parity_port = find_open_port(args.geth_port + 1) 475 | else: 476 | args.parity_port = find_open_port(args.port + 1) 477 | 478 | parity_instance = parity.ParityClient(genesis=genesis, port=args.parity_port) 479 | parity_instance.etheno = ETHENO 480 | for account in accounts: 481 | # TODO: Make some sort of progress bar here 482 | parity_instance.import_account(account.private_key) 483 | parity_instance.start(unlock_accounts=True) 484 | if ETHENO.master_client is None: 485 | ETHENO.master_client = parity_instance 486 | else: 487 | ETHENO.add_client(AddressSynchronizingClient(parity_instance)) 488 | 489 | for client in args.client: 490 | ETHENO.add_client(AddressSynchronizingClient(RpcProxyClient(client))) 491 | 492 | for client in args.raw: 493 | ETHENO.add_client(RawTransactionClient(RpcProxyClient(client), accounts)) 494 | 495 | if args.truffle: 496 | truffle_controller = truffle.Truffle( 497 | truffle_cmd=args.truffle_cmd, parent_logger=ETHENO.logger 498 | ) 499 | 500 | def truffle_thread(): 501 | if ETHENO.master_client: 502 | ETHENO.master_client.wait_until_running() 503 | ETHENO.logger.info("Etheno Started! Running Truffle...") 504 | ret = truffle_controller.run(args.truffle_args) 505 | if ret != 0: 506 | ETHENO.logger.error("Truffle exited with code %s" % ret) 507 | ETHENO.shutdown() 508 | # TODO: Propagate the error code elsewhere so Etheno doesn't exit with code 0 509 | 510 | for plugin in ETHENO.plugins: 511 | plugin.finalize() 512 | 513 | if not ETHENO.clients and not ETHENO.plugins: 514 | ETHENO.logger.info("No clients or plugins running; exiting...") 515 | ETHENO.shutdown() 516 | 517 | thread = Thread(target=truffle_thread) 518 | thread.start() 519 | 520 | # Without Manticore integration the only client types are geth, parity, and command-line raw/regular clients. 521 | # So checking len() >= 1 should be sufficient. 522 | if ( 523 | args.run_differential 524 | and (ETHENO.master_client is not None) 525 | and len(ETHENO.clients) >= 1 526 | ): 527 | # There are at least two non-Manticore clients running 528 | ETHENO.logger.info( 529 | "Initializing differential tests to compare clients %s" 530 | % ", ".join(map(str, [ETHENO.master_client] + ETHENO.clients)) 531 | ) 532 | ETHENO.add_plugin(DifferentialTester()) 533 | 534 | had_plugins = len(ETHENO.plugins) > 0 535 | 536 | if ETHENO.master_client is None and not ETHENO.clients and not ETHENO.plugins: 537 | if not had_plugins: 538 | ETHENO.logger.info("No clients or plugins provided; exiting...") 539 | # else: this can also happen if there were plugins but they uninstalled themselves after running 540 | return 541 | 542 | etheno = EthenoView() 543 | app.add_url_rule("/", view_func=etheno.as_view("etheno")) 544 | 545 | ETHENO.run(debug=args.debug, run_publicly=args.run_publicly, port=args.port) 546 | if args.truffle: 547 | truffle_controller.terminate() 548 | 549 | if args.log_file is not None: 550 | print("Log file saved to: %s" % os.path.realpath(args.log_file)) 551 | if args.log_dir is not None: 552 | print( 553 | "Logs %ssaved to: %s" 554 | % (["", "also "][args.log_file is not None], os.path.realpath(args.log_dir)) 555 | ) 556 | 557 | 558 | if __name__ == "__main__": 559 | main() 560 | -------------------------------------------------------------------------------- /etheno/ascii_escapes.py: -------------------------------------------------------------------------------- 1 | from typing import Iterable, Union 2 | 3 | CONTROL_CODES = { 4 | b"0": b"\0", 5 | b"a": b"\x07", # alert 6 | b"b": b"\x08", # backspace 7 | b"f": b"\x0C", # form feed 8 | b"n": b"\x0A", # newline (line feed) 9 | b"r": b"\x0D", # carriage return 10 | b"t": b"\x09", # horizontal tab 11 | b"v": b"\x0B", # vertical tab 12 | b'"': b"\x22", # double quote 13 | b"&": b"", # empty string 14 | b"'": b"\x27", # single quote 15 | b"\\": b"\x5C", # backslash 16 | b"NUL": b"\0", # null character 17 | b"SOH": b"\x01", # start of heading 18 | b"STX": b"\x02", # start of text 19 | b"ETX": b"\x03", # end of text 20 | b"EOT": b"\x04", # end of transmission 21 | b"ENQ": b"\x05", # enquiry 22 | b"ACK": b"\x06", # acknowledge 23 | b"BEL": b"\x07", # bell 24 | b"BS": b"\x08", # backspace 25 | b"HT": b"\x09", # horizontal tab 26 | b"LF": b"\x0A", # line feed (newline) 27 | b"VT": b"\x0B", # vertical tab 28 | b"FF": b"\x0C", # form feed 29 | b"CR": b"\x0D", # carriage return 30 | b"SO": b"\x0E", # shift out 31 | b"SI": b"\x0F", # shift in 32 | b"DLE": b"\x10", # data link escape 33 | b"DC1": b"\x11", # device control 1 34 | b"DC2": b"\x12", # device control 2 35 | b"DC3": b"\x13", # device control 3 36 | b"DC4": b"\x14", # device control 4 37 | b"NAK": b"\x15", # negative acknowledge 38 | b"SYN": b"\x16", # synchronous idle 39 | b"ETB": b"\x17", # end of transmission block 40 | b"CAN": b"\x18", # cancel 41 | b"EM": b"\x19", # end of medium 42 | b"SUB": b"\x1A", # substitute 43 | b"ESC": b"\x1B", # escape 44 | b"FS": b"\x1C", # file separator 45 | b"GS": b"\x1D", # group separator 46 | b"RS": b"\x1E", # record separator 47 | b"US": b"\x1F", # unit separator 48 | b"SP": b"\x20", # space 49 | b"DEL": b"\x7F", # delete 50 | b"^@": b"\0", 51 | b"^[": b"\x1B", # escape 52 | b"^\\": b"\x1C", # file separator 53 | b"^]": b"\x1D", # group separator 54 | b"^^": b"\x1E", # record separator 55 | b"^_": b"\x1F", # unit separator 56 | } 57 | 58 | for i in range(26): 59 | CONTROL_CODES[bytes([ord("^"), ord("A") + i])] = bytes([i + 1]) 60 | 61 | 62 | def decode(text: Union[str, bytes, Iterable[int]]) -> bytes: 63 | escaped = None 64 | ret = b"" 65 | for c in text: 66 | if isinstance(c, str): 67 | c = ord(c) 68 | c = bytes([c]) 69 | if escaped is not None: 70 | 71 | escaped += c 72 | if escaped in CONTROL_CODES: 73 | ret += CONTROL_CODES[escaped] 74 | escaped = None 75 | elif len(escaped) >= 3: 76 | if len(escaped) == 3: 77 | # see if it is an integer in the range [0, 255] 78 | try: 79 | value = int(escaped) 80 | if 0 <= value <= 255: 81 | ret += bytes([value]) 82 | escaped = None 83 | continue 84 | except ValueError: 85 | pass 86 | raise ValueError(f"Unknown escape sequence: {escaped!r}") 87 | elif c == b"\\": 88 | escaped = b"" 89 | else: 90 | ret += c 91 | return ret 92 | -------------------------------------------------------------------------------- /etheno/client.py: -------------------------------------------------------------------------------- 1 | import http 2 | import inspect 3 | import json 4 | import time 5 | from typing import Any, Dict, List, Optional, Set, Union 6 | from urllib.request import Request, urlopen 7 | 8 | from . import logger 9 | from .utils import decode_hex, format_hex_address, webserver_is_up 10 | 11 | 12 | def jsonrpc(**types): 13 | def decorator(function): 14 | signature = inspect.getfullargspec(function).args 15 | 16 | def wrapper(self, *args, **kwargs): 17 | rpc_kwargs = dict(kwargs) 18 | return_type = None 19 | converted_args = [] 20 | for i, arg in enumerate(args): 21 | if signature[i + 1] in types: 22 | converted_args.append(types[signature[i + 1]](arg)) 23 | else: 24 | converted_args.append(arg) 25 | rpc_kwargs[signature[i + 1]] = arg 26 | args = tuple(converted_args) 27 | kwargs = dict(kwargs) 28 | for arg_name, conversion in types.items(): 29 | if arg_name == "RETURN": 30 | return_type = conversion 31 | elif arg_name in kwargs: 32 | kwargs[arg_name] = conversion(kwargs[arg_name]) 33 | return function(self, *args, **kwargs) 34 | 35 | return wrapper 36 | 37 | return decorator 38 | 39 | 40 | class RpcHttpProxy: 41 | def __init__(self, urlstring): 42 | self.urlstring = urlstring 43 | self.rpc_id = 0 44 | 45 | def post(self, data) -> Dict[str, Union[int, str, Dict[str, Any]]]: 46 | data = dict(data) 47 | self.rpc_id += 1 48 | return_id = None 49 | if "jsonrpc" not in data: 50 | data["jsonrpc"] = "2.0" 51 | if "id" in data: 52 | return_id = data["id"] 53 | data["id"] = self.rpc_id 54 | request = Request( 55 | self.urlstring, 56 | data=bytearray(json.dumps(data), "utf8"), 57 | headers={"Content-type": "application/json"}, 58 | ) 59 | ret = json.loads(urlopen(request).read()) 60 | if return_id is not None and "id" in ret: 61 | ret["id"] = return_id 62 | return ret 63 | 64 | def __str__(self): 65 | return f"{self.__class__.__name__}<{self.urlstring}>" 66 | 67 | def __repr__(self): 68 | return f"{self.__class__.__name__}({self.urlstring})" 69 | 70 | 71 | class JSONRPCError(RuntimeError): 72 | def __init__(self, client, data, result): 73 | super().__init__( 74 | "JSON RPC Error in Client %s when processing transaction:\n%s\n%s" 75 | % (client, data, result["error"]) 76 | ) 77 | self.client = client 78 | self.json = data 79 | self.result = result 80 | 81 | 82 | def transaction_receipt_succeeded(data): 83 | if not (data and "result" in data and data["result"]): 84 | return None 85 | elif "contractAddress" in data["result"] and data["result"]["contractAddress"]: 86 | return True 87 | elif "blockHash" in data["result"] and data["result"]["blockHash"]: 88 | return True 89 | elif "status" not in data["result"]: 90 | return None 91 | status = data["result"]["status"] 92 | if status is None: 93 | return None 94 | elif not isinstance(status, int): 95 | status = int(status, 16) 96 | return status > 0 97 | 98 | 99 | class EthenoClient: 100 | _etheno = None 101 | logger = None 102 | _short_name = None 103 | 104 | @property 105 | def etheno(self): 106 | return self._etheno 107 | 108 | @etheno.setter 109 | def etheno(self, instance): 110 | if self._etheno is not None: 111 | if instance is None: 112 | self._etheno = None 113 | return 114 | elif instance == self._etheno: 115 | return 116 | raise ValueError( 117 | "An Etheno client can only ever be associated with a single Etheno instance" 118 | ) 119 | self._etheno = instance 120 | self.logger = logger.EthenoLogger(self.short_name, parent=self._etheno.logger) 121 | self.etheno_set() 122 | 123 | @property 124 | def log_directory(self) -> Optional[str]: 125 | """Returns a log directory that this client can use to save additional files, or None if one is not available""" 126 | if self.logger is None: 127 | return None 128 | else: 129 | return self.logger.directory 130 | 131 | def etheno_set(self): 132 | """A callback for once the etheno instance and logger for this client is set""" 133 | pass 134 | 135 | def create_account(self, balance=0, address=None): 136 | """A request for the client to create a new account. 137 | 138 | Subclasses implementing this function should raise a NotImplementedError if an address 139 | was provided that the client is unable to create an account at that address 140 | 141 | :param balance: The initial balance for the account 142 | :param address: The address for the account, or None if the address should be auto-generated 143 | :return: returns the address of the account created 144 | """ 145 | raise NotImplementedError("Clients must extend this function") 146 | 147 | def shutdown(self): 148 | pass 149 | 150 | def wait_for_transaction(self, tx_hash): 151 | return None 152 | 153 | @property 154 | def short_name(self): 155 | if self._short_name is None: 156 | return str(self) 157 | else: 158 | return self._short_name 159 | 160 | @short_name.setter 161 | def short_name(self, name): 162 | self._short_name = name 163 | 164 | 165 | class SelfPostingClient(EthenoClient): 166 | def __init__(self, client): 167 | self.client = client 168 | self._accounts: Optional[List[int]] = None 169 | self._created_account_index = -1 170 | # maintain a set of failed transactions so we know not to block on eth_getTransactionReceipt 171 | self._failed_transactions: Set[str] = set() 172 | 173 | def create_account(self, balance: int = 0, address: Optional[int] = None): 174 | if address is not None: 175 | raise NotImplementedError() 176 | if self._accounts is None: 177 | self._accounts = list( 178 | int(a, 16) 179 | for a in self.post( 180 | {"id": 1, "jsonrpc": "2.0", "method": "eth_accounts"} 181 | )["result"] 182 | ) 183 | self._created_account_index += 1 184 | return self._accounts[self._created_account_index] 185 | 186 | def wait_until_running(self): 187 | pass 188 | 189 | # TODO: need to ensure that JSON RPC calls match latest API spec 190 | def post(self, data: Dict[str, Any]) -> Optional[Dict[str, Any]]: 191 | ret = self.client.post(data) 192 | if ret is not None and "error" in ret: 193 | if "method" in data and ( 194 | data["method"] == "eth_sendTransaction" 195 | or data["method"] == "eth_sendRawTransaction" 196 | ): 197 | if ( 198 | self.etheno.master_client != self 199 | and self.etheno.rpc_client_result 200 | and not isinstance(self.etheno.rpc_client_result, JSONRPCError) 201 | and "result" in self.etheno.rpc_client_result 202 | ): 203 | self.logger.error( 204 | f"{self!s}: Failed transaction associated with master client transaction " 205 | f"{self.etheno.rpc_client_result['result']}" 206 | ) 207 | self._failed_transactions.add( 208 | self.etheno.rpc_client_result["result"].lower() 209 | ) 210 | # TODO: Figure out a better way to handle JSON RPC errors 211 | raise JSONRPCError(self, data, ret) 212 | return ret 213 | 214 | def estimate_gas(self, transaction: Dict[str, Any]) -> int: 215 | """Estimates the gas cost for the given transaction or call 216 | 217 | :param transaction: a dict containing the entire transaction as if it were to be sent to `post()` 218 | :return: the gas cost in wei as an int 219 | """ 220 | return int( 221 | self.post( 222 | { 223 | "id": 1, 224 | "jsonrpc": "2.0", 225 | "method": "eth_estimateGas", 226 | "params": transaction["params"], 227 | } 228 | )["result"], 229 | 16, 230 | ) 231 | 232 | def get_gas_price(self) -> int: 233 | return int( 234 | self.post({"id": 1, "jsonrpc": "2.0", "method": "eth_gasPrice"})["result"], 235 | 16, 236 | ) 237 | 238 | def get_net_version(self) -> int: 239 | return int( 240 | self.post({"id": 1, "jsonrpc": "2.0", "method": "net_version"})["result"], 241 | 16, 242 | ) 243 | 244 | def get_transaction_count(self, from_address) -> int: 245 | return int( 246 | self.post( 247 | { 248 | "id": 1, 249 | "jsonrpc": "2.0", 250 | "method": "eth_getTransactionCount", 251 | "params": [format_hex_address(from_address, True), "latest"], 252 | } 253 | )["result"], 254 | 16, 255 | ) 256 | 257 | def wait_for_transaction(self, tx_hash): 258 | """Blocks until the given transaction has been mined 259 | :param tx_hash: the transaction hash for the transaction to monitor 260 | :return: The transaction receipt 261 | """ 262 | while True: 263 | request_object = self.etheno.get_transaction_receipt_request(tx_hash) 264 | receipt = self.post(request_object) 265 | if ( 266 | tx_hash in self._failed_transactions 267 | or transaction_receipt_succeeded(receipt) is not None 268 | ): 269 | return receipt 270 | self.logger.info("Waiting to mine transaction %s..." % tx_hash) 271 | time.sleep(5.0) 272 | 273 | def __str__(self): 274 | return f"{self.__class__.__name__}[{self.client!s}]" 275 | 276 | def __repr__(self): 277 | return f"{self.__class__.__name__}[{self.client!r}]" 278 | 279 | 280 | class RpcProxyClient(SelfPostingClient): 281 | def __init__(self, rpcurl): 282 | super().__init__(RpcHttpProxy(rpcurl)) 283 | 284 | def post(self, data): 285 | while True: 286 | try: 287 | return super().post(data) 288 | except http.client.RemoteDisconnected as e: 289 | self.logger.warning(str(e)) 290 | time.sleep(1.0) 291 | self.logger.info(f"Retrying JSON RPC call to {self.client.urlstring}") 292 | 293 | def is_running(self) -> bool: 294 | return webserver_is_up(self.client.urlstring) 295 | 296 | def wait_until_running(self): 297 | slept = 0.0 298 | while not self.is_running(): 299 | time.sleep(0.25) 300 | slept += 0.25 301 | if slept % 5 == 0: 302 | self.logger.info("Waiting for the client to start...") 303 | 304 | 305 | def QUANTITY(to_convert: Optional[str]) -> Optional[int]: 306 | if to_convert is None: 307 | return None 308 | elif to_convert[:2] == "0x": 309 | return int(to_convert[2:], 16) 310 | else: 311 | return int(to_convert) 312 | 313 | 314 | def DATA(to_convert: Optional[str]) -> Optional[bytes]: 315 | return decode_hex(to_convert) 316 | -------------------------------------------------------------------------------- /etheno/contracts.py: -------------------------------------------------------------------------------- 1 | from .client import RpcProxyClient 2 | from .etheno import EthenoPlugin 3 | from .utils import format_hex_address 4 | 5 | # TODO: what is this file for? 6 | class ContractSynchronizer(EthenoPlugin): 7 | def __init__(self, source_client, contract_address): 8 | if isinstance(source_client, str): 9 | source_client = RpcProxyClient(source_client) 10 | self.source = source_client 11 | self.contract = format_hex_address(contract_address, True) 12 | 13 | def added(self): 14 | # get the contract: 15 | pass 16 | -------------------------------------------------------------------------------- /etheno/differentials.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | import os 3 | 4 | from .client import JSONRPCError, SelfPostingClient 5 | from .etheno import EthenoPlugin 6 | 7 | 8 | class DifferentialTest(object): 9 | def __init__(self, tester, test_name, success, message=""): 10 | self.tester = tester 11 | self.test_name = test_name 12 | self.message = message 13 | self.success = success 14 | self.tester.logger.make_constant_logged_file( 15 | self.message, 16 | prefix=["FAILED", "PASSED"][self.success.value], 17 | suffix=".log", 18 | dir=os.path.join(self.tester.logger.directory, self.test_name), 19 | ) 20 | 21 | def __str__(self): 22 | return "[%s] %s\t%s" % (self.test_name, self.success, self.message) 23 | 24 | __repr__ = __str__ 25 | 26 | 27 | class TestResult(Enum): 28 | FAILED = 0 29 | PASSED = 1 30 | 31 | 32 | class DifferentialTester(EthenoPlugin): 33 | def __init__(self): 34 | self._transactions_by_hash = {} 35 | self._unprocessed_transactions = set() 36 | self.tests = {} 37 | self._printed_summary = False 38 | 39 | def add_test_result(self, result): 40 | if result.test_name not in self.tests: 41 | self.tests[result.test_name] = {} 42 | if result.success not in self.tests[result.test_name]: 43 | self.tests[result.test_name][result.success] = [] 44 | self.tests[result.test_name][result.success].append(result) 45 | 46 | def after_post(self, data, client_results): 47 | method = data["method"] 48 | 49 | # First, see if any of the clients returned an error. If one did, they all should! 50 | clients_with_errors = tuple( 51 | i 52 | for i, result in enumerate(client_results) 53 | if isinstance(result, JSONRPCError) 54 | ) 55 | clients_without_errors = tuple( 56 | sorted( 57 | frozenset(range(len(client_results))) - frozenset(clients_with_errors) 58 | ) 59 | ) 60 | 61 | if clients_with_errors: 62 | clients = [self.etheno.master_client] + self.etheno.clients 63 | if clients_without_errors: 64 | test = DifferentialTest( 65 | self, 66 | "JSON_RPC_ERRORS", 67 | TestResult.FAILED, 68 | "%s executed JSON RPC call %s with no errors, but %s executed the same transaction with errors:\n%s" 69 | % ( 70 | ", ".join( 71 | str(clients[client]) for client in clients_without_errors 72 | ), 73 | data, 74 | ", ".join( 75 | str(clients[client]) for client in clients_with_errors 76 | ), 77 | "\n".join( 78 | str(client_results[client]) 79 | for client in clients_with_errors 80 | ), 81 | ), 82 | ) 83 | else: 84 | test = DifferentialTest( 85 | self, 86 | "JSON_RPC_ERRORS", 87 | TestResult.PASSED, 88 | "All clients executed JSON RPC call %s with errors" % data, 89 | ) 90 | self.add_test_result(test) 91 | self.logger.error(test.message) 92 | return 93 | else: 94 | self.add_test_result( 95 | DifferentialTest( 96 | self, 97 | "JSON_RPC_ERRORS", 98 | TestResult.PASSED, 99 | "All clients executed transaction %s without error" % data, 100 | ) 101 | ) 102 | 103 | master_result = client_results[0] 104 | if method == "eth_sendTransaction" or method == "eth_sendRawTransaction": 105 | if ( 106 | not isinstance(master_result, JSONRPCError) 107 | and "result" in master_result 108 | and master_result["result"] 109 | ): 110 | self._unprocessed_transactions.add(master_result["result"]) 111 | self._transactions_by_hash[master_result["result"]] = data 112 | elif method == "eth_getTransactionReceipt": 113 | if master_result and "result" in master_result and master_result["result"]: 114 | # mark that we have processed the receipt for this transaction: 115 | if data["params"][0] in self._unprocessed_transactions: 116 | self._unprocessed_transactions.remove(data["params"][0]) 117 | 118 | if ( 119 | "contractAddress" in master_result["result"] 120 | and master_result["result"]["contractAddress"] 121 | ): 122 | # the master client created a new contract 123 | # so make sure that all of the other clients did, too 124 | for client, client_data in zip( 125 | self.etheno.clients, client_results[1:] 126 | ): 127 | created = False 128 | try: 129 | created = client_data["result"]["contractAddress"] 130 | except Exception: 131 | pass 132 | if not created: 133 | test = DifferentialTest( 134 | self, 135 | "CONTRACT_CREATION", 136 | TestResult.FAILED, 137 | f"{self.etheno.master_client} created a contract for transaction {data['params'][0]}, but {client} did not", 138 | ) 139 | self.add_test_result(test) 140 | self.logger.error(test.message) 141 | else: 142 | self.add_test_result( 143 | DifferentialTest( 144 | self, 145 | "CONTRACT_CREATION", 146 | TestResult.PASSED, 147 | "client %s transaction %s" 148 | % (client, data["params"][0]), 149 | ) 150 | ) 151 | if ( 152 | "gasUsed" in master_result["result"] 153 | and master_result["result"]["gasUsed"] 154 | ): 155 | # make sure each client used the same amount of gas 156 | master_gas = int(master_result["result"]["gasUsed"], 16) 157 | for client, client_data in zip( 158 | self.etheno.clients, client_results[1:] 159 | ): 160 | gas_used = 0 161 | try: 162 | gas_used = int(client_data["result"]["gasUsed"], 16) 163 | except Exception: 164 | pass 165 | if gas_used != master_gas: 166 | test = DifferentialTest( 167 | self, 168 | "GAS_USAGE", 169 | TestResult.FAILED, 170 | f"""Transaction {data['params'][0]} used: 171 | 172 | {hex(master_gas)} gas in {self.etheno.master_client} but 173 | {hex(gas_used)} gas in {client} 174 | 175 | while mining this transaction: 176 | 177 | {self._transactions_by_hash.get(data['params'][0], 'UNKNOWN TRANSACTION')}""", 178 | ) 179 | self.add_test_result(test) 180 | self.logger.error(test.message) 181 | else: 182 | self.add_test_result( 183 | DifferentialTest( 184 | self, 185 | "GAS_USAGE", 186 | TestResult.PASSED, 187 | "client %s transaction %s used 0x%x gas" 188 | % (client, data["params"][0], gas_used), 189 | ) 190 | ) 191 | 192 | # we have processed this transaction, so no need to keep its original arguments around: 193 | if data["params"][0] in self._transactions_by_hash: 194 | del self._transactions_by_hash[data["params"][0]] 195 | 196 | def finalize(self): 197 | unprocessed = self._unprocessed_transactions 198 | self._unprocessed_transactions = set() 199 | for tx_hash in unprocessed: 200 | self.logger.info( 201 | "Requesting transaction receipt for %s to check differentials..." 202 | % tx_hash 203 | ) 204 | if not isinstance(self.etheno.master_client, SelfPostingClient): 205 | self.logger.warn( 206 | "The DifferentialTester currently only supports master clients that extend from SelfPostingClient, but %s does not; skipping checking transaction(s) %s" 207 | % (self.etheno.master_client, ", ".join(unprocessed)) 208 | ) 209 | return 210 | while True: 211 | receipt = self.etheno.post( 212 | { 213 | "jsonrpc": "2.0", 214 | "method": "eth_getTransactionReceipt", 215 | "params": [tx_hash], 216 | } 217 | ) 218 | # if this post is successful, it will trigger the `after_post` callback above 219 | # where were check for the differentials 220 | if "result" in receipt and receipt["result"]: 221 | break 222 | # The transaction is still pending 223 | time.sleep(3.0) 224 | 225 | def shutdown(self): 226 | # super().shutdown() should automatically call self.finalize() 227 | super().shutdown() 228 | if self.tests and not self._printed_summary: 229 | self._printed_summary = True 230 | ret = "\nDifferential Test Summary:\n\n" 231 | for test in sorted(self.tests): 232 | ret += " %s\n" % test 233 | total = sum(map(len, self.tests[test].values())) 234 | for result in self.tests[test]: 235 | ret += " %s\t%d / %d\n" % ( 236 | result, 237 | len(self.tests[test][result]), 238 | total, 239 | ) 240 | ret += "\n" 241 | self.logger.info(ret) 242 | -------------------------------------------------------------------------------- /etheno/etheno.py: -------------------------------------------------------------------------------- 1 | import pkg_resources 2 | import os 3 | from threading import Thread 4 | from typing import Any, Dict, List, Optional 5 | from werkzeug.serving import make_server 6 | 7 | from flask import Flask, jsonify, request, abort 8 | from flask.views import MethodView 9 | 10 | from . import logger 11 | from . import threadwrapper 12 | from .client import EthenoClient, JSONRPCError, SelfPostingClient 13 | from .utils import format_hex_address 14 | 15 | VERSION: str = pkg_resources.require("etheno")[0].version 16 | VERSION_NAME = f"ToB/v{VERSION}/source/Etheno" 17 | JSONRPC_VERSION = "2.0" 18 | VERSION_ID = 67 19 | 20 | app = Flask(__name__) 21 | 22 | GETH_DEFAULT_RPC_PORT = 8545 23 | ETH_DEFAULT_RPC_PORT = 8545 24 | PARITY_DEFAULT_RPC_PORT = 8545 25 | PYETHAPP_DEFAULT_RPC_PORT = 4000 26 | 27 | 28 | def to_account_address(raw_address: int) -> str: 29 | addr = "%x" % raw_address 30 | return "0x%s%s" % ("0" * (40 - len(addr)), addr) 31 | 32 | 33 | _CONTROLLER = threadwrapper.MainThreadController() 34 | 35 | 36 | class DropPost(RuntimeError): 37 | pass 38 | 39 | 40 | OptionalLogger = Optional[logger.EthenoLogger] 41 | 42 | 43 | class EthenoPlugin: 44 | _etheno: Optional["Etheno"] = None 45 | logger: OptionalLogger = None 46 | 47 | @property 48 | def etheno(self) -> "Etheno": 49 | return self._etheno 50 | 51 | @etheno.setter 52 | def etheno(self, instance: "Etheno"): 53 | if self._etheno is not None: 54 | if instance is None: 55 | self._etheno = None 56 | return 57 | raise ValueError( 58 | "An Etheno plugin can only ever be associated with a single Etheno instance" 59 | ) 60 | self._etheno = instance 61 | self.logger = logger.EthenoLogger( 62 | self.__class__.__name__, parent=self._etheno.logger 63 | ) 64 | 65 | @property 66 | def log_directory(self): 67 | """Returns a log directory that this client can use to save additional files, or None if one is not available""" 68 | if self.logger is None: 69 | return None 70 | else: 71 | return self.logger.directory 72 | 73 | def added(self): 74 | """ 75 | A callback when this plugin is added to an Etheno instance 76 | """ 77 | pass 78 | 79 | def before_post(self, post_data: Dict[str, Any]) -> Optional[Dict[str, Any]]: 80 | """ 81 | A callback when Etheno receives a JSON RPC POST, but before it is processed. 82 | :param post_data: The raw JSON RPC data 83 | :return: the post_data to be used by Etheno (can be modified); if None, the post proceeds as usual and is not 84 | modified; if you want to drop the post, `raise DropPost` 85 | """ 86 | return None 87 | 88 | def after_post(self, post_data: Dict[str, Any], client_results): 89 | """ 90 | A callback when Etheno receives a JSON RPC POST after it is processed by all clients. 91 | :param post_data: The raw JSON RPC data 92 | :param client_results: A lost of the results returned by each client 93 | """ 94 | pass 95 | 96 | def run(self): 97 | """ 98 | A callback when Etheno is running and all other clients and plugins are initialized 99 | """ 100 | pass 101 | 102 | def finalize(self): 103 | """ 104 | Called when an analysis pass should be finalized (e.g., after a Truffle migration completes). 105 | Subclasses implementing this function should support it to be called multiple times in a row. 106 | """ 107 | pass 108 | 109 | def shutdown(self): 110 | """ 111 | Called before Etheno shuts down. 112 | The default implementation calls `finalize()`. 113 | """ 114 | self.finalize() 115 | 116 | 117 | class Etheno: 118 | def __init__(self, master_client: Optional[SelfPostingClient] = None): 119 | self.accounts = [] 120 | self._master_client: Optional[SelfPostingClient] = None 121 | if master_client is None: 122 | self.master_client = None 123 | else: 124 | self.master_client = master_client 125 | self.clients: List[EthenoClient] = [] 126 | self.rpc_client_result = None 127 | self.plugins: List[EthenoPlugin] = [] 128 | self._shutting_down: bool = False 129 | self.logger: logger.EthenoLogger = logger.EthenoLogger("Etheno", logger.INFO) 130 | 131 | @property 132 | def log_level(self) -> int: 133 | return self.logger.log_level 134 | 135 | @log_level.setter 136 | def log_level(self, level: int): 137 | self.logger.log_level = level 138 | 139 | @property 140 | def master_client(self) -> Optional[SelfPostingClient]: 141 | return self._master_client 142 | 143 | @master_client.setter 144 | def master_client(self, client: Optional[SelfPostingClient]): 145 | if client is None: 146 | if self._master_client is not None: 147 | self._master_client.etheno = None 148 | self._master_client = None 149 | return 150 | if not isinstance(client, SelfPostingClient): 151 | raise Exception( 152 | "The master client must be an instance of a SelfPostingClient" 153 | ) 154 | client.etheno = self 155 | self._master_client = client 156 | self.accounts: list[int] = list( 157 | map( 158 | lambda a: int(a, 16), 159 | client.post({"id": 1, "jsonrpc": "2.0", "method": "eth_accounts"})[ 160 | "result" 161 | ], 162 | ) 163 | ) 164 | for client in self.clients: 165 | self._create_accounts(client) 166 | 167 | def estimate_gas(self, transaction) -> Optional[int]: 168 | """ 169 | Estimates the gas cost of a transaction. 170 | Iterates through all clients until it finds a client that is capable of estimating the gas cost without error. 171 | If all clients return an error, this function will return None. 172 | """ 173 | clients = [self.master_client] + [ 174 | client for client in self.clients if hasattr(client, "estimate_gas") 175 | ] # type: ignore 176 | for client in clients: 177 | try: 178 | return client.estimate_gas(transaction) 179 | except JSONRPCError: 180 | continue 181 | return None 182 | 183 | def post(self, data): 184 | self.logger.debug(f"Handling JSON RPC request {data}") 185 | 186 | for plugin in self.plugins: 187 | try: 188 | new_data = plugin.before_post(dict(data)) 189 | if new_data is not None and new_data != data: 190 | self.logger.debug( 191 | f"Incoming JSON RPC request {data} changed by plugin {plugin!r} to {new_data}" 192 | ) 193 | data = new_data 194 | except DropPost: 195 | self.logger.info( 196 | f"Incoming JSON RPC request {data} dropped by plugin {plugin!r}" 197 | ) 198 | 199 | method = data["method"] 200 | args = () 201 | kwargs = {} 202 | if "params" in data: 203 | params = data["params"] 204 | if len(params) == 1 and isinstance(params[0], dict): 205 | kwargs = dict(params[0]) 206 | # handle Python reserved words: 207 | if "from" in kwargs: 208 | kwargs["from_addr"] = kwargs["from"] 209 | del kwargs["from"] 210 | else: 211 | args = data["params"] 212 | 213 | if self.master_client is None: 214 | ret = None 215 | else: 216 | if method == "eth_getTransactionReceipt": 217 | # for eth_getTransactionReceipt, make sure we block until all clients have mined the transaction 218 | ret = self.master_client.wait_for_transaction(data["params"][0]) 219 | if "id" in data and "id" in ret: 220 | ret["id"] = data["id"] 221 | else: 222 | try: 223 | ret = self.master_client.post(data) 224 | except JSONRPCError as e: 225 | self.logger.error(e) 226 | ret = e 227 | 228 | self.rpc_client_result = ret 229 | self.logger.debug( 230 | f"Result from the master client ({self.master_client}): {ret}" 231 | ) 232 | 233 | results = [] 234 | 235 | for client in self.clients: 236 | try: 237 | if hasattr(client, method): 238 | self.logger.info( 239 | "Enrobing JSON RPC call to %s.%s" % (client, method) 240 | ) 241 | function = getattr(client, method) 242 | if function is not None: 243 | kwargs["rpc_client_result"] = ret 244 | results.append(function(*args, **kwargs)) 245 | else: 246 | self.logger.warn(f"Function {method} of {client} is None!") 247 | results.append(None) 248 | elif isinstance(client, SelfPostingClient): 249 | if method == "eth_getTransactionReceipt": 250 | # for eth_getTransactionReceipt, make sure we block until all clients have mined the transaction 251 | results.append(client.wait_for_transaction(data["params"][0])) 252 | else: 253 | results.append(client.post(data)) 254 | else: 255 | results.append(None) 256 | except JSONRPCError as e: 257 | self.logger.error(e) 258 | results.append(e) 259 | self.logger.debug(f"Result from client {client}: {results[-1]}") 260 | 261 | if ret is None: 262 | return None 263 | 264 | results = [ret] + results 265 | for plugin in self.plugins: 266 | plugin.after_post(data, results) 267 | 268 | return ret 269 | 270 | def add_plugin(self, plugin: EthenoPlugin): 271 | plugin.etheno = self 272 | self.plugins.append(plugin) 273 | plugin.added() 274 | 275 | def remove_plugin(self, plugin: EthenoPlugin): 276 | """Removes a plugin, automatically calling plugin.shutdown() in the process 277 | 278 | :param plugin: The plugin to remove 279 | """ 280 | self.plugins.remove(plugin) 281 | plugin.shutdown() 282 | plugin.etheno = None 283 | 284 | def _create_accounts(self, client): 285 | for account in self.accounts: 286 | # TODO: Actually get the correct balance from the JSON RPC client instead of using hard-coded 100.0 ETH 287 | client.create_account(balance=int(100.0 * 10**18), address=account) 288 | 289 | def add_client(self, client: EthenoClient): 290 | client.etheno = self 291 | self.clients.append(client) 292 | self._create_accounts(client) 293 | 294 | def deploy_contract( 295 | self, from_address, bytecode, gas=0x99999, gas_price=None, value=0 296 | ) -> Optional[int]: 297 | if gas_price is None: 298 | gas_price = self.master_client.get_gas_price() 299 | if isinstance(bytecode, bytes): 300 | bytecode = bytecode.decode() 301 | if not bytecode.startswith("0x"): 302 | bytecode = "0x%s" % bytecode 303 | tx_hash = self.post( 304 | { 305 | "id": 1, 306 | "jsonrpc": "2.0", 307 | "method": "eth_sendTransaction", 308 | "params": [ 309 | { 310 | "from": format_hex_address(from_address, True), 311 | "gas": "0x%x" % gas, 312 | "gasPrice": "0x%x" % gas_price, 313 | "value": "0x0", 314 | "data": bytecode, 315 | } 316 | ], 317 | } 318 | )["result"] 319 | receipt = self.master_client.wait_for_transaction(tx_hash) 320 | if ( 321 | "result" in receipt 322 | and receipt["result"] 323 | and "contractAddress" in receipt["result"] 324 | and receipt["result"]["contractAddress"] 325 | ): 326 | return int(receipt["result"]["contractAddress"], 16) 327 | else: 328 | return None 329 | 330 | def get_transaction_receipt_request(self, tx_hash: str) -> Dict: 331 | """ 332 | Takes in a transaction hash and returns the request object for an eth_getTransactionReceipt API call 333 | """ 334 | return { 335 | "id": 1, 336 | "jsonrpc": "2.0", 337 | "method": "eth_getTransactionReceipt", 338 | "params": [tx_hash], 339 | } 340 | 341 | def shutdown(self, port: int = GETH_DEFAULT_RPC_PORT): 342 | if self._shutting_down: 343 | return 344 | self._shutting_down = True 345 | for plugin in self.plugins: 346 | plugin.shutdown() 347 | # Send a web request to the server to shut down: 348 | if self.master_client: 349 | self.master_client.shutdown() 350 | for client in self.clients: 351 | client.shutdown() 352 | self.logger.close() 353 | _CONTROLLER.quit() 354 | 355 | def run(self, debug=True, run_publicly=False, port=GETH_DEFAULT_RPC_PORT): 356 | # Manticore only works in the main thread, so use a threadsafe wrapper: 357 | def server_thread(): 358 | IS_DOCKER = os.environ.get("DOCKER", 0) 359 | if run_publicly or IS_DOCKER: 360 | host = "0.0.0.0" 361 | else: 362 | host = "127.0.0.1" 363 | # Do not use the reloader, because Flask needs to run in the main thread to use the reloader 364 | server = make_server(host=host, port=port, app=app, threaded=True) 365 | return server 366 | # app.run(debug=debug, host=host, port=port, use_reloader=False) 367 | 368 | server = server_thread() 369 | thread = Thread(target=server.serve_forever) 370 | thread.start() 371 | self.logger.info("Etheno v%s" % VERSION) 372 | 373 | for plugin in self.plugins: 374 | plugin.run() 375 | 376 | _CONTROLLER.run() 377 | self.shutdown() 378 | self.logger.info("Shutting Etheno down") 379 | server.shutdown() 380 | thread.join() 381 | 382 | 383 | ETHENO = Etheno() 384 | 385 | 386 | class EthenoView(MethodView): 387 | def post(self): 388 | data = request.get_json() 389 | was_list = False 390 | 391 | if isinstance(data, list): 392 | if len(data) == 1: 393 | was_list = True 394 | data = data[0] 395 | else: 396 | ETHENO.logger.error("Unexpected POST data: %s" % data) 397 | abort(400) 398 | 399 | if "jsonrpc" not in data or "method" not in data: 400 | abort(400) 401 | try: 402 | jsonrpc_version = float(data["jsonrpc"]) 403 | except ValueError: 404 | abort(400) 405 | if jsonrpc_version < 2.0: 406 | abort(426) 407 | elif jsonrpc_version > 2.0: 408 | ETHENO.logger.warn( 409 | f"Client is using a newer version of the JSONRPC protocol! Expected 2.0, but got {jsonrpc_version}" 410 | ) 411 | 412 | ret = ETHENO.post(data) 413 | 414 | ETHENO.logger.debug(f"Returning {ret}") 415 | 416 | if ret is None: 417 | return None 418 | 419 | if isinstance(ret, JSONRPCError): 420 | ret = ret.result 421 | 422 | if was_list: 423 | ret = [ret] 424 | ret = jsonify(ret) 425 | 426 | return ret 427 | -------------------------------------------------------------------------------- /etheno/ganache.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import atexit 4 | import shlex 5 | import shutil 6 | import subprocess 7 | import time 8 | 9 | from .client import RpcHttpProxy, SelfPostingClient 10 | from .logger import PtyLogger 11 | from .utils import is_port_free 12 | from .etheno import ETHENO 13 | 14 | 15 | class Ganache(RpcHttpProxy): 16 | def __init__(self, cmd=None, args=None, port=8546): 17 | super().__init__("http://127.0.0.1:%d/" % port) 18 | self.port = port 19 | if cmd is not None: 20 | cmd = shlex.split(cmd) 21 | else: 22 | cmd = ["/usr/bin/env", "ganache"] 23 | if args is None: 24 | args = [] 25 | self.args = ( 26 | cmd + ["-d", "-p", str(port), "--chain.allowUnlimitedContractSize"] + args 27 | ) 28 | self.ganache = None 29 | self._client = None 30 | 31 | def start(self): 32 | if self.ganache: 33 | return 34 | if shutil.which("ganache") is None: 35 | raise ValueError( 36 | "`ganache` is not installed! Install it by running `npm -g i ganache`" 37 | ) 38 | if self._client: 39 | self.ganache = PtyLogger(self._client.logger, self.args) 40 | self.ganache.start() 41 | 42 | def ganache_errored() -> int: 43 | if self.ganache.is_done(): 44 | return self.ganache.exitstatus 45 | return 0 46 | 47 | else: 48 | ETHENO.logger.debug(f"Running ganache: {self.args}") 49 | self.ganache = subprocess.Popen( 50 | self.args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1 51 | ) 52 | 53 | def ganache_errored(): 54 | try: 55 | return self.ganache.wait(0.5) 56 | except TimeoutError: 57 | return 0 58 | 59 | atexit.register(Ganache.stop.__get__(self, Ganache)) 60 | # wait until Ganache has started listening: 61 | while is_port_free(self.port) and not self.ganache.is_done(): 62 | time.sleep(0.25) 63 | retcode = ganache_errored() 64 | if retcode != 0: 65 | raise RuntimeError( 66 | f"{' '.join(self.args)} exited with non-zero status {retcode}" 67 | ) 68 | 69 | def post(self, data): 70 | if self.ganache is None: 71 | self.start() 72 | return super().post(data) 73 | 74 | def stop(self): 75 | if self.ganache is not None: 76 | ganache = self.ganache 77 | self.ganache = None 78 | ganache.terminate() 79 | ganache.wait() 80 | if isinstance(ganache, PtyLogger): 81 | ganache.close() 82 | 83 | 84 | if __name__ == "__main__": 85 | ganache = Ganache() 86 | ganache.start() 87 | 88 | 89 | class GanacheClient(SelfPostingClient): 90 | def __init__(self, ganache_instance): 91 | super().__init__(ganache_instance) 92 | ganache_instance._client = self 93 | self.short_name = "Ganache@%d" % ganache_instance.port 94 | 95 | def wait_until_running(self): 96 | while is_port_free(self.client.port): 97 | time.sleep(0.25) 98 | 99 | def shutdown(self): 100 | self.client.stop() 101 | -------------------------------------------------------------------------------- /etheno/genesis.py: -------------------------------------------------------------------------------- 1 | from web3.auto import w3 2 | 3 | from .utils import format_hex_address 4 | 5 | 6 | class Account(object): 7 | def __init__(self, address, balance=None, private_key=None): 8 | self._address = address 9 | self.balance = balance 10 | self._private_key = private_key 11 | 12 | @property 13 | def address(self): 14 | return self._address 15 | 16 | @property 17 | def private_key(self): 18 | return self._private_key 19 | 20 | 21 | def make_genesis( 22 | network_id=0x657468656E6F, 23 | difficulty=20, 24 | gas_limit=200000000000, 25 | accounts=None, 26 | byzantium_block=0, 27 | dao_fork_block=0, 28 | homestead_block=0, 29 | eip150_block=0, 30 | eip155_block=0, 31 | eip158_block=0, 32 | constantinople_block=None, 33 | ): 34 | if accounts: 35 | alloc = { 36 | format_hex_address(acct.address): { 37 | "balance": "%d" % acct.balance, 38 | "privateKey": format_hex_address(acct.private_key), 39 | } 40 | for acct in accounts 41 | } 42 | else: 43 | alloc = {} 44 | 45 | ret = { 46 | "config": { 47 | "chainId": network_id, 48 | "byzantiumBlock": byzantium_block, 49 | "daoForkBlock": dao_fork_block, 50 | "homesteadBlock": homestead_block, 51 | "eip150Block": eip150_block, 52 | "eip155Block": eip155_block, 53 | "eip158Block": eip158_block, 54 | }, 55 | "difficulty": "%d" % difficulty, 56 | "gasLimit": "%d" % gas_limit, 57 | "alloc": alloc, 58 | } 59 | 60 | if constantinople_block is not None: 61 | ret["config"]["constantinopleBlock"] = constantinople_block 62 | 63 | return ret 64 | 65 | 66 | def geth_to_parity(genesis): 67 | """Converts a Geth style genesis to Parity style""" 68 | ret = { 69 | "name": "etheno", 70 | "engine": { 71 | "instantSeal": None, 72 | # 'Ethash': { 73 | # 'params': { 74 | # 'minimumDifficulty': "0x%s" % genesis['difficulty'], 75 | # 'difficultyBoundDivisor': '0x100000000', 76 | # 'homesteadTransition': 0, 77 | # 'eip150Transition': 0, 78 | # 'eip160Transition': 0, 79 | # 'eip161abcTransition': 0, 80 | # 'eip161dTransition': 0, 81 | # } 82 | # } 83 | }, 84 | "genesis": { 85 | "seal": { 86 | "generic": "0x0" 87 | # 'ethereum': { 88 | # 'nonce': '0x0000000000000042', 89 | # 'mixHash': '0x0000000000000000000000000000000000000000000000000000000000000000' 90 | # } 91 | }, 92 | "difficulty": "0x%s" % genesis["difficulty"], 93 | "gasLimit": "0x%s" % genesis["gasLimit"], 94 | "author": list(genesis["alloc"])[-1], 95 | }, 96 | "params": { 97 | "networkID": "0x%x" % genesis["config"]["chainId"], 98 | "maximumExtraDataSize": "0x20", 99 | "minGasLimit": "0x%s" % genesis["gasLimit"], 100 | "gasLimitBoundDivisor": "1", 101 | "eip150Transition": "0x%x" % genesis["config"]["eip150Block"], 102 | "eip160Transition": "0x0", 103 | "eip161abcTransition": "0x0", 104 | "eip161dTransition": "0x0", 105 | "eip155Transition": "0x%x" % genesis["config"]["eip155Block"], 106 | "eip98Transition": "0x7fffffffffffff", 107 | # 'eip86Transition': '0x7fffffffffffff', 108 | "maxCodeSize": 24576, 109 | "maxCodeSizeTransition": "0x0", 110 | "eip140Transition": "0x0", 111 | "eip211Transition": "0x0", 112 | "eip214Transition": "0x0", 113 | "eip658Transition": "0x0", 114 | "wasmActivationTransition": "0x0", 115 | }, 116 | "accounts": dict(genesis["alloc"]), 117 | } 118 | 119 | if "constantinopleBlock" in genesis["config"]: 120 | block = "0x%x" % genesis["config"]["constantinopleBlock"] 121 | ret["params"]["eip145Transition"] = block 122 | ret["params"]["eip1014Transition"] = block 123 | ret["params"]["eip1052Transition"] = block 124 | 125 | return ret 126 | 127 | 128 | DEFAULT_PRIVATE_KEYS = [ 129 | 0xF2F48EE19680706196E2E339E5DA3491186E0C4C5030670656B0E0164837257D, 130 | 0x5D862464FE9303452126C8BC94274B8C5F9874CBD219789B3EB2128075A76F72, 131 | 0xDF02719C4DF8B9B8AC7F551FCB5D9EF48FA27EEF7A66453879F4D8FDC6E78FB1, 132 | 0xFF12E391B79415E941A94DE3BF3A9AEE577AED0731E297D5CFA0B8A1E02FA1D0, 133 | 0x752DD9CF65E68CFABA7D60225CBDBC1F4729DD5E5507DEF72815ED0D8ABC6249, 134 | 0xEFB595A0178EB79A8DF953F87C5148402A224CDF725E88C0146727C6ACEADCCD, 135 | 0x83C6D2CC5DDCF9711A6D59B417DC20EB48AFD58D45290099E5987E3D768F328F, 136 | 0xBB2D3F7C9583780A7D3904A2F55D792707C345F21DE1BACB2D389934D82796B2, 137 | 0xB2FD4D29C1390B71B8795AE81196BFD60293ADF99F9D32A0AFF06288FCDAC55F, 138 | 0x23CB7121166B9A2F93AE0B7C05BDE02EAE50D64449B2CBB42BC84E9D38D6CC89, 139 | ] 140 | 141 | 142 | def make_accounts(num_accounts, default_balance=None): 143 | ret = [] 144 | if num_accounts > len(DEFAULT_PRIVATE_KEYS): 145 | raise Exception("TODO: Too many accounts") 146 | for i in range(num_accounts): 147 | acct = w3.eth.account.from_key(DEFAULT_PRIVATE_KEYS[i]) 148 | ret.append( 149 | Account( 150 | address=int(acct.address, 16), 151 | private_key=int(acct.privateKey.hex(), 16), 152 | balance=default_balance, 153 | ) 154 | ) 155 | return ret 156 | -------------------------------------------------------------------------------- /etheno/geth.py: -------------------------------------------------------------------------------- 1 | import atexit 2 | import os 3 | import subprocess 4 | import time 5 | 6 | from . import logger 7 | from .client import JSONRPCError 8 | from .jsonrpcclient import JSONRPCClient 9 | from .utils import format_hex_address 10 | 11 | 12 | def ltrim_ansi(text): 13 | if text.startswith(logger.ANSI_RESET): 14 | return ltrim_ansi(text[len(logger.ANSI_RESET) :]) 15 | elif text.startswith(logger.ANSI_BOLD): 16 | return ltrim_ansi(text[len(logger.ANSI_BOLD) :]) 17 | for color in logger.CGAColors: 18 | ansi = logger.ANSI_COLOR % (30 + color.value) 19 | if text.startswith(ansi): 20 | return ltrim_ansi(text[len(ansi) :]) 21 | for color in logger.CGAColors: 22 | ansi = f"\033[{30 + color.value}m" 23 | if text.startswith(ansi): 24 | return ltrim_ansi(text[len(ansi) :]) 25 | return text 26 | 27 | 28 | class GethClient(JSONRPCClient): 29 | def __init__(self, genesis, port=8546): 30 | super().__init__("Geth", genesis, port) 31 | atexit.register(GethClient.shutdown.__get__(self, GethClient)) 32 | 33 | def initialized(self): 34 | def log(logger, message): 35 | msg = ltrim_ansi(message) 36 | if msg.startswith("ERROR"): 37 | logger.error(msg[5:].lstrip()) 38 | elif msg.startswith("WARNING"): 39 | logger.warning(msg[7:].lstrip()) 40 | elif msg.startswith("WARN"): 41 | logger.warning(msg[4:].lstrip()) 42 | elif msg.startswith("DEBUG"): 43 | logger.debug(msg[5:].lstrip()) 44 | elif msg.startswith("INFO"): 45 | logger.info(msg[4:].lstrip()) 46 | else: 47 | logger.info(message) 48 | 49 | self.instance.log = log 50 | 51 | def etheno_set(self): 52 | super().etheno_set() 53 | try: 54 | args = [ 55 | "/usr/bin/env", 56 | "geth", 57 | "init", 58 | self.logger.to_log_path(self.genesis_file), 59 | "--datadir", 60 | self.logger.to_log_path(self.datadir), 61 | ] 62 | self.add_to_run_script(args) 63 | subprocess.check_call( 64 | args, 65 | stdout=subprocess.DEVNULL, 66 | stderr=subprocess.DEVNULL, 67 | cwd=self.log_directory, 68 | ) 69 | except Exception as e: 70 | self.cleanup() 71 | raise e 72 | 73 | def import_account(self, private_key): 74 | content = format_hex_address(private_key).encode("utf-8") + bytes([ord("\n")]) 75 | import_dir = os.path.join(self.log_directory, "private_keys") 76 | keyfile = self.logger.make_constant_logged_file( 77 | content, prefix="private", suffix=".key", dir=import_dir 78 | ) 79 | while True: 80 | args = [ 81 | "/usr/bin/env", 82 | "geth", 83 | "account", 84 | "import", 85 | "--datadir", 86 | self.logger.to_log_path(self.datadir), 87 | "--password", 88 | self.logger.to_log_path(self.passwords), 89 | self.logger.to_log_path(keyfile), 90 | ] 91 | self.add_to_run_script(args) 92 | geth = subprocess.Popen( 93 | args, 94 | stdout=subprocess.PIPE, 95 | stderr=subprocess.PIPE, 96 | cwd=self.log_directory, 97 | ) 98 | if geth.wait() == 0: 99 | return 100 | # This sometimes happens with geth, I have no idea why, so just try again 101 | 102 | def post(self, data): 103 | # geth takes a while to unlock all of the accounts, so check to see if that caused an error and just wait a bit 104 | while True: 105 | try: 106 | return super().post(data) 107 | except JSONRPCError as e: 108 | if ( 109 | e.result["error"]["code"] == -32000 110 | and "authentication needed" in e.result["error"]["message"] 111 | ): 112 | self.logger.info( 113 | "Waiting for Geth to finish unlocking our accounts..." 114 | ) 115 | time.sleep(3.0) 116 | else: 117 | raise e 118 | 119 | def get_start_command(self, unlock_accounts=True): 120 | if self.logger.log_level == logger.CRITICAL: 121 | verbosity = 0 122 | elif self.logger.log_level == logger.ERROR: 123 | verbosity = 1 124 | elif self.logger.log_level == logger.WARNING: 125 | verbosity = 2 126 | elif self.logger.log_level == logger.DEBUG: 127 | verbosity = 3 128 | else: 129 | verbosity = 4 130 | base_args = [ 131 | "/usr/bin/env", 132 | "geth", 133 | "--nodiscover", 134 | "--rpc", 135 | "--rpcport", 136 | "%d" % self.port, 137 | "--networkid", 138 | "%d" % self.genesis["config"]["chainId"], 139 | "--datadir", 140 | self.logger.to_log_path(self.datadir), 141 | "--mine", 142 | "--etherbase", 143 | format_hex_address(self.miner_account.address), 144 | f"--verbosity={verbosity}", 145 | "--minerthreads=1", 146 | ] 147 | if unlock_accounts: 148 | addresses = filter( 149 | lambda a: a != format_hex_address(self.miner_account.address), 150 | map(format_hex_address, self.genesis["alloc"]), 151 | ) 152 | unlock_args = [ 153 | "--unlock", 154 | ",".join(addresses), 155 | "--password", 156 | self.passwords, 157 | ] 158 | else: 159 | unlock_args = [] 160 | return base_args + unlock_args 161 | -------------------------------------------------------------------------------- /etheno/jsonrpc.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import Dict, TextIO, Union 3 | 4 | from .etheno import EthenoPlugin 5 | from .utils import format_hex_address 6 | from .client import JSONRPCError 7 | 8 | # source: https://ethereum.stackexchange.com/a/83855 9 | import rlp 10 | from eth_typing import HexStr 11 | from eth_utils import keccak, to_bytes 12 | from rlp.sedes import Binary, big_endian_int, binary 13 | from web3 import Web3 14 | from web3.auto import w3 15 | 16 | 17 | class Transaction(rlp.Serializable): 18 | fields = [ 19 | ("nonce", big_endian_int), 20 | ("gas_price", big_endian_int), 21 | ("gas", big_endian_int), 22 | ("to", Binary.fixed_length(20, allow_empty=True)), 23 | ("value", big_endian_int), 24 | ("data", binary), 25 | ("v", big_endian_int), 26 | ("r", big_endian_int), 27 | ("s", big_endian_int), 28 | ] 29 | 30 | 31 | def hex_to_bytes(data: str) -> bytes: 32 | return to_bytes(hexstr=HexStr(data)) 33 | 34 | 35 | def decode_raw_tx(raw_tx: str): 36 | tx_bytes = hex_to_bytes(raw_tx) 37 | tx = rlp.decode(tx_bytes, Transaction) 38 | hash_tx = Web3.toHex(keccak(tx_bytes)) 39 | from_ = w3.eth.account.recover_transaction(raw_tx) 40 | to = w3.toChecksumAddress(tx.to) if tx.to else None 41 | data = w3.toHex(tx.data) 42 | r = hex(tx.r) 43 | s = hex(tx.s) 44 | chain_id = (tx.v - 35) // 2 if tx.v % 2 else (tx.v - 36) // 2 45 | return { 46 | "txHash": hash_tx, 47 | "from": from_, 48 | "to": to, 49 | "nonce": tx.nonce, 50 | "gas": hex(tx.gas), 51 | "gasPrice": hex(tx.gas_price), 52 | "value": hex(tx.value), 53 | "data": data, 54 | "chainId": chain_id, 55 | "r": r, 56 | "s": s, 57 | "v": tx.v, 58 | } 59 | 60 | 61 | class JSONExporter: 62 | def __init__(self, out_stream: Union[str, TextIO]): 63 | self._was_path = isinstance(out_stream, str) 64 | if self._was_path: 65 | self.output = open(out_stream, "w", encoding="utf8") 66 | else: 67 | self.output = out_stream 68 | self.output.write("[") 69 | self._count = 0 70 | self._finalized = False 71 | 72 | def finalize(self): 73 | if self._finalized: 74 | return 75 | if self._count: 76 | self.output.write("\n") 77 | self.output.write("]") 78 | self.output.flush() 79 | if self._was_path: 80 | self.output.close() 81 | self._finalized = True 82 | 83 | def write_entry(self, entry): 84 | if self._finalized: 85 | return 86 | if self._count > 0: 87 | self.output.write(",") 88 | self._count += 1 89 | self.output.write("\n") 90 | json.dump(entry, self.output) 91 | self.output.flush() 92 | 93 | 94 | class JSONRPCExportPlugin(EthenoPlugin): 95 | def __init__(self, out_stream: Union[str, TextIO]): 96 | self._exporter = JSONExporter(out_stream) 97 | 98 | def after_post(self, post_data, client_results): 99 | self._exporter.write_entry([post_data, client_results]) 100 | 101 | def finalize(self): 102 | self._exporter.finalize() 103 | if hasattr(self._exporter.output, "name"): 104 | self.logger.info( 105 | f"Raw JSON RPC messages dumped to {self._exporter.output.name}" 106 | ) 107 | 108 | 109 | class EventSummaryPlugin(EthenoPlugin): 110 | def __init__(self): 111 | self._transactions: Dict[ 112 | int, Dict[str, object] 113 | ] = {} # Maps transaction hashes to their eth_sendTransaction arguments 114 | 115 | def handle_contract_created( 116 | self, 117 | creator_address: str, 118 | contract_address: str, 119 | gas_used: str, 120 | gas_price: str, 121 | data: str, 122 | value: str, 123 | ): 124 | self.logger.info( 125 | f"Contract created at {contract_address} with {(len(data)-2)//2} bytes of data by account {creator_address} for {gas_used} gas with a gas price of {gas_price}" 126 | ) 127 | 128 | def handle_function_call( 129 | self, 130 | from_address: str, 131 | to_address: str, 132 | gas_used: str, 133 | gas_price: str, 134 | data: str, 135 | value: str, 136 | ): 137 | self.logger.info( 138 | f"Function call with {value} wei from {from_address} to {to_address} with {(len(data)-2)//2} bytes of data for {gas_used} gas with a gas price of {gas_price}" 139 | ) 140 | 141 | def handle_unlogged_transactions(self): 142 | unlogged_transactions = dict( 143 | filter(lambda txn: txn[1]["is_logged"] == False, self._transactions.items()) 144 | ) 145 | for (tx_hash, txn) in unlogged_transactions.items(): 146 | post_data = self._etheno.get_transaction_receipt_request(tx_hash) 147 | self._etheno.post(post_data) 148 | 149 | def after_post(self, post_data, result): 150 | if len(result): 151 | result = result[0] 152 | if "method" not in post_data: 153 | return 154 | # Fixes bug that occurs when a JSONRPCError is attempted to be logged 155 | if isinstance(result, JSONRPCError): 156 | self.logger.info( 157 | f"Received a JSON RPC Error when logging transaction...skipping event logging" 158 | ) 159 | return 160 | 161 | elif ( 162 | post_data["method"] == "eth_sendTransaction" 163 | or post_data["method"] == "eth_sendRawTransaction" 164 | ) and "result" in result: 165 | transaction_hash = result["result"] 166 | # Add a boolean to check at shutdown whether everything has been logged. 167 | if post_data["method"] == "eth_sendRawTransaction": 168 | self._transactions[transaction_hash] = { 169 | "transaction": decode_raw_tx(post_data["params"][0]), 170 | "is_logged": False, 171 | } 172 | else: 173 | self._transactions[transaction_hash] = { 174 | "transaction": post_data["params"][0], 175 | "is_logged": False, 176 | } 177 | elif post_data["method"] == "evm_mine": 178 | self.handle_increase_block_number() 179 | elif post_data["method"] == "evm_increaseTime": 180 | self.handle_increase_block_timestamp(post_data["params"][0]) 181 | elif post_data["method"] == "eth_getTransactionReceipt": 182 | transaction_hash = post_data["params"][0] 183 | if transaction_hash not in self._transactions: 184 | self.logger.error( 185 | f'Received transaction receipt {result} for unknown transaction hash {post_data["params"][0]}' 186 | ) 187 | return 188 | (original_transaction, is_logged) = ( 189 | self._transactions[transaction_hash]["transaction"], 190 | self._transactions[transaction_hash]["is_logged"], 191 | ) 192 | # Check if it was logged already 193 | if is_logged: 194 | self.logger.debug( 195 | f"Transaction hash {transaction_hash} has already been logged. This should not happen." 196 | ) 197 | return 198 | if ( 199 | "value" not in original_transaction 200 | or original_transaction["value"] is None 201 | ): 202 | value = "0x0" 203 | else: 204 | value = original_transaction["value"] 205 | if "to" not in result["result"] or result["result"]["to"] is None: 206 | # this transaction is creating a contract: 207 | # TODO: key errors are likely here...need to figure out a better way to do error handling 208 | # TODO: log a warning about non-zero ether values 209 | contract_address = result["result"]["contractAddress"] 210 | self.handle_contract_created( 211 | original_transaction["from"], 212 | contract_address, 213 | result["result"]["gasUsed"], 214 | result["result"]["effectiveGasPrice"], 215 | original_transaction["data"], 216 | value, 217 | ) 218 | else: 219 | self.handle_function_call( 220 | original_transaction["from"], 221 | original_transaction["to"], 222 | result["result"]["gasUsed"], 223 | result["result"]["effectiveGasPrice"], 224 | original_transaction["data"] 225 | if "data" in original_transaction 226 | else "0x", 227 | value, 228 | ) 229 | # Transaction has been logged successfully 230 | self._transactions[transaction_hash]["is_logged"] = True 231 | 232 | 233 | class EventSummaryExportPlugin(EventSummaryPlugin): 234 | def __init__(self, out_stream: Union[str, TextIO]): 235 | super().__init__() 236 | self._exporter = JSONExporter(out_stream) 237 | 238 | def run(self): 239 | for address in self.etheno.accounts: 240 | self._exporter.write_entry( 241 | {"event": "AccountCreated", "address": format_hex_address(address)} 242 | ) 243 | super().run() 244 | 245 | def handle_increase_block_number(self): 246 | self._exporter.write_entry( 247 | {"event": "BlockMined", "number_increment": "1", "timestamp_increment": "0"} 248 | ) 249 | 250 | def handle_increase_block_timestamp(self, number: str): 251 | self._exporter.write_entry( 252 | { 253 | "event": "BlockMined", 254 | "number_increment": "0", 255 | "timestamp_increment": str(number), 256 | } 257 | ) 258 | 259 | def handle_contract_created( 260 | self, 261 | creator_address: str, 262 | contract_address: str, 263 | gas_used: str, 264 | gas_price: str, 265 | data: str, 266 | value: str, 267 | ): 268 | self._exporter.write_entry( 269 | { 270 | "event": "ContractCreated", 271 | "from": creator_address, 272 | "contract_address": contract_address, 273 | "gas_used": gas_used, 274 | "gas_price": gas_price, 275 | "data": data, 276 | "value": value, 277 | } 278 | ) 279 | super().handle_contract_created( 280 | creator_address, contract_address, gas_used, gas_price, data, value 281 | ) 282 | 283 | def handle_function_call( 284 | self, 285 | from_address: str, 286 | to_address: str, 287 | gas_used: str, 288 | gas_price: str, 289 | data: str, 290 | value: str, 291 | ): 292 | self._exporter.write_entry( 293 | { 294 | "event": "FunctionCall", 295 | "from": from_address, 296 | "to": to_address, 297 | "gas_used": gas_used, 298 | "gas_price": gas_price, 299 | "data": data, 300 | "value": value, 301 | } 302 | ) 303 | super().handle_function_call( 304 | from_address, to_address, gas_used, gas_price, data, value 305 | ) 306 | 307 | def finalize(self): 308 | super().handle_unlogged_transactions() 309 | self._exporter.finalize() 310 | if hasattr(self._exporter.output, "name"): 311 | self.logger.info( 312 | f"Event summary JSON saved to {self._exporter.output.name}" 313 | ) 314 | -------------------------------------------------------------------------------- /etheno/jsonrpcclient.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Sequence 2 | import copy 3 | import json 4 | import os 5 | 6 | from .client import RpcProxyClient 7 | from .genesis import make_accounts 8 | from .logger import PtyLogger 9 | from .utils import format_hex_address, is_port_free 10 | 11 | 12 | class JSONRPCClient(RpcProxyClient): 13 | def __init__(self, name, genesis, port=8546): 14 | super().__init__("http://localhost:%d/" % port) 15 | self._basename = name 16 | self.short_name = "%s@%d" % (name, port) 17 | self.port = port 18 | self.genesis = copy.deepcopy(genesis) 19 | self.miner_account = make_accounts(1)[0] 20 | self.genesis["alloc"][format_hex_address(self.miner_account.address)] = { 21 | "balance": "0", 22 | "privateKey": format_hex_address(self.miner_account.private_key), 23 | } 24 | self._accounts = [] 25 | self._created_address_index = -1 26 | self._runscript = [] 27 | # These are set in self.etheno_set(): 28 | self.genesis_file = None 29 | self.passwords = None 30 | self.datadir = None 31 | # This is set when self.start() is called: 32 | self.instance = None 33 | 34 | def write_genesis(self, outfile): 35 | outfile.write(json.dumps(self.genesis).encode("utf-8")) 36 | 37 | def write_passwords(self, outfile): 38 | for i in range(len(self.genesis["alloc"])): 39 | outfile.write(b"etheno\n") 40 | 41 | def etheno_set(self): 42 | super().etheno_set() 43 | self.datadir = os.path.join(self.log_directory, "chain_data") 44 | os.makedirs(self.datadir) 45 | with self.logger.make_logged_file( 46 | prefix="genesis", suffix=".json" 47 | ) as genesis_output: 48 | self.genesis_file = genesis_output.name 49 | self.write_genesis(genesis_output) 50 | genesis_output.close() 51 | with self.logger.make_logged_file( 52 | prefix=self._basename, suffix=".passwd" 53 | ) as password_output: 54 | self.passwords = password_output.name 55 | self.write_passwords(password_output) 56 | 57 | def add_to_run_script(self, command): 58 | if isinstance(command, Sequence): 59 | command = " ".join(command) 60 | self._runscript.append(command) 61 | 62 | def import_account(self, private_key): 63 | raise NotImplementedError() 64 | 65 | @property 66 | def accounts(self): 67 | for addr, bal in self.genesis["alloc"].items(): 68 | yield int(addr, 16) 69 | 70 | def create_account(self, balance: int = 0, address=None): 71 | accounts = list(self.accounts) 72 | if address is None: 73 | self._created_address_index += 1 74 | if self._created_address_index >= len(accounts): 75 | raise Exception( 76 | "Ran out of %s genesis accounts and could not create a new one!" 77 | % self.short_name 78 | ) 79 | return accounts[self._created_address_index] 80 | elif address not in accounts: 81 | valid_accounts = "\n".join(map(hex, accounts)) 82 | raise ValueError( 83 | f"Account {address!s} did not exist in the genesis for client {self.short_name}! " 84 | f"Valid accounts:\n{valid_accounts}" 85 | ) 86 | else: 87 | return address 88 | 89 | def get_start_command(self, unlock_accounts=True): 90 | raise NotImplementedError() 91 | 92 | def save_run_script(self): 93 | run_script = os.path.join( 94 | self.log_directory, "run_%s.sh" % self._basename.lower() 95 | ) 96 | with open(run_script, "w") as f: 97 | script = "\n".join(self._runscript) 98 | f.write(script) 99 | # make the script executable: 100 | os.chmod(run_script, 0o755) 101 | 102 | def start(self, unlock_accounts=True): 103 | start_args = self.get_start_command(unlock_accounts) 104 | self.instance = PtyLogger(self.logger, start_args, cwd=self.log_directory) 105 | if self.log_directory: 106 | self.add_to_run_script(start_args) 107 | self.save_run_script() 108 | self.initialized() 109 | self.instance.start() 110 | self.wait_until_running() 111 | 112 | def initialized(self): 113 | """Called once the client is completely intialized but before it is started""" 114 | pass 115 | 116 | def is_running(self): 117 | return not is_port_free(self.port) 118 | 119 | def stop(self): 120 | if self.instance is not None: 121 | instance = self.instance 122 | self.instance = None 123 | instance.terminate() 124 | instance.wait() 125 | instance.close() 126 | 127 | def shutdown(self): 128 | self.stop() 129 | -------------------------------------------------------------------------------- /etheno/keyfile.py: -------------------------------------------------------------------------------- 1 | # Code adapted from https://github.com/ethereum/eth-keyfile/blob/master/eth_keyfile/keyfile.py 2 | # to be compatible with Parity 3 | # Specifically, Parity requires a 256bit salt 4 | # 5 | # This file is licensed under the MIT License (MIT) 6 | # 7 | # Copyright (c) 2017 Piper Merriam 8 | # 9 | # Permission is hereby granted, free of charge, to any person obtaining a copy 10 | # of this software and associated documentation files (the "Software"), to deal 11 | # in the Software without restriction, including without limitation the rights 12 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | # copies of the Software, and to permit persons to whom the Software is 14 | # furnished to do so, subject to the following conditions: 15 | # 16 | # The above copyright notice and this permission notice shall be included in all 17 | # copies or substantial portions of the Software. 18 | # 19 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | # SOFTWARE. 26 | 27 | import hashlib 28 | import hmac 29 | import json 30 | import uuid 31 | 32 | from Crypto import Random 33 | from Crypto.Cipher import AES 34 | from Crypto.Protocol.KDF import scrypt 35 | from Crypto.Util import Counter 36 | 37 | from eth_keys import keys 38 | 39 | from eth_utils import ( 40 | big_endian_to_int, 41 | decode_hex, 42 | encode_hex, 43 | int_to_big_endian, 44 | is_dict, 45 | is_string, 46 | keccak, 47 | remove_0x_prefix, 48 | to_dict, 49 | ) 50 | 51 | 52 | def encode_hex_no_prefix(value): 53 | return remove_0x_prefix(encode_hex(value)) 54 | 55 | 56 | def load_keyfile(path_or_file_obj): 57 | if is_string(path_or_file_obj): 58 | with open(path_or_file_obj) as keyfile_file: 59 | return json.load(keyfile_file) 60 | else: 61 | return json.load(path_or_file_obj) 62 | 63 | 64 | def create_keyfile_json( 65 | private_key, password, version=3, kdf="pbkdf2", iterations=None 66 | ): 67 | if version == 3: 68 | return _create_v3_keyfile_json(private_key, password, kdf, iterations) 69 | else: 70 | raise NotImplementedError("Not yet implemented") 71 | 72 | 73 | def decode_keyfile_json(raw_keyfile_json, password): 74 | keyfile_json = normalize_keys(raw_keyfile_json) 75 | version = keyfile_json["version"] 76 | 77 | if version == 3: 78 | return _decode_keyfile_json_v3(keyfile_json, password) 79 | else: 80 | raise NotImplementedError("Not yet implemented") 81 | 82 | 83 | def extract_key_from_keyfile(path_or_file_obj, password): 84 | keyfile_json = load_keyfile(path_or_file_obj) 85 | private_key = decode_keyfile_json(keyfile_json, password) 86 | return private_key 87 | 88 | 89 | @to_dict 90 | def normalize_keys(keyfile_json): 91 | for key, value in keyfile_json.items(): 92 | if is_string(key): 93 | norm_key = key.lower() 94 | else: 95 | norm_key = key 96 | 97 | if is_dict(value): 98 | norm_value = normalize_keys(value) 99 | else: 100 | norm_value = value 101 | 102 | yield norm_key, norm_value 103 | 104 | 105 | # 106 | # Version 3 creators 107 | # 108 | DKLEN = 32 109 | SCRYPT_R = 1 110 | SCRYPT_P = 8 111 | 112 | 113 | def _create_v3_keyfile_json(private_key, password, kdf, work_factor=None): 114 | salt = Random.get_random_bytes(32) 115 | 116 | if work_factor is None: 117 | work_factor = get_default_work_factor_for_kdf(kdf) 118 | 119 | if kdf == "pbkdf2": 120 | derived_key = _pbkdf2_hash( 121 | password, 122 | hash_name="sha256", 123 | salt=salt, 124 | iterations=work_factor, 125 | dklen=DKLEN, 126 | ) 127 | kdfparams = { 128 | "c": work_factor, 129 | "dklen": DKLEN, 130 | "prf": "hmac-sha256", 131 | "salt": encode_hex_no_prefix(salt), 132 | } 133 | elif kdf == "scrypt": 134 | derived_key = _scrypt_hash( 135 | password, 136 | salt=salt, 137 | buflen=DKLEN, 138 | r=SCRYPT_R, 139 | p=SCRYPT_P, 140 | n=work_factor, 141 | ) 142 | kdfparams = { 143 | "dklen": DKLEN, 144 | "n": work_factor, 145 | "r": SCRYPT_R, 146 | "p": SCRYPT_P, 147 | "salt": encode_hex_no_prefix(salt), 148 | } 149 | else: 150 | raise NotImplementedError("KDF not implemented: {0}".format(kdf)) 151 | 152 | iv = big_endian_to_int(Random.get_random_bytes(16)) 153 | encrypt_key = derived_key[:16] 154 | ciphertext = encrypt_aes_ctr(private_key, encrypt_key, iv) 155 | mac = keccak(derived_key[16:32] + ciphertext) 156 | 157 | address = keys.PrivateKey(private_key).public_key.to_address() 158 | 159 | return { 160 | "address": remove_0x_prefix(address), 161 | "crypto": { 162 | "cipher": "aes-128-ctr", 163 | "cipherparams": { 164 | "iv": encode_hex_no_prefix(int_to_big_endian(iv)), 165 | }, 166 | "ciphertext": encode_hex_no_prefix(ciphertext), 167 | "kdf": kdf, 168 | "kdfparams": kdfparams, 169 | "mac": encode_hex_no_prefix(mac), 170 | }, 171 | "id": str(uuid.uuid4()), 172 | "version": 3, 173 | } 174 | 175 | 176 | # 177 | # Verson 3 decoder 178 | # 179 | def _decode_keyfile_json_v3(keyfile_json, password): 180 | crypto = keyfile_json["crypto"] 181 | kdf = crypto["kdf"] 182 | 183 | # Derive the encryption key from the password using the key derivation 184 | # function. 185 | if kdf == "pbkdf2": 186 | derived_key = _derive_pbkdf_key(crypto, password) 187 | elif kdf == "scrypt": 188 | derived_key = _derive_scrypt_key(crypto, password) 189 | else: 190 | raise TypeError("Unsupported key derivation function: {0}".format(kdf)) 191 | 192 | # Validate that the derived key matchs the provided MAC 193 | ciphertext = decode_hex(crypto["ciphertext"]) 194 | mac = keccak(derived_key[16:32] + ciphertext) 195 | 196 | expected_mac = decode_hex(crypto["mac"]) 197 | 198 | if not hmac.compare_digest(mac, expected_mac): 199 | raise ValueError("MAC mismatch") 200 | 201 | # Decrypt the ciphertext using the derived encryption key to get the 202 | # private key. 203 | encrypt_key = derived_key[:16] 204 | cipherparams = crypto["cipherparams"] 205 | iv = big_endian_to_int(decode_hex(cipherparams["iv"])) 206 | 207 | private_key = decrypt_aes_ctr(ciphertext, encrypt_key, iv) 208 | 209 | return private_key 210 | 211 | 212 | # 213 | # Key derivation 214 | # 215 | def _derive_pbkdf_key(crypto, password): 216 | kdf_params = crypto["kdfparams"] 217 | salt = decode_hex(kdf_params["salt"]) 218 | dklen = kdf_params["dklen"] 219 | should_be_hmac, _, hash_name = kdf_params["prf"].partition("-") 220 | assert should_be_hmac == "hmac" 221 | iterations = kdf_params["c"] 222 | 223 | derive_pbkdf_key = _pbkdf2_hash(password, hash_name, salt, iterations, dklen) 224 | 225 | return derive_pbkdf_key 226 | 227 | 228 | def _derive_scrypt_key(crypto, password): 229 | kdf_params = crypto["kdfparams"] 230 | salt = decode_hex(kdf_params["salt"]) 231 | p = kdf_params["p"] 232 | r = kdf_params["r"] 233 | n = kdf_params["n"] 234 | buflen = kdf_params["dklen"] 235 | 236 | derived_scrypt_key = _scrypt_hash( 237 | password, 238 | salt=salt, 239 | n=n, 240 | r=r, 241 | p=p, 242 | buflen=buflen, 243 | ) 244 | return derived_scrypt_key 245 | 246 | 247 | def _scrypt_hash(password, salt, n, r, p, buflen): 248 | derived_key = scrypt( 249 | password, 250 | salt=salt, 251 | key_len=buflen, 252 | N=n, 253 | r=r, 254 | p=p, 255 | num_keys=1, 256 | ) 257 | return derived_key 258 | 259 | 260 | def _pbkdf2_hash(password, hash_name, salt, iterations, dklen): 261 | derived_key = hashlib.pbkdf2_hmac( 262 | hash_name=hash_name, 263 | password=password, 264 | salt=salt, 265 | iterations=iterations, 266 | dklen=dklen, 267 | ) 268 | 269 | return derived_key 270 | 271 | 272 | # 273 | # Encryption and Decryption 274 | # 275 | def decrypt_aes_ctr(ciphertext, key, iv): 276 | ctr = Counter.new(128, initial_value=iv, allow_wraparound=True) 277 | encryptor = AES.new(key, AES.MODE_CTR, counter=ctr) 278 | return encryptor.decrypt(ciphertext) 279 | 280 | 281 | def encrypt_aes_ctr(value, key, iv): 282 | ctr = Counter.new(128, initial_value=iv, allow_wraparound=True) 283 | encryptor = AES.new(key, AES.MODE_CTR, counter=ctr) 284 | ciphertext = encryptor.encrypt(value) 285 | return ciphertext 286 | 287 | 288 | # 289 | # Utility 290 | # 291 | def get_default_work_factor_for_kdf(kdf): 292 | if kdf == "pbkdf2": 293 | return 1000000 294 | elif kdf == "scrypt": 295 | return 262144 296 | else: 297 | raise ValueError("Unsupported key derivation function: {0}".format(kdf)) 298 | 299 | 300 | if __name__ == "__main__": 301 | from utils import int_to_bytes 302 | 303 | print( 304 | create_keyfile_json( 305 | int_to_bytes( 306 | 0xDA105EBBEDE69170F1D13C70B0B82715A7CB46740779457D7EE4FBFA54BA95C1 307 | ), 308 | b"etheno", 309 | ) 310 | ) 311 | -------------------------------------------------------------------------------- /etheno/logger.py: -------------------------------------------------------------------------------- 1 | import enum 2 | import logging 3 | import os 4 | import tempfile 5 | import threading 6 | import time 7 | from typing import Callable, List, Optional, Union, Any 8 | 9 | import ptyprocess 10 | 11 | CRITICAL = logging.CRITICAL 12 | ERROR = logging.ERROR 13 | WARNING = logging.WARNING 14 | INFO = logging.INFO 15 | DEBUG = logging.DEBUG 16 | NOTSET = logging.NOTSET 17 | 18 | 19 | class CGAColors(enum.Enum): 20 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) 21 | 22 | 23 | ANSI_RESET = "\033[0m" 24 | ANSI_COLOR = "\033[1;%dm" 25 | ANSI_BOLD = "\033[1m" 26 | 27 | LEVEL_COLORS = { 28 | CRITICAL: CGAColors.MAGENTA, 29 | ERROR: CGAColors.RED, 30 | WARNING: CGAColors.YELLOW, 31 | INFO: CGAColors.GREEN, 32 | DEBUG: CGAColors.CYAN, 33 | NOTSET: CGAColors.BLUE, 34 | } 35 | 36 | # TODO: seems like this function can be removed, no references? 37 | def formatter_message(message: str, use_color: bool = True) -> str: 38 | if use_color: 39 | message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) 40 | else: 41 | message = message.replace("$RESET", "").replace("$BOLD", "") 42 | return message 43 | 44 | 45 | class ComposableFormatter: 46 | def __init__(self, *args, **kwargs): 47 | if len(args) == 1 and not isinstance(args[0], str): 48 | self._parent_formatter = args[0] 49 | else: 50 | self._parent_formatter = self.new_formatter(*args, **kwargs) 51 | 52 | def new_formatter(self, *args, **kwargs): 53 | return logging.Formatter(*args, **kwargs) 54 | 55 | def __getattr__(self, name): 56 | return getattr(self._parent_formatter, name) 57 | 58 | 59 | class ColorFormatter(ComposableFormatter): 60 | def reformat(self, fmt: str) -> str: 61 | for color in CGAColors: 62 | fmt = fmt.replace("$%s" % color.name, ANSI_COLOR % (30 + color.value)) 63 | fmt = fmt.replace("$RESET", ANSI_RESET) 64 | fmt = fmt.replace("$BOLD", ANSI_BOLD) 65 | return fmt 66 | 67 | @staticmethod 68 | def remove_color(fmt: str) -> str: 69 | for color in CGAColors: 70 | fmt = fmt.replace("$%s" % color.name, "") 71 | fmt = fmt.replace("$RESET", "") 72 | fmt = fmt.replace("$BOLD", "") 73 | fmt = fmt.replace("$LEVELCOLOR", "") 74 | return fmt 75 | 76 | def new_formatter(self, fmt: str, *args, **kwargs) -> logging.Formatter: 77 | if "datefmt" in kwargs: 78 | kwargs["datefmt"] = self.reformat(kwargs["datefmt"]) 79 | return super().new_formatter(self.reformat(fmt), *args, **kwargs) 80 | 81 | def format(self, *args, **kwargs) -> str: 82 | levelcolor = LEVEL_COLORS.get(args[0].levelno, LEVEL_COLORS[NOTSET]) 83 | ret = self._parent_formatter.format(*args, **kwargs) 84 | ret = ret.replace("$LEVELCOLOR", ANSI_COLOR % (30 + levelcolor.value)) 85 | ret = ret.replace("\n", self.reformat("$RESET $BOLD$BLUE\\$RESET\n"), 1) 86 | ret = ret.replace("\n", self.reformat("\n$RESET$BOLD$BLUE> $RESET")) 87 | return ret 88 | 89 | 90 | class NonInfoFormatter(ComposableFormatter): 91 | _vanilla_formatter = logging.Formatter() 92 | 93 | def format(self, *args, **kwargs) -> str: 94 | if args and args[0].levelno == INFO: 95 | return self._vanilla_formatter.format(*args, **kwargs) 96 | else: 97 | return self._parent_formatter.format(*args, **kwargs) 98 | 99 | 100 | ETHENO_LOGGERS = {} 101 | 102 | _LOGGING_GETLOGGER = logging.getLogger 103 | 104 | 105 | def getLogger(name: str): 106 | if name in ETHENO_LOGGERS: 107 | # TODO: Only enable this if Etheno was run as a standalone application 108 | ret = ETHENO_LOGGERS[name] 109 | else: 110 | ret = _LOGGING_GETLOGGER(name) 111 | return ret 112 | 113 | 114 | logging.getLogger = getLogger 115 | 116 | 117 | class EthenoLogger: 118 | DEFAULT_FORMAT = ( 119 | "$RESET$LEVELCOLOR$BOLD%(levelname)-8s $BLUE[$RESET$WHITE%(asctime)14s$BLUE$BOLD]$NAME$RESET " 120 | "%(message)s" 121 | ) 122 | 123 | def __init__( 124 | self, 125 | name: str, 126 | log_level: Optional[int] = None, 127 | parent: Optional["EthenoLogger"] = None, 128 | cleanup_empty: bool = False, 129 | displayname: Optional[str] = None, 130 | ): 131 | if name in ETHENO_LOGGERS: 132 | raise Exception( 133 | f"An EthenoLogger instance for name {name} already exists: {ETHENO_LOGGERS[name]}" 134 | ) 135 | ETHENO_LOGGERS[name] = self 136 | self._directory: Optional[str] = None 137 | self.parent: Optional[EthenoLogger] = parent 138 | self.cleanup_empty: bool = cleanup_empty 139 | self.children: List[EthenoLogger] = [] 140 | self._descendant_handlers = [] 141 | if displayname is None: 142 | self.displayname: str = name 143 | else: 144 | self.displayname = displayname 145 | if log_level is None: 146 | if parent is None: 147 | raise ValueError( 148 | "A logger must be provided a parent if `log_level` is None" 149 | ) 150 | log_level = parent.log_level 151 | self._log_level: int = log_level 152 | self._logger: logging.Logger = _LOGGING_GETLOGGER(name) 153 | self._handlers: List[logging.Handler] = [logging.StreamHandler()] 154 | if log_level is not None: 155 | self.log_level = log_level 156 | formatter = ColorFormatter( 157 | self.DEFAULT_FORMAT.replace("$NAME", self._name_format()), 158 | datefmt="%m$BLUE-$WHITE%d$BLUE|$WHITE%H$BLUE:$WHITE%M$BLUE:$WHITE%S", 159 | ) 160 | if self.parent is None: 161 | formatter = NonInfoFormatter(formatter) 162 | else: 163 | parent._add_child(self) 164 | self._handlers[0].setFormatter(formatter) # type: ignore 165 | self._logger.addHandler(self._handlers[0]) 166 | self._tmpdir = None 167 | 168 | def close(self): 169 | for child in self.children: 170 | child.close() 171 | if self.cleanup_empty: 172 | # first, check any files that handlers have created: 173 | for h in self._handlers: 174 | if isinstance(h, logging.FileHandler): 175 | if h.stream is not None: 176 | log_path = h.stream.name 177 | if os.path.exists(log_path) and os.stat(log_path).st_size == 0: 178 | h.close() 179 | os.remove(log_path) 180 | # next, check if the output directory can be cleaned up 181 | if self.directory: 182 | for dirpath, dirnames, filenames in os.walk( 183 | self.directory, topdown=False 184 | ): 185 | if ( 186 | len(dirnames) == 0 187 | and len(filenames) == 0 188 | and dirpath != self.directory 189 | ): 190 | os.rmdir(dirpath) 191 | if self._tmpdir is not None: 192 | self._tmpdir.cleanup() 193 | self._tmpdir = None 194 | 195 | @property 196 | def directory(self) -> Optional[str]: 197 | return self._directory 198 | 199 | def _add_child(self, child): 200 | if child in self.children or any( 201 | c for c in self.children if c.name == child.name 202 | ): 203 | raise ValueError( 204 | "Cannot double-add child logger %s to logger %s" 205 | % (child.name, self.name) 206 | ) 207 | self.children.append(child) 208 | if self.directory is not None: 209 | child.save_to_directory( 210 | os.path.join(self.directory, child.name.replace(os.sep, "-")) 211 | ) 212 | else: 213 | child._tmpdir = tempfile.TemporaryDirectory() 214 | child.save_to_directory(child._tmpdir.name) 215 | parent = self 216 | while parent is not None: 217 | for handler in self._descendant_handlers: 218 | child.addHandler(handler, include_descendants=True) 219 | parent = parent.parent 220 | 221 | def _name_format(self): 222 | if self.parent is not None and self.parent.parent is not None: 223 | ret = self.parent._name_format() 224 | else: 225 | ret = "" 226 | return ret + "[$RESET$WHITE%s$BLUE$BOLD]" % self.displayname 227 | 228 | def addHandler( 229 | self, 230 | handler: logging.Handler, 231 | include_descendants: bool = True, 232 | set_log_level: bool = True, 233 | ): 234 | if set_log_level: 235 | handler.setLevel(self.log_level) 236 | self._logger.addHandler(handler) 237 | self._handlers.append(handler) 238 | if include_descendants: 239 | self._descendant_handlers.append(handler) 240 | for child in self.children: 241 | if isinstance(child, EthenoLogger): 242 | child.addHandler( 243 | handler, 244 | include_descendants=include_descendants, 245 | set_log_level=set_log_level, 246 | ) 247 | else: 248 | child.addHandler(handler) 249 | 250 | def make_logged_file( 251 | self, prefix=None, suffix=None, mode="w+b", dir: Optional[str] = None 252 | ): 253 | """Returns an opened file stream to a unique file created according to the provided naming scheme""" 254 | if dir is None: 255 | dir = "" 256 | else: 257 | dir = os.path.relpath( 258 | os.path.realpath(dir), start=os.path.realpath(self.directory) 259 | ) 260 | os.makedirs(os.path.join(self.directory, dir), exist_ok=True) 261 | i = 1 262 | while True: 263 | if i == 1: 264 | filename = f"{prefix}{suffix}" 265 | else: 266 | filename = f"{prefix}{i}{suffix}" 267 | path = os.path.join(self.directory, dir, filename) 268 | if not os.path.exists(path): 269 | return open(path, mode) 270 | i += 1 271 | 272 | def make_constant_logged_file(self, contents: Union[str, bytes], *args, **kwargs): 273 | """Creates a logged file, populates it with the provided contents, and returns the absolute path to the file.""" 274 | if isinstance(contents, str): 275 | contents = contents.encode("utf-8") 276 | with self.make_logged_file(*args, **kwargs) as f: 277 | f.write(contents) # type: ignore 278 | return os.path.realpath(f.name) 279 | 280 | def to_log_path(self, absolute_path): 281 | if self.directory is None: 282 | return absolute_path 283 | absolute_path = os.path.realpath(absolute_path) 284 | dirpath = os.path.realpath(self.directory) 285 | return os.path.relpath(absolute_path, start=dirpath) 286 | 287 | def save_to_file(self, path, include_descendants=True, log_level=None): 288 | if log_level is None: 289 | log_level = self.log_level 290 | handler = logging.FileHandler(path) 291 | handler.setLevel(log_level) 292 | handler.setFormatter( 293 | logging.Formatter( 294 | ColorFormatter.remove_color( 295 | self.DEFAULT_FORMAT.replace("$NAME", self._name_format()) 296 | ), 297 | datefmt="%m-%d|%H:%M:%S", 298 | ) 299 | ) 300 | self.addHandler( 301 | handler, include_descendants=include_descendants, set_log_level=False 302 | ) 303 | 304 | def save_to_directory(self, path): 305 | if self.directory == path: 306 | # we are already set to save to this directory 307 | return 308 | elif self.directory is not None: 309 | raise ValueError( 310 | "Logger %s's save directory is already set to %s" % (self.name, path) 311 | ) 312 | self._directory = os.path.realpath(path) 313 | os.makedirs(path, exist_ok=True) 314 | self.save_to_file( 315 | os.path.join(path, "%s.log" % self.name.replace(os.sep, "-")), 316 | include_descendants=False, 317 | log_level=DEBUG, 318 | ) 319 | for child in self.children: 320 | child.save_to_directory(os.path.join(path, child.name)) 321 | 322 | @property 323 | def log_level(self): 324 | if self._log_level is None: 325 | if self.parent is None: 326 | raise ValueError( 327 | "A logger must be provided a parent if `log_level` is None" 328 | ) 329 | return self.parent.log_level 330 | else: 331 | return self._log_level 332 | 333 | @log_level.setter 334 | def log_level(self, level): 335 | if not isinstance(level, int): 336 | try: 337 | level = getattr(logging, str(level).upper()) 338 | except AttributeError: 339 | raise ValueError("Invalid log level: %s" % level) 340 | elif level not in (CRITICAL, ERROR, WARNING, INFO, DEBUG): 341 | raise ValueError("Invalid log level: %d" % level) 342 | self._log_level = level 343 | self._logger.setLevel(level) 344 | for handler in self._handlers: 345 | handler.setLevel(level) 346 | 347 | def __getattr__(self, name): 348 | return getattr(self._logger, name) 349 | 350 | def __repr__(self): 351 | return f"{type(self).__name__}(name={self.name!r}, log_level={self.log_level!r}, parent={self.parent!r}, cleanup_empty={self.cleanup_empty!r}, displayname={self.displayname!r})" 352 | 353 | 354 | class StreamLogger(threading.Thread): 355 | def __init__(self, logger: logging.Logger, *streams, newline_char=b"\n"): 356 | super().__init__(daemon=True) 357 | self.logger: logging.Logger = logger 358 | self.streams = streams 359 | if isinstance(newline_char, str): 360 | newline_char = newline_char.encode("utf-8") 361 | self._newline_char = newline_char 362 | self._buffers = [b"" for i in range(len(streams))] 363 | self._done: bool = False 364 | # TODO: Made a small change here due to the ellipses not being allowed, make sure it does not create any other issues 365 | self.log: Callable[ 366 | [logging.Logger, Union[str, bytes]], Any 367 | ] = lambda lgr, message: lgr.info(message) 368 | 369 | def is_done(self) -> bool: 370 | return self._done 371 | 372 | def run(self): 373 | while not self.is_done(): 374 | while True: 375 | got_byte = False 376 | try: 377 | for i, stream in enumerate(self.streams): 378 | byte = stream.read(1) 379 | while byte is not None and len(byte): 380 | if isinstance(byte, str): 381 | byte = byte.encode("utf-8") 382 | if byte == self._newline_char: 383 | self.log(self.logger, self._buffers[i].decode()) 384 | self._buffers[i] = b"" 385 | else: 386 | self._buffers[i] += byte 387 | got_byte = True 388 | byte = stream.read(1) 389 | except Exception: 390 | self._done = True 391 | if not got_byte or self._done: 392 | break 393 | time.sleep(0.5) 394 | 395 | 396 | class ProcessLogger(StreamLogger): 397 | def __init__(self, logger, process): 398 | self.process = process 399 | super().__init__( 400 | logger, 401 | open(process.stdout.fileno(), buffering=1), 402 | open(process.stderr.fileno(), buffering=1), 403 | ) 404 | 405 | def is_done(self): 406 | return self.process.poll() is not None 407 | 408 | 409 | class PtyLogger(StreamLogger): 410 | def __init__(self, logger, args, cwd=None, **kwargs): 411 | self.process = ptyprocess.PtyProcessUnicode.spawn(args, cwd=cwd) 412 | super().__init__(logger, self.process, **kwargs) 413 | 414 | def is_done(self): 415 | return not self.process.isalive() 416 | 417 | def __getattr__(self, name): 418 | return getattr(self.process, name) 419 | 420 | 421 | if __name__ == "__main__": 422 | logger = EthenoLogger("Testing", DEBUG) 423 | logger.info("Info") 424 | logger.critical("Critical") 425 | -------------------------------------------------------------------------------- /etheno/parity.py: -------------------------------------------------------------------------------- 1 | import atexit 2 | import json 3 | import os 4 | import tempfile 5 | 6 | from .client import JSONRPCError 7 | from .genesis import geth_to_parity 8 | from .jsonrpcclient import JSONRPCClient 9 | from .keyfile import create_keyfile_json 10 | from .utils import find_open_port, format_hex_address, int_to_bytes 11 | 12 | 13 | def make_config(genesis_path, base_path, port, accounts, password_file, **kwargs): 14 | return """[parity] 15 | public_node = false 16 | no_download = false 17 | no_consensus = false 18 | no_persistent_txqueue = false 19 | 20 | chain = "{genesis_path}" 21 | base_path = "{base_path}" 22 | db_path = "{base_path}/chains" 23 | keys_path = "{base_path}/keys" 24 | 25 | [account] 26 | unlock = [{account_addresses}] 27 | password = ["{password_file}"] 28 | 29 | [network] 30 | port = {port} 31 | min_peers = 1 32 | max_peers = 1 33 | id = {chainId} 34 | discovery = false 35 | 36 | [rpc] 37 | disable = false 38 | port = {rpc_port} 39 | interface = "local" 40 | apis = ["web3", "eth", "pubsub", "net", "parity", "parity_pubsub", "traces", "rpc", "shh", "shh_pubsub"] 41 | hosts = ["none"] 42 | 43 | [websockets] 44 | disable = true 45 | 46 | [ipc] 47 | disable = true 48 | 49 | [secretstore] 50 | disable = true 51 | 52 | [ipfs] 53 | enable = false 54 | 55 | [mining] 56 | author = "{miner}" 57 | engine_signer = "{miner}" 58 | force_sealing = true 59 | reseal_on_txs = "all" 60 | #reseal_min_period = 4000 61 | #reseal_max_period = 60000 62 | #gas_floor_target = "4700000" 63 | #gas_cap = "6283184" 64 | #tx_queue_gas = "off" 65 | #tx_gas_limit = "6283184" 66 | #tx_time_limit = 500 #ms 67 | #remove_solved = false 68 | #notify_work = ["http://localhost:3001"] 69 | refuse_service_transactions = false 70 | 71 | [footprint] 72 | tracing = "auto" 73 | pruning = "auto" 74 | pruning_history = 64 75 | pruning_memory = 32 76 | cache_size_db = 128 77 | cache_size_blocks = 8 78 | cache_size_queue = 40 79 | cache_size_state = 25 80 | cache_size = 128 # Overrides above caches with total size 81 | fast_and_loose = false 82 | db_compaction = "ssd" 83 | fat_db = "auto" 84 | scale_verifiers = true 85 | num_verifiers = 6 86 | 87 | [snapshots] 88 | disable_periodic = false 89 | 90 | [misc] 91 | logging = "own_tx=trace" 92 | log_file = "{log_path}" 93 | color = true 94 | """.format( 95 | genesis_path=genesis_path, 96 | base_path=base_path, 97 | port=find_open_port(30303), 98 | rpc_port=port, 99 | log_path=kwargs.get("log_path", "%s/parity.log" % base_path), 100 | chainId=kwargs.get("chainId", 1), 101 | miner=format_hex_address(accounts[-1], True), 102 | account_addresses=", ".join( 103 | map(lambda s: '"0x%s"' % s, map(format_hex_address, accounts)) 104 | ), 105 | password_file=password_file, 106 | ).encode( 107 | "utf-8" 108 | ) 109 | 110 | 111 | class ParityClient(JSONRPCClient): 112 | def __init__(self, genesis, port=8546): 113 | super().__init__("Parity", genesis, port) 114 | self._unlock_accounts = True 115 | 116 | self.config = None 117 | 118 | atexit.register(ParityClient.shutdown.__get__(self, ParityClient)) 119 | 120 | def etheno_set(self): 121 | super().etheno_set() 122 | self.import_account(self.miner_account.private_key) 123 | self.config = self.logger.make_constant_logged_file( 124 | make_config( 125 | genesis_path=self.logger.to_log_path(self.genesis_file), 126 | base_path=self.logger.to_log_path(self.datadir), 127 | port=self.port, 128 | chainId=self.genesis["config"]["chainId"], 129 | accounts=tuple(self.accounts), 130 | password_file=self.logger.to_log_path(self.passwords), 131 | ), 132 | prefix="config", 133 | suffix=".toml", 134 | ) 135 | 136 | def write_passwords(self, outfile): 137 | outfile.write(b"etheno") 138 | 139 | def write_genesis(self, outfile): 140 | parity_genesis = geth_to_parity(self.genesis) 141 | parity_genesis["genesis"]["author"] = format_hex_address( 142 | self.miner_account.address, True 143 | ) 144 | outfile.write(json.dumps(parity_genesis).encode("utf-8")) 145 | 146 | def import_account(self, private_key): 147 | keyfile = create_keyfile_json(int_to_bytes(private_key), b"etheno") 148 | keyfile_json = json.dumps(keyfile) 149 | keysdir = os.path.join(self.datadir, "keys", "etheno") 150 | os.makedirs(keysdir, exist_ok=True) 151 | output = tempfile.NamedTemporaryFile( 152 | prefix="account", suffix=".key", dir=keysdir, delete=False 153 | ) 154 | try: 155 | output.write(keyfile_json.encode("utf-8")) 156 | finally: 157 | output.close() 158 | if self.log_directory is None: 159 | self._tempfiles.append(output) 160 | 161 | def unlock_account(self, account): 162 | addr = format_hex_address(account, True) 163 | self.logger.info("Unlocking Parity account %s..." % addr) 164 | return self.post( 165 | { 166 | "id": addr, 167 | "jsonrpc": "2.0", 168 | "method": "personal_unlockAccount", 169 | "params": [addr, "etheno", None], # Unlock the account for one day 170 | } 171 | ) 172 | 173 | def post(self, data, unlock_if_necessary=None): 174 | if unlock_if_necessary is None: 175 | unlock_if_necessary = self._unlock_accounts 176 | try: 177 | return super().post(data) 178 | except JSONRPCError as e: 179 | if ( 180 | unlock_if_necessary 181 | and "data" in e.result["error"] 182 | and e.result["error"]["data"].lower() == "notunlocked" 183 | ): 184 | self.unlock_account(int(data["params"][0]["from"], 16)) 185 | return self.post(data, unlock_if_necessary=False) 186 | else: 187 | raise e 188 | 189 | def get_start_command(self, unlock_accounts=True): 190 | return [ 191 | "/usr/bin/env", 192 | "parity", 193 | "--config", 194 | self.logger.to_log_path(self.config), 195 | "--fast-unlock", 196 | "--jsonrpc-apis=all", 197 | ] 198 | 199 | def start(self, unlock_accounts=True): 200 | self._unlock_accounts = unlock_accounts 201 | super().start(unlock_accounts=unlock_accounts) 202 | -------------------------------------------------------------------------------- /etheno/signals.py: -------------------------------------------------------------------------------- 1 | import signal 2 | 3 | 4 | def add_handler(signal_type, handler): 5 | current_handler = signal.getsignal(signal_type) 6 | if current_handler == signal.SIG_IGN or current_handler == signal.SIG_DFL: 7 | current_handler = None 8 | 9 | def new_handler(sig_type, frame): 10 | if current_handler: 11 | current_handler(sig_type, frame) 12 | handler(sig_type, frame) 13 | 14 | signal.signal(signal_type, new_handler) 15 | 16 | 17 | def add_sigint_handler(handler): 18 | add_handler(signal.SIGINT, handler) 19 | -------------------------------------------------------------------------------- /etheno/synchronization.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import eth_utils 4 | from web3.auto import w3 5 | 6 | from .client import ( 7 | EthenoClient, 8 | SelfPostingClient, 9 | jsonrpc, 10 | JSONRPCError, 11 | DATA, 12 | QUANTITY, 13 | transaction_receipt_succeeded, 14 | ) 15 | from .utils import decode_hex, format_hex_address, int_to_bytes 16 | 17 | 18 | def _decode_value(value): 19 | if isinstance(value, int): 20 | return value 21 | try: 22 | return int(value, 16) 23 | except Exception: 24 | return None 25 | 26 | 27 | def _remap_params(client, params, mapping, method, remap_data=False): 28 | if isinstance(params, dict): 29 | for key, value in params.items(): 30 | decoded = _decode_value(value) 31 | if decoded is None: 32 | params[key] = _remap_params( 33 | client, value, mapping, "%s['%s']" % (method, key) 34 | ) 35 | elif decoded in mapping: 36 | client.logger.debug( 37 | "Converting %s parameter '%s' from %x to %x" 38 | % (method, key, decoded, mapping[decoded]) 39 | ) 40 | params[key] = format_hex_address(mapping[decoded], True) 41 | elif remap_data and key == "data": 42 | new_value = params["data"] 43 | for old, new in mapping.items(): 44 | prev = new_value 45 | new_value = new_value.replace( 46 | format_hex_address(old), format_hex_address(new) 47 | ) 48 | if prev != new_value: 49 | client.logger.debug( 50 | "Converting %x in %s['data'] to %x" % (old, method, new) 51 | ) 52 | if new_value != params["data"]: 53 | params["data"] = new_value 54 | elif isinstance(params, list) or isinstance(params, tuple): 55 | for i, p in enumerate(params): 56 | decoded = _decode_value(p) 57 | if decoded is None: 58 | params[i] = _remap_params(client, p, mapping, "%s['%d']" % (method, i)) 59 | elif decoded in mapping: 60 | client.logger.debug( 61 | "Converting %s parameter %d from %x to %x" 62 | % (method, i, decoded, mapping[decoded]) 63 | ) 64 | params[i] = format_hex_address(mapping[decoded], True) 65 | else: 66 | decoded = _decode_value(params) 67 | if decoded is not None and decoded in mapping: 68 | client.logger.debug( 69 | "Converting %s from %x to %x" % (method, decoded, mapping[decoded]) 70 | ) 71 | return mapping[decoded] 72 | return params 73 | 74 | 75 | class ChainSynchronizer(object): 76 | def __init__(self, client): 77 | if not isinstance(client, SelfPostingClient): 78 | raise TypeError( 79 | "TODO: Implement support for address synchronization on clients other than SelfPostingClients" 80 | ) 81 | self.mapping = {} 82 | self.filter_mapping = {} 83 | self._old_post = getattr(client, "post") 84 | self._old_create_account = getattr(client, "create_account") 85 | self._client = client 86 | 87 | def create_account(self, balance=0, address=None): 88 | # TODO: not sure what the data field is supposed to do here 89 | if self._client == self._client.etheno.master_client: 90 | return self._old_create_account(data) 91 | try: 92 | # First, see if the client can handle creating this address: 93 | return self._old_create_account(balance=balance, address=address) 94 | except NotImplementedError: 95 | pass 96 | new_address = self._old_create_account(balance=balance, address=None) 97 | if address is not None and address != new_address: 98 | self.mapping[address] = new_address 99 | return new_address 100 | 101 | def post(self, data, *args, **kwargs): 102 | if self._client == self._client.etheno.master_client: 103 | return self._old_post(data, *args, **kwargs) 104 | 105 | method = data["method"] 106 | 107 | if method == "eth_getTransactionReceipt": 108 | # first, make sure the master client's transaction succeeded; if not, we can just ignore this 109 | if not transaction_receipt_succeeded(self._client.etheno.rpc_client_result): 110 | # the master client's transaction receipt command failed, so we can skip calling this client's 111 | return self._client.etheno.rpc_client_result 112 | elif _decode_value(data["params"][0]) not in self.mapping: 113 | # we don't know about this transaction receipt, which probably means that the transaction failed 114 | # on this client. So return the receipt here, because below we will block on a result: 115 | return self._old_post(data, *args, **kwargs) 116 | 117 | uninstalling_filter = None 118 | if "params" in data: 119 | data["params"] = _remap_params( 120 | self._client, data["params"], self.mapping, method, remap_data=True 121 | ) 122 | if ( 123 | "filter" in method.lower() and "get" in method.lower() 124 | ) or method == "eth_uninstallFilter": 125 | # we are accessing a filter by its ID, so remap the ID 126 | old_id = data["params"][0] 127 | if old_id not in self.filter_mapping: 128 | self._client.logger.warn( 129 | "%s called on unknown filter ID %s; ignoring..." 130 | % (method, old_id) 131 | ) 132 | else: 133 | self._client.logger.info( 134 | "Mapping filter ID %s to %s for %s" 135 | % (old_id, self.filter_mapping[old_id], method) 136 | ) 137 | data["params"] = [self.filter_mapping[old_id]] 138 | if method == "eth_uninstallFilter": 139 | uninstalling_filter = old_id 140 | ret = self._old_post(data, *args, **kwargs) 141 | if uninstalling_filter is not None: 142 | if ret["result"]: 143 | # the uninstall succeeded, so we no longer need to keep the mapping: 144 | del self.filter_mapping[uninstalling_filter] 145 | elif "filter" in method.lower() and "new" in method.lower() and "result" in ret: 146 | # a new filter was just created, so record the mapping 147 | self.filter_mapping[self._client.etheno.rpc_client_result["result"]] = ret[ 148 | "result" 149 | ] 150 | elif method == "eth_sendTransaction" or method == "eth_sendRawTransaction": 151 | # record the transaction hash mapping 152 | if ret and "result" in ret and ret["result"]: 153 | if ( 154 | self._client.etheno.rpc_client_result 155 | and not isinstance( 156 | self._client.etheno.rpc_client_result, JSONRPCError 157 | ) 158 | and "result" in self._client.etheno.rpc_client_result 159 | and self._client.etheno.rpc_client_result["result"] 160 | ): 161 | old_decoded = _decode_value( 162 | self._client.etheno.rpc_client_result["result"] 163 | ) 164 | new_decoded = _decode_value(ret["result"]) 165 | if old_decoded is not None and new_decoded is not None: 166 | self._client.logger.info( 167 | "Mapping transaction hash %x to %x" 168 | % (old_decoded, new_decoded) 169 | ) 170 | self.mapping[old_decoded] = new_decoded 171 | elif not (old_decoded is None and new_decoded is None): 172 | self._client.logger.warn( 173 | "Call to %s returned %s from the master client but %s from this client; ignoring..." 174 | % ( 175 | method, 176 | self._client.etheno.rpc_client_result["result"], 177 | ret["result"], 178 | ) 179 | ) 180 | elif method == "eth_getTransactionReceipt": 181 | # by this point we know that the master client has already successfully mined the transaction and returned a receipt 182 | # so make sure that we block until this client has also mined the transaction and returned a receipt 183 | while transaction_receipt_succeeded(ret) is None: 184 | self._client.logger.info( 185 | "Waiting to mine transaction %s..." % data["params"][0] 186 | ) 187 | time.sleep(5.0) 188 | ret = self._old_post(data, *args, **kwargs) 189 | # update the mapping with the address if a new contract was created 190 | if "contractAddress" in ret["result"] and ret["result"]["contractAddress"]: 191 | master_address = _decode_value( 192 | self._client.etheno.rpc_client_result["result"]["contractAddress"] 193 | ) 194 | our_address = _decode_value(ret["result"]["contractAddress"]) 195 | if master_address is not None and our_address is not None: 196 | self.mapping[master_address] = our_address 197 | elif not (master_address is None and our_address is None): 198 | self._client.logger.warn( 199 | "Call to %s returned %s from the master client but %s from this client; ignoring..." 200 | % ( 201 | method, 202 | self._client.etheno.rpc_client_result["result"][ 203 | "contractAddress" 204 | ], 205 | ret["result"]["contractAddress"], 206 | ) 207 | ) 208 | 209 | return ret 210 | 211 | 212 | def AddressSynchronizingClient(etheno_client): 213 | synchronizer = ChainSynchronizer(etheno_client) 214 | 215 | setattr( 216 | etheno_client, 217 | "create_account", 218 | ChainSynchronizer.create_account.__get__(synchronizer, ChainSynchronizer), 219 | ) 220 | setattr( 221 | etheno_client, 222 | "post", 223 | ChainSynchronizer.post.__get__(synchronizer, ChainSynchronizer), 224 | ) 225 | 226 | return etheno_client 227 | 228 | 229 | class RawTransactionSynchronizer(ChainSynchronizer): 230 | def __init__(self, client, accounts): 231 | super().__init__(client) 232 | self.accounts = accounts 233 | self._private_keys = {} 234 | self._account_index = -1 235 | self._chain_id = client.get_net_version() 236 | 237 | def create_account(self, balance=0, address=None): 238 | self._account_index += 1 239 | new_address = self.accounts[self._account_index].address 240 | self._private_keys[new_address] = int_to_bytes( 241 | self.accounts[self._account_index].private_key 242 | ) 243 | if address is not None and address != new_address: 244 | self.mapping[address] = new_address 245 | return new_address 246 | 247 | def post(self, data, *args, **kwargs): 248 | method = data["method"] 249 | 250 | if method == "eth_sendTransaction": 251 | # This client does not support sendTransaction because it does not have any of the requisite accounts. 252 | # So let's manually sign the transaction and send it to the client using eth_sendRawTransaction, instead. 253 | params = _remap_params( 254 | self._client, 255 | dict(data["params"][0]), 256 | self.mapping, 257 | method, 258 | remap_data=True, 259 | ) 260 | from_str = params["from"] 261 | from_address = int(from_str, 16) 262 | if from_address in self._private_keys: 263 | private_key = self._private_keys[from_address] 264 | else: 265 | # see if it is in self.accounts: 266 | for account in self.accounts: 267 | if from_address == account.address: 268 | private_key = account.private_key 269 | break 270 | else: 271 | raise Exception( 272 | "Error: eth_sendTransaction sent from unknown address %s:\n%s" 273 | % (from_str, data) 274 | ) 275 | params["chainId"] = self._client.get_net_version() 276 | # Workaround for a bug in web3.eth.account: 277 | # the signTransaction function checks to see if the 'from' field is present, and if so it validates that it 278 | # corresponds to the address of the private key. However, web3.eth.account doesn't perform this check case 279 | # insensitively, so it can erroneously fail. Therefore, set the 'from' field using the same value that 280 | # this call validates against: 281 | params["from"] = w3.eth.account.privateKeyToAccount(private_key).address 282 | # web3.eth.acount.signTransaction expects the `to` field to be a checksum address: 283 | if "to" in params: 284 | params["to"] = eth_utils.address.to_checksum_address(params["to"]) 285 | transaction_count = self._client.get_transaction_count(from_address) 286 | params["nonce"] = transaction_count 287 | signed_txn = w3.eth.account.signTransaction(params, private_key=private_key) 288 | return super().post( 289 | { 290 | "id": 1, 291 | "jsonrpc": "2.0", 292 | "method": "eth_sendRawTransaction", 293 | "params": [signed_txn.rawTransaction.hex()], 294 | } 295 | ) 296 | else: 297 | return super().post(data, *args, **kwargs) 298 | 299 | 300 | def RawTransactionClient(etheno_client, accounts): 301 | synchronizer = RawTransactionSynchronizer(etheno_client, accounts) 302 | 303 | setattr( 304 | etheno_client, 305 | "create_account", 306 | RawTransactionSynchronizer.create_account.__get__( 307 | synchronizer, RawTransactionSynchronizer 308 | ), 309 | ) 310 | setattr( 311 | etheno_client, 312 | "post", 313 | RawTransactionSynchronizer.post.__get__( 314 | synchronizer, RawTransactionSynchronizer 315 | ), 316 | ) 317 | 318 | return etheno_client 319 | -------------------------------------------------------------------------------- /etheno/threadwrapper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import threading 4 | from threading import Condition 5 | 6 | 7 | def is_main_thread(): 8 | return isinstance(threading.current_thread(), threading._MainThread) 9 | 10 | 11 | class MainThreadController(object): 12 | def __init__(self): 13 | if not is_main_thread(): 14 | raise Exception("A controller can only be created from the main thread") 15 | self._main_wake_up = Condition() 16 | self._main_wake_up.acquire() 17 | self._obj = None 18 | self._caller_wake_up = None 19 | self._args = None 20 | self._kwargs = None 21 | self._return = None 22 | self._quit = False 23 | 24 | def invoke(self, obj, *args, **kwargs): 25 | if is_main_thread(): 26 | return obj.__call__(*args, **kwargs) 27 | released = False 28 | self._main_wake_up.acquire() 29 | try: 30 | self._caller_wake_up = Condition() 31 | with self._caller_wake_up: 32 | self._obj = obj 33 | self._args = args 34 | self._kwargs = kwargs 35 | # tell the main thread to wake up 36 | self._main_wake_up.notify_all() 37 | self._main_wake_up.release() 38 | released = True 39 | self._caller_wake_up.wait() 40 | # tell the main thread that we received the result: 41 | self._caller_wake_up.notify_all() 42 | ret = self._return 43 | return ret 44 | finally: 45 | self._obj = None 46 | self._args = None 47 | self._kwargs = None 48 | self._caller_wake_up = None 49 | self._return = None 50 | if not released: 51 | self._main_wake_up.release() 52 | 53 | def quit(self): 54 | self._main_wake_up.acquire() 55 | try: 56 | self._quit = True 57 | self._main_wake_up.notify_all() 58 | finally: 59 | self._main_wake_up.release() 60 | 61 | def run(self): 62 | if not is_main_thread(): 63 | raise Exception("run can only be called from the main thread!") 64 | from . import signals 65 | 66 | def signal_handler(signal, frame): 67 | self._quit = True 68 | 69 | signals.add_sigint_handler(signal_handler) 70 | while True: 71 | try: 72 | self._main_wake_up.wait(1.0) 73 | except KeyboardInterrupt: 74 | self._quit = True 75 | if self._quit: 76 | return 77 | elif self._caller_wake_up is None: 78 | # we timed out 79 | continue 80 | with self._caller_wake_up: 81 | self._return = self._obj.__call__(*self._args, **self._kwargs) 82 | self._caller_wake_up.notify_all() 83 | # wait for the calling thread to confirm it received the result 84 | while not self._caller_wake_up.wait(1.0): 85 | if self._quit: 86 | return 87 | 88 | 89 | class MainThreadWrapper(object): 90 | def __init__(self, mainobj, controller): 91 | self._main = mainobj 92 | self._controller = controller 93 | 94 | def __call__(self, *args, **kwargs): 95 | ret = self._controller.invoke(self._main, *args, **kwargs) 96 | if id(self._main) == id(ret): 97 | return MainThreadWrapper(ret, self._controller) 98 | else: 99 | return ret 100 | 101 | def __getattribute__(self, name): 102 | if name == "_main" or name == "_controller": 103 | return object.__getattribute__(self, name) 104 | elif isinstance(getattr(type(self._main), name), property): 105 | return getattr(self._main, name) 106 | else: 107 | return MainThreadWrapper(getattr(self._main, name), self._controller) 108 | 109 | 110 | if __name__ == "__main__": 111 | 112 | class MainThreadOnlyClass(object): 113 | def do_stuff(self): 114 | if not is_main_thread(): 115 | raise Exception("ERROR!") 116 | return 1337 117 | 118 | main_thread_only = MainThreadOnlyClass() 119 | 120 | controller = MainThreadController() 121 | 122 | def dostuff(mtoc): 123 | print(mtoc.do_stuff()) 124 | 125 | from threading import Thread 126 | 127 | thread = Thread( 128 | target=dostuff, args=(MainThreadWrapper(main_thread_only, controller),) 129 | ) 130 | thread.start() 131 | controller.run() 132 | thread.join() 133 | -------------------------------------------------------------------------------- /etheno/truffle.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Sequence 2 | import shlex 3 | import time 4 | 5 | from typing import Iterable 6 | 7 | from .logger import EthenoLogger, PtyLogger 8 | 9 | 10 | def make_list(args: Iterable): 11 | if isinstance(args, str): 12 | return shlex.split(args) 13 | elif isinstance(args, Sequence) and not isinstance(args, bytes): 14 | if isinstance(args, list): 15 | return args 16 | else: 17 | return list(args) 18 | else: 19 | return [args] 20 | 21 | 22 | class Truffle(object): 23 | def __init__(self, truffle_cmd="truffle", parent_logger=None, log_level=None): 24 | self._running = False 25 | self.logger = EthenoLogger("Truffle", log_level=log_level, parent=parent_logger) 26 | self.truffle_cmd = make_list(truffle_cmd) 27 | 28 | def terminate(self): 29 | self._running = False 30 | 31 | def run_tests(self): 32 | return self.run("test") 33 | 34 | def run_migrate(self): 35 | return self.run("migrate") 36 | 37 | def run(self, args): 38 | self._running = True 39 | args = make_list(args) 40 | 41 | p = PtyLogger(self.logger, ["/usr/bin/env"] + self.truffle_cmd + args) 42 | p.start() 43 | 44 | try: 45 | while p.isalive(): 46 | if not self._running: 47 | self.logger.info( 48 | "Etheno received a shutdown signal; terminating truffle %s" 49 | % " ".join(args) 50 | ) 51 | break 52 | time.sleep(1.0) 53 | except KeyboardInterrupt as e: 54 | self.logger.info( 55 | "Caught keyboard interrupt; terminating truffle %s" % " ".join(args) 56 | ) 57 | raise e 58 | finally: 59 | p.close(force=True) 60 | return p.wait() 61 | -------------------------------------------------------------------------------- /etheno/utils.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import socket 4 | import tempfile 5 | from typing import Optional, Union 6 | from urllib.request import urlopen 7 | from urllib.error import HTTPError, URLError 8 | 9 | 10 | class ConstantTemporaryFile: 11 | def __init__(self, constant_content, **kwargs): 12 | self.constant_content = constant_content 13 | self._file = None 14 | self._kwargs = dict(kwargs) 15 | self._kwargs["mode"] = "w+b" 16 | self._kwargs["delete"] = False 17 | 18 | def __enter__(self) -> str: 19 | self._file = tempfile.NamedTemporaryFile(**self._kwargs) 20 | self._file.write(self.constant_content) 21 | self._file.close() 22 | return self._file.name 23 | 24 | def __exit__(self, type, value, traceback): 25 | if self._file and os.path.exists(self._file.name): 26 | os.remove(self._file.name) 27 | self._file = None 28 | 29 | 30 | def int_to_bytes(n: int) -> bytes: 31 | number_of_bytes = int(math.ceil(n.bit_length() / 8)) 32 | return n.to_bytes(number_of_bytes, byteorder="big") 33 | 34 | 35 | def decode_hex(data: Optional[str]) -> Optional[bytes]: 36 | if data is None: 37 | return None 38 | if data.startswith("0x"): 39 | data = data[2:] 40 | return bytes.fromhex(data) 41 | 42 | 43 | def decode_value(v: Union[str, int]) -> int: 44 | if isinstance(v, int): 45 | return v 46 | elif v.startswith("0x") or ( 47 | frozenset(["a", "b", "c", "d", "e", "f"]) & frozenset(v) 48 | ): 49 | # this is a hex string 50 | return int(v, 16) 51 | else: 52 | # assume it is a regular int 53 | return int(v) 54 | 55 | 56 | def format_hex_address( 57 | addr: Optional[Union[int, str]], add_0x: bool = False 58 | ) -> Optional[str]: 59 | if addr is None: 60 | return None 61 | if isinstance(addr, int): 62 | addr = "%x" % addr 63 | if addr.lower().startswith("0x"): 64 | addr = addr[2:] 65 | if len(addr) < 40: 66 | addr = "%s%s" % ("0" * (40 - len(addr)), addr) 67 | elif 40 < len(addr) < 64: 68 | # this is likely something like a transaction hash, so round up to 32 bytes: 69 | addr = "%s%s" % ("0" * (64 - len(addr)), addr) 70 | if add_0x: 71 | addr = "0x%s" % addr 72 | return addr 73 | 74 | 75 | def webserver_is_up(url: str) -> bool: 76 | try: 77 | return urlopen(url).getcode() 78 | except HTTPError: 79 | # This means we connected 80 | return True 81 | except URLError: 82 | return False 83 | 84 | 85 | def is_port_free(port: int) -> bool: 86 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 87 | return sock.connect_ex(("127.0.0.1", port)) != 0 88 | 89 | 90 | def find_open_port(starting_port: int = 1025) -> int: 91 | for port in range(starting_port, 65536): 92 | if is_port_free(port): 93 | return port 94 | return -1 95 | 96 | 97 | def clear_directory(path: str): 98 | """ 99 | Deletes the contents of a directory, but not the directory itself. 100 | This is safe to use on symlinked directories. 101 | Symlinks will be deleted, but the files and directories they point to will not be deleted. 102 | If `path` itself is a symlink, the symlink will be deleted. 103 | """ 104 | if os.path.islink(path): 105 | os.unlink(path) 106 | return 107 | 108 | for dirpath, dirnames, filenames in os.walk(path, topdown=False): 109 | for dirname in dirnames: 110 | subdir = os.path.join(dirpath, dirname) 111 | os.rmdir(subdir) 112 | for filename in filenames: 113 | os.remove(os.path.join(dirpath, filename)) 114 | 115 | 116 | def ynprompt(prompt: str) -> bool: 117 | while True: 118 | yn = input(prompt) 119 | yn = yn[0:1].lower() 120 | if yn == "n" or yn == "": 121 | return False 122 | elif yn == "y": 123 | return True 124 | -------------------------------------------------------------------------------- /logo/etheno.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crytic/etheno/e0e8028c6d38c1c6d0a7988dd68e4e77f9ce235e/logo/etheno.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="etheno", 5 | description="Etheno is a JSON RPC multiplexer, differential fuzzer, and test framework integration tool.", 6 | url="https://github.com/trailofbits/etheno", 7 | author="Trail of Bits", 8 | version="0.3.2", 9 | packages=find_packages(), 10 | python_requires=">=3.7", 11 | install_requires=[ 12 | "ptyprocess", 13 | "pysha3>=1.0.2", 14 | # TODO: identify what is the oldest flask version that the new shutdown mechanism is compatible with 15 | "flask", 16 | # Pinning web3 to a low version to prevent conflicts with other packages 17 | "web3>=3.16.4", 18 | # Contextual version conflicts between eth-hash, eth-utils, eth-rlp, and rusty-rlp 19 | # This works only if `--platform linux/amd64` is set since rusty-rlp==0.1.15 is not available for ARM architectures 20 | # This is super hacky but it works for now 21 | # This is likely going to cause conflicts with other packages :( 22 | "eth-hash>=0.3.1,<0.4.0", 23 | "eth-utils==1.10.0", 24 | "eth-rlp<0.3.0", 25 | "setuptools", 26 | ], 27 | entry_points={"console_scripts": ["etheno = etheno.__main__:main"]}, 28 | classifiers=[ 29 | "Development Status :: 4 - Beta", 30 | "Environment :: Console", 31 | "Intended Audience :: Developers", 32 | "License :: OSI Approved :: GNU Affero General Public License v3", 33 | "Topic :: Security", 34 | "Topic :: Software Development :: Testing", 35 | ], 36 | ) 37 | -------------------------------------------------------------------------------- /tests/drizzle/contracts/ComplexStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.21 <0.7.0; 3 | 4 | contract ComplexStorage { 5 | uint public storeduint1 = 15; 6 | uint public constant constuint = 16; 7 | uint128 public investmentsLimit = 17055; 8 | uint32 public investmentsDeadlineTimeStamp = uint32(now); 9 | 10 | bytes16 public string1 = "test1"; 11 | bytes32 public string2 = "test1236"; 12 | string public string3 = "lets string something"; 13 | 14 | mapping (address => uint) uints1; 15 | mapping (address => DeviceData) structs1; 16 | 17 | uint[] public uintarray; 18 | DeviceData[] public deviceDataArray; 19 | DeviceData public singleDD; 20 | 21 | struct DeviceData { 22 | string deviceBrand; 23 | string deviceYear; 24 | string batteryWearLevel; 25 | } 26 | 27 | constructor() public { 28 | address address1 = 0xbCcc714d56bc0da0fd33d96d2a87b680dD6D0DF6; 29 | address address2 = 0xaee905FdD3ED851e48d22059575b9F4245A82B04; 30 | 31 | uints1[address1] = 88; 32 | uints1[address2] = 99; 33 | 34 | structs1[address1] = DeviceData("deviceBrand", "deviceYear", "wearLevel"); 35 | structs1[address2] = DeviceData("deviceBrand2", "deviceYear2", "wearLevel2"); 36 | singleDD = DeviceData("deviceBrand3", "deviceYear3", "wearLevel3"); 37 | 38 | uintarray.push(8000); 39 | uintarray.push(9000); 40 | 41 | deviceDataArray.push(structs1[address1]); 42 | deviceDataArray.push(structs1[address2]); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tests/drizzle/contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.21 <0.7.0; 3 | 4 | contract Migrations { 5 | address public owner; 6 | uint public last_completed_migration; 7 | 8 | constructor() public { 9 | owner = msg.sender; 10 | } 11 | 12 | modifier restricted() { 13 | if (msg.sender == owner) _; 14 | } 15 | 16 | function setCompleted(uint completed) public restricted { 17 | last_completed_migration = completed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/drizzle/contracts/SimpleStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.21 <0.7.0; 3 | 4 | contract SimpleStorage { 5 | event StorageSet(string _message); 6 | 7 | uint256 public storedData; 8 | 9 | function set(uint256 x) public { 10 | storedData = x; 11 | 12 | emit StorageSet("Data stored successfully!"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/drizzle/contracts/TutorialToken.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.21 <0.7.0; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 5 | 6 | contract TutorialToken is ERC20 { 7 | string public name = "TutorialToken"; 8 | string public symbol = "TT"; 9 | uint256 public decimals = 2; 10 | uint256 public INITIAL_SUPPLY = 12000; 11 | 12 | constructor() public { 13 | _mint(msg.sender, INITIAL_SUPPLY); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tests/drizzle/hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomiclabs/hardhat-waffle"); 2 | 3 | module.exports = { 4 | networks: { 5 | localhost: { 6 | host: "127.0.0.1", 7 | port: 8545, 8 | } 9 | }, 10 | solidity: { 11 | compilers: [ 12 | { 13 | version: "0.6.12", 14 | }, 15 | { 16 | version: "0.5.0", 17 | } 18 | ] 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /tests/drizzle/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "drizzle-box", 3 | "dependencies": { 4 | "@openzeppelin/contracts": "^2.4.0" 5 | }, 6 | "devDependencies": { 7 | "@nomiclabs/hardhat-waffle": "^2.0.3", 8 | "chai": "^4.3.6", 9 | "ethers": "^5.6.2", 10 | "ganache": "^7.3.2", 11 | "hardhat": "^2.9.2", 12 | "@nomiclabs/hardhat-ethers": "^2.0.5", 13 | "ethereum-waffle": "^3.4.4" 14 | } 15 | } -------------------------------------------------------------------------------- /tests/drizzle/test/TestSimpleStorage.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.4.21 <0.7.0; 2 | 3 | import "truffle/Assert.sol"; 4 | import "truffle/DeployedAddresses.sol"; 5 | import "../contracts/SimpleStorage.sol"; 6 | 7 | contract TestSimpleStorage { 8 | function testItStoresAValue() public { 9 | SimpleStorage simpleStorage = SimpleStorage(DeployedAddresses.SimpleStorage()); 10 | 11 | simpleStorage.set(89); 12 | 13 | uint expected = 89; 14 | 15 | Assert.equal(simpleStorage.storedData(), expected, "It should store the value 89."); 16 | } 17 | } -------------------------------------------------------------------------------- /tests/drizzle/test/simplestorage.js: -------------------------------------------------------------------------------- 1 | const {expect} = require("chai"); 2 | const {ethers} = require("hardhat") 3 | 4 | describe("Deploy SimpleStorage", function() { 5 | it("Deploy", async function() { 6 | // Get Factory 7 | const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage"); 8 | // Deploy 9 | const SimpleStorage = await SimpleStorageFactory.deploy(); 10 | 11 | const [account] = await ethers.getSigners() 12 | await SimpleStorage.set(89, { from: account.address }); 13 | // Check stored value 14 | expect(await SimpleStorage.storedData()).to.equal(89); 15 | // Deploy another 16 | const SimpleStorageTwo = await SimpleStorageFactory.deploy(); 17 | }); 18 | }); 19 | --------------------------------------------------------------------------------