diff --git a/.codespell-whitelist b/.codespell-whitelist deleted file mode 100644 index 21c9c7e4ce907a..00000000000000 --- a/.codespell-whitelist +++ /dev/null @@ -1,7 +0,0 @@ -uint -ith -mitre -readded -crate -developper -ist diff --git a/.gitattributes b/.gitattributes index 98eb0e8ece596f..a9a9d1eb55a62f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,7 @@ # GitHub highlighting for Solidity files # See https://github.com/github/linguist/pull/3973#issuecomment-357507741 *.sol linguist-language=Solidity + +# Force Linux line endings on all files +# Necessary for running eipw locally +* text=auto eol=lf diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000000000..21f1400916aee7 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @eth-bot diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 00000000000000..a34cc168a6aa00 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,3 @@ +Please review [EIP-1](https://eips.ethereum.org/EIPS/eip-1) for EIP guidelines. + + diff --git a/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md similarity index 53% rename from ISSUE_TEMPLATE.md rename to .github/ISSUE_TEMPLATE.md index 28fdd5878292be..63a10ad1ea3073 100644 --- a/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,12 +1,11 @@ - -ATTENTION! If you would like to submit an EIP and it has already been written as a draft (see the [template](https://github.com/ethereum/EIPs/blob/master/eip-X.md) for an example), please submit it as a [Pull Request](https://github.com/ethereum/EIPs/pulls). +ATTENTION! If you would like to submit an EIP and it has already been written as a draft (see the [template](https://github.com/ethereum/EIPs/blob/master/eip-template.md) for an example), please submit it as a [Pull Request](https://github.com/ethereum/EIPs/pulls). If you are considering a proposal but would like to get some feedback on the idea before submitting a draft, then continue opening an Issue as a thread for discussion. Note that the more clearly and completely you state your idea the higher the quality of the feedback you are likely to receive. Keep in mind the following guidelines from [EIP-1](https://eips.ethereum.org/EIPS/eip-1): -> Each EIP must have a champion - someone who writes the EIP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The EIP champion (a.k.a. Author) should first attempt to ascertain whether the idea is EIP-able. Posting to the the Protocol Discussion forum or opening an Issue is the best way to go about this. +> Each EIP must have a champion - someone who writes the EIP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The EIP champion (a.k.a. Author) should first attempt to ascertain whether the idea is EIP-able. Posting to the Protocol Discussion forum or opening an Issue is the best way to go about this. -> Vetting an idea publicly before going as far as writing a EIP is meant to save the potential author time. Asking the Ethereum community first if an idea is original helps prevent too much time being spent on something that is guaranteed to be rejected based on prior discussions (searching the Internet does not always do the trick). It also helps to make sure the idea is applicable to the entire community and not just the author. Just because an idea sounds good to the author does not mean it will work for most people in most areas where Ethereum is used. +> Vetting an idea publicly before going as far as writing an EIP is meant to save the potential author time. Asking the Ethereum community first if an idea is original helps prevent too much time being spent on something that is guaranteed to be rejected based on prior discussions (searching the Internet does not always do the trick). It also helps to make sure the idea is applicable to the entire community and not just the author. Just because an idea sounds good to the author does not mean it will work for most people in most areas where Ethereum is used. -> Once the champion has asked the Ethereum community as to whether an idea has any chance of acceptance, a draft EIP should be presented as a Pull Request. This gives the author a chance to flesh out the draft EIP to make properly formatted, of high quality, and to address initial concerns about the proposal. +> Once the champion has asked the Ethereum community as to whether an idea has any chance of acceptance, a draft EIP should be presented as a Pull Request. This gives the author a chance to flesh out the draft EIP to properly format it, ensure it is high quality, and address initial concerns about the proposal. diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 00000000000000..59893b3a4fb322 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,29 @@ +name: Bug Report +description: File a bug report +labels: ['bug'] + +body: + - type: markdown + attributes: + value: Thanks for taking the time to fill out this bug report! + - type: input + id: pull-request + attributes: + label: Pull Request + description: Link to the pull request where the issue occurred + validations: + required: false + - type: textarea + id: what-happened + attributes: + label: What happened? + description: Also tell us, what did you expect to happen? + placeholder: Tell us what you see! + validations: + required: true + - type: textarea + id: logs + attributes: + label: Relevant log output + description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks. + render: shell diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000000000..1b97141a73a3cf --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Do you want to discuss EIP ideas or ask questions about the process? + url: https://ethereum-magicians.org/ + about: Use the Fellowship of Ethereum Magicians for EIP-related discussion! diff --git a/.github/ISSUE_TEMPLATE/propose-process-change.yml b/.github/ISSUE_TEMPLATE/propose-process-change.yml new file mode 100644 index 00000000000000..4d97a6ba8ab2c9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/propose-process-change.yml @@ -0,0 +1,13 @@ +name: Do you want to propose a change to the EIP process itself? +description: Use this if you want to propose changes to the EIP process +labels: ['enhancement'] + +body: + - type: textarea + id: proposed-change + attributes: + label: Proposed Change + description: What do you think should be different? + placeholder: Describe your proposed change here + validations: + required: true diff --git a/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md similarity index 71% rename from PULL_REQUEST_TEMPLATE.md rename to .github/PULL_REQUEST_TEMPLATE.md index 03f1f3dabb79a2..135008ace3ab1d 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,8 +1,12 @@ -When opening a pull request to submit a new EIP, please use the suggested template: https://github.com/ethereum/EIPs/blob/master/eip-X.md +**ATTENTION: ERC-RELATED PULL REQUESTS NOW OCCUR IN [ETHEREUM/ERCS](https://github.com/ethereum/ercs)** + +-- + +When opening a pull request to submit a new EIP, please use the suggested template: https://github.com/ethereum/EIPs/blob/master/eip-template.md We have a GitHub bot that automatically merges some PRs. It will merge yours immediately if certain criteria are met: - The PR edits only existing draft PRs. - The build passes. - - Your Github username or email address is listed in the 'author' header of all affected PRs, inside . + - Your GitHub username or email address is listed in the 'author' header of all affected PRs, inside . - If matching on email address, the email address is the one publicly listed on your GitHub profile. diff --git a/.github/actions/merge-repos/action.yml b/.github/actions/merge-repos/action.yml new file mode 100644 index 00000000000000..7bab2c33072655 --- /dev/null +++ b/.github/actions/merge-repos/action.yml @@ -0,0 +1,24 @@ +name: Merge ERCs + +runs: + using: 'composite' + steps: + - name: Checkout ERCs + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: ethereum/ERCs + path: ERCs + - name: Merge Repos + shell: bash + run: | + mkdir -p $GITHUB_WORKSPACE/ERCs/ERCS + mkdir -p $GITHUB_WORKSPACE/ERCs/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/ERCS/. $GITHUB_WORKSPACE/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/EIPS/. $GITHUB_WORKSPACE/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/assets/. $GITHUB_WORKSPACE/assets + cd $GITHUB_WORKSPACE/EIPS + find . -name "erc-*.md" -type f -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/erc/eip/)"' _ {} \; | sh + cd $GITHUB_WORKSPACE/assets + find . -name "erc-*" -type d -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/erc/eip/)"' _ {} \; | sh + cd $GITHUB_WORKSPACE + rm -rf ERCs diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 00000000000000..73445ef763d831 --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "config:base", + ":disableDependencyDashboard" + ], + "prConcurrentLimit": 100, + "ignorePaths": [ + "**/assets/**" + ], + "ignoreDeps": [ + "Pandapip1/jekyll-label-action", + "ethereum/eipw-action", + "ethereum/eip-review-bot", + "ethereum/EIP-Bot" + ], + "enabled": false +} diff --git a/.github/workflows/auto-review-bot.yml b/.github/workflows/auto-review-bot.yml new file mode 100644 index 00000000000000..600268097b1e76 --- /dev/null +++ b/.github/workflows/auto-review-bot.yml @@ -0,0 +1,32 @@ +on: + workflow_run: + workflows: + - Auto Review Bot Trigger + types: + - completed + +name: Auto Review Bot +jobs: + auto-review-bot: + runs-on: ubuntu-latest + name: Run + steps: + - name: Fetch PR Number + uses: dawidd6/action-download-artifact@246dbf436b23d7c49e21a7ab8204ca9ecd1fe615 + with: + name: pr-number + workflow: auto-review-trigger.yml + run_id: ${{ github.event.workflow_run.id }} + + - name: Save PR Number + id: save-pr-number + run: echo "pr=$(cat pr-number.txt)" >> $GITHUB_OUTPUT + + - name: Auto Review Bot + id: auto-review-bot + uses: ethereum/eip-review-bot@dist + continue-on-error: true + with: + token: ${{ secrets.TOKEN }} + config: config/eip-editors.yml + pr_number: ${{ steps.save-pr-number.outputs.pr }} diff --git a/.github/workflows/auto-review-trigger.yml b/.github/workflows/auto-review-trigger.yml new file mode 100644 index 00000000000000..ee0a3764d46f8e --- /dev/null +++ b/.github/workflows/auto-review-trigger.yml @@ -0,0 +1,59 @@ +on: + pull_request_target: + pull_request_review: + workflow_dispatch: + inputs: + pr_number: + description: Pull Request Number + type: string + required: true + issue_comment: + types: + - created + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +name: Auto Review Bot Trigger +jobs: + trigger: + runs-on: ubuntu-latest + name: Trigger + steps: + - name: Write PR Number - PR Target + run: echo $PR_NUMBER > pr-number.txt + if: github.event_name == 'pull_request_target' && ((!endsWith(github.event.sender.login, '-bot') && !endsWith(github.event.sender.login, '[bot]')) || github.event.sender.login == 'renovate[bot]') + env: + PR_NUMBER: ${{ github.event.number }} + + - name: Write PR Number - PR Review + run: echo $PR_NUMBER > pr-number.txt + if: github.event_name == 'pull_request_review' && !endsWith(github.event.sender.login, '-bot') && !endsWith(github.event.sender.login, '[bot]') + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + + - name: Write PR Number - Workflow Dispatch + run: echo $PR_NUMBER > pr-number.txt + if: github.event_name == 'workflow_dispatch' + env: + PR_NUMBER: ${{ inputs.pr_number }} + + - name: Write PR Number - Comment Retrigger + run: echo $PR_NUMBER > pr-number.txt + if: github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '@eth-bot rerun') + env: + PR_NUMBER: ${{ github.event.issue.number }} + + - name: Check File Existence + uses: andstor/file-existence-action@20b4d2e596410855db8f9ca21e96fbe18e12930b + id: check_pr_number_exists + with: + files: pr-number.txt + + - name: Save PR Number + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 + if: steps.check_pr_number_exists.outputs.files_exists == 'true' + with: + name: pr-number + path: pr-number.txt diff --git a/.github/workflows/auto-stagnate-bot.yml b/.github/workflows/auto-stagnate-bot.yml new file mode 100644 index 00000000000000..25aca3bf9c9c97 --- /dev/null +++ b/.github/workflows/auto-stagnate-bot.yml @@ -0,0 +1,24 @@ +on: + schedule: + # A job that runs every sunday at 00:00 + - cron: '0 0 * * 0' + workflow_dispatch: + +name: Auto Stagnant Bot +jobs: + auto_merge_bot: + if: github.repository == 'ethereum/eips' + runs-on: ubuntu-latest + name: Auto Stagnant Bot + steps: + - name: Checkout + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f + - name: Setup Node.js Environment + uses: actions/setup-node@d98fa1113850e562f83c7fc3a89c0ecd7a87fbed + with: + node-version: '14' + - name: auto-stagnant-bot + uses: ethereum/EIP-Bot@b3ac0ba3600aea27157fc68d1e36c08cc5a6db77 # mark-eips-stale + id: auto-stagnant-bot + with: + GITHUB-TOKEN: ${{ secrets.TOKEN }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000000000..51060d2f3efaf2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,156 @@ +name: Continuous Integration + +on: + pull_request: + types: + - opened + - reopened + - synchronize + - ready_for_review + - edited + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + save-pr: + name: Save PR Number + runs-on: ubuntu-latest + + steps: + - name: Save PR number + env: + PR_NUMBER: ${{ github.event.number }} + PR_SHA: ${{ github.event.pull_request.head.sha }} + MERGE_SHA: ${{ github.sha }} + run: | + mkdir -p ./pr + echo $PR_NUMBER > ./pr/pr_number + echo $PR_SHA > ./pr/pr_sha + echo $MERGE_SHA > ./pr/merge_sha + + - name: Upload PR Number + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 + with: + name: pr_number + path: pr/ + + htmlproofer: + name: HTMLProofer + runs-on: ubuntu-24.04 + + steps: + - name: Checkout EIPs + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: ethereum/EIPs + path: '' + - name: Merge Repos + uses: ./.github/actions/merge-repos + - name: Setup Ruby + uses: ruby/setup-ruby@fb404b9557c186e349162b0d8efb06e2bc36edea # v1.232.0 + with: + ruby-version: '3.1' # Not needed with a .ruby-version file + bundler-cache: true # runs 'bundle install' and caches installed gems automatically + cache-version: 0 # Increment this number if you need to re-download cached gems + - name: Build with Jekyll + run: bundle exec jekyll build + env: + JEKYLL_ENV: production + + - name: Build Website + run: | + bundle exec jekyll doctor + bundle exec jekyll build + + - name: HTML Proofer + run: bundle exec htmlproofer --allow-missing-href --disable-external --assume-extension '.html' --log-level=:info --cache='{"timeframe":{"external":"6w"}}' --checks 'Links,Images,Scripts,OpenGraph' --no-check-sri --ignore-empty-alt --no-enforce_https ./_site + - name: DNS Validator + run: bundle exec github-pages health-check + + link-check: + name: Link Check + runs-on: ubuntu-latest + + steps: + - name: Checkout EIP Repository + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f + + - name: Link Checker + uses: gaurav-nelson/github-action-markdown-link-check@d53a906aa6b22b8979d33bc86170567e619495ec + with: + config-file: config/mlc_config.json + use-quiet-mode: no + use-verbose-mode: yes + check-modified-files-only: yes + + codespell: + name: CodeSpell + runs-on: ubuntu-latest + + steps: + - name: Checkout EIP Repository + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f + + - name: Get Changed Files + id: changed + continue-on-error: true + run: | + echo "CHANGED_FILES<> $GITHUB_ENV + gh pr diff ${{ github.event.number }} --name-only | sed -e 's|$|,|' | xargs -i echo "{}" >> $GITHUB_ENV + echo "EOF" >> $GITHUB_ENV + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Run CodeSpell + uses: codespell-project/actions-codespell@57beb9f38f49d773d641ac555d1565c3b6a59938 + if: steps.changed.outcome == 'success' + with: + check_filenames: true + ignore_words_file: config/.codespell-whitelist + path: ${{ env.CHANGED_FILES }} + skip: .git,Gemfile.lock,**/*.png,**/*.gif,**/*.jpg,**/*.svg,.codespell-whitelist,vendor,_site,_config.yml,style.css + + eipw-validator: + name: EIP Walidator + runs-on: ubuntu-latest + + steps: + - name: Checkout EIP Repository + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f + - name: Merge Repos + uses: ./.github/actions/merge-repos + + - uses: ethereum/eipw-action@be3fa642ec311d0b8e1fdb811e5c9b4ada3d3d93 + id: eipw + with: + token: ${{ secrets.GITHUB_TOKEN }} + unchecked: 1, 5069, 5757 + options-file: config/eipw.toml + + markdownlint: + name: Markdown Linter + runs-on: ubuntu-latest + steps: + - name: Checkout EIP Repository + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f + + - name: Get Changed Files + id: changed + continue-on-error: true + run: | + echo "CHANGED_FILES<> $GITHUB_ENV + gh pr diff ${{ github.event.number }} --name-only | grep -E -x '[^/]+\.md|EIPS/eip-[0-9]+\.md' >> $GITHUB_ENV + echo "EOF" >> $GITHUB_ENV + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Lint + uses: DavidAnson/markdownlint-cli2-action@f5cf187ef11bd3a68a127321b794aa252ff23019 + if: steps.changed.outcome == 'success' + with: + command: config + globs: | + config/.markdownlint.yaml + ${{ env.CHANGED_FILES }} diff --git a/.github/workflows/jekyll-label-bot.yml b/.github/workflows/jekyll-label-bot.yml new file mode 100644 index 00000000000000..73307415ca91dd --- /dev/null +++ b/.github/workflows/jekyll-label-bot.yml @@ -0,0 +1,20 @@ +on: + pull_request_target: + branches: + - master + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +name: Jekyll Label Bot +jobs: + jekyll-label-action: + name: Label + runs-on: ubuntu-latest + + steps: + - uses: Pandapip1/jekyll-label-action@4b7cce7588a8686f5146a8e12aab7269042057ce + with: + token: ${{ secrets.GITHUB_TOKEN }} + config-path: config/.jekyll-labels.yml diff --git a/.github/workflows/jekyll.yml b/.github/workflows/jekyll.yml new file mode 100644 index 00000000000000..3abe21988a7efa --- /dev/null +++ b/.github/workflows/jekyll.yml @@ -0,0 +1,71 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +# Sample workflow for building and deploying a Jekyll site to GitHub Pages +name: Deploy Jekyll site to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["master"] + schedule: + - cron: "*/15 * * * *" # Every 15 minutes + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + # Build job + build: + runs-on: ubuntu-latest + steps: + - name: Checkout EIPs + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: ethereum/EIPs + path: '' + - name: Merge Repos + uses: ./.github/actions/merge-repos + - name: Setup Ruby + uses: ruby/setup-ruby@f26937343756480a8cb3ae1f623b9c8d89ed6984 # v1.196.0 + with: + ruby-version: '3.1' # Not needed with a .ruby-version file + bundler-cache: true # runs 'bundle install' and caches installed gems automatically + cache-version: 0 # Increment this number if you need to re-download cached gems + - name: Setup Pages + id: pages + uses: actions/configure-pages@v5 + - name: Build with Jekyll + # Outputs to the './_site' directory by default + run: bundle exec jekyll build --baseurl "${{ steps.pages.outputs.base_path }}" + env: + JEKYLL_ENV: production + - name: Upload artifact + # Automatically uploads an artifact from the './_site' directory by default + uses: actions/upload-pages-artifact@v3 + + # Deployment job + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/post-ci.yml b/.github/workflows/post-ci.yml new file mode 100644 index 00000000000000..7057a97f3017cd --- /dev/null +++ b/.github/workflows/post-ci.yml @@ -0,0 +1,56 @@ +on: + workflow_run: + workflows: + - Continuous Integration + types: + - completed + +name: Post CI + +# This is adapted from https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run (2022-07-17) + +jobs: + on-failure: + runs-on: ubuntu-latest + steps: + - name: Fetch PR Data + uses: dawidd6/action-download-artifact@246dbf436b23d7c49e21a7ab8204ca9ecd1fe615 + with: + name: pr_number + workflow: ci.yml + run_id: ${{ github.event.workflow_run.id }} + + - name: Save PR Data + id: save-pr-data + run: | + echo "pr_number=$(cat pr_number)" >> $GITHUB_OUTPUT + echo "pr_sha=$(cat pr_sha)" >> $GITHUB_OUTPUT + echo "merge_sha=$(cat merge_sha)" >> $GITHUB_OUTPUT + + - name: Add Comment + uses: marocchino/sticky-pull-request-comment@39c5b5dc7717447d0cba270cd115037d32d28443 + if: ${{ github.event.workflow_run.conclusion == 'failure' }} + with: + number: ${{ steps.save-pr-data.outputs.pr_number }} + recreate: true + message: | + The commit ${{ steps.save-pr-data.outputs.pr_sha }} (as a parent of ${{ steps.save-pr-data.outputs.merge_sha }}) contains errors. + Please inspect the [Run Summary](https://github.com/ethereum/EIPs/pull/${{ steps.save-pr-data.outputs.pr_number }}/files) for details. + + - name: Add Waiting Label + uses: actions-ecosystem/action-add-labels@288072f1a3b596f4350fe135bcfe381a23abadef + if: ${{ github.event.workflow_run.conclusion == 'failure' }} + with: + labels: w-ci + number: ${{ steps.save-pr-data.outputs.pr_number }} + repo: ${{ github.repository }} + github_token: ${{ github.token }} + + - name: Remove Waiting Label + uses: actions-ecosystem/action-remove-labels@d05162525702062b6bdef750ed8594fc024b3ed7 + if: ${{ github.event.workflow_run.conclusion != 'failure' }} + with: + labels: w-ci + number: ${{ steps.save-pr-data.outputs.pr_number }} + repo: ${{ github.repository }} + github_token: ${{ github.token }} diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 00000000000000..f66a950b09ce8b --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,35 @@ +name: Mark stale PRs & Issues + +on: + schedule: + - cron: 0 0 * * * # Runs at 00:00 UTC every day. + +permissions: + issues: write + pull-requests: write + +jobs: + stale: + if: github.repository == 'ethereum/eips' + runs-on: ubuntu-latest + name: Mark Stale Issues + steps: + - uses: actions/stale@03af7c36d33f4905e618fac0a1bb7e6d05f0d41b + with: + # General + repo-token: ${{ secrets.GITHUB_TOKEN }} + ascending: true # Since we have so many issues, the stale bot finds it hard to keep track. This makes sure that at least the oldest are removed. + # Issue config + stale-issue-message: There has been no activity on this issue for six months. It will be closed in 7 days if there is no new activity. + close-issue-message: This issue was closed due to inactivity. If you are still pursuing it, feel free to reopen it and respond to any feedback. + days-before-issue-stale: 183 + days-before-issue-close: 190 + exempt-issue-labels: discussions-to + stale-issue-label: w-stale + # PR config + stale-pr-message: There has been no activity on this issue for six months. It will be closed in 7 days if there is no new activity. If you would like to move this PR forward, please respond to any outstanding feedback or add a comment indicating that you have addressed all required feedback and are ready for a review. + close-pr-message: This pull request was closed due to inactivity. If you are still pursuing it, feel free to reopen it and respond to any feedback or request a review in a comment. + days-before-pr-stale: 183 + days-before-pr-close: 190 + exempt-pr-milestones: "Manual Merge Queue" + stale-pr-label: w-stale diff --git a/.gitignore b/.gitignore index 45c150536e5f38..8503a3cdadb0d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,13 @@ +# Website packaging _site .sass-cache .jekyll-metadata +vendor + +# Editor files +.gitpod.yml +.DS_Store +/.idea + +# Secrets +.vercel diff --git a/.travis-ci.sh b/.travis-ci.sh deleted file mode 100755 index 98b6f81471edd4..00000000000000 --- a/.travis-ci.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -set -e # halt script on error - -HTMLPROOFER_OPTIONS="./_site --internal-domains=eips.ethereum.org --check-html --check-opengraph --report-missing-names --log-level=:debug --assume-extension --empty-alt-ignore --timeframe=6w --url-ignore=/EIPS/eip-1,EIPS/eip-1,/EIPS/eip-107,/EIPS/eip-858" - -if [[ $TASK = 'htmlproofer' ]]; then - bundle exec jekyll doctor - bundle exec jekyll build - bundle exec htmlproofer $HTMLPROOFER_OPTIONS --disable-external - - # Validate GH Pages DNS setup - bundle exec github-pages health-check -elif [[ $TASK = 'htmlproofer-external' ]]; then - bundle exec jekyll doctor - bundle exec jekyll build - bundle exec htmlproofer $HTMLPROOFER_OPTIONS --external_only -elif [[ $TASK = 'eip-validator' ]]; then - BAD_FILES="$(ls EIPS | egrep -v "eip-[0-9]+.md|eip-20-token-standard.md")" || true - if [[ ! -z $BAD_FILES ]]; then - echo "Files found with invalid names:" - echo $BAD_FILES - exit 1 - fi - - FILES="$(ls EIPS/*.md | egrep "eip-[0-9]+.md")" - bundle exec eip_validator $FILES -elif [[ $TASK = 'codespell' ]]; then - codespell -q4 -I .codespell-whitelist eip-X.md EIPS/ -fi diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 70b2fd191a57fe..00000000000000 --- a/.travis.yml +++ /dev/null @@ -1,48 +0,0 @@ -sudo: false # route your build to the container-based infrastructure for a faster build - -language: ruby - -before_install: - - gem install bundler -v '< 2' - -cache: - # Cache Ruby bundles - - bundler - - directories: - - $TRAVIS_BUILD_DIR/tmp/.htmlproofer #https://github.com/gjtorikian/html-proofer/issues/381 - - /usr/local/lib/python3.3/dist-packages/pip/ - -# Assume bundler is being used, therefore -# the `install` step will run `bundle install` by default. -script: "bash -ex .travis-ci.sh" - -env: - global: - - NOKOGIRI_USE_SYSTEM_LIBRARIES=true # speeds up installation of html-proofer - -matrix: - fast_finish: true - include: - - rvm: 2.2.5 - env: TASK='htmlproofer' - - rvm: 2.2.5 - env: TASK='htmlproofer-external' - - rvm: 2.2.5 - env: TASK='eip-validator' - - python: 3.3 - env: TASK='codespell' - before_script: "sudo pip install urllib3[secure] && sudo pip install codespell" - allow_failures: - - rvm: 2.2.5 - env: TASK='htmlproofer-external' - -notifications: - webhooks: - urls: - - https://ethlab-183014.appspot.com/merge/ - on_success: always - -addons: - apt: - packages: - "libcurl4-openssl-dev" # https://github.com/gjtorikian/html-proofer/issues/376#issuecomment-332767999 diff --git a/404.html b/404.html index c472b4ea0a7810..faf7e23559089f 100644 --- a/404.html +++ b/404.html @@ -18,7 +18,6 @@

404

-

Page not found :(

The requested page could not be found.

diff --git a/EIPS/eip-1.md b/EIPS/eip-1.md index 642965c0dab5ab..b3ee5d459633a2 100644 --- a/EIPS/eip-1.md +++ b/EIPS/eip-1.md @@ -1,12 +1,10 @@ --- eip: 1 title: EIP Purpose and Guidelines -status: Active +status: Living type: Meta -author: Martin Becze , Hudson Jameson , and others - https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1.md +author: Martin Becze , Hudson Jameson , et al. created: 2015-10-27 -updated: 2015-12-07, 2016-02-01, 2018-03-21, 2018-05-29, 2018-10-17 --- ## What is an EIP? @@ -23,113 +21,134 @@ For Ethereum implementers, EIPs are a convenient way to track the progress of th There are three types of EIP: -- A **Standard Track EIP** describes any change that affects most or all Ethereum implementations, such as a change to the network protocol, a change in block or transaction validity rules, proposed application standards/conventions, or any change or addition that affects the interoperability of applications using Ethereum. Furthermore Standard EIPs can be broken down into the following categories. Standards Track EIPs consist of three parts, a design document, implementation, and finally if warranted an update to the [formal specification]. - - **Core** - improvements requiring a consensus fork (e.g. [EIP5], [EIP101]), as well as changes that are not necessarily consensus critical but may be relevant to [“core dev” discussions](https://github.com/ethereum/pm) (for example, [EIP90], and the miner/node strategy changes 2, 3, and 4 of [EIP86]). - - **Networking** - includes improvements around [devp2p] ([EIP8]) and [Light Ethereum Subprotocol], as well as proposed improvements to network protocol specifications of [whisper] and [swarm]. - - **Interface** - includes improvements around client [API/RPC] specifications and standards, and also certain language-level standards like method names ([EIP6]) and [contract ABIs]. The label “interface” aligns with the [interfaces repo] and discussion should primarily occur in that repository before an EIP is submitted to the EIPs repository. - - **ERC** - application-level standards and conventions, including contract standards such as token standards ([ERC20]), name registries ([ERC26], [ERC137]), URI schemes ([ERC67]), library/package formats ([EIP82]), and wallet formats ([EIP75], [EIP85]). +- A **Standards Track EIP** describes any change that affects most or all Ethereum implementations, such as—a change to the network protocol, a change in block or transaction validity rules, proposed application standards/conventions, or any change or addition that affects the interoperability of applications using Ethereum. Standards Track EIPs consist of three parts—a design document, an implementation, and (if warranted) an update to the [formal specification](https://github.com/ethereum/yellowpaper). Furthermore, Standards Track EIPs can be broken down into the following categories: + - **Core**: improvements requiring a consensus fork (e.g. [EIP-5](./eip-5.md), [EIP-101](./eip-101.md)), as well as changes that are not necessarily consensus critical but may be relevant to [“core dev” discussions](https://github.com/ethereum/pm) (for example, [EIP-90], and the miner/node strategy changes 2, 3, and 4 of [EIP-86](./eip-86.md)). + - **Networking**: includes improvements around [devp2p](https://github.com/ethereum/devp2p/blob/readme-spec-links/rlpx.md) ([EIP-8](./eip-8.md)) and [Light Ethereum Subprotocol](https://ethereum.org/en/developers/docs/nodes-and-clients/#light-node), as well as proposed improvements to network protocol specifications of [whisper](https://github.com/ethereum/go-ethereum/issues/16013#issuecomment-364639309) and [swarm](https://github.com/ethereum/go-ethereum/pull/2959). + - **Interface**: includes improvements around language-level standards like method names ([EIP-6](./eip-6.md)) and [contract ABIs](https://docs.soliditylang.org/en/develop/abi-spec.html). + - **ERC**: application-level standards and conventions, including contract standards such as token standards ([ERC-20](./eip-20.md)), name registries ([ERC-137](./eip-137.md)), URI schemes, library/package formats, and wallet formats. + - A **Meta EIP** describes a process surrounding Ethereum or proposes a change to (or an event in) a process. Process EIPs are like Standards Track EIPs but apply to areas other than the Ethereum protocol itself. They may propose an implementation, but not to Ethereum's codebase; they often require community consensus; unlike Informational EIPs, they are more than recommendations, and users are typically not free to ignore them. Examples include procedures, guidelines, changes to the decision-making process, and changes to the tools or environment used in Ethereum development. Any meta-EIP is also considered a Process EIP. + - An **Informational EIP** describes an Ethereum design issue, or provides general guidelines or information to the Ethereum community, but does not propose a new feature. Informational EIPs do not necessarily represent Ethereum community consensus or a recommendation, so users and implementers are free to ignore Informational EIPs or follow their advice. It is highly recommended that a single EIP contain a single key proposal or new idea. The more focused the EIP, the more successful it tends to be. A change to one client doesn't require an EIP; a change that affects multiple clients, or defines a standard for multiple apps to use, does. An EIP must meet certain minimum criteria. It must be a clear and complete description of the proposed enhancement. The enhancement must represent a net improvement. The proposed implementation, if applicable, must be solid and must not complicate the protocol unduly. +### Special requirements for Core EIPs + +If a **Core** EIP mentions or proposes changes to the EVM (Ethereum Virtual Machine), it should refer to the instructions by their mnemonics and define the opcodes of those mnemonics at least once. A preferred way is the following: + +``` +REVERT (0xfe) +``` + ## EIP Work Flow +### Shepherding an EIP + Parties involved in the process are you, the champion or *EIP author*, the [*EIP editors*](#eip-editors), and the [*Ethereum Core Developers*](https://github.com/ethereum/pm). -:warning: Before you begin, vet your idea, this will save you time. Ask the Ethereum community first if an idea is original to avoid wasting time on something that will be rejected based on prior research (searching the Internet does not always do the trick). It also helps to make sure the idea is applicable to the entire community and not just the author. Just because an idea sounds good to the author does not mean it will work for most people in most areas where Ethereum is used. Examples of appropriate public forums to gauge interest around your EIP include [the Ethereum subreddit], [the Issues section of this repository], and [one of the Ethereum Gitter chat rooms]. In particular, [the Issues section of this repository] is an excellent place to discuss your proposal with the community and start creating more formalized language around your EIP. +Before you begin writing a formal EIP, you should vet your idea. Ask the Ethereum community first if an idea is original to avoid wasting time on something that will be rejected based on prior research. It is thus recommended to open a discussion thread on [the Ethereum Magicians forum](https://ethereum-magicians.org/) to do this. -Your role as the champion is to write the EIP using the style and format described below, shepherd the discussions in the appropriate forums, and build community consensus around the idea. Following is the process that a successful EIP will move along: +Once the idea has been vetted, your next responsibility will be to present (by means of an EIP) the idea to the reviewers and all interested parties, invite editors, developers, and the community to give feedback on the aforementioned channels. You should try and gauge whether the interest in your EIP is commensurate with both the work involved in implementing it and how many parties will have to conform to it. For example, the work required for implementing a Core EIP will be much greater than for an ERC and the EIP will need sufficient interest from the Ethereum client teams. Negative community feedback will be taken into consideration and may prevent your EIP from moving past the Draft stage. -``` -[ WIP ] -> [ DRAFT ] -> [ LAST CALL ] -> [ ACCEPTED ] -> [ FINAL ] -``` +### Core EIPs + +For Core EIPs, given that they require client implementations to be considered **Final** (see "EIPs Process" below), you will need to either provide an implementation for clients or convince clients to implement your EIP. + +The best way to get client implementers to review your EIP is to present it on an AllCoreDevs call. You can request to do so by posting a comment linking your EIP on an [AllCoreDevs agenda GitHub Issue](https://github.com/ethereum/pm/issues). + +The AllCoreDevs call serves as a way for client implementers to do three things. First, to discuss the technical merits of EIPs. Second, to gauge what other clients will be implementing. Third, to coordinate EIP implementation for network upgrades. + +These calls generally result in a "rough consensus" around what EIPs should be implemented. This "rough consensus" rests on the assumptions that EIPs are not contentious enough to cause a network split and that they are technically sound. + +:warning: The EIPs process and AllCoreDevs call were not designed to address contentious non-technical issues, but, due to the lack of other ways to address these, often end up entangled in them. This puts the burden on client implementers to try and gauge community sentiment, which hinders the technical coordination function of EIPs and AllCoreDevs calls. If you are shepherding an EIP, you can make the process of building community consensus easier by making sure that [the Ethereum Magicians forum](https://ethereum-magicians.org/) thread for your EIP includes or links to as much of the community discussion as possible and that various stakeholders are well-represented. + +*In short, your role as the champion is to write the EIP using the style and format described below, shepherd the discussions in the appropriate forums, and build community consensus around the idea.* + +### EIP Process + +The following is the standardization process for all EIPs in all tracks: + +![EIP Status Diagram](../assets/eip-1/EIP-process-update.jpg) + +**Idea** - An idea that is pre-draft. This is not tracked within the EIP Repository. + +**Draft** - The first formally tracked stage of an EIP in development. An EIP is merged by an EIP Editor into the EIP repository when properly formatted. + +**Review** - An EIP Author marks an EIP as ready for and requesting Peer Review. + +**Last Call** - This is the final review window for an EIP before it is moved to `Final`. An EIP enters `Last Call` when the specification is stable and the author opens a PR with a review end date (`last-call-deadline`), typically 14 days later. -Each status change is requested by the EIP author and reviewed by the EIP editors. Use a pull request to update the status. Please include a link to where people should continue discussing your EIP. The EIP editors will process these requests as per the conditions below. - -* **Active** -- Some Informational and Process EIPs may also have a status of “Active” if they are never meant to be completed. E.g. EIP 1 (this EIP). -* **Work in progress (WIP)** -- Once the champion has asked the Ethereum community whether an idea has any chance of support, they will write a draft EIP as a [pull request]. Consider including an implementation if this will aid people in studying the EIP. - * :arrow_right: Draft -- If agreeable, EIP editor will assign the EIP a number (generally the issue or PR number related to the EIP) and merge your pull request. The EIP editor will not unreasonably deny an EIP. - * :x: Draft -- Reasons for denying draft status include being too unfocused, too broad, duplication of effort, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the [Ethereum philosophy](https://github.com/ethereum/wiki/wiki/White-Paper#philosophy). -* **Draft** -- Once the first draft has been merged, you may submit follow-up pull requests with further changes to your draft until such point as you believe the EIP to be mature and ready to proceed to the next status. An EIP in draft status must be implemented to be considered for promotion to the next status (ignore this requirement for core EIPs). - * :arrow_right: Last Call -- If agreeable, the EIP editor will assign Last Call status and set a review end date (`review-period-end`), normally 14 days later. - * :x: Last Call -- A request for Last Call status will be denied if material changes are still expected to be made to the draft. We hope that EIPs only enter Last Call once, so as to avoid unnecessary noise on the RSS feed. -* **Last Call** -- This EIP will listed prominently on the https://eips.ethereum.org/ website (subscribe via RSS at [last-call.xml](/last-call.xml)). - * :x: -- A Last Call which results in material changes or substantial unaddressed technical complaints will cause the EIP to revert to Draft. - * :arrow_right: Accepted (Core EIPs only) -- A successful Last Call without material changes or unaddressed technical complaints will become Accepted. - * :arrow_right: Final (Not core EIPs) -- A successful Last Call without material changes or unaddressed technical complaints will become Final. -* **Accepted (Core EIPs only)** -- This EIP is in the hands of the Ethereum client developers. Their process for deciding whether to encode it into their clients as part of a hard fork is not part of the EIP process. - * :arrow_right: Final -- Standards Track Core EIPs must be implemented in at least three viable Ethereum clients before it can be considered Final. When the implementation is complete and adopted by the community, the status will be changed to “Final”. -* **Final** -- This EIP represents the current state-of-the-art. A Final EIP should only be updated to correct errata. - -Other exceptional statuses include: - -* **Deferred** -- This is for core EIPs that have been put off for a future hard fork. -* **Rejected** -- An EIP that is fundamentally broken or a Core EIP that was rejected by the Core Devs and will not be implemented. -* **Active** -- This is similar to Final, but denotes an EIP which may be updated without changing its EIP number. -* **Superseded** -- An EIP which was previously final but is no longer considered state-of-the-art. Another EIP will be in Final status and reference the Superseded EIP. +If this period results in necessary normative changes it will revert the EIP to `Review`. + +**Final** - This EIP represents the final standard. A Final EIP exists in a state of finality and should only be updated to correct errata and add non-normative clarifications. + +A PR moving an EIP from Last Call to Final SHOULD contain no changes other than the status update. Any content or editorial proposed change SHOULD be separate from this status-updating PR and committed prior to it. + +**Stagnant** - Any EIP in `Draft` or `Review` or `Last Call` if inactive for a period of 6 months or greater is moved to `Stagnant`. An EIP may be resurrected from this state by Authors or EIP Editors through moving it back to `Draft` or its earlier status. If not resurrected, a proposal may stay forever in this status. + +>*EIP Authors are notified of any algorithmic change to the status of their EIP* + +**Withdrawn** - The EIP Author(s) have withdrawn the proposed EIP. This state has finality and can no longer be resurrected using this EIP number. If the idea is pursued at later date it is considered a new proposal. + +**Living** - A special status for EIPs that are designed to be continually updated and not reach a state of finality. This includes most notably EIP-1. ## What belongs in a successful EIP? Each EIP should have the following parts: -- Preamble - RFC 822 style headers containing metadata about the EIP, including the EIP number, a short descriptive title (limited to a maximum of 44 characters), and the author details. See [below](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1.md#eip-header-preamble) for details. -- Simple Summary - “If you can’t explain it simply, you don’t understand it well enough.” Provide a simplified and layman-accessible explanation of the EIP. -- Abstract - a short (~200 word) description of the technical issue being addressed. -- Motivation (*optional) - The motivation is critical for EIPs that want to change the Ethereum protocol. It should clearly explain why the existing protocol specification is inadequate to address the problem that the EIP solves. EIP submissions without sufficient motivation may be rejected outright. -- Specification - The technical specification should describe the syntax and semantics of any new feature. The specification should be detailed enough to allow competing, interoperable implementations for any of the current Ethereum platforms (cpp-ethereum, go-ethereum, parity, ethereumJ, ethereumjs-lib, [and others](https://github.com/ethereum/wiki/wiki/Clients). -- Rationale - The rationale fleshes out the specification by describing what motivated the design and why particular design decisions were made. It should describe alternate designs that were considered and related work, e.g. how the feature is supported in other languages. The rationale may also provide evidence of consensus within the community, and should discuss important objections or concerns raised during discussion. -- Backwards Compatibility - All EIPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The EIP must explain how the author proposes to deal with these incompatibilities. EIP submissions without a sufficient backwards compatibility treatise may be rejected outright. -- Test Cases - Test cases for an implementation are mandatory for EIPs that are affecting consensus changes. Other EIPs can choose to include links to test cases if applicable. -- Implementations - The implementations must be completed before any EIP is given status “Final”, but it need not be completed before the EIP is merged as draft. While there is merit to the approach of reaching consensus on the specification and rationale before writing code, the principle of “rough consensus and running code” is still useful when it comes to resolving many discussions of API details. -- Copyright Waiver - All EIPs must be in the public domain. See the bottom of this EIP for an example copyright waiver. +- Preamble - RFC 822 style headers containing metadata about the EIP, including the EIP number, a short descriptive title (limited to a maximum of 44 characters), a description (limited to a maximum of 140 characters), and the author details. Irrespective of the category, the title and description should not include EIP number. See [below](./eip-1.md#eip-header-preamble) for details. +- Abstract - Abstract is a multi-sentence (short paragraph) technical summary. This should be a very terse and human-readable version of the specification section. Someone should be able to read only the abstract to get the gist of what this specification does. +- Motivation *(optional)* - A motivation section is critical for EIPs that want to change the Ethereum protocol. It should clearly explain why the existing protocol specification is inadequate to address the problem that the EIP solves. This section may be omitted if the motivation is evident. +- Specification - The technical specification should describe the syntax and semantics of any new feature. The specification should be detailed enough to allow competing, interoperable implementations for any of the current Ethereum platforms (besu, erigon, ethereumjs, go-ethereum, nethermind, or others). +- Rationale - The rationale fleshes out the specification by describing what motivated the design and why particular design decisions were made. It should describe alternate designs that were considered and related work, e.g. how the feature is supported in other languages. The rationale should discuss important objections or concerns raised during discussion around the EIP. +- Backwards Compatibility *(optional)* - All EIPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their consequences. The EIP must explain how the author proposes to deal with these incompatibilities. This section may be omitted if the proposal does not introduce any backwards incompatibilities, but this section must be included if backward incompatibilities exist. +- Test Cases *(optional)* - Test cases for an implementation are mandatory for EIPs that are affecting consensus changes. Tests should either be inlined in the EIP as data (such as input/expected output pairs) or included in `../assets/eip-###/`. This section may be omitted for non-Core proposals. +- Reference Implementation *(optional)* - An optional section that contains a reference/example implementation that people can use to assist in understanding or implementing this specification. This section may be omitted for all EIPs. +- Security Considerations - All EIPs must contain a section that discusses the security implications/considerations relevant to the proposed change. Include information that might be important for security discussions, surfaces risks and can be used throughout the life-cycle of the proposal. E.g. include security-relevant design decisions, concerns, important discussions, implementation-specific guidance and pitfalls, an outline of threats and risks and how they are being addressed. EIP submissions missing the "Security Considerations" section will be rejected. An EIP cannot proceed to status "Final" without a Security Considerations discussion deemed sufficient by the reviewers. +- Copyright Waiver - All EIPs must be in the public domain. The copyright waiver MUST link to the license file and use the following wording: `Copyright and related rights waived via [CC0](../LICENSE.md).` ## EIP Formats and Templates -EIPs should be written in [markdown] format. -Image files should be included in a subdirectory of the `assets` folder for that EIP as follows: `assets/eip-X` (for eip **X**). When linking to an image in the EIP, use relative links such as `../assets/eip-X/image.png`. +EIPs should be written in [markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) format. There is a [template](https://github.com/ethereum/EIPs/blob/master/eip-template.md) to follow. ## EIP Header Preamble -Each EIP must begin with an [RFC 822](https://www.ietf.org/rfc/rfc822.txt) style header preamble, preceded and followed by three hyphens (`---`). This header is also termed ["front matter" by Jekyll](https://jekyllrb.com/docs/front-matter/). The headers must appear in the following order. Headers marked with "*" are optional and are described below. All other headers are required. +Each EIP must begin with an [RFC 822](https://www.ietf.org/rfc/rfc822.txt) style header preamble, preceded and followed by three hyphens (`---`). This header is also termed ["front matter" by Jekyll](https://jekyllrb.com/docs/front-matter/). The headers must appear in the following order. -` eip:` (this is determined by the EIP editor) +`eip`: *EIP number* -` title:` +`title`: *The EIP title is a few words, not a complete sentence* -` author:` +`description`: *Description is one full (short) sentence* -` * discussions-to:` \ +`author`: *The list of the author's or authors' name(s) and/or username(s), or name(s) and email(s). Details are below.* -` status:` +`discussions-to`: *The url pointing to the official discussion thread* -`* review-period-end:` +`status`: *Draft, Review, Last Call, Final, Stagnant, Withdrawn, Living* -` type:` +`last-call-deadline`: *The date last call period ends on* (Optional field, only needed when status is `Last Call`) -` * category:` +`type`: *One of `Standards Track`, `Meta`, or `Informational`* -` created:` +`category`: *One of `Core`, `Networking`, `Interface`, or `ERC`* (Optional field, only needed for `Standards Track` EIPs) -` * updated:` +`created`: *Date the EIP was created on* -` * requires:` +`requires`: *EIP number(s)* (Optional field) -` * replaces:` - -` * superseded-by:` - -` * resolution:` \ +`withdrawal-reason`: *A sentence explaining why the EIP was withdrawn.* (Optional field, only needed when status is `Withdrawn`) Headers that permit lists must separate elements with commas. Headers requiring dates will always do so in the format of ISO 8601 (yyyy-mm-dd). -#### `author` header +### `author` header -The `author` header optionally lists the names, email addresses or usernames of the authors/owners of the EIP. Those who prefer anonymity may use a username only, or a first name and a username. The format of the author header value must be: +The `author` header lists the names, email addresses or usernames of the authors/owners of the EIP. Those who prefer anonymity may use a username only, or a first name and a username. The format of the `author` header value must be: > Random J. User <address@dom.ain> @@ -137,77 +156,413 @@ or > Random J. User (@username) -if the email address or GitHub username is included, and +or -> Random J. User +> Random J. User (@username) <address@dom.ain> -if the email address is not given. +if the email address and/or GitHub username is included, and -#### `resolution` header +> Random J. User -The `resolution` header is required for Standards Track EIPs only. It contains a URL that should point to an email message or other web resource where the pronouncement about the EIP is made. +if neither the email address nor the GitHub username are given. -#### `discussions-to` header +At least one author must use a GitHub username, in order to get notified on change requests and have the capability to approve or reject them. -While an EIP is a draft, a `discussions-to` header will indicate the mailing list or URL where the EIP is being discussed. As mentioned above, examples for places to discuss your EIP include [Ethereum topics on Gitter](https://gitter.im/ethereum/topics), an issue in this repo or in a fork of this repo, [Ethereum Magicians](https://ethereum-magicians.org/) (this is suitable for EIPs that may be contentious or have a strong governance aspect), and [Reddit r/ethereum](https://www.reddit.com/r/ethereum/). +### `discussions-to` header -No `discussions-to` header is necessary if the EIP is being discussed privately with the author. +While an EIP is a draft, a `discussions-to` header will indicate the URL where the EIP is being discussed. -As a single exception, `discussions-to` cannot point to GitHub pull requests. +The preferred discussion URL is a topic on [Ethereum Magicians](https://ethereum-magicians.org/). The URL cannot point to Github pull requests, any URL which is ephemeral, and any URL which can get locked over time (i.e. Reddit topics). -#### `type` header +### `type` header The `type` header specifies the type of EIP: Standards Track, Meta, or Informational. If the track is Standards please include the subcategory (core, networking, interface, or ERC). -#### `category` header +### `category` header The `category` header specifies the EIP's category. This is required for standards-track EIPs only. -#### `created` header +### `created` header The `created` header records the date that the EIP was assigned a number. Both headers should be in yyyy-mm-dd format, e.g. 2001-08-14. -#### `updated` header +### `requires` header + +EIPs may have a `requires` header, indicating the EIP numbers that this EIP depends on. If such a dependency exists, this field is required. + +A `requires` dependency is created when the current EIP cannot be understood or implemented without a concept or technical element from another EIP. Merely mentioning another EIP does not necessarily create such a dependency. + +## Linking to External Resources + +Other than the specific exceptions listed below, links to external resources **SHOULD NOT** be included. External resources may disappear, move, or change unexpectedly. + +The process governing permitted external resources is described in [EIP-5757](./eip-5757.md). + +### Execution Client Specifications + +Links to the Ethereum Execution Client Specifications may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Execution Client Specifications](https://github.com/ethereum/execution-specs/blob/9a1f22311f517401fed6c939a159b55600c454af/README.md) +``` + +Which renders to: + +[Ethereum Execution Client Specifications](https://github.com/ethereum/execution-specs/blob/9a1f22311f517401fed6c939a159b55600c454af/README.md) + +Permitted Execution Client Specifications URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/ethereum/execution-specs/(blob|commit)/[0-9a-f]{40}/.*|https://github.com/ethereum/execution-specs/tree/[0-9a-f]{40}/.*)$ +``` + +### Execution Specification Tests + +Links to the Ethereum Execution Specification Tests (EEST) may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Execution Specification Tests](https://github.com/ethereum/execution-spec-tests/blob/c9b9307ff320c9bb0ecb9a951aeab0da4d9d1684/README.md) +``` + +Which renders to: + +[Ethereum Execution Specification Tests](https://github.com/ethereum/execution-spec-tests/blob/c9b9307ff320c9bb0ecb9a951aeab0da4d9d1684/README.md) + +Permitted Execution Specification Tests URLs must anchor to a specific commit, and so must match one of these regular expressions: + +```regex +^https://(www\.)?github\.com/ethereum/execution-spec-tests/(blob|tree)/[a-f0-9]{40}/.+$ +``` + +```regex +^https://(www\.)?github\.com/ethereum/execution-spec-tests/commit/[a-f0-9]{40}$ +``` + +### Consensus Layer Specifications + +Links to specific commits of files within the Ethereum Consensus Layer Specifications may be included using normal markdown syntax, such as: + +```markdown +[Beacon Chain](https://github.com/ethereum/consensus-specs/blob/26695a9fdb747ecbe4f0bb9812fedbc402e5e18c/specs/sharding/beacon-chain.md) +``` + +Which renders to: + +[Beacon Chain](https://github.com/ethereum/consensus-specs/blob/26695a9fdb747ecbe4f0bb9812fedbc402e5e18c/specs/sharding/beacon-chain.md) + +Permitted Consensus Layer Specifications URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^https://github.com/ethereum/consensus-specs/(blob|commit)/[0-9a-f]{40}/.*$ +``` + +### Networking Specifications + +Links to specific commits of files within the Ethereum Networking Specifications may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md) +``` + +Which renders as: + +[Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md) + +Permitted Networking Specifications URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^https://github.com/ethereum/devp2p/(blob|commit)/[0-9a-f]{40}/.*$ +``` + +### Portal Specifications + +Links to specific commits of files within the Ethereum Portal Specifications may be included using normal markdown syntax, such as: + +```markdown +[Portal Wire Protocol](https://github.com/ethereum/portal-network-specs/blob/5e321567b67bded7527355be714993c24371de1a/portal-wire-protocol.md) +``` + +Which renders as: + +[Portal Wire Protocol](https://github.com/ethereum/portal-network-specs/blob/5e321567b67bded7527355be714993c24371de1a/portal-wire-protocol.md) + +Permitted Networking Specifications URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^https://github.com/ethereum/portal-network-specs/(blob|commit)/[0-9a-f]{40}/.*$ +``` + +### World Wide Web Consortium (W3C) + +Links to a W3C "Recommendation" status specification may be included using normal markdown syntax. For example, the following link would be allowed: + +```markdown +[Secure Contexts](https://www.w3.org/TR/2021/CRD-secure-contexts-20210918/) +``` + +Which renders as: + +[Secure Contexts](https://www.w3.org/TR/2021/CRD-secure-contexts-20210918/) + +Permitted W3C recommendation URLs MUST anchor to a specification in the technical reports namespace with a date, and so MUST match this regular expression: + +```regex +^https://www\.w3\.org/TR/[0-9][0-9][0-9][0-9]/.*$ +``` + +### Web Hypertext Application Technology Working Group (WHATWG) + +Links to WHATWG specifications may be included using normal markdown syntax, such as: + +```markdown +[HTML](https://html.spec.whatwg.org/commit-snapshots/578def68a9735a1e36610a6789245ddfc13d24e0/) +``` + +Which renders as: + +[HTML](https://html.spec.whatwg.org/commit-snapshots/578def68a9735a1e36610a6789245ddfc13d24e0/) -The `updated` header records the date(s) when the EIP was updated with "substantial" changes. This header is only valid for EIPs of Draft and Active status. +Permitted WHATWG specification URLs must anchor to a specification defined in the `spec` subdomain (idea specifications are not allowed) and to a commit snapshot, and so must match this regular expression: -#### `requires` header +```regex +^https:\/\/[a-z]*\.spec\.whatwg\.org/commit-snapshots/[0-9a-f]{40}/$ +``` + +Although not recommended by WHATWG, EIPs must anchor to a particular commit so that future readers can refer to the exact version of the living standard that existed at the time the EIP was finalized. This gives readers sufficient information to maintain compatibility, if they so choose, with the version referenced by the EIP and the current living standard. + +### Internet Engineering Task Force (IETF) + +Links to an IETF Request For Comment (RFC) specification may be included using normal markdown syntax, such as: + +```markdown +[RFC 8446](https://www.rfc-editor.org/rfc/rfc8446) +``` + +Which renders as: + +[RFC 8446](https://www.rfc-editor.org/rfc/rfc8446) + +Permitted IETF specification URLs MUST anchor to a specification with an assigned RFC number (meaning cannot reference internet drafts), and so MUST match this regular expression: + +```regex +^https:\/\/www.rfc-editor.org\/rfc\/.*$ +``` -EIPs may have a `requires` header, indicating the EIP numbers that this EIP depends on. +### Bitcoin Improvement Proposal -#### `superseded-by` and `replaces` headers +Links to Bitcoin Improvement Proposals may be included using normal markdown syntax, such as: + +```markdown +[BIP 38](https://github.com/bitcoin/bips/blob/3db736243cd01389a4dfd98738204df1856dc5b9/bip-0038.mediawiki) +``` + +Which renders to: + +[BIP 38](https://github.com/bitcoin/bips/blob/3db736243cd01389a4dfd98738204df1856dc5b9/bip-0038.mediawiki) + +Permitted Bitcoin Improvement Proposal URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/bitcoin/bips/blob/[0-9a-f]{40}/bip-[0-9]+\.mediawiki)$ +``` + +### National Vulnerability Database (NVD) + +Links to the Common Vulnerabilities and Exposures (CVE) system as published by the National Institute of Standards and Technology (NIST) may be included, provided they are qualified by the date of the most recent change, using the following syntax: + +```markdown +[CVE-2023-29638 (2023-10-17T10:14:15)](https://nvd.nist.gov/vuln/detail/CVE-2023-29638) +``` + +Which renders to: + +[CVE-2023-29638 (2023-10-17T10:14:15)](https://nvd.nist.gov/vuln/detail/CVE-2023-29638) + +### Chain Agnostic Improvement Proposals (CAIPs) + +Links to a Chain Agnostic Improvement Proposals (CAIPs) specification may be included using normal markdown syntax, such as: + +```markdown +[CAIP 10](https://github.com/ChainAgnostic/CAIPs/blob/5dd3a2f541d399a82bb32590b52ca4340b09f08b/CAIPs/caip-10.md) +``` + +Which renders to: + +[CAIP 10](https://github.com/ChainAgnostic/CAIPs/blob/5dd3a2f541d399a82bb32590b52ca4340b09f08b/CAIPs/caip-10.md) + +Permitted Chain Agnostic URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/ChainAgnostic/CAIPs/blob/[0-9a-f]{40}/CAIPs/caip-[0-9]+\.md)$ +``` -EIPs may also have a `superseded-by` header indicating that an EIP has been rendered obsolete by a later document; the value is the number of the EIP that replaces the current document. The newer EIP must have a `replaces` header containing the number of the EIP that it rendered obsolete. +### Ethereum Yellow Paper + +Links to the Ethereum Yellow Paper may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Yellow Paper](https://github.com/ethereum/yellowpaper/blob/9c601d6a58c44928d4f2b837c0350cec9d9259ed/paper.pdf) +``` + +Which renders to: + +[Ethereum Yellow Paper](https://github.com/ethereum/yellowpaper/blob/9c601d6a58c44928d4f2b837c0350cec9d9259ed/paper.pdf) + +Permitted Yellow Paper URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github\.com/ethereum/yellowpaper/blob/[0-9a-f]{40}/paper\.pdf)$ +``` + +### Execution Client Specification Tests + +Links to the Ethereum Execution Client Specification Tests may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Execution Client Specification Tests](https://github.com/ethereum/execution-spec-tests/blob/d5a3188f122912e137aa2e21ed2a1403e806e424/README.md) +``` + +Which renders to: + +[Ethereum Execution Client Specification Tests](https://github.com/ethereum/execution-spec-tests/blob/d5a3188f122912e137aa2e21ed2a1403e806e424/README.md) + +Permitted Execution Client Specification Tests URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/ethereum/execution-spec-tests/(blob|commit)/[0-9a-f]{40}/.*|https://github.com/ethereum/execution-spec-tests/tree/[0-9a-f]{40}/.*)$ +``` + +### Digital Object Identifier System + +Links qualified with a Digital Object Identifier (DOI) may be included using the following syntax: + +````markdown +This is a sentence with a footnote.[^1] + +[^1]: + ```csl-json + { + "type": "article", + "id": 1, + "author": [ + { + "family": "Jameson", + "given": "Hudson" + } + ], + "DOI": "00.0000/a00000-000-0000-y", + "title": "An Interesting Article", + "original-date": { + "date-parts": [ + [2022, 12, 31] + ] + }, + "URL": "https://sly-hub.invalid/00.0000/a00000-000-0000-y", + "custom": { + "additional-urls": [ + "https://example.com/an-interesting-article.pdf" + ] + } + } + ``` +```` + +Which renders to: + + + + +This is a sentence with a footnote.[^1] + +[^1]: + ```csl-json + { + "type": "article", + "id": 1, + "author": [ + { + "family": "Jameson", + "given": "Hudson" + } + ], + "DOI": "00.0000/a00000-000-0000-y", + "title": "An Interesting Article", + "original-date": { + "date-parts": [ + [2022, 12, 31] + ] + }, + "URL": "https://sly-hub.invalid/00.0000/a00000-000-0000-y", + "custom": { + "additional-urls": [ + "https://example.com/an-interesting-article.pdf" + ] + } + } + ``` + + + +See the [Citation Style Language Schema](https://resource.citationstyles.org/schema/v1.0/input/json/csl-data.json) for the supported fields. In addition to passing validation against that schema, references must include a DOI and at least one URL. + +The top-level URL field must resolve to a copy of the referenced document which can be viewed at zero cost. Values under `additional-urls` must also resolve to a copy of the referenced document, but may charge a fee. + +### Execution API Specification + +Links to the Ethereum Execution API Specification may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Execution API Specification](https://github.com/ethereum/execution-apis/blob/dd00287101e368752ba264950585dde4b61cdc17/README.md) +``` + +Which renders to: + +[Ethereum Execution API Specification](https://github.com/ethereum/execution-apis/blob/dd00287101e368752ba264950585dde4b61cdc17/README.md) + +Permitted Execution API Specification URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/ethereum/execution-apis/(blob|commit)/[0-9a-f]{40}/.*|https://github.com/ethereum/execution-apis/tree/[0-9a-f]{40}/.*)$ +``` + +## Linking to other EIPs + +References to other EIPs should follow the format `EIP-N` where `N` is the EIP number you are referring to. Each EIP that is referenced in an EIP **MUST** be accompanied by a relative markdown link the first time it is referenced, and **MAY** be accompanied by a link on subsequent references. The link **MUST** always be done via relative paths so that the links work in this GitHub repository, forks of this repository, the main EIPs site, mirrors of the main EIP site, etc. For example, you would link to this EIP as `./eip-1.md`. ## Auxiliary Files -EIPs may include auxiliary files such as diagrams. Such files must be named EIP-XXXX-Y.ext, where “XXXX” is the EIP number, “Y” is a serial number (starting at 1), and “ext” is replaced by the actual file extension (e.g. “png”). +Images, diagrams and auxiliary files should be included in a subdirectory of the `assets` folder for that EIP as follows: `assets/eip-N` (where **N** is to be replaced with the EIP number). When linking to an image in the EIP, use relative links such as `../assets/eip-1/image.png`. ## Transferring EIP Ownership It occasionally becomes necessary to transfer ownership of EIPs to a new champion. In general, we'd like to retain the original author as a co-author of the transferred EIP, but that's really up to the original author. A good reason to transfer ownership is because the original author no longer has the time or interest in updating it or following through with the EIP process, or has fallen off the face of the 'net (i.e. is unreachable or isn't responding to email). A bad reason to transfer ownership is because you don't agree with the direction of the EIP. We try to build consensus around an EIP, but if that's not possible, you can always submit a competing EIP. -If you are interested in assuming ownership of an EIP, send a message asking to take over, addressed to both the original author and the EIP editor. If the original author doesn't respond to email in a timely manner, the EIP editor will make a unilateral decision (it's not like such decisions can't be reversed :)). +If you are interested in assuming ownership of an EIP, send a message asking to take over, addressed to both the original author and the EIP editor. If the original author doesn't respond to the email in a timely manner, the EIP editor will make a unilateral decision (it's not like such decisions can't be reversed :)). ## EIP Editors The current EIP editors are -` * Nick Johnson (@arachnid)` - -` * Casey Detrio (@cdetrio)` - -` * Hudson Jameson (@Souptacular)` +- Matt Garnett (@lightclient) +- Sam Wilson (@SamWilsn) +- Zainan Victor Zhou (@xinbenlv) +- Gajinder Singh (@g11tech) +- Jochem Brouwer (@jochem-brouwer) -` * Vitalik Buterin (@vbuterin)` +Emeritus EIP editors are -` * Nick Savers (@nicksavers)` +- Alex Beregszaszi (@axic) +- Casey Detrio (@cdetrio) +- Gavin John (@Pandapip1) +- Greg Colvin (@gcolvin) +- Hudson Jameson (@Souptacular) +- Martin Becze (@wanderer) +- Micah Zoltu (@MicahZoltu) +- Nick Johnson (@arachnid) +- Nick Savers (@nicksavers) +- Vitalik Buterin (@vbuterin) -` * Martin Becze (@wanderer)` - -` * Greg Colvin (@gcolvin)` - -` * Alex Beregszaszi (@axic)` +If you would like to become an EIP editor, please check [EIP-5069](./eip-5069.md). ## EIP Editor Responsibilities @@ -215,69 +570,50 @@ For each new EIP that comes in, an editor does the following: - Read the EIP to check if it is ready: sound and complete. The ideas must make technical sense, even if they don't seem likely to get to final status. - The title should accurately describe the content. -- Check the EIP for language (spelling, grammar, sentence structure, etc.), markup (Github flavored Markdown), code style +- Check the EIP for language (spelling, grammar, sentence structure, etc.), markup (GitHub flavored Markdown), code style If the EIP isn't ready, the editor will send it back to the author for revision, with specific instructions. Once the EIP is ready for the repository, the EIP editor will: -- Assign an EIP number (generally the PR number or, if preferred by the author, the Issue # if there was discussion in the Issues section of this repository about this EIP) - -- Merge the corresponding pull request - +- Assign an EIP number (generally incremental; editors can reassign if number sniping is suspected) +- Merge the corresponding [pull request](https://github.com/ethereum/EIPs/pulls) - Send a message back to the EIP author with the next step. Many EIPs are written and maintained by developers with write access to the Ethereum codebase. The EIP editors monitor EIP changes, and correct any structure, grammar, spelling, or markup mistakes we see. The editors don't pass judgment on EIPs. We merely do the administrative & editorial part. +## Style Guide + +### Titles + +The `title` field in the preamble: + +- Should not include the word "standard" or any variation thereof; and +- Should not include the EIP's number. + +### Descriptions + +The `description` field in the preamble: + +- Should not include the word "standard" or any variation thereof; and +- Should not include the EIP's number. + +### EIP numbers + +When referring to an EIP with a `category` of `ERC`, it must be written in the hyphenated form `ERC-X` where `X` is that EIP's assigned number. When referring to EIPs with any other `category`, it must be written in the hyphenated form `EIP-X` where `X` is that EIP's assigned number. + +### RFC 2119 and RFC 8174 + +EIPs are encouraged to follow [RFC 2119](https://www.ietf.org/rfc/rfc2119.html) and [RFC 8174](https://www.ietf.org/rfc/rfc8174.html) for terminology and to insert the following at the beginning of the Specification section: + +> The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + ## History -This document was derived heavily from [Bitcoin's BIP-0001] written by Amir Taaki which in turn was derived from [Python's PEP-0001]. In many places text was simply copied and modified. Although the PEP-0001 text was written by Barry Warsaw, Jeremy Hylton, and David Goodger, they are not responsible for its use in the Ethereum Improvement Process, and should not be bothered with technical questions specific to Ethereum or the EIP. Please direct all comments to the EIP editors. - -December 7, 2015: EIP 1 has been improved and will be placed as a PR. - -February 1, 2016: EIP 1 has added editors, made draft improvements to process, and has merged with Master stream. - -March 21, 2018: Minor edits to accommodate the new automatically-generated EIP directory on [eips.ethereum.org](https://eips.ethereum.org/). - -May 29, 2018: A last call process was added. - -Oct 17, 2018: The `updated` header was introduced. - -See [the revision history for further details](https://github.com/ethereum/EIPs/commits/master/EIPS/eip-1.md), which is also available by clicking on the History button in the top right of the EIP. - -### Bibliography - -[EIP5]: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-5.md -[EIP101]: https://github.com/ethereum/EIPs/issues/28 -[EIP90]: https://github.com/ethereum/EIPs/issues/90 -[EIP86]: https://github.com/ethereum/EIPs/issues/86#issue-145324865 -[devp2p]: https://github.com/ethereum/wiki/wiki/%C3%90%CE%9EVp2p-Wire-Protocol -[EIP8]: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-8.md -[Light Ethereum Subprotocol]: https://github.com/ethereum/wiki/wiki/Light-client-protocol -[whisper]: https://github.com/ethereum/go-ethereum/wiki/Whisper-Overview -[swarm]: https://github.com/ethereum/go-ethereum/pull/2959 -[API/RPC]: https://github.com/ethereum/wiki/wiki/JSON-RPC -[EIP6]: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-6.md -[contract ABIs]: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI -[interfaces repo]: https://github.com/ethereum/interfaces -[ERC20]: https://github.com/ethereum/EIPs/issues/20 -[ERC26]: https://github.com/ethereum/EIPs/issues/26 -[ERC137]: https://github.com/ethereum/EIPs/issues/137 -[ERC67]: https://github.com/ethereum/EIPs/issues/67 -[EIP82]: https://github.com/ethereum/EIPs/issues/82 -[EIP75]: https://github.com/ethereum/EIPs/issues/75 -[EIP85]: https://github.com/ethereum/EIPs/issues/85 -[the Ethereum subreddit]: https://www.reddit.com/r/ethereum/ -[one of the Ethereum Gitter chat rooms]: https://gitter.im/ethereum/ -[pull request]: https://github.com/ethereum/EIPs/pulls -[formal specification]: https://github.com/ethereum/yellowpaper -[the Issues section of this repository]: https://github.com/ethereum/EIPs/issues -[markdown]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet -[Bitcoin's BIP-0001]: https://github.com/bitcoin/bips -[Python's PEP-0001]: https://www.python.org/dev/peps/ +This document was derived heavily from [Bitcoin's BIP-0001](https://github.com/bitcoin/bips) written by Amir Taaki which in turn was derived from [Python's PEP-0001](https://peps.python.org/). In many places text was simply copied and modified. Although the PEP-0001 text was written by Barry Warsaw, Jeremy Hylton, and David Goodger, they are not responsible for its use in the Ethereum Improvement Process, and should not be bothered with technical questions specific to Ethereum or the EIP. Please direct all comments to the EIP editors. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-101.md b/EIPS/eip-101.md index 91dd8d86c108c8..11723850ae517c 100644 --- a/EIPS/eip-101.md +++ b/EIPS/eip-101.md @@ -1,8 +1,8 @@ --- eip: 101 title: Serenity Currency and Crypto Abstraction -author: Vitalik Buterin -status: Draft +author: Vitalik Buterin (@vbuterin) +status: Stagnant type: Standards Track category: Core created: 2015-11-15 @@ -56,7 +56,7 @@ This essentially implements signature and nonce checking, and if both checks pas Miners can follow the following algorithm upon receiving transactions: 1. Run the code for a maximum of 50000 gas, stopping if they see an operation or call that threatens to go over this limit -2. Upon seeing that operation, make sure that it leaves at last 50000 gas to spare (either by checking that the static gas consumption is small enough or by checking that it is a call with `msg.gas - 50000` as its gas limit parameter) +2. Upon seeing that operation, make sure that it leaves at least 50000 gas to spare (either by checking that the static gas consumption is small enough or by checking that it is a call with `msg.gas - 50000` as its gas limit parameter) 3. Pattern-match to make sure that gas payment code at the end is *exactly* the same as in the code above. This process ensures that miners *waste* at most 50000 gas before knowing whether or not it will be worth their while to include the transaction, and is also highly general so users can experiment with new cryptography (eg. ed25519, Lamport), ring signatures, quasi-native multisig, etc. Theoretically, one can even create an account for which the *valid signature* type is a valid Merkle branch of a receipt, creating a quasi-native alarm clock. diff --git a/EIPS/eip-1010.md b/EIPS/eip-1010.md index b6bf09987c68d9..794fee16428eb8 100644 --- a/EIPS/eip-1010.md +++ b/EIPS/eip-1010.md @@ -3,7 +3,7 @@ eip: 1010 title: Uniformity Between 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B and 0x15E55EF43efA8348dDaeAa455F16C43B64917e3c author: Anderson Wesley (@andywesley) discussions-to: https://github.com/andywesley/EIPs/issues/1 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-04-18 @@ -65,5 +65,4 @@ consistently among all clients as intended by the proposal process will be suffi to ensure that backwards compatibility is not a concern. ## Copyright -Copyright and related rights waived via -[CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1011.md b/EIPS/eip-1011.md index a35c0a7b6de81b..a571322ed40ae4 100644 --- a/EIPS/eip-1011.md +++ b/EIPS/eip-1011.md @@ -1,7 +1,7 @@ --- eip: 1011 title: Hybrid Casper FFG -status: Draft +status: Stagnant type: Standards Track category: Core author: Danny Ryan (@djrtwo), Chih-Cheng Liang (@ChihChengLiang) @@ -342,7 +342,7 @@ Most other decisions were made to minimize changes across clients. For example, #### Deploying Casper Contract The `MSG_HASHER_CODE` and `PURITY_CHECKER_CODE` both do not require any initialization so the EVM bytecode can simply be placed at `MSG_HASHER_ADDR` and `PURITY_CHECKER_ADDR`. On the other hand, the casper contract _does_ require passing in parameters and initialization of state. This initialization would normally occur by the EVM init code interacting with the CREATE opcode. Due to the nature of this contract being deployed outside of normal block transactions and to a particular address, the EVM init code/CREATE method requires client specific "hacks" to make it work. For simplicity of specifying across clients, the EVM bytecode -- `CASPER_CODE` -- is placed at `CASPER_ADDR` followed by an explicit `CALL` to a one-time `init` method on the casper contract. `init` handles all of the logic that a constructor normally would, accepting contract parameters as arguments and setting initial variable values, and can only be run _once_. -`CASPER_INIT_DATA` is composed of the the byte signature of the `init` method of the casper contract concatenated with the 32-byte encodings of the following variables in the following order: +`CASPER_INIT_DATA` is composed of the byte signature of the `init` method of the casper contract concatenated with the 32-byte encodings of the following variables in the following order: * `EPOCH_LENGTH` * `WITHDRAWAL_DELAY` @@ -395,12 +395,12 @@ Below is a table of deposit sizes with associated annual interest rate and appro #### Gas Changes Normal block transactions cannot affect casper `vote` validation results, but casper `vote` validation results can affect normal block transaction execution. Due to this asymmetrical relationship, `vote` transactions can be processed in parallel with normal block transactions if `vote` transactions are placed after all normal block transactions. Because `vote` transactions can be processed in parallel to normal block transactions, `vote` transactions cost 0 gas for validators, ensuring that validators can submit votes even in highly congested or high gas-price periods. -`vote_gas_used` is introduced to ensure that `vote` transactions do not put an undue burden on block processing. The additional overhead from `vote` transactions is capped at the same limit as normal block transactions so that, when run in parallel, neither sets of transactions exceeds the overhead defined by the `block_gas_limit`. +`vote_gas_used` is introduced to ensure that `vote` transactions do not put an undue burden on block processing. The additional overhead from `vote` transactions is capped at the same limit as normal block transactions so that, when run in parallel, neither sets of transactions exceed the overhead defined by the `block_gas_limit`. The call to `initialize_epoch` at the beginning of each epoch requires 0 gas so that this protocol state transition does not take any gas allowance away from normal transactions. #### NULL_SENDER and Account Abstraction -This EIP implements a limited version of account abstraction for validators' `vote` transactions. The general design was borrowed from [EIP 86](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-86.md). Rather than relying upon native transaction signatures, each validator specifies a signature contract when sending their `deposit` to `CASPER_ADDR`. When casting a `vote`, the validator bundles and signs the parameters of their `vote` according to the requirements of their signature contract. The `vote` method of the casper contract checks the signature of the parameters against the validator's signature contract, exiting the transaction as unsuccessful if the signature is not successfully verified. +This EIP implements a limited version of account abstraction for validators' `vote` transactions. The general design was borrowed from [EIP-86](./eip-86.md). Rather than relying upon native transaction signatures, each validator specifies a signature contract when sending their `deposit` to `CASPER_ADDR`. When casting a `vote`, the validator bundles and signs the parameters of their `vote` according to the requirements of their signature contract. The `vote` method of the casper contract checks the signature of the parameters against the validator's signature contract, exiting the transaction as unsuccessful if the signature is not successfully verified. This allows validators to customize their own signing scheme for votes. Use cases include: * quantum-secure signature schemes @@ -437,4 +437,4 @@ This setting is suggested default disabled because the block producer will almos This EIP is not forward compatible and introduces backwards incompatibilities in the state, fork choice rule, block reward, transaction validity, and gas calculations on certain transactions. Therefore, all changes should be included in a scheduled hardfork at `HYBRID_CASPER_FORK_BLKNUM`. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1013.md b/EIPS/eip-1013.md index e4cf68a98a7530..0c7b04a82b7f54 100644 --- a/EIPS/eip-1013.md +++ b/EIPS/eip-1013.md @@ -17,16 +17,16 @@ This meta-EIP specifies the changes included in the Ethereum hardfork named Cons - Codename: Constantinople - Aliases: Metropolis/Constantinople, Metropolis part 2 - Activation: - - `Block >= 7_280_000` on the Ethereum mainnet + - `Block >= 7_280_000` on the Ethereum Mainnet - `Block >= 4,230,000` on the Ropsten testnet - `Block >= 9_200_000` on the Kovan testnet - `Block >= 3_660_663` on the Rinkeby testnet - Included EIPs: - - [EIP 145](https://eips.ethereum.org/EIPS/eip-145): Bitwise shifting instructions in EVM - - [EIP 1014](https://eips.ethereum.org/EIPS/eip-1014): Skinny CREATE2 - - [EIP 1052](https://eips.ethereum.org/EIPS/eip-1052): EXTCODEHASH Opcode - - [EIP 1234](https://eips.ethereum.org/EIPS/eip-1234): Delay difficulty bomb, adjust block reward - - [EIP 1283](https://eips.ethereum.org/EIPS/eip-1283): Net gas metering for SSTORE without dirty maps + - [EIP-145](./eip-145.md): Bitwise shifting instructions in EVM + - [EIP-1014](./eip-1014.md): Skinny CREATE2 + - [EIP-1052](./eip-1052.md): EXTCODEHASH Opcode + - [EIP-1234](./eip-1234.md): Delay difficulty bomb, adjust block reward + - [EIP-1283](./eip-1283.md): Net gas metering for SSTORE without dirty maps ## References @@ -35,4 +35,4 @@ This meta-EIP specifies the changes included in the Ethereum hardfork named Cons ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1014.md b/EIPS/eip-1014.md index 0aa0aaea973f3f..31d4d62ec1dfc9 100644 --- a/EIPS/eip-1014.md +++ b/EIPS/eip-1014.md @@ -10,7 +10,7 @@ created: 2018-04-20 ### Specification -Adds a new opcode at 0xf5, which takes 4 stack arguments: endowment, memory_start, memory_length, salt. Behaves identically to CREATE, except using `keccak256( 0xff ++ address ++ salt ++ keccak256(init_code))[12:]` instead of the usual sender-and-nonce-hash as the address where the contract is initialized at. +Adds a new opcode (`CREATE2`) at `0xf5`, which takes 4 stack arguments: endowment, memory_start, memory_length, salt. Behaves identically to `CREATE` (`0xf0`), except using `keccak256( 0xff ++ address ++ salt ++ keccak256(init_code))[12:]` instead of the usual sender-and-nonce-hash as the address where the contract is initialized at. The `CREATE2` has the same `gas` schema as `CREATE`, but also an extra `hashcost` of `GSHA3WORD * ceil(len(init_code) / 32)`, to account for the hashing that must be performed. The `hashcost` is deducted at the same time as memory-expansion gas and `CreateGas` is deducted: _before_ evaluation of the resulting address and the execution of `init_code`. @@ -42,19 +42,19 @@ Since address calculation depends on hashing the `init_code`, it would leave cli The `init_code` is the code that, when executed, produces the runtime bytecode that will be placed into the state, and which typically is used by high level languages to implement a 'constructor'. -This EIP makes collisions possible. The behaviour at collisions is specified by [EIP 684](https://github.com/ethereum/EIPs/issues/684): +This EIP makes collisions possible. The behaviour at collisions is specified by [EIP-684](https://github.com/ethereum/EIPs/issues/684): -> If a contract creation is attempted, due to either a creation transaction or the CREATE (or future CREATE2) opcode, and the destination address already has either nonzero nonce, or nonempty code, then the creation throws immediately, with exactly the same behavior as would arise if the first byte in the init code were an invalid opcode. This applies retroactively starting from genesis. +> If a contract creation is attempted, due to either a creation transaction or the `CREATE` (or future `CREATE2`) opcode, and the destination address already has either nonzero nonce, or nonempty code, then the creation throws immediately, with exactly the same behavior as would arise if the first byte in the init code were an invalid opcode. This applies retroactively starting from genesis. Specifically, if `nonce` or `code` is nonzero, then the create-operation fails. -With [EIP 161](https://eips.ethereum.org/EIPS/eip-161) +With [EIP-161](./eip-161.md) -> Account creation transactions and the CREATE operation SHALL, prior to the execution of the initialisation code, increment the nonce over and above its normal starting value by one +> Account creation transactions and the `CREATE` operation SHALL, prior to the execution of the initialisation code, increment the nonce over and above its normal starting value by one This means that if a contract is created in a transaction, the `nonce` is immediately non-zero, with the side-effect that a collision within the same transaction will always fail -- even if it's carried out from the `init_code` itself. -It should also be noted that `SELFDESTRUCT` has no immediate effect on `nonce` or `code`, thus a contract cannot be destroyed and recreated within one transaction. +It should also be noted that `SELFDESTRUCT` (`0xff`) has no immediate effect on `nonce` or `code`, thus a contract cannot be destroyed and recreated within one transaction. ### Examples diff --git a/EIPS/eip-1015.md b/EIPS/eip-1015.md index 0d690fa6ccc18d..f1679228809e66 100644 --- a/EIPS/eip-1015.md +++ b/EIPS/eip-1015.md @@ -3,7 +3,7 @@ eip: 1015 title: Configurable On Chain Issuance author: Alex Van de Sande discussions-to: https://ethereum-magicians.org/t/eip-dynamic-block-rewards-with-governance-contract/204 -status: Deferred +status: Stagnant type: Standards Track category: Core created: 2018-04-20 @@ -20,24 +20,24 @@ These are current EIPs that are being developed or debated. They might seem unre #### Casper and PoS -Moving to PoS has been on the roadmap since day 0 for ethereum, along with a reduction in issuance to a cost equivalent to the Validator's cost of security (considered to be more eficient than PoW). But the exact issuance necessary for PoS has yet to be determined and is currently being researched. Casper validation will be an on chain contract and therefore it will need to be funded. It's unlikely that a definitive final answer on how much issuance is needed for validation will be reached in the next years as new research will uncover new arguments, so it would make sense to allow some flexibility on this matter +Moving to PoS has been on the roadmap since day 0 for ethereum, along with a reduction in issuance to a cost equivalent to the Validator's cost of security (considered to be more efficient than PoW). But the exact issuance necessary for PoS has yet to be determined and is currently being researched. Casper validation will be an on chain contract and therefore it will need to be funded. It's unlikely that a definitive final answer on how much issuance is needed for validation will be reached in the next years as new research will uncover new arguments, so it would make sense to allow some flexibility on this matter #### Issuance Cap at 120 Million -[EIP 960](https://github.com/ethereum/EIPs/issues/960), Vitalik's not so jokey april's fool has been taken seriously. It proposes the issuance to be slowly reduced until it reaches 120 million ether. One of the main counterpoints by Vlad can be simplified by [we don't know enough to know what that ether can be used for](https://medium.com/@Vlad_Zamfir/against-vitaliks-fixed-supply-eip-eip-960-18e182a7e5bd) and Vitalik's counterpoint is that [reducing emissions can be a way to reduce future abuse of these funds by finding a schelling point at 0](https://medium.com/@VitalikButerin/to-be-clear-im-not-necessarily-wedded-to-a-finite-supply-cap-a7aa48ab880c). Issuance has already been reduced once, from 5 ether to the current 3 ether per block. The main point of a hard cap is that a lot of people consider *not issuing* as having a positive contribution, that can outweigh other actions. Burning ether is also a valid issuance decision. +[EIP-960](https://github.com/ethereum/EIPs/issues/960), Vitalik's not so jokey april's fool has been taken seriously. It proposes the issuance to be slowly reduced until it reaches 120 million ether. One of the main counterpoints by Vlad can be simplified by [we don't know enough to know what that ether can be used for](https://medium.com/@Vlad_Zamfir/against-vitaliks-fixed-supply-eip-eip-960-18e182a7e5bd) and Vitalik's counterpoint is that [reducing emissions can be a way to reduce future abuse of these funds by finding a schelling point at 0](https://medium.com/@VitalikButerin/to-be-clear-im-not-necessarily-wedded-to-a-finite-supply-cap-a7aa48ab880c). Issuance has already been reduced once, from 5 ether to the current 3 ether per block. The main point of a hard cap is that a lot of people consider *not issuing* as having a positive contribution, that can outweigh other actions. Burning ether is also a valid issuance decision. -#### Asics and advantadges of PoW +#### Asics and advantages of PoW -[EIP 960](https://eips.ethereum.org/EIPS/eip-969) proposes a change in algorithm to avoid mining being dominated by ASICS. Counter arguments by Phil Daian argue among others than [resisting economies of scale is futile and there might be specific security advantadges to specialized hardware](https://pdaian.com/blog/anti-asic-forks-considered-harmful/). One of the main arguments for PoW mining, even when it doesn't provide security, it is useful as a fair distribution mechanism, that **PoW allows any person with a computer, internet access and electricity to obtain currency without having to deal with government imposed currency controls**. +[EIP-960](https://eips.ethereum.org/EIPS/eip-969) proposes a change in algorithm to avoid mining being dominated by ASICS. Counter arguments by Phil Daian argue among others than [resisting economies of scale is futile and there might be specific security advantages to specialized hardware](https://pdaian.com/blog/anti-asic-forks-considered-harmful/). One of the main arguments for PoW mining, even when it doesn't provide security, it is useful as a fair distribution mechanism, that **PoW allows any person with a computer, internet access and electricity to obtain currency without having to deal with government imposed currency controls**. #### Recovery Forks -After the Parity Multisig library self destruction, three different strategies have been attempted to recover the funds: [a general protocol improvement to allow reviving self destructed contracts](https://gist.github.com/5chdn/a9bb8617cc8523a030126a3d1c60baf3) (which was considered dangerous), a [general process to recover funds](https://github.com/ethereum/EIPs/pull/867) and a [specific recovery of the multisig library](https://eips.ethereum.org/EIPS/eip-999). The latter two are finding a lot of resistance from the community, but it's unlikely that these issues are going away soon. The affected parties have a large incentive (fluctuating at almost half a billion dollars) to keep trying, and it's an issue that is likely to occur again in the future. If they get reimbursed, [there are many other special cases of ether provably burnt or stuck](https://github.com/ethereum/EIPs/issues/156) that might deserve the same treatment. If they get shut down, they have an incentive to move forward a fork implementation: even if they are a minority chain, it's likely they'll recover an amount larger than 0, which is what they would otherwise, and it means the main ethereum community might lose a valuable team of developers. +After the Parity Multisig library self destruction, three different strategies have been attempted to recover the funds: [a general protocol improvement to allow reviving self destructed contracts](https://gist.github.com/5chdn/a9bb8617cc8523a030126a3d1c60baf3) (which was considered dangerous), a [general process to recover funds](https://github.com/ethereum/EIPs/pull/867) and a [specific recovery of the multisig library](./eip-999.md). The latter two are finding a lot of resistance from the community, but it's unlikely that these issues are going away soon. The affected parties have a large incentive (fluctuating at almost half a billion dollars) to keep trying, and it's an issue that is likely to occur again in the future. If they get reimbursed, [there are many other special cases of ether provably burnt or stuck](https://github.com/ethereum/EIPs/issues/156) that might deserve the same treatment. If they get shut down, they have an incentive to move forward a fork implementation: even if they are a minority chain, it's likely they'll recover an amount larger than 0, which is what they would otherwise, and it means the main ethereum community might lose a valuable team of developers. #### Other Public Goods -There are many other types of public goods that could be funded by issuance. By *Public Good*, I'm using a strict definition of something that brings value to everyone, both those who funded it and free-loaders, making it hard to fund it exclusively by traditional private incentives. They can be research, whole network security, [incentivize full clients and networking](https://eips.ethereum.org/EIPS/eip-908), fair distribution of tokens etc. +There are many other types of public goods that could be funded by issuance. By *Public Good*, I'm using a strict definition of something that brings value to everyone, both those who funded it and free-loaders, making it hard to fund it exclusively by traditional private incentives. They can be research, whole network security, [incentivize full clients and networking](./eip-908.md), fair distribution of tokens etc. ## Proposed Solution ### Issuance Contract @@ -48,15 +48,15 @@ This EIP proposes a future hard fork where block reward is not issued to miners/ ##### It can only deal with issuance -It's not meant to be a general governance contract. The contract **should NOT be used to** to decide software updates, to freeze funds, change contracts balances or anything on the consensus layer other than the strict definition of *where block rewards go*. It should be seen as a platform to settle disputes to avoid the implementation of contentious hard forks, not as a mean to remove the power of users and developers to execute them. +It's not meant to be a general governance contract. The contract **should NOT be used** to decide software updates, to freeze funds, change contract balances or anything on the consensus layer other than the strict definition of *where block rewards go*. It should be seen as a platform to settle disputes to avoid the implementation of contentious hard forks, not as a mean to remove the power of users and developers to execute them. ##### It cannot only decrease issuance, and once decreased it cannot be increased again In order to reduce future abuse and uncertainty, **once issuance is reduced, it cannot be increased**. To prevent a single action reducing it to 0, the reduction is limited up to a percentage per time, so if the **decision assembly** is aggressively to reduce issuance to zero, it would take a known number of years. -##### Results are locked for six months +##### Results are locked for s -Whenever a new decision on either reducing the issuance or changing the target is made, the effects will have a six month delay to it. Once a decision is made it is final, it will take place six months after that, but if it's shortly reversed, then that change will be short lived. The rationale behind is that it allows time to anyone disagreeing with the decision to: +Whenever a new decision on either reducing the issuance or changing the target is made, the effects will have a six-month delay to it. Once a decision is made it is final, it will take place six months after that, but if it's shortly reversed, then that change will be short lived. The rationale behind is that it allows time to anyone disagreeing with the decision to: * Sell their coins so that if a bad actor takes over they will have a reduced reward * Attempt to revert the decision as soon as possible, to reduce the duration that the change will take place @@ -94,7 +94,7 @@ A contract that has the power to decide the changes to issuance, the core of the The decision would be made by multiple signalling contracts, each one implemented by separate groups and representing one aspect of the community or one sort of measurement. Each signaling process would have a `int` bound in which they could vote and they would have their own internal process to decide that. As new governance methods are tested and debated, new signalling contracts should be added and removed. Suggested signalling contracts: * Futarchy and prediction markets based on multiple measures -* Votes weighted by ether balance (optionally with multipliers if the voters where committed to locking votes) +* Votes weighted by ether balance (optionally with multipliers if the voters were committed to locking votes) * Token votes, weighted by their own relative ether exchange rate * Votes by individual humans if a good sybil resistance, coercion mechanism is developed * Block-signalling, as a way to measure validators/miners choices @@ -116,4 +116,4 @@ A lot of things are suggested in this EIP, so I would like to propose these ques ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1046.md b/EIPS/eip-1046.md index ab29e214b35045..d831616c7de4e3 100644 --- a/EIPS/eip-1046.md +++ b/EIPS/eip-1046.md @@ -1,87 +1,7 @@ --- eip: 1046 -title: ERC20 Metadata Extension -author: Tommy Nicholas (@tomasienrbc), Matt Russo (@mateosu), John Zettler (@JohnZettler), Matt Condon (@shrugs) -discussions-to: https://www.reddit.com/r/raredigitalart/comments/8hfh1g/erc20_metadata_extension_eip_1046/ -status: Draft -type: Standards Track category: ERC -created: 2018-04-13 -requires: 20 +status: Moved --- -## Simple Summary -Optionally extend ERC20 token interface to support the same metadata standard as ERC721 tokens. - -## Abstract -The ERC721 standard introduced the `tokenURI` parameter for non-fungible tokens to handle metadata such as: - -- thumbnail image -- title -- description -- special asset properties -- etc. - -Metadata is critical for assets such as crypto-collectibles and video game assets to have real utility and value. However, not all crypto-collectibles and gaming assets will be non-fungible. It is critical for fungible ERC20 tokens to have a metadata standard like that of ERC721 tokens. Standardization of metadata between ERC20 and ERC721 will simplify development of dApps and infrastructure that must support both fungible and non-fungible assets. - -## Motivation -The ERC721 standard was created to support the creation of perfectly unique, 1-of-1, non-divisible tokens known as "non-fungible tokens". - -The initial use case for the ERC721 standard was to support the creation of crypto-collectibles and gaming assets, initially for the ["Crypto Kitties"](https://www.cryptokitties.co/) collectibles game. The success of Crypto Kitties catalyzed significant application development to support the display of ERC721 assets using the `tokenURI` metadata parameter. - -However, not all crypto-collectibles and gaming assets need to be unique and non-fungible. Gaming assets (items, weapons, characters), crypto-artworks with non-unique "prints", and more will function more like traditional ERC20 tokens with a fungible `supply`. Many applications such as wallets, exchanges, games, etc. will want to support both fungible and non-fungible assets containing similar metadata. This proposal will extend the ERC20 standard to optionally include a nearly identical `tokenURI` parameter supporting the same JSON metadata schema as the ERC721 standard. - -## Specification - -The **metadata extension** will be OPTIONAL for ERC20 contracts. This allows your smart contract to be interrogated for its name and for details about the assets which your tokens represent. - -```solidity -/// @title ERC-20 optional metadata extension -interface TokenMetaData /* is ERC20 */ { - - /// @notice A distinct Uniform Resource Identifier (URI) for a given token. - function tokenURI() external view returns (string); -} -``` - -This is the "Token Metadata JSON Schema" referenced above. - -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents", - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents", - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", - } - } -} -``` - -The token's name() and symbol() getters should be preferred over the name and/or symbol properties in the tokenURI JSON. - -## Rationale -This proposal will make adding metadata to ERC20 tokens straightforward for developers with minimal-to-no disruption to the overall ecosystem. By using the same parameter name and by consolidating the underlying Token JSON Metadata Standard, developers will confidently understand how to add and interpret token metadata between ERC20 and ERC721 tokens. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation simply extends the functionality of ERC20 tokens and is optional. - -## Test Cases -TO-DO - -## Implementation - -- [Rare Art Labs](https://rareart.io) (WIP) -- [Open Zeppelin](https://github.com/OpenZeppelin/zeppelin-solidity) (WIP) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1046.md diff --git a/EIPS/eip-1047.md b/EIPS/eip-1047.md deleted file mode 100644 index 071cf93a11a1d8..00000000000000 --- a/EIPS/eip-1047.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -eip: 1047 -title: Token Metadata JSON Schema -author: Tommy Nicholas (@tomasienrbc), Matt Russo (@mateosu), John Zettler (@JohnZettler) -discussions-to: https://www.reddit.com/r/raredigitalart/comments/8hfk2a/token_metadata_json_schema_eip_1047/ -status: Draft -type: Standards Track -category: ERC -created: 2018-04-13 ---- - -## Simple Summary -A standard interface for token metadata - -## Abstract -The ERC721 standard introduced the "tokenURI" parameter for non-fungible tokens to handle metadata such as: - -- thumbnail image -- title -- description -- properties -- etc. - -This is particularly critical for crypto-collectibles and gaming assets. - -This standard includes a reference to a metadata standard named "ERC721 Metadata JSON Schema". This schema is actually equally relevant to ERC20 tokens and therefore should be its own standard, separate from the ERC721 standard. - -## Motivation -Metadata is critical for both ERC721 and ERC20 tokens representing things like crypto-collectibles, gaming assets, etc. Not all crypto-collectibles and gaming assets will be non-fungible. It is critical for fungible ERC20 tokens to have a metadata standard similar to that of ERC721 tokens. Standardization of metadata between ERC20 and ERC721 will simplify development of dApps and infrastructure that must support both fungible and non-fungible assets. - -It is more logical and easier to maintain one Token Metadata JSON Schema rather than multiple schemas contained in their own EIPs. - -This should result in no code changes to the ERC721 standard or ERC20 standard and will serve only to simplify the process of maintaining a standard JSON Schema for token metadata. - -## Specification - -This "Token Metadata JSON Schema" mimics the structure of the ERC721 standard. Only grammatical changes are being recommended at this time. - -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents", - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents", - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", - } - } -} -``` -## Rationale -One JSON schema standard will allow for simpler maintenance of this critical schema. - -## Backwards Compatibility -Fully backwards compatible requiring no code changes at this time - -## Test Cases -TO-DO - -## Implementation -TO-DO - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/EIPS/eip-1051.md b/EIPS/eip-1051.md index d6b575e09ca8ca..6d40d605ee39c3 100644 --- a/EIPS/eip-1051.md +++ b/EIPS/eip-1051.md @@ -3,7 +3,7 @@ eip: 1051 title: Overflow checking for the EVM author: Nick Johnson discussions-to: https://ethereum-magicians.org/t/eip-arithmetic-overflow-detection-for-the-evm/261 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-05-02 @@ -23,21 +23,21 @@ Two new flags are added to the EVM state: overflow (`ovf`) and signed overflow ( The `ovf` flag is set in the following circumstances: - - When an `ADD` opcode, with both inputs treated as unsigned integers, produces an ideal output in excess of 2^256 - 1. - - When a `SUB` opcode, with both inputs treated as unsigned integers, produces an ideal output less than 0. - - When a 'MUL' opcode, with both inputs treated as unsigned integers, produces an ideal output in excess of 2^256 - 1. + - When an `ADD` (`0x01`) opcode, with both inputs treated as unsigned integers, produces an ideal output in excess of 2^256 - 1. + - When a `SUB` (`0x03`) opcode, with both inputs treated as unsigned integers, produces an ideal output less than 0. + - When a `MUL` (`0x02`) opcode, with both inputs treated as unsigned integers, produces an ideal output in excess of 2^256 - 1. The `sovf` flag is set whenever the `ovf` flag is set, and additionally in the following circumstances: - When an `ADD` opcode with both inputs having the same MSB results in the output having a different MSB (eg, `(+a) + (+b) = (-c)` or `(-a) + (-b) = (+c)`). - - When a `SUB` opcode occurs and the result has the same MSB as the subtractand (second argument) (eg, `(+a) - (-b) = (-c)` or `(-a) - (+b) = (+c)`. + - When a `SUB` opcode occurs and the result has the same MSB as the subtracted (second argument) (eg, `(+a) - (-b) = (-c)` or `(-a) - (+b) = (+c)`). - When a `MUL` opcode with both inputs being positive has a negative output. - - When a 'MUL' opcode with both inputs being negative has a negative output. - - When a 'MUL' opcode with one negative input and one positive input has a positive output. + - When a `MUL` opcode with both inputs being negative has a negative output. + - When a `MUL` opcode with one negative input and one positive input has a positive output. -A new opcode, `OFV` is added, with number 0x0C. This opcode takes 0 arguments from the stack. When executed, it pushes `1` if the `ovf` flag is set, and `0` otherwise. It then sets the `ovf` flag to false. +A new opcode, `OFV` is added, with number `0x0c`. This opcode takes 0 arguments from the stack. When executed, it pushes `1` if the `ovf` flag is set, and `0` otherwise. It then sets the `ovf` flag to false. -A new opcode, `SOVF` is added, with number 0x0D. This opcode takes 0 arguments from the stack. When executed, it pushes `1` if the `sovf` flag is set, and `0` otherwise. It then sets the `sovf` flag to false. +A new opcode, `SOVF` is added, with number `0x0d`. This opcode takes 0 arguments from the stack. When executed, it pushes `1` if the `sovf` flag is set, and `0` otherwise. It then sets the `sovf` flag to false. ## Rationale Any change to implement overflow protection needs to preserve behaviour of existing contracts, which precludes many changes to the arithmetic operations themselves. One option would be to provide an opcode that enables overflow protection, causing a throw or revert if an overflow happens. However, this limits the manner in which overflows can be handled. @@ -56,4 +56,4 @@ TBD TBD ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1052.md b/EIPS/eip-1052.md index cce394ecd9cd1c..2dcbc7ce1563e9 100644 --- a/EIPS/eip-1052.md +++ b/EIPS/eip-1052.md @@ -7,6 +7,7 @@ status: Final type: Standards Track category: Core created: 2018-05-02 +requires: 161 --- ## Abstract @@ -15,16 +16,16 @@ This EIP specifies a new opcode, which returns the keccak256 hash of a contract' ## Motivation Many contracts need to perform checks on a contract's bytecode, but do not necessarily need the bytecode itself. For instance, a contract may want to check if another contract's bytecode is one of a set of permitted implementations, or it may perform analyses on code and whitelist any contract with matching bytecode if the analysis passes. -Contracts can presently do this using the `EXTCODECOPY` opcode, but this is expensive, especially for large contracts, in cases where only the hash is required. As a result, we propose a new opcode, `EXTCODEHASH`, which returns the keccak256 hash of a contract's bytecode. +Contracts can presently do this using the `EXTCODECOPY` (`0x3c`) opcode, but this is expensive, especially for large contracts, in cases where only the hash is required. As a result, we propose a new opcode, `EXTCODEHASH`, which returns the keccak256 hash of a contract's bytecode. ## Specification -A new opcode, `EXTCODEHASH`, is introduced, with number 0x3F. The `EXTCODEHASH` +A new opcode, `EXTCODEHASH`, is introduced, with number `0x3f`. The `EXTCODEHASH` takes one argument from the stack, zeros the first 96 bits and pushes to the stack the keccak256 hash of the code of the account at the address being the remaining 160 bits. -In case the account does not exist `0` is pushed to the stack. +In case the account does not exist or is empty (as defined by [EIP-161](./eip-161.md)) `0` is pushed to the stack. In case the account does not have code the keccak256 hash of empty data (i.e. `c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`) @@ -42,12 +43,12 @@ The gas cost is the same as the gas cost for the `BALANCE` opcode because the execution of the `EXTCODEHASH` requires the same account lookup as in `BALANCE`. Only the 20 last bytes of the argument are significant (the first 12 bytes are -ignored) similarly to the semantics of the `BALANCE`, `EXTCODESIZE` and -`EXTCODECOPY`. +ignored) similarly to the semantics of the `BALANCE` (`0x31`), `EXTCODESIZE` (`0x3b`) and +`EXTCODECOPY` (`0x3c`). -The `EXTCODEHASH` distincts accounts without code and non-existing accounts. +The `EXTCODEHASH` distinguishes accounts without code and non-existing accounts. This is consistent with the way accounts are represented in the state trie. -This also allows smart contracts to check whenever an account exists. +This also allows smart contracts to check whether an account exists. ## Backwards Compatibility @@ -58,14 +59,14 @@ There are no backwards compatibility concerns. ## Test Cases 1. The `EXTCODEHASH` of the account without code is `c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` - what is the keccack256 hash of empty data. + what is the keccak256 hash of empty data. 2. The `EXTCODEHASH` of non-existent account is `0`. -3. The `EXTCODEHASH` of an precompiled contract is either `c5d246...` or `0`. +3. The `EXTCODEHASH` of a precompiled contract is either `c5d246...` or `0`. 4. If `EXTCODEHASH` of `A` is `X`, then `EXTCODEHASH` of `A + 2**160` is `X`. 5. The `EXTCODEHASH` of an account that selfdestructed in the current transaction. 6. The `EXTCODEHASH` of an account that selfdestructed and later the selfdestruct has been reverted. 7. The `EXTCODEHASH` of an account created in the current transaction. -8. The `EXTCODEHASH` of an account that has been newly create and later the creation has been reverted. +8. The `EXTCODEHASH` of an account that has been newly created and later the creation has been reverted. 9. The `EXTCODEHASH` of an account that firstly does not exist and later is empty. 10. The `EXTCODEHASH` of an empty account that is going to be cleared by the state clearing rule. @@ -74,4 +75,4 @@ There are no backwards compatibility concerns. TBD ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1056.md b/EIPS/eip-1056.md new file mode 100644 index 00000000000000..12110c18a0d770 --- /dev/null +++ b/EIPS/eip-1056.md @@ -0,0 +1,7 @@ +--- +eip: 1056 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1056.md diff --git a/EIPS/eip-1057.md b/EIPS/eip-1057.md index 5ffc0b9f7d313a..0cd85a2660f174 100644 --- a/EIPS/eip-1057.md +++ b/EIPS/eip-1057.md @@ -1,9 +1,9 @@ --- eip: 1057 title: ProgPoW, a Programmatic Proof-of-Work -author: IfDefElse +author: Greg Colvin , Andrea Lanfranchi (@AndreaLanfranchi), Michael Carter (@bitsbetrippin), IfDefElse discussions-to: https://ethereum-magicians.org/t/eip-progpow-a-programmatic-proof-of-work/272 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-05-02 @@ -15,13 +15,34 @@ A new Proof-of-Work algorithm to replace Ethash that utilizes almost all parts o ## Abstract -ProgPoW is a proof-of-work algorithm designed to close the efficiency gap available to specialized ASICs. It utilizes almost all parts of commodity hardware (GPUs), and comes pre-tuned for the most common hardware utilized in the Ethereum network. +ProgPoW is a proof-of-work algorithm designed to close the efficiency gap available to specialized ASICs. It utilizes almost all parts of commodity hardware (GPUs), and comes pre-tuned for the most common hardware utilized in the Ethereum network. + +This document presents an overview of the algorithm and examines what it means to be “ASIC-resistant.” Next, we compare existing PoW designs by analyzing how each algorithm executes in hardware. Finally, we present the detailed implementation by walking through the code. ## Motivation -Ever since the first bitcoin mining ASIC was released, many new Proof of Work algorithms have been created with the intention of being “ASIC-resistant”. The goal of “ASIC-resistance” is to resist the centralization of PoW mining power such that these coins couldn’t be so easily manipulated by a few players. +Ever since the first bitcoin mining ASIC was released, many new Proof of Work algorithms have been created with the intention of being “ASIC-resistant”. The goal of “ASIC-resistance” is to resist the centralization of PoW mining power such that these coins couldn’t be so easily manipulated by a few players. -This document presents an overview of the algorithm and examines what it means to be “ASIC-resistant.” Next, we compare existing PoW designs by analyzing how each algorithm executes in hardware. Finally, we present the detailed implementation by walking through the code. +Ethereum's approach is to incentivize a geographically-distributed community of miners with a low barrier to entry on commodity hardware. As stated in the [Yellow Paper](https://ethereum.github.io/yellowpaper/paper.pdf): + +> 11.5. Mining Proof-of-Work. The mining proof-ofwork (PoW) exists as a cryptographically secure nonce that proves beyond reasonable doubt that a particular amount of computation has been expended in the determination of some token value n. It is utilised to enforce the blockchain security by giving meaning and credence to the notion of difficulty (and, by extension, total difficulty). However, since mining new blocks comes with an attached reward, the proof-of-work not only functions as a method of securing confidence that the blockchain will remain canonical into the future, but also as a wealth distribution mechanism. + +> For both reasons, there are two important goals of the proof-of-work function; firstly, it should be as accessible as possible to as many people as possible. The requirement of, or reward from, specialised and uncommon hardware should be minimised. This makes the distribution model as open as possible, and, ideally, makes the act of mining a simple swap from electricity to Ether at roughly the same rate for anyone around the world. + +> Secondly, it should not be possible to make super-linear profits, and especially not so with a high initial barrier. Such a mechanism allows a well-funded adversary to gain a troublesome amount of the network’s total mining power and as such gives them a super-linear reward (thus skewing distribution in their favour) as well as reducing the network security... + +> ... While ASICs exist for a proof-of-work function, both goals are placed in jeopardy. Because of this, a proof-of-work function that is ASIC-resistant (i.e. difficult or economically inefficient to implement in specialised compute hardware) has been identified as the proverbial silver bullet. + +It is from these premises that Ethash was designed as an ASIC-resistant proof-of-work: + +> Two directions exist for ASIC resistance; firstly make it sequential memory-hard, i.e. engineer the function such that the determination of the nonce requires a lot of memory and bandwidth such that the memory cannot be used in parallel to discover multiple nonces simultaneously. The second is to make the type of computation it would need to do general-purpose; the meaning of “specialised hardware” for a general-purpose task set is, naturally, general purpose hardware and as such commodity desktop computers are likely to be pretty close to “specialised hardware” for the task. For Ethereum 1.0 we have chosen the first path. + +5 years of experience with the Ethereum blockchain have demonstrated the success of our approach. This success cannot be taken for granted. +* 11 years of experience with PoW Blockchains have shown a centralization in hardware development, resulting in a [few companies](https://www.asicminervalue.com/) controlling the lifecycle of new hardware with limited distribution. +* New ASICs for Ethash are providing higher efficiency than GPUs, such as the [Antminer E3](https://shop.bitmain.com/product/detail?pid=00020181031134626816gh0zYNKC06A3). +* As much as 40% of the Ethereum network may now be secured by ASICs. + +ProgPow restores Ethash' ASIC-resistance by extending Ethash with a GPU-specific approach to the second path — making the “specialised hardware” for the PoW task commodity hardware. ### ProgPoW Overview The design goal of ProgPoW is to have the algorithm’s requirements match what is available on commodity GPUs: If the algorithm were to be implemented on a custom ASIC there should be little opportunity for efficiency gains compared to a commodity GPU. @@ -45,13 +66,13 @@ These would result in minimal, roughly 1.1-1.2x, efficiency gains. This is much ### Rationale for PoW on Commodity Hardware With the growth of large mining pools, the control of hashing power has been delegated to the top few pools to provide a steadier economic return for small miners. While some have made the argument that large centralized pools defeats the purpose of “ASIC resistance,” it’s important to note that ASIC based coins are even more centralized for several reasons. -1. No natural distribution: There isn’t an economic purpose for ultra-specialized hardware outside of mining and thus no reason for most people to have it. -2. No reserve group: Thus, there’s no reserve pool of hardware or reserve pool of interested parties to jump in when coin price is volatile and attractive for manipulation. -3. High barrier to entry: Initial miners are those rich enough to invest capital and ecological resources on the unknown experiment a new coin may be. Thus, initial coin distribution through mining will be very limited causing centralized economic bias. -4. Delegated centralization vs implementation centralization: While pool centralization is delegated, hardware monoculture is not: only the limiter buyers of this hardware can participate so there isn’t even the possibility of divesting control on short notice. +1. No natural distribution: There isn’t an economic purpose for ultra-specialized hardware outside of mining and thus no reason for most people to have it. +2. No reserve group: Thus, there’s no reserve pool of hardware or reserve pool of interested parties to jump in when coin price is volatile and attractive for manipulation. +3. High barrier to entry: Initial miners are those rich enough to invest capital and ecological resources on the unknown experiment a new coin may be. Thus, initial coin distribution through mining will be very limited causing centralized economic bias. +4. Delegated centralization vs implementation centralization: While pool centralization is delegated, hardware monoculture is not: only the limited buyers of this hardware can participate so there isn’t even the possibility of divesting control on short notice. 5. No obvious decentralization of control even with decentralized mining: Once large custom ASIC makers get into the game, designing back-doored hardware is trivial. ASIC makers have no incentive to be transparent or fair in market participation. -While the goal of “ASIC resistance” is valuable, the entire concept of “ASIC resistance” is a bit of a fallacy. CPUs and GPUs are themselves ASICs. Any algorithm that can run on a commodity ASIC (a CPU or GPU) by definition can have a customized ASIC created for it with slightly less functionality. Some algorithms are intentionally made to be “ASIC friendly” - where an ASIC implementation is drastically more efficient than the same algorithm running on general purpose hardware. The protection that this offers when the coin is unknown also makes it an attractive target for a dedicate mining ASIC company as soon as it becomes useful. +While the goal of “ASIC resistance” is valuable, the entire concept of “ASIC resistance” is a bit of a fallacy. CPUs and GPUs are themselves ASICs. Any algorithm that can run on a commodity ASIC (a CPU or GPU) by definition can have a customized ASIC created for it with slightly less functionality. Some algorithms are intentionally made to be “ASIC friendly” - where an ASIC implementation is drastically more efficient than the same algorithm running on general purpose hardware. The protection that this offers when the coin is unknown also makes it an attractive target for a dedicated mining ASIC company as soon as it becomes useful. Therefore, ASIC resistance is: the efficiency difference of specialized hardware versus hardware that has a wider adoption and applicability. A smaller efficiency difference between custom vs general hardware mean higher resistance and a better algorithm. This efficiency difference is the proper metric to use when comparing the quality of PoW algorithms. Efficiency could mean absolute performance, performance per watt, or performance per dollar - they are all highly correlated. If a single entity creates and controls an ASIC that is drastically more efficient, they can gain 51% of the network hashrate and possibly stage an attack. @@ -104,39 +125,41 @@ Ethash requires external memory due to the large size of the DAG. However that ## Specification -The DAG is generated exactly as in Ethash. All the parameters (ephoch length, DAG size, etc) are unchanged. See the original [Ethash](https://github.com/ethereum/wiki/wiki/Ethash) spec for details on generating the DAG. - ProgPoW can be tuned using the following parameters. The proposed settings have been tuned for a range of existing, commodity GPUs: + * `PROGPOW_PERIOD`: Number of blocks before changing the random program * `PROGPOW_LANES`: The number of parallel lanes that coordinate to calculate a single hash instance * `PROGPOW_REGS`: The register file usage size * `PROGPOW_DAG_LOADS`: Number of uint32 loads from the DAG per lane * `PROGPOW_CACHE_BYTES`: The size of the cache -* `PROGPOW_CNT_DAG`: The number of DAG accesses, defined as the outer loop of the algorithm (64 is the same as ethash) +* `PROGPOW_CNT_DAG`: The number of DAG accesses, defined as the outer loop of the algorithm (64 is the same as Ethash) * `PROGPOW_CNT_CACHE`: The number of cache accesses per loop * `PROGPOW_CNT_MATH`: The number of math operations per loop -The value of these parameters has been tweaked between version 0.9.2 (live on the gangnum testnet) and 0.9.3 (proposed for Ethereum adoption). See [this medium post](https://medium.com/@ifdefelse/progpow-progress-da5bb31a651b) for details. +The values of these parameters have been tweaked between the original version and the version proposed here for Ethereum adoption. See [this medium post](https://medium.com/@ifdefelse/progpow-progress-da5bb31a651b) for details. -| Parameter | 0.9.2 | 0.9.3 | -|-----------------------|-----------|-----------| -| `PROGPOW_PERIOD` | `50` | `10` | -| `PROGPOW_LANES` | `16` | `16` | -| `PROGPOW_REGS` | `32` | `32` | -| `PROGPOW_DAG_LOADS` | `4` | `4` | +| Parameter | 0.9.2 | 0.9.3 | +|-----------------------|-------|-------| +| `PROGPOW_PERIOD` | `50` | `10` | +| `PROGPOW_LANES` | `16` | `16` | +| `PROGPOW_REGS` | `32` | `32` | +| `PROGPOW_DAG_LOADS` | `4` | `4` | | `PROGPOW_CACHE_BYTES` | `16x1024` | `16x1024` | -| `PROGPOW_CNT_DAG` | `64` | `64` | -| `PROGPOW_CNT_CACHE` | `12` | `11` | -| `PROGPOW_CNT_MATH` | `20` | `18` | +| `PROGPOW_CNT_DAG` | `64` | `64` | `64` | +| `PROGPOW_CNT_CACHE` | `12` | `11` | `11` | +| `PROGPOW_CNT_MATH` | `20` | `18` | `18` | +| DAG Parameter | 0.9.2 | 0.9.3 | +|--------------------------|-------|-------| +| `ETHASH_DATASET_PARENTS` | `256` | `256` | -The random program changes every `PROGPOW_PERIOD` blocks to ensure the hardware executing the algorithm is fully programmable. If the program only changed every DAG epoch (roughly 5 days) certain miners could have time to develop hand-optimized versions of the random sequence, giving them an undue advantage. -Sample code is written in C++, this should be kept in mind when evaluating the code in the specification. +The random program changes every `PROGPOW_PERIOD` blocks (default `10`, roughly 2 minutes) to ensure the hardware executing the algorithm is fully programmable. If the program only changed every DAG epoch (roughly 5 days) certain miners could have time to develop hand-optimized versions of the random sequence, giving them an undue advantage. +Sample code is written in C++, this should be kept in mind when evaluating the code in the specification. All numerics are computed using unsigned 32 bit integers. Any overflows are trimmed off before proceeding to the next computation. Languages that use numerics not fixed to bit lengths (such as Python and JavaScript) or that only use signed integers (such as Java) will need to keep their languages' quirks in mind. The extensive use of 32 bit data values aligns with modern GPUs internal data architectures. -ProgPoW uses a 32-bit variant of **FNV1a** for merging data. The existing Ethash uses a similar vaiant of FNV1 for merging, but FNV1a provides better distribution properties. +ProgPoW uses a 32-bit variant of **FNV1a** for merging data. The existing Ethash uses a similar variant of FNV1 for merging, but FNV1a provides better distribution properties. Test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#fnv1a). @@ -181,46 +204,31 @@ Test vectors can be found [in the test vectors file](../assets/eip-1057/test-vec ```cpp void fill_mix( - uint64_t hash_seed, + uint64_t seed, uint32_t lane_id, uint32_t mix[PROGPOW_REGS] ) { // Use FNV to expand the per-warp seed to per-lane // Use KISS to expand the per-lane seed to fill mix + uint32_t fnv_hash = FNV_OFFSET_BASIS; kiss99_t st; - st.z = fnv1a(FNV_OFFSET_BASIS, seed); - st.w = fnv1a(st.z, seed >> 32); - st.jsr = fnv1a(st.w, lane_id); - st.jcong = fnv1a(st.jsr, lane_id); + st.z = fnv1a(fnv_hash, seed); + st.w = fnv1a(fnv_hash, seed >> 32); + st.jsr = fnv1a(fnv_hash, lane_id); + st.jcong = fnv1a(fnv_hash, lane_id); for (int i = 0; i < PROGPOW_REGS; i++) - mix[i] = kiss99(st); + mix[i] = kiss99(st); } ``` Like Ethash Keccak is used to seed the sequence per-nonce and to produce the final result. The keccak-f800 variant is used as the 32-bit word size matches the native word size of modern GPUs. The implementation is a variant of SHAKE with width=800, bitrate=576, capacity=224, output=256, and no padding. The result of keccak is treated as a 256-bit big-endian number - that is result byte 0 is the MSB of the value. -As with Ethash the input and output of the keccak function are fixed and relatively small. This means only a single "absorb" and "squeeze" phase are required. For a pseudo-code imenentation of the `keccak_f800_round` function see the `Round[b](A,RC)` function in the "Pseudo-code description of the permutations" section of the [official Keccak specs](https://keccak.team/keccak_specs_summary.html). - -Test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#keccak_f800_progpow). +As with Ethash the input and output of the keccak function are fixed and relatively small. This means only a single "absorb" and "squeeze" phase are required. For a pseudo-code implementation of the `keccak_f800_round` function see the `Round[b](A,RC)` function in the "Pseudo-code description of the permutations" section of the [official Keccak specs](https://keccak.team/keccak_specs_summary.html). ```cpp -hash32_t keccak_f800_progpow(hash32_t header, uint64_t seed, hash32_t digest) +hash32_t keccak_f800_progpow(uint32_t* state) { - uint32_t st[25]; - - // Initialization - for (int i = 0; i < 25; i++) - st[i] = 0; - - // Absorb phase for fixed 18 words of input - for (int i = 0; i < 8; i++) - st[i] = header.uint32s[i]; - st[8] = seed; - st[9] = seed >> 32; - for (int i = 0; i < 8; i++) - st[10+i] = digest.uint32s[i]; - // keccak_f800 call for the single absorb pass for (int r = 0; r < 22; r++) keccak_f800_round(st, r); @@ -236,9 +244,9 @@ hash32_t keccak_f800_progpow(hash32_t header, uint64_t seed, hash32_t digest) The inner loop uses FNV and KISS99 to generate a random sequence from the `prog_seed`. This random sequence determines which mix state is accessed and what random math is performed. -Since the `prog_seed` changes only once per `PROGPOW_PERIOD` it is expected that while mining `progPowLoop` will be evaluated on the CPU to generate source code for that period's sequence. The source code will be compiled on the CPU before running on the GPU. +Since the `prog_seed` changes only once per `PROGPOW_PERIOD` (10 blocks or about 2 minutes) it is expected that while mining `progPowLoop` will be evaluated on the CPU to generate source code for that period's sequence. The source code will be compiled on the CPU before running on the GPU. You can see an example sequence and generated source code in [kernel.cu](https://github.com/ifdefelse/ProgPOW/blob/824cd791634204c4cc7e31f84bb76c0c84895bd3/test/kernel.cu). -Test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#progPowInit). +Test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#progpowinit). ```cpp kiss99_t progPowInit(uint64_t prog_seed, int mix_seq_dst[PROGPOW_REGS], int mix_seq_src[PROGPOW_REGS]) @@ -316,19 +324,18 @@ uint32_t math(uint32_t a, uint32_t b, uint32_t r) } ``` - The flow of the inner loop is: * Lane `(loop % LANES)` is chosen as the leader for that loop iteration -* The leader's `mix[0]` value modulo the number of 256-byte DAG entries is is used to select where to read from the full DAG +* The leader's `mix[0]` value modulo the number of 256-byte DAG entries is used to select where to read from the full DAG * Each lane reads `DAG_LOADS` sequential words, using `(lane ^ loop) % LANES` as the starting offset within the entry. * The random sequence of math and cache accesses is performed * The DAG data read at the start of the loop is merged at the end of the loop -`prog_seed` and `loop` come from the outer loop, corresponding to the current program seed (which is block_number/PROGPOW_PERIOD) and the loop iteration number. `mix` is the state array, initially filled by `fill_mix`. `dag` is the bytes of the Ethash DAG grouped into 32 bit unsigned ints in litte-endian format. On little-endian architectures this is just a normal int32 pointer to the existing DAG. +`prog_seed` and `loop` come from the outer loop, corresponding to the current program seed (which is block_number/PROGPOW_PERIOD) and the loop iteration number. `mix` is the state array, initially filled by `fill_mix`. `dag` is the bytes of the Ethash DAG grouped into 32 bit unsigned ints in little-endian format. On little-endian architectures this is just a normal int32 pointer to the existing DAG. `DAG_BYTES` is set to the number of bytes in the current DAG, which is generated identically to the existing Ethash algorithm. -Test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#progPowLoop). +Test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#progpowloop). ```cpp void progPowLoop( @@ -381,7 +388,7 @@ void progPowLoop( if (i < PROGPOW_CNT_MATH) { // Random Math - // Generate 2 unique sources + // Generate 2 unique sources int src_rnd = kiss99(prog_rnd) % (PROGPOW_REGS * (PROGPOW_REGS-1)); int src1 = src_rnd % PROGPOW_REGS; // 0 <= src1 < PROGPOW_REGS int src2 = src_rnd / PROGPOW_REGS; // 0 <= src2 < PROGPOW_REGS - 1 @@ -409,30 +416,52 @@ void progPowLoop( ``` The flow of the overall algorithm is: -* A keccak hash of the header + nonce to create a seed -* Use the seed to generate initial mix data +* A keccak hash of the header + nonce to create a digest of 256 bits from keccak_f800 (padding is consistent with custom one in ethash) +* Use first two words of digest as seed to generate initial mix data * Loop multiple times, each time hashing random loads and random math into the mix data * Hash all the mix data into a single 256-bit value -* A final keccak hash is computed +* A final keccak hash using carry-over digest from initial data + mix_data final 256 bit value (padding is consistent with custom one in ethash) * When mining this final value is compared against a `hash32_t` target ```cpp hash32_t progPowHash( - const uint64_t prog_seed, // value is (block_number/PROGPOW_PERIOD) + const uint64_t prog_seed, // value is (block_number/PROGPOW_PERIOD) const uint64_t nonce, const hash32_t header, - const uint32_t *dag // gigabyte DAG located in framebuffer - the first portion gets cached + const uint32_t *dag // gigabyte DAG located in framebuffer - the first portion gets cached ) { + hash32_t hash_init; + hash32_t hash_final; + uint32_t mix[PROGPOW_LANES][PROGPOW_REGS]; - hash32_t digest; - for (int i = 0; i < 8; i++) - digest.uint32s[i] = 0; - // keccak(header..nonce) - hash32_t seed_256 = keccak_f800_progpow(header, nonce, digest); - // endian swap so byte 0 of the hash is the MSB of the value - uint64_t seed = bswap(seed_256[0]) << 32 | bswap(seed_256[1]); + /* + ======================================== + Absorb phase for initial keccak pass + ======================================== + */ + + { + uint32_t state[25] = {0x0}; + // 1st fill with header data (8 words) + for (int i = 0; i < 8; i++) + state[i] = header.uint32s[i]; + + // 2nd fill with nonce (2 words) + state[8] = nonce; + state[9] = nonce >> 32; + + // 3rd apply padding + state[10] = 0x00000001; + state[18] = 0x80008081; + + // keccak(header..nonce) + hash_init = keccak_f800_progpow(state); + + // get the seed to initialize mix + seed = ((uint64_t)hash_init.uint32s[1] << 32) | hash_init.uint32s[0]); + } // initialize mix for all lanes for (int l = 0; l < PROGPOW_LANES; l++) @@ -446,7 +475,7 @@ hash32_t progPowHash( uint32_t digest_lane[PROGPOW_LANES]; for (int l = 0; l < PROGPOW_LANES; l++) { - digest_lane[l] = FNV_OFFSET_BASIS + digest_lane[l] = FNV_OFFSET_BASIS; for (int i = 0; i < PROGPOW_REGS; i++) digest_lane[l] = fnv1a(digest_lane[l], mix[l][i]); } @@ -454,49 +483,93 @@ hash32_t progPowHash( for (int i = 0; i < 8; i++) digest.uint32s[i] = FNV_OFFSET_BASIS; for (int l = 0; l < PROGPOW_LANES; l++) - digest.uint32s[l%8] = fnv1a(digest.uint32s[l%8], digest_lane[l]) + digest.uint32s[l%8] = fnv1a(digest.uint32s[l%8], digest_lane[l]); + + /* + ======================================== + Absorb phase for final keccak pass + ======================================== + */ + + { + uint32_t state[25] = {0x0}; + + // 1st fill with hash_init (8 words) + for (int i = 0; i < 8; i++) + state[i] = hash_init.uint32s[i]; + + // 2nd fill with digest from main loop + for (int i = 8; i < 16; i++) + state[i] = digest.uint32s[i - 8]; + + // 3rd apply padding + state[17] = 0x00000001; + state[24] = 0x80008081; + + // keccak(header..nonce) + hash_final = keccak_f800_progpow(state); + } + + // Compare hash final to target + [...] - // keccak(header .. keccak(header..nonce) .. digest); - keccak_f800_progpow(header, seed, digest); } ``` -## Rationale +## Security Considerations + +This proposal has been software and hardware audited: +* [Least Authority — ProgPoW Software Audit PDF](https://leastauthority.com/static/publications/LeastAuthority-ProgPow-Algorithm-Final-Audit-Report.pdf) +* [Bob Rao - ProgPoW Hardware Audit PDF](https://github.com/ethereum-cat-herders/progpow-audit/raw/master/Bob%20Rao%20-%20ProgPOW%20Hardware%20Audit%20Report%20Final.pdf) -ProgPoW utilizes almost all parts of a commodity GPU, excluding: +Least Authority in their findings suggest a change to DAG generation -- modification of `ETHASH_DATASET_PARENTS` from a value of 256 to the new value of 512 -- in order to mitigate vulnerability to a "Light Evaluation" attack. Due to this the DAG memory file used by ProgPoW is would no longer compatible with the one used by Ethash (epoch length and size increase ratio remain the same though). -* The graphics pipeline (displays, geometry engines, texturing, etc); -* Floating point math. +We do not recommend implementing this fix at this time. Ethash will not be exploitable for years, and it's not clear ProgPoW will ever be exploitable. It's better to deploy the audited code. -Making use of either of these would have significant portability issues between commodity hardware vendors, and across programming languages. +After the completion of the audits a clever finding by [Kik](https://github.com/kik/) disclosed a vulnerability to [bypassing ProgPoW memory hardness](https://github.com/kik/progpow-exploit). The vulnerability is present in Ethash as well but is near-impossible to exploit. In progPoW it is not possible to exploit -- it assumes the ability to create variants of the candidate block's header hash in a fashion similar to bitcoin, which is actually not possible in Ethereum. An attacker would need modified block headers, would need customized nodes able to accept the modified block headers, and uses extraNonce/extraData as entropy -- which isn’t the standard. And the required brute-force search would be difficult to accomplish in one blocktime. And even if supported by a customized node the block propagation of such mined blocks would be immediately blocked by other peers as the header hash is invalid. -Since the GPU is almost fully utilized, there’s little opportunity for specialized ASICs to gain efficiency. Removing both the graphics pipeline and floating point math could provide up to 1.2x gains in efficiency, compared to the 2x gains possible in Ethash, and 50x gains possible for CryptoNight. +The authors have since found another vulnerability similar to Kik's, but it adds too much overhead to be ASIC-friendly. See Lanfranchi's full explanation [here](https://github.com/ifdefelse/ProgPOW/issues/51#issuecomment-690155355). To completely prevent such exploits we could change the condition modifying the input state of the last keccak pass from +* header (256 bits) + +* seed for mix initiator (64 bits) + +* mix from main loop (256 bits) +* no padding -## Backwards Compatibility +to +* digest from initial keccak (256 bits) + +* mix from main loop (256 bits) + +* padding -This algorithm is not backwards compatible with the existing Ethash, and will require a fork for adoption. Furthermore, the network hashrate will halve since twice as much memory is loaded per hash. +thus widening the constraint to target in keccak [brute force keccak linear searches](https://github.com/kik/progpow-exploit) from 64 to 256 bits. + +This fix is available as a PR to the reference implementation. Again, we do not recommend implementing this fix at this time. Kik's vulnerability and others like it cannot be exploited now and likely never will be. It's better to deploy the audited code. + +Note that these vulnerabilities cannot be exploited to deny service, double spend, or otherwise damage the network. They could at worst give their deployer an efficiency advantage over other miners. ## Test Cases -### progpow 0.9.2 +The random sequence generated for block 30,000 (prog_seed 3,000) can been seen in [kernel.cu](https://github.com/ifdefelse/ProgPOW/blob/824cd791634204c4cc7e31f84bb76c0c84895bd3/test/kernel.cu). + The algorithm run on block 30,000 produces the following digest and result: ``` -header ffeeddccbbaa9988776655443322110000112233445566778899aabbccddeeff -nonce 123456789abcdef0 - -digest: 11f19805c58ab46610ff9c719dcf0a5f18fa2f1605798eef770c47219274767d -result: 5b7ccd472dbefdd95b895cac8ece67ff0deb5a6bd2ecc6e162383d00c3728ece +Header : 0xffeeddccbbaa9988776655443322110000112233445566778899aabbccddeeff +Nonce : 0x123456789abcdef0 +Hash init : 0xee304846ddd0a47b98179e96b60ec5ceeae2727834367e593de780e3e6d1892f +Mix seed : 0x7ba4d0dd464830ee +Mix hash : 0x493c13e9807440571511b561132834bbd558dddaa3b70c09515080a6a1aff6d0 +Hash final : 0x46b72b75f238bea3fcfd227e0027dc173dceaa1fb71744bd3d5e030ed2fed053 ``` -Additional test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#progPowHash). -### progpow 0.9.3 -[Machine-readable test vectors](https://github.com/ethereum/EIPs/blob/ad4e73f239d53d72a21cfd8fdc89dc81eb9d2688/assets/eip-1057/test-vectors-0.9.3.json) +Additional test vectors can be found [in the test vectors file](../assets/eip-1057/test-vectors.md#progpowhash). + +Machine-readable test vectors (T.B.D) + ## Implementation -The reference ProgPoW mining implementation located at [ProgPOW](https://github.com/ifdefelse/ProgPOW) is a derivative of ethminer so retains the GPL license. -## License and Copyright +The reference ProgPoW mining implementation is located at [the @ifdefelse ProgPOW repository](https://github.com/ifdefelse/ProgPOW). + +## Copyright -The ProgPoW algorithm and this specification are a new work. Copyright and related rights are waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). The reference ProgPoW mining implementation located at [ProgPOW](https://github.com/ifdefelse/ProgPOW) is a derivative of ethminer so retains the GPL license. diff --git a/EIPS/eip-1062.md b/EIPS/eip-1062.md index 62ae1896156ca2..186cc0b05e2eb5 100644 --- a/EIPS/eip-1062.md +++ b/EIPS/eip-1062.md @@ -1,84 +1,7 @@ --- eip: 1062 -title: Formalize IPFS hash into ENS(Ethereum Name Service) resolver -author: Phyrex Tsai , Portal Network Team -discussions-to: https://ethereum-magicians.org/t/eip-1062-formalize-ipfs-hash-into-ens-ethereum-name-service-resolver/281 -status: Draft -type: Standards Track category: ERC -created: 2018-05-02 +status: Moved --- -## Simple Summary -To specify the mapping protocol between resources stored on IPFS and ENS(Ethereum Naming Service). - -## Abstract -The following standard details the implementation of how to combine the IPFS cryptographic hash unique fingerprint with ENS public resolver. This standard provides a functionality to get and set IPFS online resources to ENS resolver. - -We think that this implementation is not only aim to let more developers and communities to provide more use cases, but also leverage the human-readable features to gain more user adoption accessing decentralized resources. We considered the IPFS ENS resolver mapping standard a cornerstone for building future Web3.0 service. - -## Motivation -To build fully decentralized web service, it’s necessary to have a decentralized file storage system. Here comes the IPFS, for three following advantages : -- Address large amounts of data, and has unique cryptographic hash for every record. -- Since IPFS is also based on peer to peer network, it can be really helpful to deliver large amounts of data to users, with safer way and lower the millions of cost for the bandwidth. -- IPFS stores files in high efficient way via tracking version history for every file, and removing the duplications across the network. - -Those features makes perfect match for integrating into ENS, and these make users can easily access content through ENS, and show up in the normal browser. - - -## Specification -The condition now is that the IPFS file fingerprint using base58 and in the meantime, the Ethereum uses hex in API to encode the binary data. So that need a way to process the condition requires not only we need to transfer from IPFS to Ethereum, but also need to convert it back. - -To solve these requirements, we can use binary buffer bridging that gap. -When mapping the IPFS base58 string to ENS resolver, first we convert the Base58 to binary buffer, turn the buffer to hex encrypted format, and save to the contract. Once we want to get the IPFS resources address represented by the specific ENS, we can first find the mapping information stored as hex format before, extract the hex format to binary buffer, and finally turn that to IPFS Base58 address string. - - -## Rationale -To implement the specification, need two methods from ENS public resolver contract, when we want to store IPFS file fingerprint to contract, convert the Base58 string identifier to the hex format and invoke the `setMultihash` method below : - -``` -function setMultihash(bytes32 node, bytes hash) public only_owner(node); -``` - -Whenever users need to visit the ENS content, we call the `multihash` method to get the IPFS hex data, transfer to the Base58 format, and return the IPFS resources to use. - -``` -function multihash(bytes32 node) public view returns (bytes); -``` - -## Test Cases - -To implement the way to transfer from base58 to hex format and the reverse one, using the ‘multihashes’ library to deal with the problem. -The library link : [https://www.npmjs.com/package/multihashes](https://www.npmjs.com/package/multihashes) -To implement the method transfer from IPFS(Base58) to hex format : - -``` -import multihash from 'multihashes' - -export const toHex = function(ipfsHash) { - let buf = multihash.fromB58String(ipfsHash); - return '0x' + multihash.toHexString(buf); -} -``` - -To implement the method transfer from hex format to IPFS(Base58) : - -``` -import multihash from 'multihashes' - -export const toBase58 = function(contentHash) { - let hex = contentHash.substring(2) - let buf = multihash.fromHexString(hex); - return multihash.toB58String(buf); -} -``` - -## Implementation -The use case can be implemented as browser extension. Users can easily download the extension, and easily get decentralized resources by just typing the ENS just like we normally type the DNS to browser the website. Solve the current pain for normal people can not easily visit the total decentralized website. - -The workable implementation repository : [https://github.com/PortalNetwork/portal-network-browser-extension](https://github.com/PortalNetwork/portal-network-browser-extension) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1062.md diff --git a/EIPS/eip-1066.md b/EIPS/eip-1066.md index c8755a5b52d75a..f5cbc61ae0e4a7 100644 --- a/EIPS/eip-1066.md +++ b/EIPS/eip-1066.md @@ -1,599 +1,7 @@ --- eip: 1066 -title: Status Codes -author: Brooklyn Zelenka (@expede), Tom Carchrae (@carchrae), Gleb Naumenko (@naumenkogs) -discussions-to: https://ethereum-magicians.org/t/erc-1066-ethereum-status-codes-esc/ -status: Draft -type: Standards Track category: ERC -created: 2018-05-05 -version: 1.0.0 +status: Moved --- -## Simple Summary - -Broadly applicable status codes for smart contracts. - -## Abstract - -This standard outlines a common set of status codes in a similar vein to HTTP statuses. This provides a shared set of signals to allow smart contracts to react to situations autonomously, expose localized error messages to users, and so on. - -The current state of the art is to either `revert` on anything other than a clear success (ie: require human intervention), or return a low-context `true` or `false`. Status codes are similar-but-orthogonal to `revert`ing with a reason, but aimed at automation, debugging, and end-user feedback (including translation). _They are fully compatible with both `revert` and `revert`-with-reason._ - -As is the case with HTTP, having a standard set of known codes has many benefits for developers. They remove friction from needing to develop your own schemes for every contract, makes inter-contract automation easier, and makes it easier to broadly understand which of the finite states your request produced. Importantly, it makes it much easier to distinguish between expected errors states, truly exceptional conditions that require halting execution, normal state transitions, and various success cases. - -## Motivation - -### Semantic Density - -HTTP status codes are widely used for this purpose. BEAM languages use atoms and tagged tuples to signify much the same information. Both provide a lot of information both to the programmer (debugging for instance), and to the program that needs to decide what to do next. - -Status codes convey a much richer set of information [than Booleans](https://existentialtype.wordpress.com/2011/03/15/boolean-blindness/), and are able to be reacted to autonomously unlike arbitrary strings. - -### User Experience (UX) - -_End users get little to no feedback, and there is no translation layer._ - -Since ERC1066 status codes are finite and known in advance, we can leverage [ERC1444](https://eips.ethereum.org/EIPS/eip-1444) to provide global, human-readable sets of status messages. These may also be translated into any language, differing levels of technical detail, added as `revert` messages, natspecs, and so on. - -Status codes convey a much richer set of information than Booleans, and are able to be reacted to autonomously unlike arbitrary strings. - -### Developer Experience (DX) - -_Developers currently have very little context exposed by their smart contracts._ - -At time of writing, other than stepping through EVM execution and inspecting memory dumps directly, it is very difficult to understand what is happening during smart contract execution. By returning more context, developers can write well-decomposed tests and assert certain codes are returned as an expression of where the smart contract got to. This includes status codes as bare values, `event`s, and `revert`s. - -Having a fixed set of codes also makes it possible to write common helper functions to react in common ways to certain signals. This can live off- or on-chain library, lowering the overhead in building smart contracts, and helping raise code quality with trusted shared components. - -We also see a desire for this [in transactions](https://eips.ethereum.org/EIPS/eip-658), and there's no reason that these status codes couldn't be used by the EVM itself. - -### Smart Contract Autonomy - -_Smart contracts don’t know much about the result of a request beyond pass/fail; they can be smarter with more context._ - -Smart contracts are largely intended to be autonomous. While each contract may define a specific interface, having a common set of semantic codes can help developers write code that can react appropriately to various situations. - -While clearly related, status codes are complementary to `revert`-with-reason. Status codes are not limited to rolling back the transaction, and may represent known error states without halting execution. They may also represent off-chain conditions, supply a string to revert, signal time delays, and more. - -All of this enables contracts to share a common vocabulary of state transitions, results, and internal changes, without having to deeply understand custom status enums or the internal business logic of collaborator contracts. - -## Specification - -### Format - -Codes are returned either on their own, or as the first value of a multiple return. - -```solidity -// Status only - -function isInt(uint num) public pure returns (byte status) { - return hex"01"; -} - -// Status and value - -uint8 private counter; - -function safeIncrement(uint8 interval) public returns (byte status, uint8 newCounter) { - uint8 updated = counter + interval; - - if (updated >= counter) { - counter = updated; - return (hex"01", updated); - } else { - return (hex"00", counter); - } -} -``` - -### Code Table - -Codes break nicely into a 16x16 matrix, represented as a 2-digit hex number. The high nibble represents the code's kind or "category", and the low nibble contains the state or "reason". We present them below as separate tables per range for explanatory and layout reasons. - -**NB: Unspecified codes are _not_ free for arbitrary use, but rather open for further specification.** - -#### `0x0*` Generic - -General codes. These double as bare "reasons", since `0x01 == 1`. - -| Code | Description | -|--------|-----------------------------------------| -| `0x00` | Failure | -| `0x01` | Success | -| `0x02` | Awaiting Others | -| `0x03` | Accepted | -| `0x04` | Lower Limit or Insufficient | -| `0x05` | Receiver Action Requested | -| `0x06` | Upper Limit | -| `0x07` | [reserved] | -| `0x08` | Duplicate, Unnecessary, or Inapplicable | -| `0x09` | [reserved] | -| `0x0A` | [reserved] | -| `0x0B` | [reserved] | -| `0x0C` | [reserved] | -| `0x0D` | [reserved] | -| `0x0E` | [reserved] | -| `0x0F` | Informational or Metadata | - -#### `0x1*` Permission & Control - -Also used for common state machine actions (ex. "stoplight" actions). - -| Code | Description | -|--------|---------------------------------------------------| -| `0x10` | Disallowed or Stop | -| `0x11` | Allowed or Go | -| `0x12` | Awaiting Other's Permission | -| `0x13` | Permission Requested | -| `0x14` | Too Open / Insecure | -| `0x15` | Needs Your Permission or Request for Continuation | -| `0x16` | Revoked or Banned | -| `0x17` | [reserved] | -| `0x18` | Not Applicable to Current State | -| `0x19` | [reserved] | -| `0x1A` | [reserved] | -| `0x1B` | [reserved] | -| `0x1C` | [reserved] | -| `0x1D` | [reserved] | -| `0x1E` | [reserved] | -| `0x1F` | Permission Details or Control Conditions | - -#### `0x2*` Find, Inequalities & Range - -This range is broadly intended for finding and matching. Data lookups and order matching are two common use cases. - -| Code | Description | -|--------|-------------------------------------| -| `0x20` | Not Found, Unequal, or Out of Range | -| `0x21` | Found, Equal or In Range | -| `0x22` | Awaiting Match | -| `0x23` | Match Request Sent | -| `0x24` | Below Range or Underflow | -| `0x25` | Request for Match | -| `0x26` | Above Range or Overflow | -| `0x27` | [reserved] | -| `0x28` | Duplicate, Conflict, or Collision | -| `0x29` | [reserved] | -| `0x2A` | [reserved] | -| `0x2B` | [reserved] | -| `0x2C` | [reserved] | -| `0x2D` | [reserved] | -| `0x2E` | [reserved] | -| `0x2F` | Matching Meta or Info | - -#### `0x3*` Negotiation & Governance - -Negotiation, and very broadly the flow of such transactions. Note that "other party" may be more than one actor (not necessarily the sender). - -| Code | Description | -|--------|-----------------------------------------| -| `0x30` | Sender Disagrees or Nay | -| `0x31` | Sender Agrees or Yea | -| `0x32` | Awaiting Ratification | -| `0x33` | Offer Sent or Voted | -| `0x34` | Quorum Not Reached | -| `0x35` | Receiver's Ratification Requested | -| `0x36` | Offer or Vote Limit Reached | -| `0x37` | [reserved] | -| `0x38` | Already Voted | -| `0x39` | [reserved] | -| `0x3A` | [reserved] | -| `0x3B` | [reserved] | -| `0x3C` | [reserved] | -| `0x3D` | [reserved] | -| `0x3E` | [reserved] | -| `0x3F` | Negotiation Rules or Participation Info | - -#### `0x4*` Availability & Time - -Service or action availability. - -| Code | Description | -|--------|------------------------------------------------------| -| `0x40` | Unavailable | -| `0x41` | Available | -| `0x42` | Paused | -| `0x43` | Queued | -| `0x44` | Not Available Yet | -| `0x45` | Awaiting Your Availability | -| `0x46` | Expired | -| `0x47` | [reserved] | -| `0x48` | Already Done | -| `0x49` | [reserved] | -| `0x4A` | [reserved] | -| `0x4B` | [reserved] | -| `0x4C` | [reserved] | -| `0x4D` | [reserved] | -| `0x4E` | [reserved] | -| `0x4F` | Availability Rules or Info (ex. time since or until) | - -#### `0x5*` Tokens, Funds & Finance - -Special token and financial concepts. Many related concepts are included in other ranges. - -| Code | Description | -|--------|---------------------------------| -| `0x50` | Transfer Failed | -| `0x51` | Transfer Successful | -| `0x52` | Awaiting Payment From Others | -| `0x53` | Hold or Escrow | -| `0x54` | Insufficient Funds | -| `0x55` | Funds Requested | -| `0x56` | Transfer Volume Exceeded | -| `0x57` | [reserved] | -| `0x58` | Funds Not Required | -| `0x59` | [reserved] | -| `0x5A` | [reserved] | -| `0x5B` | [reserved] | -| `0x5C` | [reserved] | -| `0x5D` | [reserved] | -| `0x5E` | [reserved] | -| `0x5F` | Token or Financial Information | - -#### `0x6*` TBD - -Currently unspecified. (Full range reserved) - -#### `0x7*` TBD - -Currently unspecifie. (Full range reserved) - -#### `0x8*` TBD - -Currently unspecified. (Full range reserved) - -#### `0x9*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xA*` Application-Specific Codes - -Contracts may have special states that they need to signal. This proposal only outlines the broadest meanings, but implementers may have very specific meanings for each, as long as they are coherent with the broader definition. - -| Code | Description | -|--------|----------------------------------------| -| `0xA0` | App-Specific Failure | -| `0xA1` | App-Specific Success | -| `0xA2` | App-Specific Awaiting Others | -| `0xA3` | App-Specific Acceptance | -| `0xA4` | App-Specific Below Condition | -| `0xA5` | App-Specific Receiver Action Requested | -| `0xA6` | App-Specific Expiry or Limit | -| `0xA7` | [reserved] | -| `0xA8` | App-Specific Inapplicable Condition | -| `0xA9` | [reserved] | -| `0xAA` | [reserved] | -| `0xAB` | [reserved] | -| `0xAC` | [reserved] | -| `0xAD` | [reserved] | -| `0xAE` | [reserved] | -| `0xAF` | App-Specific Meta or Info | - -#### `0xB*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xC*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xD*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xE*` Encryption, Identity & Proofs - -Actions around signatures, cryptography, signing, and application-level authentication. - -The meta code `0xEF` is often used to signal a payload describing the algorithm or process used. - -| Code | Description | -|--------|-------------------------------------| -| `0xE0` | Decrypt Failure | -| `0xE1` | Decrypt Success | -| `0xE2` | Awaiting Other Signatures or Keys | -| `0xE3` | Signed | -| `0xE4` | Unsigned or Untrusted | -| `0xE5` | Signature Required | -| `0xE6` | Known to be Compromised | -| `0xE7` | [reserved] | -| `0xE8` | Already Signed or Not Encrypted | -| `0xE9` | [reserved] | -| `0xEA` | [reserved] | -| `0xEB` | [reserved] | -| `0xEC` | [reserved] | -| `0xED` | [reserved] | -| `0xEE` | [reserved] | -| `0xEF` | Cryptography, ID, or Proof Metadata | - -#### `0xF*` Off-Chain - -For off-chain actions. Much like th `0x0*: Generic` range, `0xF*` is very general, and does little to modify the reason. - -Among other things, the meta code `0xFF` may be used to describe what the off-chain process is. - -| Code | Description | -|--------|-----------------------------------| -| `0xF0` | Off-Chain Failure | -| `0xF1` | Off-Chain Success | -| `0xF2` | Awaiting Off-Chain Process | -| `0xF3` | Off-Chain Process Started | -| `0xF4` | Off-Chain Service Unreachable | -| `0xF5` | Off-Chain Action Required | -| `0xF6` | Off-Chain Expiry or Limit Reached | -| `0xF7` | [reserved] | -| `0xF8` | Duplicate Off-Chain Request | -| `0xF9` | [reserved] | -| `0xFA` | [reserved] | -| `0xFB` | [reserved] | -| `0xFC` | [reserved] | -| `0xFD` | [reserved] | -| `0xFE` | [reserved] | -| `0xFF` | Off-Chain Info or Meta | - -### As a Grid - -| | `0x0*` General | `0x1*` Permission & Control | `0x2*` Find, Inequalities & Range | `0x3*` Negotiation & Governance | `0x4*` Availability & Time | `0x5*` Tokens, Funds & Finance | `0x6*` TBD | `0x7*` TBD | `0x8*` TBD | `0x9*` TBD | `0xA*` Application-Specific Codes | `0xB*` TBD | `0xC*` TBD | `0xD*` TBD | `0xE*` Encryption, Identity & Proofs | `0xF*` Off-Chain | -|--------|------------------------------------------------|----------------------------------------------------------|--------------------------------------------|------------------------------------------------|-------------------------------------------------------------|----------------------------------------|-------------------|-------------------|-------------------|-------------------|-----------------------------------------------|-------------------|-------------------|-------------------|--------------------------------------------|------------------------------------------| -| `0x*0` | `0x00` Failure | `0x10` Disallowed or Stop | `0x20` Not Found, Unequal, or Out of Range | `0x30` Sender Disagrees or Nay | `0x40` Unavailable | `0x50` Transfer Failed | `0x60` [reserved] | `0x70` [reserved] | `0x80` [reserved] | `0x90` [reserved] | `0xA0` App-Specific Failure | `0xB0` [reserved] | `0xC0` [reserved] | `0xD0` [reserved] | `0xE0` Decrypt Failure | `0xF0` Off-Chain Failure | -| `0x*1` | `0x01` Success | `0x11` Allowed or Go | `0x21` Found, Equal or In Range | `0x31` Sender Agrees or Yea | `0x41` Available | `0x51` Transfer Successful | `0x61` [reserved] | `0x71` [reserved] | `0x81` [reserved] | `0x91` [reserved] | `0xA1` App-Specific Success | `0xB1` [reserved] | `0xC1` [reserved] | `0xD1` [reserved] | `0xE1` Decrypt Success | `0xF1` Off-Chain Success | -| `0x*2` | `0x02` Awaiting Others | `0x12` Awaiting Other's Permission | `0x22` Awaiting Match | `0x32` Awaiting Ratification | `0x42` Paused | `0x52` Awaiting Payment From Others | `0x62` [reserved] | `0x72` [reserved] | `0x82` [reserved] | `0x92` [reserved] | `0xA2` App-Specific Awaiting Others | `0xB2` [reserved] | `0xC2` [reserved] | `0xD2` [reserved] | `0xE2` Awaiting Other Signatures or Keys | `0xF2` Awaiting Off-Chain Process | -| `0x*3` | `0x03` Accepted | `0x13` Permission Requested | `0x23` Match Request Sent | `0x33` Offer Sent or Voted | `0x43` Queued | `0x53` Hold or Escrow | `0x63` [reserved] | `0x73` [reserved] | `0x83` [reserved] | `0x93` [reserved] | `0xA3` App-Specific Acceptance | `0xB3` [reserved] | `0xC3` [reserved] | `0xD3` [reserved] | `0xE3` Signed | `0xF3` Off-Chain Process Started | -| `0x*4` | `0x04` Lower Limit or Insufficient | `0x14` Too Open / Insecure | `0x24` Below Range or Underflow | `0x34` Quorum Not Reached | `0x44` Not Available Yet | `0x54` Insufficient Funds | `0x64` [reserved] | `0x74` [reserved] | `0x84` [reserved] | `0x94` [reserved] | `0xA4` App-Specific Below Condition | `0xB4` [reserved] | `0xC4` [reserved] | `0xD4` [reserved] | `0xE4` Unsigned or Untrusted | `0xF4` Off-Chain Service Unreachable | -| `0x*5` | `0x05` Receiver Action Required | `0x15` Needs Your Permission or Request for Continuation | `0x25` Request for Match | `0x35` Receiver's Ratification Requested | `0x45` Awaiting Your Availability | `0x55` Funds Requested | `0x65` [reserved] | `0x75` [reserved] | `0x85` [reserved] | `0x95` [reserved] | `0xA5` App-Specific Receiver Action Requested | `0xB5` [reserved] | `0xC5` [reserved] | `0xD5` [reserved] | `0xE5` Signature Required | `0xF5` Off-Chain Action Required | -| `0x*6` | `0x06` Upper Limit | `0x16` Revoked or Banned | `0x26` Above Range or Overflow | `0x36` Offer or Vote Limit Reached | `0x46` Expired | `0x56` Transfer Volume Exceeded | `0x66` [reserved] | `0x76` [reserved] | `0x86` [reserved] | `0x96` [reserved] | `0xA6` App-Specific Expiry or Limit | `0xB6` [reserved] | `0xC6` [reserved] | `0xD6` [reserved] | `0xE6` Known to be Compromised | `0xF6` Off-Chain Expiry or Limit Reached | -| `0x*7` | `0x07` [reserved] | `0x17` [reserved] | `0x27` [reserved] | `0x37` [reserved] | `0x47` [reserved] | `0x57` [reserved] | `0x67` [reserved] | `0x77` [reserved] | `0x87` [reserved] | `0x97` [reserved] | `0xA7` [reserved] | `0xB7` [reserved] | `0xC7` [reserved] | `0xD7` [reserved] | `0xE7` [reserved] | `0xF7` [reserved] | -| `0x*8` | `0x08` Duplicate, Unnecessary, or Inapplicable | `0x18` Not Applicable to Current State | `0x28` Duplicate, Conflict, or Collision | `0x38` Already Voted | `0x48` Already Done | `0x58` Funds Not Required | `0x68` [reserved] | `0x78` [reserved] | `0x88` [reserved] | `0x98` [reserved] | `0xA8` App-Specific Inapplicable Condition | `0xB8` [reserved] | `0xC8` [reserved] | `0xD8` [reserved] | `0xE8` Already Signed or Not Encrypted | `0xF8` Duplicate Off-Chain Request | -| `0x*9` | `0x09` [reserved] | `0x19` [reserved] | `0x29` [reserved] | `0x39` [reserved] | `0x49` [reserved] | `0x59` [reserved] | `0x69` [reserved] | `0x79` [reserved] | `0x89` [reserved] | `0x99` [reserved] | `0xA9` [reserved] | `0xB9` [reserved] | `0xC9` [reserved] | `0xD9` [reserved] | `0xE9` [reserved] | `0xF9` [reserved] | -| `0x*A` | `0x0A` [reserved] | `0x1A` [reserved] | `0x2A` [reserved] | `0x3A` [reserved] | `0x4A` [reserved] | `0x5A` [reserved] | `0x6A` [reserved] | `0x7A` [reserved] | `0x8A` [reserved] | `0x9A` [reserved] | `0xAA` [reserved] | `0xBA` [reserved] | `0xCA` [reserved] | `0xDA` [reserved] | `0xEA` [reserved] | `0xFA` [reserved] | -| `0x*B` | `0x0B` [reserved] | `0x1B` [reserved] | `0x2B` [reserved] | `0x3B` [reserved] | `0x4B` [reserved] | `0x5B` [reserved] | `0x6B` [reserved] | `0x7B` [reserved] | `0x8B` [reserved] | `0x9B` [reserved] | `0xAB` [reserved] | `0xBB` [reserved] | `0xCB` [reserved] | `0xDB` [reserved] | `0xEB` [reserved] | `0xFB` [reserved] | -| `0x*C` | `0x0C` [reserved] | `0x1C` [reserved] | `0x2C` [reserved] | `0x3C` [reserved] | `0x4C` [reserved] | `0x5C` [reserved] | `0x6C` [reserved] | `0x7C` [reserved] | `0x8C` [reserved] | `0x9C` [reserved] | `0xAC` [reserved] | `0xBC` [reserved] | `0xCC` [reserved] | `0xDC` [reserved] | `0xEC` [reserved] | `0xFC` [reserved] | -| `0x*D` | `0x0D` [reserved] | `0x1D` [reserved] | `0x2D` [reserved] | `0x3D` [reserved] | `0x4D` [reserved] | `0x5D` [reserved] | `0x6D` [reserved] | `0x7D` [reserved] | `0x8D` [reserved] | `0x9D` [reserved] | `0xAD` [reserved] | `0xBD` [reserved] | `0xCD` [reserved] | `0xDD` [reserved] | `0xED` [reserved] | `0xFD` [reserved] | -| `0x*E` | `0x0E` [reserved] | `0x1E` [reserved] | `0x2E` [reserved] | `0x3E` [reserved] | `0x4E` [reserved] | `0x5E` [reserved] | `0x6E` [reserved] | `0x7E` [reserved] | `0x8E` [reserved] | `0x9E` [reserved] | `0xAE` [reserved] | `0xBE` [reserved] | `0xCE` [reserved] | `0xDE` [reserved] | `0xEE` [reserved] | `0xFE` [reserved] | -| `0x*F` | `0x0F` Informational or Metadata | `0x1F` Permission Details or Control Conditions | `0x2F` Matching Meta or Info | `0x3F` Negotiation Rules or Participation Info | `0x4F` Availability Rules or Info (ex. time since or until) | `0x5F` Token or Financial Information | `0x6F` [reserved] | `0x7F` [reserved] | `0x8F` [reserved] | `0x9F` [reserved] | `0xAF` App-Specific Meta or Info | `0xBF` [reserved] | `0xCF` [reserved] | `0xDF` [reserved] | `0xEF` Cryptography, ID, or Proof Metadata | `0xFF` Off-Chain Info or Meta | - -### Example Function Change - -```solidity -uint256 private startTime; -mapping(address => uint) private counters; - -// Before -function increase() public returns (bool _available) { - if (now < startTime && counters[msg.sender] == 0) { - return false; - }; - - counters[msg.sender] += 1; - return true; -} - -// After -function increase() public returns (byte _status) { - if (now < start) { return hex"44"; } // Not yet available - if (counters[msg.sender] == 0) { return hex"10"; } // Not authorized - - counters[msg.sender] += 1; - return hex"01"; // Success -} -``` - -### Example Sequence Diagrams - -``` -0x03 = Waiting -0x31 = Other Party (ie: not you) Agreed -0x41 = Available -0x44 = Not Yet Available - - - Exchange - - -AwesomeCoin DEX TraderBot - + + + - | | buy(AwesomeCoin) | - | | <------------------------+ - | buy() | | - | <---------------------+ | - | | | - | Status [0x44] | | - +---------------------> | Status [0x44] | - | +------------------------> | - | | | - | | isDoneYet() | - | | <------------------------+ - | | | - | | Status [0x44] | - | +------------------------> | - | | | - | | | - | Status [0x41] | | - +---------------------> | | - | | | - | buy() | | - | <---------------------+ | - | | | - | | | - | Status [0x31] | | - +---------------------> | Status [0x31] | - | +------------------------> | - | | | - | | | - | | | - | | | - + + + -``` - - - -``` -0x01 = Generic Success -0x10 = Disallowed -0x11 = Allowed - - Token Validation - - - Buyer RegulatedToken TokenValidator IDChecker SpendLimiter - + + + + + - | buy() | | | | - +------------------------> | check() | | | - | +-----------------------> | check() | | - | | +-----------------------> | | - | | | | | - | | | Status [0x10] | | - | | Status [0x10] | <-----------------------+ | - | revert() | <-----------------------+ | | - | <------------------------+ | | | - | | | | | -+---------------------------+ | | | | -| | | | | | -| Updates ID with provider | | | | | -| | | | | | -+---------------------------+ | | | | - | | | | | - | buy() | | | | - +------------------------> | check() | | | - | +-----------------------> | check() | | - | | +-----------------------> | | - | | | | | - | | | Status [0x11] | | - | | | <-----------------------+ | - | | | | | - | | | | check() | - | | +-------------------------------------------> | - | | | | | - | | | | Status [0x11] | - | | Status [0x11] | <-------------------------------------------+ - | Status [0x01] | <-----------------------+ | | - | <------------------------+ | | | - | | | | | - | | | | | - | | | | | - + + + + + -``` - -## Rationale - -### Encoding - -Status codes are encoded as a `byte`. Hex values break nicely into high and low nibbles: `category` and `reason`. For instance, `0x01` stands for general success (ie: `true`) and `0x00` for general failure (ie: `false`). - -As a general approach, all even numbers are blocking conditions (where the receiver does not have control), and odd numbers are nonblocking (the receiver is free to contrinue as they wish). This aligns both a simple bit check with the common encoding of Booleans. - -`bytes1` is very lightweight, portable, easily interoperable with `uint8`, cast from `enum`s, and so on. - -#### Alternatives - -Alternate schemes include `bytes32` and `uint8`. While these work reasonably well, they have drawbacks. - -`uint8` feels even more similar to HTTP status codes, and enums don't require as much casting. However does not break as evenly as a square table (256 doesn't look as nice in base 10). - -Packing multiple codes into a single `bytes32` is nice in theory, but poses additional challenges. Unused space may be interpreted as `0x00 Failure`, you can only efficiently pack four codes at once, and there is a challenge in ensuring that code combinations are sensible. Forcing four codes into a packed representation encourages multiple status codes to be returned, which is often more information than strictly necessarily. This can lead to paradoxical results (ex `0x00` and `0x01` together), or greater resources allocated to interpreting 2564 (4.3 billion) permutations. - -### Multiple Returns - -While there may be cases where packing a byte array of status codes may make sense, the simplest, most forwards-compatible method of transmission is as the first value of a multiple return. - -Familiarity is also a motivating factor. A consistent position and encoding together follow the principle of least surprise. It is both viewable as a "header" in the HTTP analogy, or like the "tag" in BEAM tagged tuples. - -### Human Readable - -Developers should not be required to memorize 256 codes. However, they break nicely into a table. Cognitive load is lowered by organizing the table into categories and reasons. `0x10` and `0x11` belong to the same category, and `0x04` shares a reason with `0x24` - -While this repository includes helper enums, we have found working directly in the hex values to be quite natural. Status code `0x10` is just as comfortable as HTTP 401, for example. - -#### Localizations - -One commonly requested application of this spec is human-readable translations of codes. This has been moved to its own proposal: [ERC-1444](https://github.com/ethereum/EIPs/pull/1444/), primarily due to a desire to keep both specs focused. - -### Extensibility - -The `0xA` category is reserved for application-specific statuses. In the case that 256 codes become insufficient, `bytes1` may be embedded in larger byte arrays. - -### EVM Codes - -The EVM also returns a status code in transactions; specifically `0x00` and `0x01`. This proposal both matches the meanings of those two codes, and could later be used at the EVM level. - -### Empty Space - -Much like how HTTP status codes have large unused ranges, there are totally empty sections in this proposal. The intent is to not impose a complete set of codes up front, and to allow users to suggest uses for these spaces as time progresses. - -### Beyond Errors - -This spec is intended to be much more than a set of common errors. One design goal is to enable easier contract-to-contract communication, protocols built on top of status codes, and flows that cross off-chain. Many of these cases include either expected kinds of exception state (as opposed to true errors), neutral states, time logic, and various successes. - -Just like how HTTP 200 has a different meaning from HTTP 201, ERC-1066 status codes can relay information between contract beyond simply pass or fail. They can be thought of as the edges in a graph that has smart contracts as nodes. - -### Fully `revert`able - -_This spec is fully compatible with `revert`-with-reason and does not intend to supplant it in any way._ Both by reverting with a common code, the developer can determine what went wrong from a set of known error states. - -Further, by leveraging ERC-1066 and a translation table (such as in ERC-1444) in conjunction, developers and end users alike can receive fully automated human-readable error messages in the language and phrasing of their choice. - -### Nibble Order - -Nibble order makes no difference to the machine, and is purely mnemonic. This design was originally in opposite order, but changed it for a few convenience factors. Since it's a different scheme from HTTP, it may feel strange initially, but becomes very natural after a couple hours of use. - -#### Short Forms - -Generic is `0x0*`, general codes are consistent with their integer representations - -```solidity -hex"1" == hex"01" == 1 // with casting -``` - -#### Contract Categories - -Many applications will always be part of the same category. For instance, validation will generally be in the `0x10` range. - -```solidity -contract Whitelist { - mapping(address => bool) private whitelist; - uint256 private deadline; - byte constant private prefix = hex"10"; - - check(address _, address _user) returns (byte _status) { - if (now >= deadline) { return prefix | 5; } - if (whitelist[_user]) { return prefix | 1; } - return prefix; - } -} -``` - -#### Helpers - -This above also means that working with app-specific enums is slightly easier, and also saves gas (fewer operations required). - -```solidity -enum Sleep { - Awake, - Asleep, - BedOccupied, - WindingDown -} - -// From the helper library - -function appCode(Sleep _state) returns (byte code) { - return byte(160 + _state); // 160 = 0xA0 -} - -// Versus - -function appCode(Sleep _state) returns (byte code) { - return byte((16 * _state) + 10); // 10 = 0xA -} -``` - -## Implementation - -Reference cases and helper libraries (Solidity and JS) can be found at: -* [Source Code](https://github.com/fission-suite/fission-codes/) -* [Package on npm](https://www.npmjs.com/package/fission-codes/) - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1066.md diff --git a/EIPS/eip-107.md b/EIPS/eip-107.md index 67caa48d96d459..ca19256546f4e6 100644 --- a/EIPS/eip-107.md +++ b/EIPS/eip-107.md @@ -3,19 +3,19 @@ eip: 107 title: safe "eth_sendTransaction" authorization via html popup author: Ronan Sandford (@wighawag) created: 2016-06-05 -status: Draft +status: Stagnant type: Standards Track category: Interface --- -Abstract -======== +## Abstract + This draft EIP describes the details of an authorization method that if provided by rpc enabled ethereum nodes would allow regular websites to send transactions (via ```eth_sendTransaction```) without the need to enable CORS. Instead, user would be asked to confirm the transaction via an html popup. Every read only rpc call the dapp wants to perform is redirected to an invisible iframe from the node's domain and for every transaction that the dapp wish to execute, an html popup is presented to the user to allow him/her to cancel or confirm the transaction. This allows the dapp to connect to the node's rpc api without being granted any kind of privileges. This allows users to safely interact with dapps running in their everyday web browser while their accounts are unlocked. In case the account is not unlocked, and the node has allowed the "personal" api via rpc,the html page also allow the user to enter their password to unlock the account for the scope of the transaction. -Motivation -========== +## Motivation + Currently, if a user navigates to a dapp running on a website using her/his everyday browser, the dapp will by default have no access to the rpc api for security reasons. The user will have to enable CORS for the website's domain in order for the dapp to work. Unfortunately if the user does so, the dapp will be able to send transactions from any unlocked account without the need for any user consent. In other words, not only does the user need to change the node's default setting, but the user is also forced to trust the dapp in order to use it. This is of course not acceptable and forces existing dapps to rely on the use of workarounds like: - if the transaction is a plain ether transfer, the user is asked to enter it in a dedicated trusted wallet like "Mist" - For more complex case, the user is asked to enter the transaction manually via the node command line interface. @@ -25,27 +25,27 @@ This proposal aims to provide a safe and user friendly alternative. Here are some screenshots of the provided implementation of that html popup: -Account unlocked : ------------------ +### Account unlocked + When the account is already unlocked, the user is presented with the following popup for every transaction that the dapp attempts to make: ![](../assets/eip-107/authorization.png) -Account locked and no "personal" api exposed via rpc: ------------------ +### Account locked and no "personal" api exposed via rpc: + When the account is locked, and the node does not provide access to account unlocking via its rpc interface, the following popup will be presented. This is not ideal since this requires the user to know how to unlock an account: ![](../assets/eip-107/authorization-locked.png) -Account locked but node exposing the "personal" api via rpc : ------------------ +### Account locked but node exposing the "personal" api via rpc : + A better option is to ask the user for their password, but this is only possible if the node allows access to the "personal" api via rpc. In such case, the following dialog will be presented to the user so he/she can accept the transaction by providing the password required to unlock the account: ![](../assets/eip-107/authorization-password.png) -Specification -============= +## Specification + In order for the mechanism to work, the node needs to serve an html file via http at the url \/authorization.html This file will then be used by the dapp in 2 different modes (invisible iframe and popup window). @@ -60,10 +60,10 @@ In this popup window mode, the html file's javascript code will allow ```eth_sen The html page also checks for the availability of the "personal" api and if so, will ask the user to unlock the account if necessary. The unlocking is temporary (3s) so the password will be asked again if a transaction is attempted before the end of this short time. In both iframe mode and window mode, the communication with the dapp is achieved using ```window.postMessage```. -The fist message the iframe/window sends is a message containing the string "ready" to let the dapp know that it now accepts messages. Then the dapp can start performing rpc call by sending message using the following object : +The first message the iframe/window sends is a message containing the string "ready" to let the dapp know that it now accepts messages. Then the dapp can start performing rpc call by sending message using the following object : ``` { - id:, //so responses can be match as there is no guarantee of the order of the response + id:, //so responses can be match as there is no guarantee of the order of the response payload: //this is the exact object that usually send to the node } ``` @@ -90,22 +90,22 @@ the error object cannot be a javascript Error object due to postMessage limitati ``` -Rationale -========= +## Rationale + The design for that proposal was chosen for its simplicity and security. A previous idea was to use an oauth-like protocol in order for the user to accept or deny a transaction request. It would have required deeper code change in the node and some geth contributors argues that such change did not fit into geth code base as it would have required dapp aware code. -The current design, instead has a very simple implementation (self contained html file that can be shared across node's implementation) and its safeness is guarantess by browsers' cross domain policies. +The current design, instead has a very simple implementation (self contained html file that can be shared across node's implementation) and its safeness is guaranteed by browsers' cross domain policies. + +The use of iframe/ window was required to have both security and user friendliness. The invisible iframe allows the dapp to execute read only calls without the need for user input, and the window ensures user approval before making a call. While we could have made it without the window mode by making the iframe confirmation use the native browser ```window.confirm``` dialog, this would have prevented the use of a more elegant confirmation popup that the current design allows. It also happens to be that the ```window.confirm``` is not safe in some browsers, as it gives focus to the accept option and can be triggered automatically (https://bugs.chromium.org/p/chromium/issues/detail?id=260653). -The use of iframe/ window was required to have both security and user friendliness. The invisble iframe allows the dapp to execute read only calls without the need for user input, and the window ensures user approval before making a call. While we could have made it without the window mode by making the iframe confirmation use the native browser ```window.confirm``` dialog, this would have prevented the use of a more elegant confirmation popup that the current design allows. It also happens to be that the ```window.confirm``` is not safe in some browsers, as it gives focus to the accept option and can be triggered automatically (https://bugs.chromium.org/p/chromium/issues/detail?id=260653). +## Implementations -Implementations -=============== In order to implement this design, the following html file or an equivalent one needs to be served at the url \/authorization.html That's it. -``` +```html @@ -612,6 +612,7 @@ That's it. ``` + ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1077.md b/EIPS/eip-1077.md index bd509879b54735..470bf46b6f1727 100644 --- a/EIPS/eip-1077.md +++ b/EIPS/eip-1077.md @@ -1,212 +1,7 @@ --- eip: 1077 -title: Executable Signed Messages refunded by the contract -author: Alex Van de Sande , Ricardo Guilherme Schmidt (@3esmit) -discussions-to: https://ethereum-magicians.org/t/erc1077-and-1078-the-magic-of-executable-signed-messages-to-login-and-do-actions/351 -status: Draft -type: Standards Track category: ERC -created: 2018-05-04 -requires: 725, 191 +status: Moved --- -## Simple Summary - -Allowing users to sign messages to show intent of execution, but allowing a third party relayer to execute them is an emerging pattern being used in many projects. Standardizing a common format for them, as well as a way in which the user allows the transaction to be paid in tokens, gives app developers a lot of flexibility and can become the main way in which app users interact with the Blockchain. - -## Abstract - -User pain points: - -* users don't want to think about ether -* users don't want to think about backing up private keys or seed phrases -* users want to be able to pay for transactions using what they already have on the system, be apple pay, xbox points or even a credit card -* Users don’t want to sign a new transaction at every move -* Users don’t want to download apps/extensions (at least on the desktop) to connect to their apps - -App developer pain points: -* Many apps use their own token and would prefer to use those as the main accounting -* Apps want to be able to have apps in multiple platforms without having to share private keys between devices or have to spend transaction costs moving funds between them -* Token developers want to be able for their users to be able to move funds and pay fees in the token -* While the system provides fees and incentives for miners, there are no inherent business model for wallet developers (or other apps that initiate many transactions) - -Using signed messages, specially combined with an identity contract that holds funds, and multiple disposable ether-less keys that can sign on its behalf, solves many of these pain points. - -### Implementation - -The signed messages require the following fields: - -* To: the target contract the transaction will be executed upon -* From: the account that will be executed on behalf of -* Value: the amount in ether to be sent -* Data: the bytecode to be executed -* Nonce: a nonce *or* a timestamp -* GasToken: a token in which the gas will be paid (leave 0 for ether) -* Gasprice: the gas price (paid in the selected token) -* GasLimit: the maximum gas to be paid - -#### Signing the message - -In order to be compliant, the transaction **MUST** request to sign a messageHash that is a concatenation of multiple fields, plus one final field `extraData` that can be left blank but is added for forward compatibility. - -The fields **MUST** be concatenated in this order: - -``` -keccak256( - byte(0x19), - byte(0), - from, - to, - value, - dataHash, - nonce, - gasPrice, - gasLimit, - gasToken, - callPrefix, - operationType, - extraHash -); -``` - -The first and second fields are to make it [ERC191](https://eips.ethereum.org/EIPS/eip-191) compliant. Starting a transaction with byte(0x19) ensure the signed data from being a [valid ethereum transaction](https://github.com/ethereum/wiki/wiki/RLP). The second argument is a version control byte. - -The `from` field will always be the contract executing the code (`address(this)`), and the `callPrefix` is the 4 byte standard prefix of the function to be called in the `from` contract. This guarantees that a signed message can be only executed in a single instance. - -`operationType` type will define what sort of operation will be executed (in assembly): 0 for a standard `call`, 1 for a `DelegateCall` and 0 for a `create` opcode. These can be extended in the future. - -#### Backwards and forwards capability: - -Not all executable signed messages contracts will have the same requirements, therefore some fields are optional. Fields `byte(0x19)`, `byte(0)`, `from`, `to`, `value`, `dataHash` are **obligatory** while `nonce`, `gasPrice`, `gasLimit`, `gasToken`, `callPrefix`, `operationType` are optional, but must be hashed in this order. - -Regardless of which fields you use, in your contract you **must** accept an extraHash that is always hashed at the end. This is done to increase future compatibility of the standard: solidity's keccak treats `keccak(a, b, c, d, e, f)` as identical to `keccak(a, b, concat(c, d, e, f)`. therefore by adding an extra field in the end that can be ignored by your contract, you allow it to be compatible with the same standard as other message standards that use it to sign it. - - -#### Multiple signatures - -If multiple signatures are required, then all signed messageHashes should then be *ordered by account* and sent to the receiving contract which then will execute the following actions: - -#### keep track of nonces: - - -Nonces work similarly to normal ethereum transactions: a transaction can only be executed if it matches the last nonce + 1, and once a transaction has occurred, the `lastNonce` will be updated to the current one. This prevents transactions to be executed out of order or more than once. - -Contracts should accept transactions without nonce (nonce = 0). The contract then must keep the full hash of the transaction to prevent it from being replayed. This option allows contracts to have more flexibilities as you can sign a transaction that can be executed out of order or not at all, but it uses more memory for each transaction. It can be used, for instance, for transactions that the user wants to schedule in the future but cannot know its future nonce, or transactions that are made for state channel contracts that are not guaranteed to be executed or are only executed when there's some dispute. - -### execute transaction - -The contract must then verify the signatures of the accounts and check if the public keys match accounts that are authorized to do what they intend to do: depending on the contract implementation, some contracts might require multiple key signatures, other might have specific actions few accounts are authorized to do. - -If an identity, then, the contract should implement ERC725 identity management levels: a key must be at least an `action` key to have authorization to demand any call to external contracts, and a `management` key to demand calls to the contract itself. - -If the signing accounts are authorized to do so, the contract must execute the requested action. If the current contract is the same as `from` field, then if can simply execute the actions by calling `_to.call.value(_value)(_data)`. - -How the contract interprets the intended action depends on its purpose. For instance a token contract can decide to implement it in a way that interprets all actions as token transfers, and uses the `value` to mean token value and `bytecode` as the data to pass to the recipient contract - -### Gas accounting and refund - -The implementing contract must keep track of the gas spent. One way to do it is to first call `gasLeft()` at the beginning of the function and then after executing the desired action and compare the difference. - -The contract then will make a token transfer (or ether, if `tokenAddress` is nil) in the value of `gasSpent * gasPrice` to the `msg.sender`, that is the account that deployed the message. If there are not enough funds, or if the total surpasses `gasLimit` then the transaction MUST revert. - -If the executed transaction fails internally, nonces should still be updated and gas needs to be paid. - -Contracts are not obligated to support ether or any other token they don’t want and can be implemented to only accept refunds in a few tokens of their choice. - -**Deployers of transactions have no guarantees that the contract they are interacting with correctly implements the standard and they will be reimbursed for gas, so they should maintain their own white/blacklists of contracts to support, as well as keep track of which tokens and for which gasPrice they’re willing to deploy transactions.** - -### Supported functions - -` -executeSigned( - address to, - address from, - uint256 value, - bytes data, - uint nonce, - uint gasPrice, - uint gasLimit, - address gasToken, - operationType, - extraHash, - bytes messageSignatures) -` - -Executes the signed message. Execution usually means that a contract will execute a `call` to the `to` address, with `value` amount of ether and `data` as its data. But in some special cases, a token can decide instead to interpret it specifically as executing a `transferAndCall(to,from,data)` or the equivalent. - -More than one signed transaction with the same parameter can be executed by this function at the same time, by passing all signatures in the `messageSignatures` field. That field will split the signature in multiple 72 character individual signatures and evaluate each one. This is used for cases in which one action might require the approval of multiple parties, in a single transaction. - -` -gasEstimate( - address to, - address from, - uint256 value, - bytes data, - uint nonce, - uint gasPrice, - uint gasLimit, - address gasToken, - operationType, - extraHash - bytes messageSignatures) - returns ( - bool canExecute, - uint gasCost) -` -A read only function that checks if the transaction will be executable and how much gas it’s expected to cost. - -`lastNonce() public returns (uint nonce)` -`lastTimestamp() public returns (uint nonce)` - -Both are simple read only functions that return the last used Nonce and last used timestamp. - -`requiredSignatures(uint type) returns (uint)` - -A function which returns the amount of signatures that are required for a given type of action (types being 1 = Management and 2 = Action). - -`event ExecutedSigned(bytes32 signHash, uint nonce, bool success);` - -Whenever a new transaction is executed it **must** emit an event with the signHash, nonce and either the transaction was successfully executed or not. Apps that are waiting for a transaction to be executed should subscribe to the identity and watch this event to see if their transaction was successful. If a different signHash is executed with an equal or higher nonce, it means that your transaction has been replaced. - -## Implementation -One initial implementation of such a contract can be found at [the Identity Gas Relay at the Status repository](https://github.com/status-im/contracts/blob/73-economic-abstraction/contracts/identity/IdentityGasRelay.sol) - -## Similar implementations - -The idea of using signed messages as executable intent has been around for a while and many other projects are taking similar approaches, which makes it a great candidate for a standard that guarantees interoperability: - -* [EIP 877](https://github.com/ethereum/EIPs/pull/877) An attempt of doing the same but with a change in the protocol -* [Status](https://github.com/status-im/ideas/issues/73) -* [Aragon](https://github.com/aragonlabs/pay-protocol) (this might not be the best link to show their work in this area) -* [Token Standard Functions for Preauthorized Actions](https://github.com/ethereum/EIPs/issues/662) -* [Token Standard Extension 865](https://github.com/ethereum/EIPs/issues/865) -* [Iuri Matias: Transaction Relay](https://github.com/iurimatias/TransactionRelay) -* [uPort: Meta transactions](https://github.com/uport-project/uport-identity#send-a-meta-tx) -* [uPort: safe Identities](https://github.com/uport-project/uport-identity/blob/develop/docs/txRelay.md) -* [Gnosis safe contracts](https://github.com/gnosis/safe-contracts) - -Swarm city uses a similar proposition for etherless transactions, called [Gas Station Service](https://github.com/swarmcity/SCLabs-gasstation-service), but it's a different approach. Instead of using signed messages, a traditional ethereum transaction is signed on an etherless account, the transaction is then sent to a service that immediately sends the exact amount of ether required and then publishes the transaction. - - -## Areas for improvements - -This ERC inherits all it's permission systems from ERC720 Identity, which has very basic levels of authorization (can call contract itself, can make external calls, cannot make any calls) and a simple generic multisig. Ideally we need a more comprehensive standard for authorizations, that enables, for instance, that a single key can only make calls to a specific contract, or specific functions. Also, the amount of signatures required to do an action could be variable, maybe a single key could have a limit on how much value it can spend in a single day, requiring more signatures to move higher amounts (how to properly measure the value of a token or NFT transfer is another matter entirely). - -## Usage examples - -This scheme opens up a great deal of possibilities on interaction as well as different experiments on business models: - -* Apps can create individual identities contract for their users which holds the actual funds and then create a different private key for each device they log into. Other apps can use the same identity and just ask to add permissioned public keys to manage the device, so that if one individual key is lost, no ether is lost. -* An app can create its own token and only charge their users in its internal currency for any ethereum transaction. The currency units can be rounded so it looks more similar to to actual amount of transactions: a standard transaction always costs 1 token, a very complex transaction costs exactly 2, etc. Since the app is the issuer of the transactions, they can do their own Sybil verifications and give a free amount of currency units to new users to get them started. -* A game company creates games with a traditional monthly subscription, either by credit card or platform-specific microtransactions. Private keys never leave the device and keep no ether and only the public accounts are sent to the company. The game then signs transactions on the device with gas price 0, sends them to the game company which checks who is an active subscriber and batches all transactions and pays the ether themselves. If the company goes bankrupt, the gamers themselves can set up similar subscription systems or just increase the gas price. End result is a **ethereum based game in which gamers can play by spending apple, google or xbox credits**. -* A standard token is created that doesn’t require its users to have ether, and instead allows tokens to be transferred by paying in tokens. A wallet is created that signs messages and send them via whisper to the network, where other nodes can compete to download the available transactions, check the current gas price, and select those who are paying enough tokens to cover the cost. **The result is a token that the end users never need to keep any ether and can pay fees in the token itself.** -* A DAO is created with a list of accounts of their employees. Employees never need to own ether, instead they sign messages, send them to whisper to a decentralized list of relayers which then deploy the transactions. The DAO contract then checks if the transaction is valid and sends ether to the deployers. Employees have an incentive not to use too many of the companies resources because they’re identifiable. The result is that the users of the DAO don't need to keep ether, and **the contract ends up paying for it's own gas usage**. - -### References - -* [Universal Logins talk at UX Unconf, Toronto](https://www.youtube.com/watch?v=qF2lhJzngto) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1077.md diff --git a/EIPS/eip-1078.md b/EIPS/eip-1078.md index 990d446f833ced..12678b4b874462 100644 --- a/EIPS/eip-1078.md +++ b/EIPS/eip-1078.md @@ -1,121 +1,7 @@ --- eip: 1078 -title: Universal login / signup using ENS subdomains -author: Alex Van de Sande -discussions-to: https://ethereum-magicians.org/t/erc1077-and-1078-the-magic-of-executable-signed-messages-to-login-and-do-actions/351 -status: Draft -type: Standards Track category: ERC -created: 2018-05-04 -requires: 1077, 725, 681, 191 +status: Moved --- -## Abstract - -This presents a method to replace the usual signup/login design pattern with a minimal ethereum native scheme, that doesn’t require passwords, backing up private keys nor typing seed phrases. From the user point of view it will be very similar to patterns they’re already used to with second factor authentication (without relying in a central server), but for dapp developers it requires a new way to think about ethereum transactions. - - -## Simple Summary - -The unique identifier of the user is a contract which implements both Identity and the Executable Signed Messages ERCs. The user should not need provide this address directly, only a ens name pointing to it. These types of contracts are indirectly controlled by private keys that can sign messages indicating intents, which are then deployed to the contract by a third party (or a decentralized network of deployers). - -In this context, therefore, a device "logging into" an app using an identity, means that the device will generate a private key locally and then request an authorization to add that key as one of the signers of that identity, with a given set of permissions. Since that private key is only used for signing messages, it is not required to hold ether, tokens or assets, and if lost, it can be simply be replaced by a new one – the user's funds are kept on the identity contract. - -In this context, ethereum accounts are used in a manner more similar to auth tokens, rather than unique keys. - -The login process is as follows: - -#### 1) Request a name from the user - -The first step of the process is to request from the user the ENS name that points to their identity. If the user doesn’t have a login set up, the app should–if they have an integrated identity manager–provide an option to provide a subdomain or a name they own. - -**UX Note:** there are many ways to provide this interface, the app can ask if they want to signup/login before hand or simply directly ask them to type the name. Note that since it’s trivial to verify if a username exists, your app should adapt to it gracefully and not require the user to type their name twice. If they ask to signup and provide a name that exists then ask them if they want to login using that name, or similarly if they ask to connect to an existing name but type a non-existent name show them a nice alert and ask them if they want to create that name now. Don’t force them to type the same name twice in two different fields. - -#### 2.a) Create a new identity - -If the user doesn’t have an identity, the app should provide the option to create one for them. Each app must have one or more domains they control which they can create immediate subdomains on demand. The app therefore will make these actions on the background: - -1. Generate a private key which it will keep saved locally on the device or browser, the safest way possible. -2. Create (or set up) an identity contract which supports both ERC720 and ERC1077 -3. Register the private key created on step 1 as the *only* admin key of the contract (the app must not add any app-controlled key, except as recovery option - see 5) -4. Register the requested subdomain and transfer its ownership to the contract (while the app controls the main domain and may keep the option to reassign them at will, the ownership of the subdomain itself should belong to the identity, therefore allowing them to transfer it) -5. (Optionally) Register a recovery method on the contract, which allows the user to regain access to the contract in case the main key is lost. - -All those steps can be designed to be set up in a single ethereum transaction. Since this step is not free, the app reserves the right to charge for registering users, or require the user to be verified in a sybil resistant manner of the app’s choosing (captcha, device ID registration, proof of work, etc) - -The user shouldn’t be forced to wait for transaction confirmation times. Instead, have an indicator somewhere on the app the shows the progress and then allow the user to interact with your app normally. It’s unlikely that they’ll need the identity in the first few minutes and if something goes wrong (username gets registered at the same time), you can then ask the user for an action. - -**Implementation note:** in order to save gas, some of these steps can be done in advance. The app can automatically deploy a small number of contracts when the gas price is low, and set up all their main variables to be 0xFFFFFF...FFFFF. These should be considered ‘vacant’ and when the user registers one, they will get a gas discount for freeing up space on the chain. This has the added benefit of allowing the user a choice in contract address/icon. - -#### 2.b) Connect to an existing identity - -If the user wants to connect with an existing identity, then the first thing the app needs to understand is what level of privilege it’s going to ask for: - -**Manager** the higher level, allows the key to initiate or sign transactions that change the identity itself, like adding or removing keys. An app should only require this level if it integrates an identity manager. Depending on how the identity is set up, it might require signature from more keys before these transactions can be deployed. - -**Action** this level allows the key to initiate or sign transactions on address other than itself. It can move funds, ether, assets etc. An app should only require this level of privilege if it’s a general purpose wallet or browser for sending ethereum transactions. Depending on how the identity is set up, it might require signature from more keys before these transactions can be deployed. - -**Encryption** the lower level has no right to initiate any transactions, but it can be used to represent the user in specific instances or off-chain signed messages. It’s the ideal level of privilege for games, chat or social media apps, as they can be used to sign moves, send messages, etc. If a game requires actual funds (say, to start a game with funds in stake) then it should still use the encryption level, and then require the main wallet/browser of the user to sign messages using the ethereum URI standard. - -Once the desired level is known, the app must take these steps: - -1. **Generate a private key** which it will keep saved locally on the device or browser, the safest way possible. -2. **Query ens** to figure the existing address of the identity -3. **Generate the bytecode** for a transaction calling the function `addKey(PUBLICKEY,LEVEL)`. -4. **Broadcast a transaction request on a whisper channel** or some other decentralized network of peers. Details on this step require further discussions -1. **If web3 is available** then attempt calling web3.eth.sendTransaction. This can be automatic or prompted by user action. -1. **Attempt calling a URI** if the app supports [URL format for transaction requests EIP](https://eips.ethereum.org/EIPS/eip-681) then attempt calling this. This can be automatic or prompted by user action. -1. **Show a QR code**: with an EIP681 formatted URL. That QR code can be clickable to attempt to retry the other options, but it should be done last: if step 1 works, the user should receive a notification on their compatible device and won't need to use the QR code. - -Here's an example of a EIP681 compatible address to add a public key generated locally in the app: - -`ethereum:bob.example.eth?function=addKey(address='0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',uint=1)` - -If adding the new key requires multiple signatures, or if the app receiving that request exclusiveky deals with executable signed messages and has no ether on itself, then it should follow the steps in the next section on how to request transactions. - -As before, the user shouldn’t be forced to wait for transaction confirmation times. Instead, have an indicator somewhere on the app the shows the progress and then allow the user to interact with your app normally. - - - -#### 3) Request transactions - -After step 2, the end result should be that your app should have the identity address of the user, their main ens name and a private key, whose public account is listed on the identity as one of their keys, with roles being either manager, action or encryption. Now it can start using that information to sign and execute transactions. - -**Not all transactions need to be on chain**, actually most common uses of signed messages should be off chain. If you have a chat app, for instance, you can use the local key for signing messages and sending it to the other parties, and they can just query the identity contract to see if that key actually comes from the user. If you have a game with funds at stake, only the first transaction moving funds and setting up the initial game needs to be executed by the identity: at each turn the players can sign a hash of the current state of the board and at the end, the last two plays can be used to determine the winner. Notice that keys can be revoked at any time, so your app should take that in consideration, for instance saving all keys at the start of the game. Keys that only need this lower level of privilege, should be set at level 4 (encryption). - -Once you decided you actually need an on-chain transaction, follow these steps: - -1. **Figure out the TO, FROM, VALUE and DATA**. These are the basics of any ethereum transaction. `from` is the compatible contract you want the transaction to be deployed from. -2. **Check the privilege level you need:** if the `to` and `from` fields are the same contract, ie, if the transaction requires the identity to act upon itself (for instance, when adding or removing a key) then you need level 1 (management), otherwise it's 2 (action). Verify if the key your app owns correspond to the required level. -3. **Verify how many keys are required** by calling `requiredSignatures(uint level)` on the target contract -4. **Figure out gasLimit**: Estimate the gas cost of the desired transaction, and add a margin (recommended: add 100k gas) -5. **Figure out gasToken and gasPrice**: Check the current gas price considering network congestions and the market price of the token the user is going to pay with. Leave gasToken as 0 for ether. Leave gasPrice as 0 if you are deploying it yourself and subsidizing the costs elsewhere. -6. **Sign an executable signed transaction** by following that standard. - -After having all the signed executable message, we need to deploy it to the chain. If the transaction only requires a single signature, then the app provider can deploy it themselves. Send the transaction to the `from` address and attempt to call the function `executeSigned`, using the parameters and signature you just collected. - -If the transaction need to collect more signatures or the app doesn't have a deployable server, the app should follow these steps: - -1. **Broadcast the transaction on a whisper channel** or some other decentralized network of peers. Details on this step require further discussions -2. **If web3 is available** then attempt calling web3.eth.personal_sign. This can be automatic or prompted by user action. -3. **Show a QR code**: with the signed transaction and the new data to be signed. That QR code can be clickable to attempt to retry the other options, but it should be done last: if step 1 works, the user should receive a notification on their compatible device and won't need to use the QR code. - -The goal is to keep broadcasting signatures via whisper until a node that is willing to deploy them is able to collect all messages. - -Once you've followed the above steps, watch the transaction pool to any transaction to that address and then take the user to your app. Once you seen the desired transaction, you can stop showing the QRcode and proceed with the app, while keeping some indication that the transaction is in progress. Subscribe to the event `ExecutedSigned` of the desired contract: once you see the transaction with the nonce, you can call it a success. If you see a different transaction with the same or higher nonce (or timestamp) then you consider the transaction permanently failed and restart the process. - - -### Implementation - -No working examples of this implementation exists, but many developers have expressed interest in adopting it. This section will be edited in the future to reflect that. - -### Conclusion and future improvements - -This scheme would allow much more lighter apps, that don't require to hold ether, and can keep unlocked private keys on the device to be able to send messages and play games without requesting user prompt every time. More work is needed to standardize common decentralized messaging protocols as well as open source tools for deployment nodes, in order to create a decentralized and reliable layer for message deployment. - -### References - -* [Universal Logins talk at UX Unconf, Toronto](https://www.youtube.com/watch?v=qF2lhJzngto) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1078.md diff --git a/EIPS/eip-1080.md b/EIPS/eip-1080.md index 18277e8fcba4a4..bc247bd4034492 100644 --- a/EIPS/eip-1080.md +++ b/EIPS/eip-1080.md @@ -1,185 +1,7 @@ --- eip: 1080 -title: Recoverable Token -author: Bradley Leatherwood -discussions-to: https://ethereum-magicians.org/t/erc-1080-recoverabletoken-standard/364 -status: Draft -type: Standards Track category: ERC -created: 2018-05-02 +status: Moved --- -## Simple Summary - -A standard interface for tokens that support chargebacks, theft prevention, and lost & found resolutions. - -## Abstract - -The following standard allows for the implementation of a standard API for tokens extending ERC-20 or ERC-791. This standard provides basic functionality to recover stolen or lost accounts, as well as provide for the chargeback of tokens. - -## Motivation - -To mitigate the effects of reasonably provable token or asset loss or theft and to help resolve other conflicts. Ethereum's protocol should not be modified because of loss, theft, or conflicts, but it is possible to solve these problems in the protocol layer. - -## Specification - -## RecoverableToken - -### Methods - -#### claimLost - -Reports the `lostAccount` address as being lost. MUST trigger the `AccountClaimedLost` event. - -After the time configured in `getLostAccountRecoveryTimeInMinutes` the implementer MUST provide a mechanism for determining the correct owner of the tokens held and moving the tokens to a new account. - -Account recoveries must trigger the `AccountRecovered` event. - -``` js -function claimLost(address lostAccount) returns (bool success) -``` - -#### cancelLostClaim - -Reports the `msg.sender`'s account as being not being lost. MUST trigger the `AccountClaimedLostCanceled` event. - -MUST fail if an account recovery process has already begun. - -Otherwise, this method MUST stop a dispute from being started to recover funds. - -``` js -function claimLost() returns (bool success) -``` - -#### reportStolen - -Reports the current address as being stolen. MUST trigger the `AccountFrozen` event. -Successful calls MUST result in the `msg.sender`'s tokens being frozen. - -The implementer MUST provide a mechanism for determining the correct owner of the tokens held and moving the tokens to a new account. - -Account recoveries must trigger the `AccountRecovered` event. - -``` js -function reportStolen() returns (bool success) -``` - -#### chargeback - -Requests a reversal of transfer on behalf of `msg.sender`. - -The implementer MUST provide a mechanism for determining the correct owner of the tokens disputed and moving the tokens to the correct account. - -MUST comply with sender's chargeback window as value configured by `setPendingTransferTimeInMinutes`. - -``` js -function chargeback(uint256 pendingTransferNumber) returns (bool success) -``` - -#### getPendingTransferTimeInMinutes - -Get the time an account has to chargeback a transfer. - -``` js -function getPendingTransferTime(address account) view returns (uint256 minutes) -``` - -#### setPendingTransferTimeInMinutes - -Sets the time `msg.sender`'s account has to chargeback a transfer. - -MUST NOT change the time if the account has any pending transfers. - -``` js -function setPendingTransferTime(uint256 minutes) returns (bool success) -``` - -#### getLostAccountRecoveryTimeInMinutes - -Get the time account has to wait before a lost account dispute can start. - -``` js -function getLostAccountRecoveryTimeInMinutes(address account) view returns (uint256 minutes) -``` - -#### setLostAccountRecoveryTimeInMinutes - -Sets the time `msg.sender`'s account has to sit before a lost account dispute can start. - -MUST NOT change the time if the account has open disputes. - -``` js -function setLostAccountRecoveryTimeInMinutes(uint256 minutes) returns (bool success) -``` - -### Events - -#### AccountRecovered - -The recovery of an account that was lost or stolen. - -``` js -event AccountClaimedLost(address indexed account, address indexed newAccount) -``` - -#### AccountClaimedLostCanceled - -An account claimed as being lost. - -``` js -event AccountClaimedLost(address indexed account) -``` - -#### AccountClaimedLost - -An account claimed as being lost. - -``` js -event AccountClaimedLost(address indexed account) -``` - -#### PendingTransfer - -A record of a transfer pending. - -``` js -event PendingTransfer(address indexed from, address indexed to, uint256 value, uint256 pendingTransferNumber) -``` - -#### ChargebackRequested - -A record of a chargeback being requested. - -``` js -event ChargebackRequested(address indexed from, address indexed to, uint256 value, uint256 pendingTransferNumber) -``` - -#### Chargeback - -A record of a transfer being reversed. - -``` js -event Chargeback(address indexed from, address indexed to, uint256 value, uint256 indexed pendingTransferNumber) -``` - -#### AccountFrozen - -A record of an account being frozen. MUST trigger when an account is frozen. - -``` js -event AccountFrozen(address indexed reported) -``` - -## Rationale - -* A recoverable token standard can provide configurable safety for users or contracts who desire this safety. -* Implementations of this standard will give users the ability to select a dispute resolution process on an opt-in basis and benefit the community by decreasing the necessity of consideration of token recovery actions. - - -## Implementation - - -Pending. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1080.md diff --git a/EIPS/eip-1081.md b/EIPS/eip-1081.md index 835ecac7edefd2..4c333bdccbb2f3 100644 --- a/EIPS/eip-1081.md +++ b/EIPS/eip-1081.md @@ -1,126 +1,7 @@ --- eip: 1081 -title: Standard Bounties -author: Mark Beylin , Kevin Owocki , Ricardo Guilherme Schmidt (@3esmit) -discussions-to: https://gitter.im/bounties-network/Lobby -status: Draft -type: Standards Track category: ERC -created: 2018-05-14 -requires: 20 +status: Moved --- - -## Simple Summary - -A standard contract and interface for issuing bounties on Ethereum, usable for any type of task, paying in any ERC20 token or in ETH. -## Abstract - -In order to encourage cross-platform interoperability of bounties on Ethereum, and for easier reputational tracking, StandardBounties can facilitate the administration of funds in exchange for deliverables corresponding to a completed task, in a publicly auditable and immutable fashion. - -## Motivation -In the absence of a standard for bounties on Ethereum, it would be difficult for platforms to collaborate and share the bounties which users create (thereby recreating the walled gardens which currently exist on Web2.0 task outsourcing platforms). A standardization of these interactions across task types also makes it far easier to track various reputational metrics (such as how frequently you pay for completed submissions, or how frequently your work gets accepted). - -## Specification -After studying bounties as they've existed for thousands of years (and after implementing and processing over 300 of them on main-net in beta), we've discovered that there are 3 core steps to every bounty: -- a bounty is **issued**: an `issuer` specifies the requirements for the task, describing the desired outcome, and how much they would be willing to pay for the completion of that task (denoted in one or several tokens). -- a bounty is **fulfilled**: a bounty `fulfiller` may see the bounty, complete the task, and produce a deliverable which is itself the desired outcome of the task, or simply a record that it was completed. Hashes of these deliverables should be stored immutably on-chain, to serve as proof after the fact. -- a fulfillment is **accepted**: a bounty `issuer` or `arbiter` may select one or more submissions to be accepted, thereby releasing payment to the bounty fulfiller(s), and transferring ownership over the given deliverable to the `issuer`. - -To implement these steps, a number of functions are needed: -- `initializeBounty(address _issuer, address _arbiter, string _data, uint _deadline)`: This is used when deploying a new StandardBounty contract, and is particularly useful when applying the proxy design pattern, whereby bounties cannot be initialized in their constructors. Here, the data string should represent an IPFS hash, corresponding to a JSON object which conforms to the schema (described below). -- `fulfillBounty(address[] _fulfillers, uint[] _numerators, uint _denomenator, string _data)`: This is called to submit a fulfillment, submitting a string representing an IPFS hash which contains the deliverable for the bounty. Initially fulfillments could only be submitted by one individual at a time, however users consistently told us they desired to be able to collaborate on fulfillments, thereby allowing the credit for submissions to be shared by several parties. The lines along which eventual payouts are split are determined by the fractions of the submission credited to each fulfiller (using the array of numerators and single denominator). Here, a bounty platform may also include themselves as a collaborator to collect a small fee for matching the bounty with fulfillers. -- `acceptFulfillment(uint _fulfillmentId, StandardToken[] _payoutTokens, uint[] _tokenAmounts)`: This is called by the `issuer` or the `arbiter` to pay out a given fulfillment, using an array of tokens, and an array of amounts of each token to be split among the contributors. This allows for the bounty payout amount to move as it needs to based on incoming contributions (which may be transferred directly to the contract address). It also allows for the easy splitting of a given bounty's balance among several fulfillments, if the need should arise. - - `drainBounty(StandardToken[] _payoutTokens)`: This may be called by the `issuer` to drain a bounty of it's funds, if the need should arise. -- `changeBounty(address _issuer, address _arbiter, string _data, uint _deadline)`: This may be called by the `issuer` to change the `issuer`, `arbiter`, `data`, and `deadline` fields of their bounty. -- `changeIssuer(address _issuer)`: This may be called by the `issuer` to change to a new `issuer` if need be -- `changeArbiter(address _arbiter)`: This may be called by the `issuer` to change to a new `arbiter` if need be -- `changeData(string _data)`: This may be called by the `issuer` to change just the `data` -- `changeDeadline(uint _deadline)`: This may be called by the `issuer` to change just the `deadline` - -Optional Functions: -- `acceptAndFulfill(address[] _fulfillers, uint[] _numerators, uint _denomenator, string _data, StandardToken[] _payoutTokens, uint[] _tokenAmounts)`: During the course of the development of this standard, we discovered the desire for fulfillers to avoid paying gas fees on their own, entrusting the bounty's `issuer` to make the submission for them, and at the same time accept it. This is useful since it still immutably stores the exchange of tokens for completed work, but avoids the need for new bounty fulfillers to have any ETH to pay for gas costs in advance of their earnings. -- `changeMasterCopy(StandardBounty _masterCopy)`: For `issuer`s to be able to change the masterCopy which their proxy contract relies on, if the proxy design pattern is being employed. -- `refundableContribute(uint[] _amounts, StandardToken[] _tokens)`: While non-refundable contributions may be sent to a bounty simply by transferring those tokens to the address where it resides, one may also desire to contribute to a bounty with the option to refund their contribution, should the bounty never receive a correct submission which is paid out. -`refundContribution(uint _contributionId)`: If a bounty hasn't yet paid out to any correct submissions and is past it's deadline, those individuals who employed the `refundableContribute` function may retrieve their funds from the contract. - -**Schemas** -Persona Schema: -``` -{ - name: // optional - A string representing the name of the persona - email: // optional - A string representing the preferred contact email of the persona - githubUsername: // optional - A string representing the github username of the persona - address: // required - A string web3 address of the persona -} -``` -Bounty issuance `data` Schema: -``` -{ - payload: { - title: // A string representing the title of the bounty - description: // A string representing the description of the bounty, including all requirements - issuer: { - // persona for the issuer of the bounty - }, - funders:[ - // array of personas of those who funded the issue. - ], - categories: // an array of strings, representing the categories of tasks which are being requested - tags: // an array of tags, representing various attributes of the bounty - created: // the timestamp in seconds when the bounty was created - tokenSymbol: // the symbol for the token which the bounty pays out - tokenAddress: // the address for the token which the bounty pays out (0x0 if ETH) - - // ------- add optional fields here ------- - sourceFileName: // A string representing the name of the file - sourceFileHash: // The IPFS hash of the file associated with the bounty - sourceDirectoryHash: // The IPFS hash of the directory which can be used to access the file - webReferenceURL: // The link to a relevant web reference (ie github issue) - }, - meta: { - platform: // a string representing the original posting platform (ie 'gitcoin') - schemaVersion: // a string representing the version number (ie '0.1') - schemaName: // a string representing the name of the schema (ie 'standardSchema' or 'gitcoinSchema') - } -} -``` -Bounty `fulfillment` data Schema: - -``` -{ - payload: { - description: // A string representing the description of the fulfillment, and any necessary links to works - sourceFileName: // A string representing the name of the file being submitted - sourceFileHash: // A string representing the IPFS hash of the file being submitted - sourceDirectoryHash: // A string representing the IPFS hash of the directory which holds the file being submitted - fulfillers: { - // personas for the individuals whose work is being submitted - } - - // ------- add optional fields here ------- - }, - meta: { - platform: // a string representing the original posting platform (ie 'gitcoin') - schemaVersion: // a string representing the version number (ie '0.1') - schemaName: // a string representing the name of the schema (ie 'standardSchema' or 'gitcoinSchema') - } -} -``` -## Rationale - -The development of this standard began a year ago, with the goal of encouraging interoperability among bounty implementations on Ethereum. The initial version had significantly more restrictions: a bounty's `data` could not be changed after issuance (it seemed unfair for bounty `issuer`s to change the requirements after work is underway), and the bounty payout could not be changed (all funds needed to be deposited in the bounty contract before it could accept submissions). - -The initial version was also far less extensible, and only allowed for fixed payments to a given set of fulfillments. This new version makes it possible for funds to be split among several correct submissions, for submissions to be shared among several contributors, and for payouts to not only be in a single token as before, but in as many tokens as the `issuer` of the bounty desires. These design decisions were made after the 8+ months which Gitcoin, the Bounties Network, and Status Open Bounty have been live and meaningfully facilitating bounties for repositories in the Web3.0 ecosystem. - -## Test Cases - -Tests for our implementation can be found here: https://github.com/Bounties-Network/StandardBounties/tree/develop/test - -## Implementation - -A reference implementation can be found here: https://github.com/Bounties-Network/StandardBounties/blob/develop/contracts/StandardBounty.sol -**Although this code has been tested, it has not yet been audited or bug-bountied, so we cannot make any assertions about it's correctness, nor can we presently encourage it's use to hold funds on the Ethereum mainnet.** - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1081.md diff --git a/EIPS/eip-1087.md b/EIPS/eip-1087.md index a79a0451f29565..5df422325d5d5c 100644 --- a/EIPS/eip-1087.md +++ b/EIPS/eip-1087.md @@ -3,17 +3,17 @@ eip: 1087 title: Net gas metering for SSTORE operations author: Nick Johnson (@arachnid) discussions-to: https://ethereum-magicians.org/t/eip-net-storage-gas-metering-for-the-evm/383 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-05-17 --- ## Abstract -This EIP proposes a change to how gas is charged for EVM SSTORE operations, in order to reduce excessive gas costs in situations where these are unwarranted, and to enable new use-cases for contract storage. +This EIP proposes a change to how gas is charged for EVM `SSTORE` operations, in order to reduce excessive gas costs in situations where these are unwarranted, and to enable new use-cases for contract storage. ## Motivation -Presently, SSTORE operations are charged as follows: +Presently, `SSTORE` (`0x55`) operations are charged as follows: - 20,000 gas to set a slot from 0 to non-0 - 5,000 gas for any other change @@ -50,7 +50,7 @@ After these changes, transactions that make only a single change to a storage sl ## Rationale We believe the proposed mechanism represents the simplest way to reduce storage gas costs in situations where they do not reflect the actual costs borne by nodes. Several alternative designs were considered and dismissed: - - Charging a flat 200 gas for SSTORE operations, and an additional 19800 / 4800 at the end of a transaction for new or modified values is simpler, and removes the need for a dirty map, but pushes a significant source of gas consumption out of the EVM stack and applies it at the end of the transaction, which is likely to complicate debugging and reduces contracts' ability to limit the gas consumption of callees, as well as introducing a new mechanism to the EVM. + - Charging a flat 200 gas for `SSTORE` operations, and an additional 19800 / 4800 at the end of a transaction for new or modified values is simpler, and removes the need for a dirty map, but pushes a significant source of gas consumption out of the EVM stack and applies it at the end of the transaction, which is likely to complicate debugging and reduces contracts' ability to limit the gas consumption of callees, as well as introducing a new mechanism to the EVM. - Keeping a separate refund counter for storage gas refunds would avoid the issue of refunds being limited to half the gas consumed (not necessary here), but would introduce additional complexity in tracking this value. - Refunding gas each time a storage slot is set back to its initial value would introduce a new mechanism (instant refunds) and complicate gas accounting for contracts calling other contracts; it would also permit the possibility of a contract call with negative execution cost. @@ -78,4 +78,4 @@ No contract should see an increase in gas cost for this change, and many will se TBD ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1102.md b/EIPS/eip-1102.md index e5eaa74f283667..6e7e743c164f0a 100644 --- a/EIPS/eip-1102.md +++ b/EIPS/eip-1102.md @@ -1,23 +1,24 @@ --- eip: 1102 title: Opt-in account exposure -author: Paul Bouchon +author: Paul Bouchon , Erik Marks (@rekmarks) discussions-to: https://ethereum-magicians.org/t/eip-1102-opt-in-provider-access/414 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2018-05-04 +requires: 1474 --- ## Simple summary -This proposal describes a way for DOM environments to expose user accounts in a way that requires user approval. +This proposal describes a communication protocol between dapps and Ethereum-enabled DOM environments that allows the Ethereum-enabled DOM environment to choose what information to supply the dapp with and when. ## Abstract The previous generation of Ethereum-enabled DOM environments follows a pattern of injecting a provider populated with accounts without user consent. This puts users of such environments at risk because malicious websites can use these accounts to view detailed account information and to arbitrarily initiate unwanted transactions on a user's behalf. -This proposal outlines a protocol in which Ethereum-enabled DOM environments expose no accounts until the user approves account access. +This proposal outlines a protocol in which Ethereum-enabled DOM environments can choose to expose no accounts until the user approves account access. ## Specification @@ -29,19 +30,19 @@ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "S #### `eth_requestAccounts` -Providers exposed by Ethereum-enabled DOM environments define a new RPC method: `eth_requestAccounts`. Calling this method triggers a user interface that allows the user to approve or reject account access for a given dapp. This method returns a `Promise` that is resolved with an `Array` of accounts if the user approves access or rejected with an `Error` if the user rejects access. +Providers exposed by Ethereum-enabled DOM environments define a new RPC method: `eth_requestAccounts`. Calling this method may trigger a user interface that allows the user to approve or reject account access for a given dapp. This method returns a `Promise` that is resolved with an `Array` of accounts or is rejected with an `Error` if accounts are not available. -```js -ethereum.send('eth_requestAccounts'): Promise +```typescript +ethereum.send('eth_requestAccounts'): Promise> ``` #### Provider#enable (DEPRECATED) -**Note: This method is deprecated in favor of the RPC method [`eth_requestAccounts`](#eth_requestAccounts).** +**Note: This method is deprecated in favor of the RPC method [`eth_requestAccounts`](#eth_requestaccounts).** Providers exposed by Ethereum-enabled DOM environments define a new RPC method: `ethereum.enable()`. Calling this method triggers a user interface that allows the user to approve or reject account access for a given dapp. This method returns a `Promise` that is resolved with an `Array` of accounts if the user approves access or rejected with an `Error` if the user rejects access. -```js +```typescript ethereum.enable(): Promise ``` @@ -75,15 +76,15 @@ IF provider is undefined ##### `[1] REQUEST` -Dapps **MUST** request account access by calling the `eth_requestAccounts` RPC method on the provider exposed at `window.ethereum`. Calling this method **MUST** trigger a user interface that allows the user to approve or reject account access for a given dapp. This method **MUST** return a `Promise` that is resolved with an array of user accounts if the user approves account access or rejected if the user rejects account access. +Dapps **MUST** request accounts by calling the `eth_requestAccounts` RPC method on the provider exposed at `window.ethereum`. Calling this method **MAY** trigger a user interface that allows the user to approve or reject account access for a given dapp. This method **MUST** return a `Promise` that is resolved with an array of one or more user accounts or rejected if no accounts are available (e.g., the user rejected account access). ##### `[2] RESOLVE` -If a user approves account access, DOM environments **MUST** populate the provider exposed at `window.ethereum` with an `Array` of user accounts. The `Promise` returned when calling the `eth_requestAccounts` RPC method **MUST** be resolved with an `Array` of user accounts. +The `Promise` returned when calling the `eth_requestAccounts` RPC method **MUST** be resolved with an `Array` of user accounts. ##### `[3] REJECT` -If a user rejects account access, the `Promise` returned when calling the `eth_requestAccounts` RPC method **MUST** be rejected with an informative `Error`. +The `Promise` returned when calling the `eth_requestAccounts` RPC method **MUST** be rejected with an informative `Error` if no accounts are available for any reason. ### Example initialization @@ -100,20 +101,17 @@ try { ### Constraints -* Browsers **MUST** expose a provider at `window.ethereum`. -* Browsers **MUST NOT** populate the provider with user accounts by default. +* Browsers **MUST** expose a provider at `window.ethereum` . * Browsers **MUST** define an `eth_requestAccounts` RPC method. -* Browsers **MUST** show an account access approval UI when `eth_requestAccounts` is called. -* Browsers **MUST** populate the provider with accounts if account access is approved. -* Browsers **MUST** resolve the `Promise` returned by `eth_requestAccounts` if account access is approved. -* Browsers **MUST NOT** populate the provider with accounts if account access is rejected. -* Browsers **MUST** reject the `Promise` returned by `eth_requestAccounts` with an `Error` if account access is rejected. +* Browsers **MAY** wait for a user interaction before resolving/rejecting the `eth_requestAccounts` promise. +* Browsers **MUST** include at least one account if the `eth_requestAccounts` promise is resolved. +* Browsers **MUST** reject the promise with an informative error if no accounts are available. ## Rationale The pattern of automatic account exposure followed by the previous generation of Ethereum-enabled DOM environments fails to protect user privacy and fails to maintain safe user experience: untrusted websites can both view detailed account information and arbitrarily initiate transactions on a user's behalf. Even though most users may reject unsolicited transactions on untrusted websites, a protocol for account access should make such unsolicited requests impossible. -This proposal establishes a new pattern wherein dapps must request access to user accounts. This protocol directly strengthens user privacy by hiding user accounts and preventing unsolicited transaction requests on untrusted sites. +This proposal establishes a new pattern wherein dapps must request access to user accounts. This protocol directly strengthens user privacy by allowing the browser to hide user accounts and preventing unsolicited transaction requests on untrusted sites. ### Immediate value-add @@ -137,4 +135,4 @@ The MetaMask team [has implemented](https://github.com/MetaMask/metamask-extensi ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1108.md b/EIPS/eip-1108.md index e67cd8a8f286c6..1b8b4818f0f8bf 100644 --- a/EIPS/eip-1108.md +++ b/EIPS/eip-1108.md @@ -3,7 +3,7 @@ eip: 1108 title: Reduce alt_bn128 precompile gas costs author: Antonio Salazar Cardozo (@shadowfiend), Zachary Williamson (@zac-williamson) discussions-to: https://ethereum-magicians.org/t/eip-1108-reduce-alt-bn128-precompile-gas-costs/3206 -status: Draft +status: Final type: Standards Track category: Core created: 2018-05-21 @@ -73,9 +73,9 @@ components because of the structure of the algorithm. Thus using a 'fair' price of 25.86 gas per microsecond, we get a gas formula of ~`35,000 * k + 45,000` gas, where `k` is the number of pairings being computed. [4] -[1]- Per [EIP-196](https://github.com/ethereum/EIPs/blob/984cf5de90bbf5fbe7e49be227b0c2f9567e661e/EIPS/eip-196.md#gas-costs). +[1]- Per [EIP-196](./eip-196.md). -[2]- Per [EIP-197](https://github.com/ethereum/EIPs/blob/df132cd37efb3986f9cd3ef4922b15a767d2c54a/EIPS/eip-197.md#specification). +[2]- Per [EIP-197](./eip-197.md). [3]- [Parity benchmarks.](https://gist.github.com/zac-williamson/838410a3da179d47d31b25b586c15e53) @@ -87,12 +87,70 @@ Thus using a 'fair' price of 25.86 gas per microsecond, we get a gas formula of Fast elliptic curve cryptography is a keystone of a growing number of protocols built on top of Ethereum. To list a few: -* [The AZTEC protocol](https://github.com/AztecProtocol/AZTEC) utilizes the elliptic curve precompiles to construct private tokens, with zero-knowledge transaction logic, via the [ERC1723](https://github.com/ethereum/EIPs/issues/1723) and [ERC1724](https://github.com/ethereum/EIPs/issues/1724) standard. +* [The AZTEC protocol](https://github.com/AztecProtocol/AZTEC) utilizes the elliptic curve precompiles to construct private tokens, with zero-knowledge transaction logic, via the [ERC-1723](https://github.com/ethereum/EIPs/issues/1723) and [ERC-1724](https://github.com/ethereum/EIPs/issues/1724) standard. * [Matter Labs](https://github.com/matter-labs/matter-network) utilizes the precompiles to implement Ignis, a scaling solution with a throughput of 500txns per second * [Rollup](https://github.com/rollup/rollup) utilizes the precompiles to create L2 scaling solutions, where the correctness of transactions is guaranteed by main-net, without an additional consensus layer -* [ZEther](https://crypto.stanford.edu/~buenz/papers/zether.pdf) uses precompiles `ECADD` and `ECMUL` to construct confidential transactions - -These are all technologies that have been, or are in the process of being, deployed to main-net. There protocols would all benefit from reducing the gas cost of the precompiles. +* ZEther[^1] uses precompiles `ECADD` and `ECMUL` to construct confidential transactions + +[^1]: + ```csl-json + { + "publisher-place": "Cham", + "URL": "https://eprint.iacr.org/2019/191.pdf", + "custom": { + "additional-urls": [ + "https://web.archive.org/web/20220819003610/https://crypto.stanford.edu/~buenz/papers/zether.pdf" + ] + }, + "DOI": "10.1007/978-3-030-51280-4_23", + "abstract": "Smart contract platforms such as Ethereum and Libra provide ways to seamlessly remove trust and add transparency to various distributed applications. Yet, these platforms lack mechanisms to guarantee user privacy, even at the level of simple payments, which are essential for most smart contracts.", + "author": [ + { + "given": "Benedikt", + "family": "Bünz" + }, + { + "given": "Shashank", + "family": "Agrawal" + }, + { + "given": "Mahdi", + "family": "Zamani" + }, + { + "given": "Dan", + "family": "Boneh" + } + ], + "container-title": "Financial Cryptography and Data Security", + "editor": [ + { + "given": "Joseph", + "family": "Bonneau" + }, + { + "given": "Nadia", + "family": "Heninger" + } + ], + "type": "paper-conference", + "id": "10.1007/978-3-030-51280-4_23", + "citation-key": "10.1007/978-3-030-51280-4_23", + "ISBN": "978-3-030-51280-4", + "issued": { + "date-parts": [ + [ + 2020 + ] + ] + }, + "page": "423-443", + "publisher": "Springer International Publishing", + "title": "Zether: Towards Privacy in a Smart Contract World" + } + ``` + +These are all technologies that have been, or are in the process of being, deployed to main-net. These protocols would all benefit from reducing the gas cost of the precompiles. To give a concrete example, it currently costs `820,000` gas to validate the cryptography in a typical AZTEC confidential transaction. If the gas schedule for the precompiles correctly reflected their load on the Ethereum network, this cost would be `197,000` gas. This significantly increases the potential use cases for private assets on Ethereum. AZTEC is planning to deploy several cryptographic protocols Ethereum, but these are at the limits of what is practical given the current precompile costs: @@ -115,7 +173,7 @@ If zk-SNARK verification costs are decreased, these solutions can be deployed fo ### Parity and Geth already have fast algorithms that justify reduced gas costs -This EIP does not require Parity or Geth to deploy new cryptographic libraries, as fast bn128 algorithms have already been integrated into these clients. This goal of proposing this EIP for Istanbul, is to supplement [EIP-1829](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1829.md) (arithmetic over generic elliptic curves), providing an immediate solution to the pressing problem of expensive cryptography, while more advanced solutions are developed, defined and deployed. +This EIP does not require Parity or Geth to deploy new cryptographic libraries, as fast bn128 algorithms have already been integrated into these clients. This goal of proposing this EIP for Istanbul, is to supplement [EIP-1829](./eip-1829.md) (arithmetic over generic elliptic curves), providing an immediate solution to the pressing problem of expensive cryptography, while more advanced solutions are developed, defined and deployed. ## Test Cases @@ -131,6 +189,9 @@ Both the Parity and Geth clients have already implemented cryptographic librarie * [MCL, a portable C++ pairing library](https://github.com/herumi/mcl) * [Libff, a C++ pairing library used in many zk-SNARK libraries](https://github.com/scipr-lab/libff) +## Additional References + +@vbuterin independently proposed a similar reduction after this EIP was originally created, with similar rationale, as [ethereum/EIPs#1187](https://github.com/ethereum/EIPs/issues/1187). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1109.md b/EIPS/eip-1109.md index 647796a77479f7..2e9cd53070da4f 100644 --- a/EIPS/eip-1109.md +++ b/EIPS/eip-1109.md @@ -3,7 +3,7 @@ eip: 1109 title: PRECOMPILEDCALL opcode (Remove CALL costs for precompiled contracts) author: Jordi Baylina (@jbaylina) discussions-to: https://ethereum-magicians.org/t/eip-1109-remove-call-costs-for-precompiled-contracts/447 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-05-22 @@ -11,7 +11,7 @@ created: 2018-05-22 ## Simple Summary -This EIP creates a specific OPCODE named "PRECOMPILEDCALL" to call Precompiled contracts without the costs of a normal CALL. +This EIP creates a specific opcode named `PRECOMPILEDCALL` to call Precompiled contracts without the costs of a normal `CALL`. ## Abstract @@ -21,13 +21,13 @@ This EIP tries to resolve the problem of high gas consumption when calling preco Each precompiled contract has an already defined cost for calling it. It does not make sense to add the implicit extra gas cost of the CALL opcode. -As an example, SHA256 precompiled contract costs 60 and ECADD costs 500 (proposed to costs only 50 in [EIP1108](https://github.com/ethereum/EIPs/pull/1108) . When a precompiled contract is called, 700 gas is consumed just for the CALL opcode besides the costs of the precompiled contract. +As an example, SHA256 precompiled contract costs 60 and ECADD costs 500 (proposed to costs only 50 in [EIP-1108](./eip-1108.md) . When a precompiled contract is called, 700 gas is consumed just for the CALL opcode besides the costs of the precompiled contract. This makes no sense, and right now it's impossible to define a precompiled contract whose effective cost for using it, is less than 700. ## Specification -If `block.number >= XXXXX`, define a new opcode named PRECOMPILEDCALL with code value 0xfb . +If `block.number >= XXXXX`, define a new opcode named `PRECOMPILEDCALL` with code value `0xfb`. The gas cost of the OPCODE is 2 (Gbase) plus the Specific gas cost defined for each specific precompiled smart contract. @@ -47,26 +47,26 @@ The return will be 1 in case of success call and 0 in any of the next cases: 1.- mu_s[0] is an address of an undefined precompiled smart contract. 2.- The precompiled smart contract fails (as defined on each smart contract). Invalid input parameters for example. -Precompiled smart contracs, does not execute opcodes, so there is no need to pass a gas parameter as a normal CALL. If the available gas is less that 2 plus the required gas required for the specific precompiled smart cotract, the context just STOPS executing with an "Out of Gas" error. +Precompiled smart contracts, does not execute opcodes, so there is no need to pass a gas parameter as a normal `CALL` (`0xf1`). If the available gas is less that 2 plus the required gas required for the specific precompiled smart contract, the context just STOPS executing with an "Out of Gas" error. There is no stack check for this call. -The normal CALLs to the precompiled smart contracts continue to work with the exact same behavior. +The normal `CALL`s to the precompiled smart contracts continue to work with the exact same behavior. -A PRECOMPILEDCALL to a regular address or regular smart contract, is considered a call to an "undefined smart contract", so the VM MUST not execute it and the opcode must return 0x0 . +A `PRECOMPILEDCALL` to a regular address or regular smart contract, is considered a call to an "undefined smart contract", so the VM MUST not execute it and the opcode must return 0x0 . ## Rationale -There was a first proposal for removing the gast consts for the CALL, but it looks that it's easier to implement and test a new opcode just for that. +There was a first proposal for removing the gast consts for the `CALL`, but it looks that it's easier to implement and test a new opcode just for that. -The code is just the next opcode available after the STATICCALL opcode. +The code is just the next opcode available after the `STATICCALL` opcode. ## Backwards Compatibility This EIP is backwards compatible. Smart contracts that call precompiled contracts using this new opcode will cost less from now on. -Old contracts that call precompiled smart contracts with the CALL method, will continue working. +Old contracts that call precompiled smart contracts with the `CALL` method, will continue working. ## Test Cases @@ -84,4 +84,4 @@ Old contracts that call precompiled smart contracts with the CALL method, will c Not implemented yet. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1123.md b/EIPS/eip-1123.md index aa0cf3170c52a4..41eb06e8f8005f 100644 --- a/EIPS/eip-1123.md +++ b/EIPS/eip-1123.md @@ -1,1889 +1,7 @@ --- eip: 1123 -title: Revised Ethereum Smart Contract Packaging Standard -author: g. nicholas d’andrea (@gnidan), Piper Merriam (@pipermerriam), Nick Gheorghita (@njgheorghita), Danny Ryan (@djrtwo) -discussions-to: https://github.com/ethereum/EIPs/issues/1123 -status: Draft -type: Standards Track category: ERC -created: 2018-06-01 -replaces: 190 +status: Moved --- - -Simple Summary -============== - -A data format describing a smart contract software package. - - -Abstract -========== - -This EIP defines a data format for *package manifest* documents, -representing a package of one or more smart contracts, optionally -including source code and any/all deployed instances across multiple -networks. Package manifests are minified JSON objects, to be distributed -via content addressable storage networks, such as IPFS. - -This document presents a natural language description of a formal -specification for version **2** of this format. - - -Motivation -========== - -This standard aims to encourage the Ethereum development ecosystem -towards software best practices around code reuse. By defining an open, -community-driven package data format standard, this effort seeks to -provide support for package management tools development by offering a -general-purpose solution that has been designed with observed common -practices in mind. - -As version 2 of this specification, this standard seeks to address a -number of areas of improvement found for the previous version (defined -in -[EIP-190](https://eips.ethereum.org/EIPS/eip-190)). -This version: - -- Generalizes storage URIs to represent any content addressable URI - scheme, not only IPFS. - -- Renames *release lockfile* to *package manifest*. - -- Adds support for languages other than Solidity by generalizing the - compiler information format. - -- Redefines link references to be more flexible, to represent - arbitrary gaps in bytecode (besides only addresses), in a more - straightforward way. - -- Forces format strictness, requiring that package manifests contain - no extraneous whitespace, and sort object keys in alphabetical - order, to prevent hash mismatches. - - -
- -Specification -============= - -This document defines the specification for an EthPM package manifest. A -package manifest provides metadata about a [Package](#term-package), and -in most cases should provide sufficient information about the packaged -contracts and its dependencies to do bytecode verification of its -contracts. - -> **Note** -> -> A [hosted -> version](https://ethpm.github.io/ethpm-spec) of this -> specification is available via GitHub Pages. This EIP and the hosted -> HTML document were both autogenerated from the same documentation -> source. - - -Guiding Principles ------------------- - -This specification makes the following assumptions about the document -lifecycle. - -1. Package manifests are intended to be generated programmatically by - package management software as part of the release process. - -2. Package manifests will be consumed by package managers during tasks - like installing package dependencies or building and deploying new - releases. - -3. Package manifests will typically **not** be stored alongside the - source, but rather by package registries *or* referenced by package - registries and stored in something akin to IPFS. - - -Conventions ------------ - - -### RFC2119 - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, -“SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this -document are to be interpreted as described in RFC 2119. - -- - - -### Prefixed vs Unprefixed - -A [prefixed](#term-prefixed) hexadecimal value begins with `0x`. -[Unprefixed](#term-unprefixed) values have no prefix. Unless otherwise -specified, all hexadecimal values **should** be represented with the -`0x` prefix. - - ---- - - - - - - - - - - -

Prefixed

0xdeadbeef

Unprefixed

deadbeef

- - -Document Format ---------------- - -The canonical format is a single JSON object. Packages **must** conform -to the following serialization rules. - -- The document **must** be tightly packed, meaning no linebreaks or - extra whitespace. - -- The keys in all objects must be sorted alphabetically. - -- Duplicate keys in the same object are invalid. - -- The document **must** use - [UTF-8](https://en.wikipedia.org/wiki/UTF-8) - encoding. - -- The document **must** not have a trailing newline. - - -Document Specification ----------------------- - -The following fields are defined for the package. Custom fields **may** -be included. Custom fields **should** be prefixed with `x-` to prevent -name collisions with future versions of the specification. - - ---- - - - - - - - - - - -

See Also

Formalized (JSON-Schema) version of this specification: package.spec.json

Jump To

Definitions

- - -
- -### EthPM Manifest Version: `manifest_version` - -The `manifest_version` field defines the specification version that this -document conforms to. Packages **must** include this field. - - ---- - - - - - - - - - - - - - - - - - - -

Required

Yes

Key

manifest_version

Type

String

Allowed Values

2

- - -
- -### Package Name: `package_name` - -The `package_name` field defines a human readable name for this package. -Packages **must** include this field. Package names **must** begin with -a lowercase letter and be comprised of only lowercase letters, numeric -characters, and the dash character `-`. Package names **must** not -exceed 214 characters in length. - - ---- - - - - - - - - - - - - - - - - - - -

Required

Yes

Key

package_name

Type

String

Format

must match the regular expression ^[a-zA-Z][a-zA-Z0-9_]{0,255}$

- - -### Package Meta: `meta` - -The `meta` field defines a location for metadata about the package which -is not integral in nature for package installation, but may be important -or convenient to have on-hand for other reasons. This field **should** -be included in all Packages. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

meta

Type

Package Meta Object

- - -### Version: `version` - -The `version` field declares the version number of this release. This -value **must** be included in all Packages. This value **should** -conform to the [semver](https://semver.org/) version -numbering specification. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Key

version

Type

String

- - -### Sources: `sources` - -The `sources` field defines a source tree that **should** comprise the -full source tree necessary to recompile the contracts contained in this -release. Sources are declared in a key/value mapping. - - ---- - - - - - - - - - - - - - - -

Key

sources

Type

Object (String: String)

Format

See Below.

- - -#### Format - -Keys **must** be relative filesystem paths beginning with a `./`. - -Paths **must** resolve to a path that is within the current working -directory. - -Values **must** conform to *one of* the following formats. - -- Source string. - -- [Content Addressable URI](#term-content-addressable-uri). - -When the value is a source string the key should be interpreted as a -file path. - -- If the resulting document is a directory the key should be - interpreted as a directory path. - -- If the resulting document is a file the key should be interpreted as - a file path. - - -### Contract Types: `contract_types` - -The `contract_types` field holds the [Contract -Types](#term-contract-type) which have been included in this release. -[Packages](#term-package) **should** only include contract types that -can be found in the source files for this package. Packages **should -not** include contract types from dependencies. Packages **should not** -include abstract contracts in the contract types section of a release. - - ---- - - - - - - - - - - - - - - -

Key

contract_types

Type

Object (String: Contract Type Object)

Format

Keys must be valid Contract Aliases.

-

Values must conform to the Contract Type Object definition.

- - -### Deployments: `deployments` - -The `deployments` field holds the information for the chains on which -this release has [Contract Instances](#term-contract-instance) as well -as the [Contract Types](#term-contract-type) and other deployment -details for those deployed contract instances. The set of chains defined -by the `*BIP122 URI <#bip122-uris>*` keys for this object **must** be -unique. - - ---- - - - - - - - - - - - - - - -

Key

deployments

Type

Object (String: Object(String: Contract Instance Object))

Format

See Below.

- - -#### Format - -Keys **must** be a valid BIP122 URI chain definition. - -Values **must** be objects which conform to the following format. - -- Keys **must** be valid [Contract Instance - Names](#term-contract-instance-name). - -- Values **must** be a valid [Contract Instance - Object](#contract-instance-object). - - -### Build Dependencies: `build_dependencies` - -The `build_dependencies` field defines a key/value mapping of Ethereum -[Packages](#term-package) that this project depends on. - - ---- - - - - - - - - - - - - - - - - - - -

Required

No

Key

build_dependencies

Type

Object (String: String)

Format

Keys must be valid package names matching the regular expression [a-z][-a-z0-9]{0,213}.

-

Values must be valid IPFS URIs which resolve to a valid package.

- - -Definitions ------------ - -Definitions for different objects used within the Package. All objects -allow custom fields to be included. Custom fields **should** be prefixed -with `x-` to prevent name collisions with future versions of the -specification. - - - - -### The *Link Reference* Object - -A [Link Reference](#term-link-reference) object has the following -key/value pairs. All link references are assumed to be associated with -some corresponding [Bytecode](#term-bytecode). - - -#### Offsets: `offsets` - -The `offsets` field is an array of integers, corresponding to each of -the start positions where the link reference appears in the bytecode. -Locations are 0-indexed from the beginning of the bytes representation -of the corresponding bytecode. This field is invalid if it references a -position that is beyond the end of the bytecode. - - ---- - - - - - - - - - - -

Required

Yes

Type

Array

- - -#### Length: `length` - -The `length` field is an integer which defines the length in bytes of -the link reference. This field is invalid if the end of the defined link -reference exceeds the end of the bytecode. - - ---- - - - - - - - - - - -

Required

Yes

Type

Integer

- - -#### Name: `name` - -The `name` field is a string which **must** be a valid -[Identifier](#term-identifier). Any link references which **should** be -linked with the same link value **should** be given the same name. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

String

Format

must conform to the Identifier format.

- - - - -### The *Link Value* Object - -Describes a single [Link Value](#term-link-value). - -A **Link Value object** is defined to have the following key/value -pairs. - - -
- -#### Offsets: `offsets` - -The `offsets` field defines the locations within the corresponding -bytecode where the `value` for this link value was written. These -locations are 0-indexed from the beginning of the bytes representation -of the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

Integer

Format

See Below.

- -**Format** - -Array of integers, where each integer **must** conform to all of the -following. - -- greater than or equal to zero - -- strictly less than the length of the unprefixed hexadecimal - representation of the corresponding bytecode. - - -#### Type: `type` - -The `type` field defines the `value` type for determining what is -encoded when [linking](#term-linking) the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Allowed Values

"literal" for bytecode literals

-

"reference" for named references to a particular Contract Instance

- - -#### Value: `value` - -The `value` field defines the value which should be written when -[linking](#term-linking) the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

Determined based on type, see below.

- -**Format** - -For static value *literals* (e.g. address), value **must** be a *byte -string* - -To reference the address of a [Contract -Instance](#term-contract-instance) from the current package the value -should be the name of that contract instance. - -- This value **must** be a valid contract instance name. - -- The chain definition under which the contract instance that this - link value belongs to must contain this value within its keys. - -- This value **may not** reference the same contract instance that - this link value belongs to. - -To reference a contract instance from a [Package](#term-package) from -somewhere within the dependency tree the value is constructed as -follows. - -- Let `[p1, p2, .. pn]` define a path down the dependency tree. - -- Each of `p1, p2, pn` **must** be valid package names. - -- `p1` **must** be present in keys of the `build_dependencies` for the - current package. - -- For every `pn` where `n > 1`, `pn` **must** be present in the keys - of the `build_dependencies` of the package for `pn-1`. - -- The value is represented by the string - `::<...>::` where all of ``, - ``, `` are valid package names and `` is - a valid [Contract Name](#term-contract-name). - -- The `` value **must** be a valid [Contract - Instance Name](#term-contract-instance-name). - -- Within the package of the dependency defined by ``, all of the - following must be satisfiable: - - - There **must** be *exactly* one chain defined under the - `deployments` key which matches the chain definition that this - link value is nested under. - - - The `` value **must** be present in the keys - of the matching chain. - - -### The *Bytecode* Object - -A bytecode object has the following key/value pairs. - - -#### Bytecode: `bytecode` - -The `bytecode` field is a string containing the `0x` prefixed -hexadecimal representation of the bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

0x prefixed hexadecimal.

- - -#### Link References: `link_references` - -The `link_references` field defines the locations in the corresponding -bytecode which require [linking](#term-linking). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Array

Format

All values must be valid Link Reference objects. See also below.

- -**Format** - -This field is considered invalid if *any* of the [Link -References](#term-link-reference) are invalid when applied to the -corresponding `bytecode` field, *or* if any of the link references -intersect. - -Intersection is defined as two link references which overlap. - - -#### Link Dependencies: `link_dependencies` - -The `link_dependencies` defines the [Link Values](#term-link-value) that -have been used to link the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Array

Format

All values must be valid Link Value objects. See also below.

- -**Format** - -Validation of this field includes the following: - -- Two link value objects **must not** contain any of the same values - for `offsets`. - -- Each [link value object](#link-value-object) **must** have a - corresponding [link reference object](#link-reference-object) under - the `link_references` field. - -- The length of the resolved `value` **must** be equal to the `length` - of the corresponding [Link Reference](#term-link-reference). - - -
- -### The *Package Meta* Object - -The *Package Meta* object is defined to have the following key/value -pairs. - - -#### Authors: `authors` - -The `authors` field defines a list of human readable names for the -authors of this package. Packages **may** include this field. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

authors

Type

Array (String)

- - -#### License: `license` - -The `license` field declares the license under which this package is -released. This value **should** conform to the -[SPDX](https://en.wikipedia.org/wiki/Software_Package_Data_Exchange) -format. Packages **should** include this field. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

license

Type

String

- - -#### Description: `description` - -The `description` field provides additional detail that may be relevant -for the package. Packages **may** include this field. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

description

Type

String

- - -#### Keywords: `keywords` - -The `keywords` field provides relevant keywords related to this package. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

keywords

Type

List of Strings

- - -#### Links: `links` - -The `links` field provides URIs to relevant resources associated with -this package. When possible, authors **should** use the following keys -for the following common resources. - -- `website`: Primary website for the package. - -- `documentation`: Package Documentation - -- `repository`: Location of the project source code. - - ---- - - - - - - - - - - -

Key

links

Type

Object (String: String)

- - -
- -### The *Contract Type* Object - -A *Contract Type* object is defined to have the following key/value -pairs. - - -#### Contract Name: `contract_name` - -The `contract_name` field defines the [Contract -Name](#term-contract-name) for this [Contract -Type](#term-contract-type). - - ---- - - - - - - - - - - - - - - -

Required

If the Contract Name and Contract Alias are not the same.

Type

String

Format

must be a valid Contract Name.

- - -#### Deployment Bytecode: `deployment_bytecode` - -The `deployment_bytecode` field defines the bytecode for this [Contract -Type](#term-contract-type). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Bytecode Object format.

- - -#### Runtime Bytecode: `runtime_bytecode` - -The `runtime_bytecode` field defines the unlinked `0x`-prefixed runtime -portion of [Bytecode](#term-bytecode) for this [Contract -Type](#term-contract-type). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Bytecode Object format.

- - -#### ABI: `abi` - - ---- - - - - - - - - - - - - - - -

Required

No

Type

List

Format

must conform to the Ethereum Contract ABI JSON format.

- - -#### Natspec: `natspec` - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

The union of the UserDoc and DevDoc formats.

- - -#### Compiler: `compiler` - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Compiler Information object format.

- - -
- -### The *Contract Instance* Object - -A **Contract Instance Object** represents a single deployed [Contract -Instance](#term-contract-instance) and is defined to have the following -key/value pairs. - - -#### Contract Type: `contract_type` - -The `contract_type` field defines the [Contract -Type](#term-contract-type) for this [Contract -Instance](#term-contract-instance). This can reference any of the -contract types included in this [Package](#term-package) *or* any of the -contract types found in any of the package dependencies from the -`build_dependencies` section of the [Package -Manifest](#term-package-manifest). - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

See Below.

- -**Format** - -Values for this field **must** conform to *one of* the two formats -herein. - -To reference a contract type from this Package, use the format -``. - -- The `` value **must** be a valid [Contract - Alias](#term-contract-alias). - -- The value **must** be present in the keys of the `contract_types` - section of this Package. - -To reference a contract type from a dependency, use the format -`:`. - -- The `` value **must** be present in the keys of the - `build_dependencies` of this Package. - -- The `` value **must** be be a valid [Contract - Alias](#term-contract-alias). - -- The resolved package for `` must contain the - `` value in the keys of the `contract_types` - section. - - -
- -#### Address: `address` - -The `address` field defines the [Address](#term-address) of the -[Contract Instance](#term-contract-instance). - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

Hex encoded 0x prefixed Ethereum address matching the regular expression 0x[0-9a-fA-F]{40}.

- - -#### Transaction: `transaction` - -The `transaction` field defines the transaction hash in which this -[Contract Instance](#term-contract-instance) was created. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

String

Format

0x prefixed hex encoded transaction hash.

- - -#### Block: `block` - -The `block` field defines the block hash in which this the transaction -which created this *contract instance* was mined. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

String

Format

0x prefixed hex encoded block hash.

- - -
- -#### Runtime Bytecode: `runtime_bytecode` - -The `runtime_bytecode` field defines the runtime portion of bytecode for -this [Contract Instance](#term-contract-instance). When present, the -value from this field supersedes the `runtime_bytecode` from the -[Contract Type](#term-contract-type) for this [Contract -Instance](#term-contract-instance). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Bytecode Object format.

- -Every entry in the `link_references` for this bytecode **must** have a -corresponding entry in the `link_dependencies` section. - - -
- -#### Compiler: `compiler` - -The `compiler` field defines the compiler information that was used -during compilation of this [Contract Instance](#term-contract-instance). -This field **should** be present in all [Contract -Types](#term-contract-type) which include `bytecode` or -`runtime_bytecode`. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Compiler Information Object format.

- - -
- -### The *Compiler Information* Object - -The `compiler` field defines the compiler information that was used -during compilation of this [Contract Instance](#term-contract-instance). -This field **should** be present in all contract instances that locally -declare `runtime_bytecode`. - -A *Compiler Information* object is defined to have the following -key/value pairs. - - -#### Name `name` - -The `name` field defines which compiler was used in compilation. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Key

name

Type

String

- - -
- -#### Version: `version` - -The `version` field defines the version of the compiler. The field -**should** be OS agnostic (OS not included in the string) and take the -form of either the stable version in -[semver](https://semver.org/) format or if built on a -nightly should be denoted in the form of `-` ex: -`0.4.8-commit.60cc1668`. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Key

version

Type

String

- - -#### Settings: `settings` - -The `settings` field defines any settings or configuration that was used -in compilation. For the `"solc"` compiler, this **should** conform to -the [Compiler Input and Output -Description](https://solidity.readthedocs.io/en/latest/using-the-compiler.html#compiler-input-and-output-json-description). - - ---- - - - - - - - - - - - - - - -

Required

No

Key

settings

Type

Object

- - -### BIP122 URIs - -BIP122 URIs are used to define a blockchain via a subset of the -[BIP-122](https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki) -spec. - - blockchain:///block/ - -The `` represents the blockhash of the first block on the -chain, and `` represents the hash of the -latest block that’s been reliably confirmed (package managers should be -free to choose their desired level of confirmations). - - -Rationale -========= - -The following use cases were considered during the creation of this -specification. - - ---- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

owned

A package which contains contracts which are not meant to be used by themselves but rather as base contracts to provide functionality to other contracts through inheritance.

transferable

A package which has a single dependency.

standard-token

A package which contains a reusable contract.

safe-math-lib

A package which contains deployed instance of one of the package contracts.

piper-coin

A package which contains a deployed instance of a reusable contract from a dependency.

escrow

A package which contains a deployed instance of a local contract which is linked against a deployed instance of a local library.

wallet

A package with a deployed instance of a local contract which is linked against a deployed instance of a library from a dependency.

wallet-with-send

A package with a deployed instance which links against a deep dependency.

- -Each use case builds incrementally on the previous one. - -A full listing of [Use -Cases](https://ethpm.github.io/ethpm-spec/use-cases.html) -can be found on the hosted version of this specification. - - -Glossary -========== - - -
- -ABI ---- - -The JSON representation of the application binary interface. See the -official -[specification](https://solidity.readthedocs.io/en/develop/abi-spec.html) -for more information. - - -
- -Address -------- - -A public identifier for an account on a particular chain - - -
- -Bytecode --------- - -The set of EVM instructions as produced by a compiler. Unless otherwise -specified this should be assumed to be hexadecimal encoded, representing -a whole number of bytes, and [prefixed](#term-prefixed) with `0x`. - -Bytecode can either be linked or unlinked. (see -[Linking](#term-linking)) - - ---- - - - - - - - - - - -

Unlinked Bytecode

The hexadecimal representation of a contract’s EVM instructions that contains sections of code that requires linking for the contract to be functional.

-

The sections of code which are unlinked must be filled in with zero bytes.

-

Example: 0x606060405260e06000730000000000000000000000000000000000000000634d536f

Linked Bytecode

The hexadecimal representation of a contract’s EVM instructions which has had all Link References replaced with the desired Link Values.

-

Example: 0x606060405260e06000736fe36000604051602001526040518160e060020a634d536f

- - -
- -Chain Definition ----------------- - -This definition originates from [BIP122 -URI](https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki). - -A URI in the format `blockchain:///block/` - -- `chain_id` is the unprefixed hexadecimal representation of the - genesis hash for the chain. - -- `block_hash` is the unprefixed hexadecimal representation of the - hash of a block on the chain. - -A chain is considered to match a chain definition if the the genesis -block hash matches the `chain_id` and the block defined by `block_hash` -can be found on that chain. It is possible for multiple chains to match -a single URI, in which case all chains are considered valid matches - - -
- -Content Addressable URI ------------------------ - -Any URI which contains a cryptographic hash which can be used to verify -the integrity of the content found at the URI. - -The URI format is defined in RFC3986 - -It is **recommended** that tools support IPFS and Swarm. - - -
- -Contract Alias --------------- - -This is a name used to reference a specific [Contract -Type](#term-contract-type). Contract aliases **must** be unique within a -single [Package](#term-package). - -The contract alias **must** use *one of* the following naming schemes: - -- `` - -- `[]` - -The `` portion **must** be the same as the [Contract -Name](#term-contract-name) for this contract type. - -The `[]` portion **must** match the regular expression -`\[[-a-zA-Z0-9]{1,256}]`. - - -
- -Contract Instance ------------------ - -A contract instance a specific deployed version of a [Contract -Type](#term-contract-type). - -All contract instances have an [Address](#term-address) on some specific -chain. - - -
- -Contract Instance Name ----------------------- - -A name which refers to a specific [Contract -Instance](#term-contract-instance) on a specific chain from the -deployments of a single [Package](#term-package). This name **must** be -unique across all other contract instances for the given chain. The name -must conform to the regular expression `[a-zA-Z][a-zA-Z0-9_]{0,255}` - -In cases where there is a single deployed instance of a given [Contract -Type](#term-contract-type), package managers **should** use the -[Contract Alias](#term-contract-alias) for that contract type for this -name. - -In cases where there are multiple deployed instances of a given contract -type, package managers **should** use a name which provides some added -semantic information as to help differentiate the two deployed instances -in a meaningful way. - - -
- -Contract Name -------------- - -The name found in the source code that defines a specific [Contract -Type](#term-contract-type). These names **must** conform to the regular -expression `[a-zA-Z][-a-zA-Z0-9_]{0,255}`. - -There can be multiple contracts with the same contract name in a -projects source files. - - -
- -Contract Type -------------- - -Refers to a specific contract in the package source. This term can be -used to refer to an abstract contract, a normal contract, or a library. -Two contracts are of the same contract type if they have the same -bytecode. - -Example: - - contract Wallet { - ... - } - -A deployed instance of the `Wallet` contract would be of of type -`Wallet`. - - -
- -Identifier ----------- - -Refers generally to a named entity in the [Package](#term-package). - -A string matching the regular expression `[a-zA-Z][-_a-zA-Z0-9]{0,255}` - - - - -Link Reference --------------- - -A location within a contract’s bytecode which needs to be linked. A link -reference has the following properties. - - ---- - - - - - - - - - - - - - - -

offset

Defines the location within the bytecode where the link reference begins.

length

Defines the length of the reference.

name

(optional.) A string to identify the reference

- - - - -Link Value ----------- - -A link value is the value which can be inserted in place of a [Link -Reference](#term-link-reference) - - -
- -Linking -------- - -The act of replacing [Link References](#term-link-reference) with [Link -Values](#term-link-value) within some [Bytecode](#term-bytecode). - - -
- -Package -------- - -Distribution of an application’s source or compiled bytecode along with -metadata related to authorship, license, versioning, et al. - -For brevity, the term **Package** is often used metonymously to mean -[Package Manifest](#term-package-manifest). - - -
- -Package Manifest ----------------- - -A machine-readable description of a package (See -[Specification](#package-specification) for information about the format -for package manifests.) - - -
- -Prefixed --------- - -[Bytecode](#term-bytecode) string with leading `0x`. - - ---- - - - - - - -

Example

0xdeadbeef

- - -
- -Unprefixed ----------- - -Not [Prefixed](#term-prefixed). - - ---- - - - - - - -

Example

deadbeef

- - -Backwards Compatibility -======================= - -This specification supports backwards compatibility by use of the -[manifest\_version](#manifest-version) property. This -specification corresponds to version `2` as the value for that field. - - -Implementations -=============== - -This submission aims to coincide with development efforts towards -widespread implementation in commonly-used development tools. - -The following tools are known to have begun or are nearing completion of -a supporting implementation. - -- [Truffle](http://trufflesuite.com/) - -- [Populus](https://populus.readthedocs.io/en/latest/) - -- [Embark](https://embark.status.im/) - -Full support in implementation **may** require [Further -Work](#further-work), specified below. - - -Further Work -============ - -This EIP addresses only the data format for package descriptions. -Excluded from the scope of this specification are: - -- Package registry interface definition - -- Tooling integration, or how packages are stored on disk. - -These efforts **should** be considered separate, warranting future -dependent EIP submssions. - - -Acknowledgements -================ - -The authors of this document would like to thank the original authors of -[EIP-190](https://eips.ethereum.org/EIPS/eip-190), -[ETHPrize](http://ethprize.io/) for their funding -support, all community -[contributors](https://github.com/ethpm/ethpm-spec/graphs/contributors), -and the Ethereum community at large. - - -Copyright -========= - -Copyright and related rights waived via -[CC0](https://creativecommons.org/publicdomain/zero/1.0/). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1123.md diff --git a/EIPS/eip-1129.md b/EIPS/eip-1129.md index 2097f647bf3255..a9a2238c60965f 100644 --- a/EIPS/eip-1129.md +++ b/EIPS/eip-1129.md @@ -1,153 +1,7 @@ --- eip: 1129 -title: Standardised DAPP announcements -author: Jan Turk (@ThunderDeliverer) -discussions-to: https://ethereum-magicians.org/t/eip-sda-standardised-dapp-announcements/508?u=thunderdeliverer -status: Draft -type: Standards Track category: ERC -created: 2018-05-31 +status: Moved --- - - -## Simple Summary - -Standardisation of announcements in DAPPs and services on Ethereum network. This ERC provides proposed mechanics to increase the quality of service provided by DAPP developers and service providers, by setting a framework for announcements. Be it transitioning to a new smart contract or just freezing the service for some reason. - -## Abstract - -The proposed ERC defines format on how to post announcements about the service as well as how to remove them. It also defines mechanics on posting permissions and human friendly interface. - -## Motivation - -Currently there are no guidelines on how to notify the users of the service status in the DAPPs. This is especially obvious in ERC20 and it's derivates. If the service is impeded by any reason it is good practice to have some sort of guidelines on how to announce that to the user. The standardisation would also provide traceability of the service's status. - -## Specification - - -### Structures - -#### Announcer - -Stores information about the announcement maker. The `allowedToPost` stores posting permissions and is used for modifiers limiting announcement posting only to authorised entities. The `name` is used for human friendly identifier of the author to be stored. - -``` js -struct Announcer{ - bool allowedToPost; - string name; -} -``` - - -#### Announcement - -Stores information about the individual announcement. The human friendly author identifier is stored in `author`. Ethereum address associated with the author is stored in `authorAddress`. The announcement itself is stored in `post`. - -``` js -struct Announcement{ - string author; - address authorAddress; - string post; -} -``` - - - -### Methods -#### the number of ammouncements - -Returns the number of announcement currently active. - -OPTIONAL - this method can be used to provide quicker information for the UI, but could also be retrieved from `numberOfMessages` variable. - -``` js -function theNumberOfAnnouncements() public constant returns(uint256 _numberOfAnnouncements) -``` - - -#### read posts - -Returns the specified announcement as well as human friendly poster identificator (name or nickname). - -``` js -function readPosts(uint256 _postNumber) public constant returns(string _author, string _post) -``` - - -#### give posting permission - -Sets posting permissions of the address `_newAnnouncer` to `_postingPrivileges` and can also be used to revoke those permissions. The `_posterName` is human friendly author identificator used in the announcement data. - -``` js -function givePostingPermission(address _newAnnouncer, bool _postingPrivileges, string _posterName) public onlyOwner returns(bool success) -``` - - -#### can post - -Checks if the entity that wants to post an announcement has the posting privilieges. - -``` js -modifier canPost{ - require(posterData[msg.sender].allowedToPost); - _; -} -``` - - -#### post announcement - -Lets user post announcements, but only if they have their posting privileges set to `true`. The announcement is sent in `_message` variable. - -``` js -function postAnnouncement(string _message) public canPost -``` - - -#### remove announcement - -Removes an announcement with `_messageNumber` announcement identifier and rearranges the mapping so there are no empty slots. The `_removalReason` is used to update users if the issue that caused the announcement is resolved or what are the next steps from the service provider / DAPP development team. - -``` js -function removeAnnouncement(uint256 _messageNumber, string _removalReason) public -``` - - - -### Events - -#### New announcement - -MUST trigger when new announcement is created. - -Every time there is a new announcement it should be advertised in this event. It holds the information about author `author` and the announcement istelf `message`. - -``` js -event NewAnnouncement(string author, string message) -``` - - -#### Removed announcement - -MUST trigger when an announcement is removed. - -Every time an announcement is removed it should be advertised in this event. It holds the information about author `author`, the announcement itself `message`, the reason for removal or explanation of the solution `reason` and the address of the entity that removed the announcement `remover`. - -``` js -event RemovedAnnouncement(string author, string message, string reason, address remover); -``` - -## Rationale - -The proposed solution was designed with UX in mind . It provides mechanics that serve to present the announcements in the user friendly way. It is meant to be deployed as a Solidity smart contract on Ethereum network. - -## Test Cases - -The proposed version is deployed on Ropsten testnet all of the information can be found [here](https://ropsten.etherscan.io/address/0xb04f67172b9733837e59ebaf03d277279635c8e6#readContract). - -## Implementation - - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1129.md diff --git a/EIPS/eip-1132.md b/EIPS/eip-1132.md index c5059281594930..3f0b801c8073f5 100644 --- a/EIPS/eip-1132.md +++ b/EIPS/eip-1132.md @@ -1,152 +1,7 @@ --- eip: 1132 -title: Extending ERC20 with token locking capability -author: nitika-goel -type: Standards Track category: ERC -status: Draft -created: 2018-06-03 -discussions-to: https://github.com/ethereum/EIPs/issues/1132 +status: Moved --- -## Simple Summary - -An extension to the ERC20 standard with methods for time-locking of tokens within a contract. - -## Abstract - -This proposal provides basic functionality to time-lock tokens within an ERC20 smart contract for multiple utilities without the need of transferring tokens to an external escrow smart contract. It also allows fetching balance of locked and transferable tokens. - -Time-locking can also be achieved via staking (#900), but that requires transfer of tokens to an escrow contract / stake manager, resulting in the following six concerns: - -1. additional trust on escrow contract / stake manager -2. additional approval process for token transfer -3. increased ops costs due to gas requirements in transfers -4. tough user experience as the user needs to claim the amount back from external escrows -5. inability for the user to track their true token balance / token activity -6. inability for the user to utilize their locked tokens within the token ecosystem. - -## Motivation - -dApps often require tokens to be time-locked against transfers for letting members 1) adhere to vesting schedules and 2) show skin in the game to comply with the underlying business process. I realized this need while building Nexus Mutual and GovBlocks. - -In [Nexus Mutual](https://nexusmutual.io), claim assessors are required to lock their tokens before passing a vote for claims assessment. This is important as it ensures assessors’ skin in the game. The need here was that once a claim assessor locks his tokens for ‘n’ days, he should be able to cast multiple votes during that period of ‘n’ days, which is not feasible with staking mechanism. There are other scenarios like skills/identity verification or participation in gamified token curated registries where time-locked tokens are required as well. - -In [GovBlocks](https://govblocks.io), I wanted to allow dApps to lock member tokens for governance, while still allowing members to use those locked tokens for other activities within the dApp business. This is also the case with DGX governance model where they’ve proposed quarterly token locking for participation in governance activities of DGX. - -In addition to locking functionality, I have proposed a `Lock()` and `Unlock()` event, just like the `Transfer()` event , to track token lock and unlock status. From token holder’s perspective, it gets tough to manage token holdings if certain tokens are transferred to another account for locking, because whenever `balanceOf()` queries are triggered on token holder’s account – the result does not include locked tokens. A `totalBalanceOf()` function intends to solve this problem. - -The intention with this proposal is to enhance the ERC20 standard with token-locking capability so that dApps can time-lock tokens of the members without having to transfer tokens to an escrow / stake manager and at the same time allow members to use the locked tokens for multiple utilities. - -## Specification - -I’ve extended the ERC20 interface with the following enhancements: - -### Locking of tokens -``` -/** - * @dev Locks a specified amount of tokens against an address, - * for a specified reason and time - * @param _reason The reason to lock tokens - * @param _amount Number of tokens to be locked - * @param _time Lock time in seconds - */ -function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool) -``` - -### Fetching number of tokens locked under each utility -``` -/** - * @dev Returns tokens locked for a specified address for a - * specified reason - * - * @param _of The address whose tokens are locked - * @param _reason The reason to query the lock tokens for - */ - tokensLocked(address _of, bytes32 _reason) view returns (uint256 amount) -``` - -### Fetching number of tokens locked under each utility at a future timestamp -``` -/** - * @dev Returns tokens locked for a specified address for a - * specified reason at a specific time - * - * @param _of The address whose tokens are locked - * @param _reason The reason to query the lock tokens for - * @param _time The timestamp to query the lock tokens for - */ - function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) -``` - -### Fetching number of tokens held by an address -``` -/** - * @dev @dev Returns total tokens held by an address (locked + transferable) - * @param _of The address to query the total balance of - */ -function totalBalanceOf(address _of) view returns (uint256 amount) -``` - -### Extending lock period -``` -/** - * @dev Extends lock for a specified reason and time - * @param _reason The reason to lock tokens - * @param _time Lock extension time in seconds - */ - function extendLock(bytes32 _reason, uint256 _time) public returns (bool) -``` - -### Increasing number of tokens locked -``` -/** - * @dev Increase number of tokens locked for a specified reason - * @param _reason The reason to lock tokens - * @param _amount Number of tokens to be increased - */ - function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool) -``` -### Fetching number of unlockable tokens under each utility -``` -/** - * @dev Returns unlockable tokens for a specified address for a specified reason - * @param _of The address to query the the unlockable token count of - * @param _reason The reason to query the unlockable tokens for - */ - function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) - ``` -### Fetching number of unlockable tokens -``` -/** - * @dev Gets the unlockable tokens of a specified address - * @param _of The address to query the the unlockable token count of - */ - function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) -``` -### Unlocking tokens -``` -/** - * @dev Unlocks the unlockable tokens of a specified address - * @param _of Address of user, claiming back unlockable tokens - */ - function unlock(address _of) public returns (uint256 unlockableTokens) -``` - -### Lock event recorded in the token contract -`event Locked(address indexed _of, uint256 indexed _reason, uint256 _amount, uint256 _validity)` - -### Unlock event recorded in the token contract -`event Unlocked(address indexed _of, uint256 indexed _reason, uint256 _amount)` - -## Test Cases - -Test cases are available at [https://github.com/nitika-goel/lockable-token](https://github.com/nitika-goel/lockable-token). - -## Implementation - -- Complete implementation available at https://github.com/nitika-goel/lockable-token -- [GovBlocks](https://govblocks.io) Project specific implementation available at https://github.com/somish/govblocks-protocol/blob/Locking/contracts/GBTStandardToken.sol - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1132.md diff --git a/EIPS/eip-1153.md b/EIPS/eip-1153.md index c2554a3aafd37a..1eb863b534a5a3 100644 --- a/EIPS/eip-1153.md +++ b/EIPS/eip-1153.md @@ -1,75 +1,258 @@ --- -eip: 1153 +eip: 1153 title: Transient storage opcodes -author: Alexey Akhunov (@AlexeyAkhunov) +description: Add opcodes for manipulating state that behaves almost identically to storage but is discarded after every transaction +author: Alexey Akhunov (@AlexeyAkhunov), Moody Salem (@moodysalem) discussions-to: https://ethereum-magicians.org/t/eip-transient-storage-opcodes/553 -status: Draft +status: Final type: Standards Track category: Core created: 2018-06-15 +requires: 2200, 3529 --- -## Simple Summary -Support for efficient transient storage in EVM. It is like regular storage (SLOAD/SSTORE), but with the lifetime limited to one Ethereum transaction. -Notable use case is efficient reentrancy lock. - ## Abstract -This proposal introduces transient storage, which behaves similar to storage, -but the updates will only persist within one Ethereum transaction. Transient storage is accessible to smart contracts via new opcodes: TLOAD and TSTORE (“T” stands for Transient). + +This proposal introduces transient storage opcodes, which manipulate state that behaves identically to storage, except that transient storage is discarded after every transaction, and `TSTORE` is not subject to the gas stipend check as defined in [EIP-2200](./eip-2200.md). In other words, the values of transient storage are never deserialized from storage or serialized to storage. Thus transient storage is cheaper since it never requires disk access. Transient storage is accessible to smart contracts via 2 new opcodes, `TLOAD` and `TSTORE`, where “T” stands for "transient:" + +``` +TLOAD (0x5c) +TSTORE (0x5d) +``` ## Motivation -Running a transaction in Ethereum can generate multiple nested frames of execution, each created by CALL (or similar) instructions. -Contracts can be re-entered during the same transaction, in which case there are more than one frame belonging to one contract. -Currently, these frames can communicate in two ways - via inputs/outputs passed via CALL instructions, and via storage updates. -If there is an intermediate frame belonging to another contract, communication via inputs/outputs is not secure. Notable example is a reentrancy lock which cannot rely on the intermediate frame to pass through the state of the lock. -Communication via storage (`SSTORE`/`SLOAD`) is costly. Transient storage is a dedicated and gas efficient solution to the problem of inter frame communication. -Language support could be added in relatively easy way. For example, in Solidity, a qualifier “transient” can be introduced (similar to the existing qualifiers “memory” and “storage”). Since addressing scheme of `TSTORE` and `TLOAD` is the same as for `SSTORE` and `SLOAD`, code generation routines that exist for storage variables, can be easily generalised to also support transient storage. +Running a transaction in Ethereum can generate multiple nested frames of execution, each created by `CALL` (or similar) instructions. Contracts can be re-entered during the same transaction, in which case there are more than one frame belonging to one contract. Currently, these frames can communicate in two ways: via inputs/outputs passed via `CALL` instructions, and via storage updates. If there is an intermediate frame belonging to another untrusted contract, communication via inputs/outputs is not secure. Notable example is a reentrancy lock which cannot rely on the intermediate frame to pass through the state of the lock. Communication via storage (`SSTORE`/`SLOAD`) is costly. Transient storage is a dedicated and gas efficient solution to the problem of inter frame communication. + +Storage refunds accumulated due to inter frame communication are also limited to 20% of gas spent by a transaction due to [EIP-3529](./eip-3529.md) (introduced in the London hard fork). This greatly reduces the refunds for transiently-set storage slots in otherwise low-cost transactions. For example, in order to receive the full refund of one re-entrancy lock, the transaction must spend ~80k gas on other operations. + +Language support could be added in relatively easy way. For example, in Solidity, a qualifier `transient` can be introduced (similar to the existing qualifiers `memory` and `storage`, and Java's own `transient` keyword with a similar meaning). Since the addressing scheme of `TSTORE` and `TLOAD` is the same as for `SSTORE` and `SLOAD`, code generation routines that exist for storage variables, can be easily generalised to also support transient storage. + +Potential use cases enabled or improved by this EIP include: + +1. Reentrancy locks +2. On-chain computable CREATE2 addresses: constructor arguments are read from the factory contract instead of passed as part of init code hash +3. Single transaction [ERC-20](./eip-20.md) approvals, e.g. `#temporaryApprove(address spender, uint256 amount)` +4. Fee-on-transfer contracts: pay a fee to a token contract to unlock transfers for the duration of a transaction +5. "Till" pattern: allowing users to perform all actions as part of a callback, and checking the "till" is balanced at the end +6. Proxy call metadata: pass additional metadata to an implementation contract without using calldata, e.g. values of immutable proxy constructor arguments -Potential use cases unlocked by this EIP include: -1. Reentrancy lock -2. Passing error codes and messages from the execution frames up the execution stack -3. More generic libraries that use callbacks, for example generalised sorting with functions `Less` and `Swap` defined. -4. Shared memory (borrowed from early draft of similar EIP by @holiman). When implementing contract-proxies using `DELEGATECALL`, all direct arguments are relayed from the caller to the callee via the `CALLDATA`, leaving no room for meta-data between the proxy and the proxee. Also, the proxy must be careful about `storage` access to avoid collision with `target` `storage`-slots. Since `transient storage` would be shared, it would be possible to use `transient storage` to pass information between the `proxy` and the `target`. +These opcodes are more efficient to execute than the `SSTORE` and `SLOAD` opcodes because the original value never needs to be loaded from storage (i.e. is always 0). The gas accounting rules are also simpler, since no refunds are required. ## Specification -Two new opcodes are added to EVM, `TLOAD` and `TSTORE`. -They use the same arguments on stack as `SLOAD` and `SSTORE`. +Two new opcodes are added to EVM, `TLOAD` (`0x5c`) and `TSTORE` (`0x5d`). (Note that previous drafts of this EIP specified the values `0xb3` and `0xb4` for `TLOAD` and `TSTORE` respectively to avoid conflict with other EIPs. The conflict has since been removed.) -`TLOAD` pops one 32-byte word from the top of the stack, treats this value as the address, fetches 32-byte word from the transient storage at that address, and pops the value on top of the stack. +They use the same arguments on stack as `SLOAD` (`0x54`) and `SSTORE` (`0x55`). -`TSTORE` pops two 32-byte words from the top of the stack. The word on the top is the address, and the next is the value. TSTORE saves the value at the given address in the transient storage. +`TLOAD` pops one 32-byte word from the top of the stack, treats this value as the address, fetches 32-byte word from the transient storage at that address, and pushes the value on top of the stack. + +`TSTORE` pops two 32-byte words from the top of the stack. The word on the top is the address, and the next is the value. `TSTORE` saves the value at the given address in the transient storage. Addressing is the same as `SLOAD` and `SSTORE`. i.e. each 32-byte address points to a unique 32-byte word. -Gas cost for both is 8 units of gas, regardless of values stored. +Gas cost for `TSTORE` is the same as a warm `SSTORE` of a dirty slot (i.e. original value is not new value and is not current value, currently 100 gas), and gas cost of `TLOAD` is the same as a hot `SLOAD` (value has been read before, currently 100 gas). Gas cost cannot be on par with memory access due to transient storage's interactions with reverts. + +All values in transient storage are discarded at the end of the transaction. + +Transient storage is private to the contract that owns it, in the same way as persistent storage. Only owning contract frames may access their transient storage. And when they do, all the frames access the same transient store, in the same way as persistent storage, but unlike memory. -The effects of transient storage are discarded at the end of the transaction. +When transient storage is used in the context of `DELEGATECALL` or `CALLCODE`, then the owning contract of the transient storage is the contract that issued `DELEGATECALL` or `CALLCODE` instruction (the caller) as with persistent storage. When transient storage is used in the context of `CALL` or `STATICCALL`, then the owning contract of the transient storage is the contract that is the target of the `CALL` or `STATICCALL` instruction (the callee). -Transient storage is private to the contract that owns it, in the same way as "regular" storage is. Only owning contract frames may access their transient storage. And when they do, all the frames access the same transient store, in the same way as "regular" storage, but unlike "memory". +If a frame reverts, all writes to transient storage that took place between entry to the frame and the return are reverted, including those that took place in inner calls. This mimics the behavior of persistent storage. -When transient storage is used in the context of `DELEGATECALL` or `CALLCODE`, then the owning contract of the transient storage is the contract that issued `DELEGATECALL` or `CALLCODE` instruction (the caller). When transient storage is used in the context of `CALL` or `STATICCALL`, then the owning contract of the transient storage is the contract that is the target of the `CALL` or `STATICCALL` instruction (the callee). +If the `TSTORE` opcode is called within the context of a `STATICCALL`, it will result in an exception instead of performing the modification. `TLOAD` is allowed within the context of a `STATICCALL`. -Transient storage does not interact with reverts or invalid transactions, that means if a frame reverts, its effects on the transient storage remain until the end of the transaction. +The behavior of the opcodes for transient storage differs from the opcodes for storage in that `TSTORE` does not require _gasleft_, as defined in [EIP-2200](./eip-2200.md), to be less than or equal to the gas stipend (currently 2,300). ## Rationale -There is a proposal to alleviate the cost of inter-frame communication by reducing the cost of `SSTORE` when it modifies the same item multiple times within the same transaction (EIP-1087). -Relative cons of the transient storage: new opcodes; new code in the clients; new concept for the yellow paper (more to update); requires separation of concerns (persistence and inter-frame communication) when programming. +Another option to solve the problem of inter-frame communication is repricing the `SSTORE` and `SLOAD` opcodes to be cheaper for the transient storage use case. This has already been done as of [EIP-2200](./eip-2200.md). However, [EIP-3529](./eip-3529.md) reduced the maximum refund to only 20% of the transaction gas cost, which means the use of transient storage is severely limited. + +Another approach is to keep the refund counter for transient storage separate from the refund counter for other storage uses, and remove the refund cap for transient storage. However, that approach is more complex to implement and understand. For example, the 20% refund cap must be applied to the gas used _after_ subtracting the uncapped gas refund. Otherwise, the refund amount available subject to the 20% refund cap could be increased by executing transient storage writes. Thus it is preferable to have a separate mechanism that does not interact with the refund counter. Future hard forks can remove the complex refund behavior meant to support the transient storage use case, encouraging migration to contracts that are more efficient for the Ethereum clients to execute. + +There is a known objection to the word-addressed storage-like interface of the `TSTORE` and `TLOAD` opcodes since transient storage is more akin to memory than storage in lifecycle. A byte-addressed memory-like interface is another option. The storage-like word-addressed interface is preferred due to the usefulness of mappings in combination with the transaction-scoped memory region. Often times, you will need to keep transient state with arbitrary keys, such as in the [ERC-20](./eip-20.md) temporary approval use case which uses a mapping of `(owner, spender)` to `allowance`. Mappings are difficult to implement using linear memory, and linear memory must also have dynamic gas costs. It is also more complicated to handle reverts with a linear memory. It is possible to have a memory-like interface while the underlying implementation uses a map to allow for storage in arbitrary offsets, but this would result in a third memory-storage hybrid interface that would require new code paths in compilers. + +Some think that a unique transaction identifier may obviate the need for transient storage as described in this EIP. This is a misconception: a transaction identifier used in combination with regular storage has all the same issues that motivate this EIP. The two features are orthogonal. -Relative pros of the transient storage: cheaper to use; does not change the semantics of the existing operations; very simple gas accounting rules; +Relative cons of this transient storage EIP: + +- Does not address transient usages of storage in existing contracts +- New code in the clients +- New concept for the yellow paper (more to update) + +Relative pros of this transient storage EIP: + +- Transient storage opcodes are considered separately in protocol upgrades and not inadvertently broken (e.g. [EIP-3529](./eip-3529.md)) +- Clients do not need to load the original value +- No upfront gas cost to account for non-transient writes +- Does not change the semantics of the existing operations +- No need to clear storage slots after usage +- Simpler gas accounting rules +- Future storage designs (e.g. Verkle tree) do not need to account for transient storage refunds ## Backwards Compatibility + This EIP requires a hard fork to implement. -Since this EIP does not change semantics of any existing opcodes, it does not pose risk of backwards incompatibility for existing deployed contracts. +Since this EIP does not change behavior of any existing opcodes, it is backwards compatible with all existing smart contracts. ## Test Cases -TBD -## Implementation -Most straightforward implementation would be a dictionary (map), similar to what exists for the ‘dirty’ storage, with the difference that it gets re-initialised at the start of each transaction, and does not get persisted. +A test suite for this EIP can be found [here](https://github.com/ethereum/execution-spec-tests/tree/1983444bbe1a471886ef7c0e82253ffe2a4053e1/tests/cancun/eip1153_tstore). + +## Reference Implementation + +Because the transient storage must behave almost identically to storage within the context of a single transaction with regards to revert behavior, it is necessary to be able to revert to a previous state of transient storage within a transaction. At the same time reverts are exceptional cases and loads, stores and returns should be cheap. + +A map of current state plus a journal of all changes and a list of checkpoints is recommended. This has the following time complexities: + +- On entry to a call frame, a call marker is added to the list - `O(1)` +- New values are written to the current state, and the previous value is written to the journal - `O(1)` +- When a call exits successfully, the marker to the journal index of when that call was entered is discarded - `O(1)` +- On revert all entries are reverted up to the last checkpoint, in reverse - `O(N)` where `N` = number of journal entries since last checkpoint + +```typescript +interface JournalEntry { + addr: string + key: string + prevValue: string +} + +type Journal = JournalEntry[] + +type Checkpoints = Journal['length'][] + +interface Current { + [addr: string]: { + [key: string]: string + } +} + +const EMPTY_VALUE = '0x0000000000000000000000000000000000000000000000000000000000000000' + +class TransientStorage { + /** + * The current state of transient storage. + */ + private current: Current = {} + /** + * All changes are written to the journal. On revert, we apply the changes in reverse to the last checkpoint. + */ + private journal: Journal = [] + /** + * The length of the journal at the time of each checkpoint + */ + private checkpoints: Checkpoints = [0] + + /** + * Returns the current value of the given contract address and key + * @param addr The address of the contract + * @param key The key of transient storage for the address + */ + public get(addr: string, key: string): string { + return this.current[addr]?.[key] ?? EMPTY_VALUE + } + + /** + * Set the current value in the map + * @param addr the address of the contract for which the key is being set + * @param key the slot to set for the address + * @param value the new value of the slot to set + */ + public put(addr: string, key: string, value: string) { + this.journal.push({ + addr, + key, + prevValue: this.get(addr, key), + }) + + this.current[addr] = this.current[addr] ?? {} + this.current[addr][key] = value; + } + + /** + * Commit all the changes since the last checkpoint + */ + public commit(): void { + if (this.checkpoints.length === 0) throw new Error('Nothing to commit') + this.checkpoints.pop() // The last checkpoint is discarded. + } + + /** + * To be called whenever entering a new context. If revert is called after checkpoint, all changes made after the latest checkpoint are reverted. + */ + public checkpoint(): void { + this.checkpoints.push(this.journal.length) + } + + /** + * Revert transient storage to the state from the last call to checkpoint + */ + public revert() { + const lastCheckpoint = this.checkpoints.pop() + if (typeof lastCheckpoint === 'undefined') throw new Error('Nothing to revert') + + for (let i = this.journal.length - 1; i >= lastCheckpoint; i--) { + const {addr, key, prevValue} = this.journal[i] + // we can assume it exists, since it was written in the journal + this.current[addr][key] = prevValue + } + this.journal.splice(lastCheckpoint, this.journal.length - lastCheckpoint) + } +} +``` + +The worst case time complexity can be produced by writing the maximum number of keys that can fit in one block, and then reverting. In this case, the client is required to do twice as many writes to apply all the entries in the journal. However, the same case applies to the state journaling implementation of existing clients, and cannot be DOS'd with the following code. + +```solidity +pragma solidity =0.8.13; + +contract TryDOS { + uint256 slot; + + constructor() { + slot = 1; + } + + function tryDOS() external { + uint256 i = 1; + while (gasleft() > 5000) { + unchecked { + slot = i++; + } + } + revert(); + } +} +``` + +## Security Considerations + +`TSTORE` presents a new way to allocate memory on a node with linear cost. In other words, each TSTORE allows the developer to store 32 bytes for 100 gas, excluding any other required operations to prepare the stack. Given 30 million gas, the maximum amount of memory that can be allocated using TSTORE is: + +``` +30M gas * 1 TSTORE / 100 gas * 32 bytes / 1 TSTORE * 1MB / 2^20 bytes ~= 9.15MB +``` + +Given the same amount of gas, the maximum amount of memory that can be allocated in a single context by `MSTORE` is ~3.75MB: + +``` +30M gas = 3x + x^2 / 512 => x = ~123,169 32-byte words +~123,169 words * 32 bytes/word * 1MB / 2^20 bytes = 3.75MB +``` + +However, if you only spend 1M gas allocating memory in each context, and make calls to reset the memory expansion cost, you can allocate ~700KB per million gas, for a total of ~20MB of memory allocated: + +``` +1M gas = 3x + x^2 / 512 => x = ~21,872 32-byte words +30M gas * ~21,872 words / 1M gas * 32 bytes/word * 1MB / 2^20 bytes = ~20MB +``` + +Smart contract developers should understand the lifetime of transient storage variables before use. Because transient storage is automatically cleared at the end of the transaction, smart contract developers may be tempted to avoid clearing slots as part of a call in order to save gas. However, this could prevent further interactions with the contract in the same transaction (e.g. in the case of re-entrancy locks) or cause other bugs, so smart contract developers should be careful to _only_ leave transient storage slots with nonzero values when those slots are intended to be used by future calls within the same transaction. Otherwise, these opcodes behave exactly the same as `SSTORE` and `SLOAD`, so all the usual security considerations apply especially in regard to reentrancy risk. + +Smart contract developers may also be tempted to use transient storage as an alternative to in-memory mappings. They should be aware that transient storage is not discarded when a call returns or reverts, as is memory, and should prefer memory for these use cases so as not to create unexpected behavior on reentrancy in the same transaction. The necessarily high cost of transient storage over memory should already discourage this usage pattern. Most usages of in-memory mappings can be better implemented with key-sorted lists of entries, and in-memory mappings are rarely required in smart contracts (i.e. the author knows of no known use cases in production). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1154.md b/EIPS/eip-1154.md index 4e8dc483fdd133..2873d8496253c6 100644 --- a/EIPS/eip-1154.md +++ b/EIPS/eip-1154.md @@ -1,110 +1,7 @@ --- eip: 1154 -title: Oracle Interface -author: Alan Lu (@cag) -discussions-to: https://github.com/ethereum/EIPs/issues/1161 -status: Draft -type: Standards Track category: ERC -created: 2018-06-13 +status: Moved --- -## Simple Summary -A standard interface for oracles. - -## Abstract -In order for ethereum smart contracts to interact with off-chain systems, oracles must be used. These oracles report values which are normally off-chain, allowing smart contracts to react to the state of off-chain systems. A distinction and a choice is made between push and pull based oracle systems. Furthermore, a standard interface for oracles is described here, allowing different oracle implementations to be interchangeable. - -## Motivation -The Ethereum ecosystem currently has many different oracle implementations available, but they do not provide a unified interface. Smart contract systems would be locked into a single set of oracle implementations, or they would require developers to write adapters/ports specific to the oracle system chosen in a given project. - -Beyond naming differences, there is also the issue of whether or not an oracle report-resolving transaction _pushes_ state changes by calling affected contracts, or changes the oracle state allowing dependent contracts to _pull_ the updated value from the oracle. These differing system semantics could introduce inefficiencies when adapting between them. - -Ultimately, the value in different oracle systems comes from their underlying resolution mechanics, and points where these systems are virtually identical should be standardized. - -These oracles may be used for answering questions about "real-world events", where each ID can be correlated with a specification of a question and its answers (so most likely for prediction markets, basically). - -Another use case could be for decision-making processes, where the results given by the oracle represent decisions made by the oracle (e.g. futarchies). DAOs may require their use in decision making processes. - -Both the ID and the results are intentionally unstructured so that things like time series data (via splitting the ID) and different sorts of results (like one of a few, any subset of up to 256, or some value in a range with up to 256 bits of granularity) can be represented. - -## Specification - -
-
Oracle
-
An entity which reports data to the blockchain.
- -
Oracle consumer
-
A smart contract which receives data from an oracle.
- -
ID
-
A way of indexing the data which an oracle reports. May be derived from or tied to a question for which the data provides the answer.
- -
Result
-
Data associated with an id which is reported by an oracle. This data oftentimes will be the answer to a question tied to the id. Other equivalent terms that have been used include: answer, data, outcome.
- -
Report
-
A pair (ID, result) which an oracle sends to an oracle consumer.
-
- -```solidity -interface OracleConsumer { - function receiveResult(bytes32 id, bytes result) external; -} -``` - -`receiveResult` MUST revert if the `msg.sender` is not an oracle authorized to provide the `result` for that `id`. - -`receiveResult` MUST revert if `receiveResult` has been called with the same `id` before. - -`receiveResult` MAY revert if the `id` or `result` cannot be handled by the consumer. - -Consumers MUST coordinate with oracles to determine how to encode/decode results to and from `bytes`. For example, `abi.encode` and `abi.decode` may be used to implement a codec for results in Solidity. `receiveResult` SHOULD revert if the consumer receives a unexpected result format from the oracle. - -The oracle can be any Ethereum account. - -## Rationale -The specs are currently very similar to what is implemented by ChainLink (which can use any arbitrarily-named callback) and Oraclize (which uses `__callback`). - -With this spec, the oracle _pushes_ state to the consumer, which must react accordingly to the updated state. An alternate _pull_-based interface can be prescribed, as follows: - -### Alternate Pull-based Interface -Here are alternate specs loosely based on Gnosis prediction market contracts v1. Reality Check also exposes a similar endpoint (`getFinalAnswer`). - -```solidity -interface Oracle { - function resultFor(bytes32 id) external view returns (bytes result); -} -``` - -`resultFor` MUST revert if the result for an `id` is not available yet. - -`resultFor` MUST return the same result for an `id` after that result is available. - -### Push vs Pull -Note that push-based interfaces may be adapted into pull-based interfaces. Simply deploy an oracle consumer which stores the result received and implements `resultFor` accordingly. - -Similarly, every pull-based system can be adapted into a push-based system: just add a method on the oracle smart contract which takes an oracle consumer address and calls `receiveResult` on that address. - -In both cases, an additional transaction would have to be performed, so the choice to go with push or pull should be based on the dominant use case for these oracles. - -In the simple case where a single account has the authority to decide the outcome of an oracle question, there is no need to deploy an oracle contract and store the outcome on that oracle contract. Similarly, in the case where the outcome comes down to a vote, existing multisignature wallets can be used as the authorized oracle. - -#### Multiple Oracle Consumers -In the case that many oracle consumers depend on a single oracle result and all these consumers expect the result to be pushed to them, the push and pull adaptations mentioned before may be combined if the pushing oracle cannot be trusted to send the same result to every consumer (in a sense, this forwards the trust to the oracle adaptor implementation). - -In a pull-based system, each of the consumers would have to be called to pull the result from the oracle contract, but in the proposed push-based system, the adapted oracle would have to be called to push the results to each of the consumers. - -Transaction-wise, both systems are roughly equivalent in efficiency in this scenario, but in the push-based system, there's a need for the oracle consumers to store the results again, whereas in the pull-based system, the consumers may continue to refer to the oracle for the results. Although this may be somewhat less efficient, requiring the consumers to store the results can also provide security guarantees, especially with regards to result immutability. - -#### Result Immutability -In both the proposed specification and the alternate specification, results are immutable once they are determined. This is due to the expectation that typical consumers will require results to be immutable in order to determine a resulting state consistently. With the proposed push-based system, the consumer enforces the result immutability requirement, whereas in the alternate pull-based system, either the oracle would have to be trusted to implement the spec correctly and enforce the immutability requirement, or the consumer would also have to handle result immutability. - -For data which mutates over time, the `id` field may be structured to specify "what" and "when" for the data (using 128 bits to specify "when" is still safe for many millennia). - -## Implementation - -* [Tidbit](https://github.com/levelkdev/tidbit) tracks this EIP. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1154.md diff --git a/EIPS/eip-1155.md b/EIPS/eip-1155.md index c736f9bf8f84e4..f7c6bc8c1c84ce 100644 --- a/EIPS/eip-1155.md +++ b/EIPS/eip-1155.md @@ -1,639 +1,7 @@ --- eip: 1155 -title: ERC-1155 Multi Token Standard -author: Witek Radomski , Andrew Cooke , Philippe Castonguay , James Therien , Eric Binet , Ronan Sandford -type: Standards Track category: ERC -status: Draft -review-period-end: 2019-03-28 -created: 2018-06-17 -discussions-to: https://github.com/ethereum/EIPs/issues/1155 -requires: 165 +status: Moved --- -## Simple Summary - -A standard interface for contracts that manage multiple token types. A single deployed contract may include any combination of fungible tokens, non-fungible tokens, or other configurations (e.g. semi-fungible tokens). - -## Abstract - -This standard outlines a smart contract interface that can represent any number of Fungible and Non-Fungible token types. Existing standards such as ERC-20 require deployment of separate contracts per token type. The ERC-721 standard's token ID is a single non-fungible index and the group of these non-fungibles is deployed as a single contract with settings for the entire collection. In contrast, the ERC-1155 Multi Token Standard allows for each token ID to represent a new configurable token type, which may have its own metadata, supply and other attributes. - -The `_id` argument contained in each function's argument set indicates a specific token or token type in a transaction. - -## Motivation - -Tokens standards like ERC-20 and ERC-721 require a separate contract to be deployed for each token type or collection. This places a lot of redundant bytecode on the Ethereum blockchain and limits certain functionality by the nature of separating each token contract into its own permissioned address. With the rise of blockchain games and platforms like Enjin Coin, game developers may be creating thousands of token types, and a new type of token standard is needed to support them. However, ERC-1155 is not specific to games, and many other applications can benefit from this flexibility. - -New functionality is possible with this design, such as transferring multiple token types at once, saving on transaction costs. Trading (escrow / atomic swaps) of multiple tokens can be built on top of this standard and it removes the need to "approve" individual token contracts separately. It is also easy to describe and mix multiple fungible or non-fungible token types in a single contract. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Smart contracts implementing the ERC-1155 standard MUST implement the `ERC1155` and `ERC165` interfaces.** - -```solidity -pragma solidity ^0.5.8; - -/** - @title ERC-1155 Multi Token Standard - @dev See https://eips.ethereum.org/EIPS/eip-1155 - Note: The ERC-165 identifier for this interface is 0xd9b67a26. - */ -interface ERC1155 /* is ERC165 */ { - /** - @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - The `_from` argument MUST be the address of the holder whose balance is decreased. - The `_to` argument MUST be the address of the recipient whose balance is increased. - The `_id` argument MUST be the token type being transferred. - The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). - */ - event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); - - /** - @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - The `_from` argument MUST be the address of the holder whose balance is decreased. - The `_to` argument MUST be the address of the recipient whose balance is increased. - The `_ids` argument MUST be the list of tokens being transferred. - The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). - */ - event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); - - /** - @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled). - */ - event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); - - /** - @dev MUST emit when the URI is updated for a token ID. - URIs are defined in RFC 3986. - The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". - */ - event URI(string _value, uint256 indexed _id); - - /** - @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). - @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). - MUST revert if `_to` is the zero address. - MUST revert if balance of holder for token `_id` is lower than the `_value` sent. - MUST revert on any other error. - MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). - After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). - @param _from Source address - @param _to Target address - @param _id ID of the token type - @param _value Transfer amount - @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` - */ - function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; - - /** - @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). - @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). - MUST revert if `_to` is the zero address. - MUST revert if length of `_ids` is not the same as length of `_values`. - MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. - MUST revert on any other error. - MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). - Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). - After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). - @param _from Source address - @param _to Target address - @param _ids IDs of each token type (order and length must match _values array) - @param _values Transfer amounts per token type (order and length must match _ids array) - @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` - */ - function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; - - /** - @notice Get the balance of an account's Tokens. - @param _owner The address of the token holder - @param _id ID of the token - @return The _owner's balance of the token type requested - */ - function balanceOf(address _owner, uint256 _id) external view returns (uint256); - - /** - @notice Get the balance of multiple account/token pairs - @param _owners The addresses of the token holders - @param _ids ID of the Tokens - @return The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair) - */ - function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); - - /** - @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. - @dev MUST emit the ApprovalForAll event on success. - @param _operator Address to add to the set of authorized operators - @param _approved True if the operator is approved, false to revoke approval - */ - function setApprovalForAll(address _operator, bool _approved) external; - - /** - @notice Queries the approval status of an operator for a given owner. - @param _owner The owner of the Tokens - @param _operator Address of authorized operator - @return True if the operator is approved, false if not - */ - function isApprovedForAll(address _owner, address _operator) external view returns (bool); -} -``` - -### ERC-1155 Token Receiver - -Smart contracts **MUST** implement this interface to accept transfers. See "Safe Transfer Rules" for further detail. - -```solidity -pragma solidity ^0.5.8; - -/** - Note: The ERC-165 identifier for this interface is 0x43b236a2. -*/ -interface ERC1155TokenReceiver { - /** - @notice Handle the receipt of a single ERC1155 token type. - @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. - This function MUST return `bytes4(keccak256("accept_erc1155_tokens()"))` (i.e. 0x4dc21a2f) if it accepts the transfer. - This function MUST revert if it rejects the transfer. - Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. - @param _operator The address which initiated the transfer (i.e. msg.sender) - @param _from The address which previously owned the token - @param _id The ID of the token being transferred - @param _value The amount of tokens being transferred - @param _data Additional data with no specified format - @return `bytes4(keccak256("accept_erc1155_tokens()"))` - */ - function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); - - /** - @notice Handle the receipt of multiple ERC1155 token types. - @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. - This function MUST return `bytes4(keccak256("accept_batch_erc1155_tokens()"))` (i.e. 0xac007889) if it accepts the transfer(s). - This function MUST revert if it rejects the transfer(s). - Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. - @param _operator The address which initiated the batch transfer (i.e. msg.sender) - @param _from The address which previously owned the token - @param _ids An array containing ids of each token being transferred (order and length must match _values array) - @param _values An array containing amounts of each token being transferred (order and length must match _ids array) - @param _data Additional data with no specified format - @return `bytes4(keccak256("accept_batch_erc1155_tokens()"))` - */ - function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); - - /** - @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. - @dev This function MUST return `bytes4(keccak256("isERC1155TokenReceiver()"))` (i.e. 0x0d912442). - This function MUST NOT consume more than 5,000 gas. - @return `bytes4(keccak256("isERC1155TokenReceiver()"))` - */ - function isERC1155TokenReceiver() external view returns (bytes4); -} -``` - -### Safe Transfer Rules - -To be more explicit about how safeTransferFrom and safeBatchTransferFrom MUST operate with respect to the `ERC1155TokenReceiver` hook functions, a list of scenarios and rules follows. - -#### Scenarios - -**_Scenario#1 :_** The recipient is not a contract. -* `onERC1155Received` and `onERC1155BatchReceived` MUST NOT be called on an EOA (Externally Owned Account). - -**_Scenario#2 :_** The transaction is not a mint/transfer of a token. -* `onERC1155Received` and `onERC1155BatchReceived` MUST NOT be called outside of a mint or transfer process. - -**_Scenario#3 :_** The receiver does not implement the necessary `ERC1155TokenReceiver` interface function(s). -* The transfer MUST be reverted with the one caveat below. - - If the tokens being sent are part of a hybrid implementation of another standard, that particular standard's rules on sending to a contract MAY now be followed instead. See "Compatibility with other standards" section. - -**_Scenario#4 :_** The receiver implements the necessary `ERC1155TokenReceiver` interface function(s) but returns an unknown value. -* The transfer MUST be reverted. - -**_Scenario#5 :_** The receiver implements the necessary `ERC1155TokenReceiver` interface function(s) but throws an error. -* The transfer MUST be reverted. - -**_Scenario#6 :_** The receiver implements the `ERC1155TokenReceiver` interface and is the recipient of one and only one balance change (e.g. safeTransferFrom called). -* All the balances in the transfer MUST have been updated to match the senders intent before any hook is called on a recipient. -* All the transfer events for the transfer MUST have been emitted to reflect the balance changes before any hook is called on a recipient. -* One of `onERC1155Received` or `onERC1155BatchReceived` MUST be called on the recipient. -* The `onERC1155Received` hook SHOULD be called on the recipient contract and its rules followed. - - See "onERC1155Received rules" for further rules that MUST be followed. -* The `onERC1155BatchReceived` hook MAY be called on the recipient contract and its rules followed. - - See "onERC1155BatchReceived rules" for further rules that MUST be followed. - -**_Scenario#7 :_** The receiver implements the `ERC1155TokenReceiver` interface and is the recipient of more than one balance change (e.g. safeBatchTransferFrom called). -* All the balances in the transfer MUST have been updated to match the senders intent before any hook is called on a recipient. -* All the transfer events for the transfer MUST have been emitted to reflect the balance changes before any hook is called on a recipient. -* `onERC1155Received` or `onERC1155BatchReceived` MUST be called on the recipient as many times as necessary such that every balance change for the recipient in the scenario is accounted for. - - The return magic value for every hook call MUST be checked and acted upon as per "onERC1155Received rules" and "onERC1155BatchReceived rules". -* The `onERC1155BatchReceived` hook SHOULD be called on the recipient contract and its rules followed. - - See "onERC1155BatchReceived rules" for further rules that MUST be followed. -* The `onERC1155Received` hook MAY be called on the recipient contract and its rules followed. - - See "onERC1155Received rules" for further rules that MUST be followed. - -**_Scenario#8 :_** You are the creator of a contract that implements the `ERC1155TokenReceiver` interface and you forward the token(s) onto another address in one or both of `onERC1155Received` and `onERC1155BatchReceived`. -* Forwarding should be considered acceptance and then initiating a new `safeTransferFrom` or `safeBatchTransferFrom` in a new context. - - The prescribed keccak256 acceptance value magic for the receiver hook being called MUST be returned after forwarding is successful. -* The `_data` argument MAY be re-purposed for the new context. -* If forwarding fails the transaction MAY be reverted. - - If the contract logic wishes to keep the ownership of the token(s) itself in this case it MAY do so. - -#### Rules - -**_safeTransferFrom rules:_** -* Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section). -* MUST revert if `_to` is the zero address. -* MUST revert if balance of holder for token `_id` is lower than the `_value` sent to the recipient. -* MUST revert on any other error. -* MUST emit the `TransferSingle` event to reflect the balance change (see "TransferSingle and TransferBatch event rules" section). -* After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "onERC1155Received rules" section). - - The `_data` argument provided by the sender for the transfer MUST be passed with its contents unaltered to the `onERC1155Received` hook function via its `_data` argument. - -**_safeBatchTransferFrom rules:_** -* Caller must be approved to manage all the tokens being transferred out of the `_from` account (see "Approval" section). -* MUST revert if `_to` is the zero address. -* MUST revert if length of `_ids` is not the same as length of `_values`. -* MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. -* MUST revert on any other error. -* MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "TransferSingle and TransferBatch event rules" section). -* The balance changes and events MUST occur in the array order they were submitted (_ids[0]/_values[0] before _ids[1]/_values[1], etc). -* After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` or `onERC1155BatchReceived` on `_to` and act appropriately (see "onERC1155Received and onERC1155BatchReceived rules" section). - - The `_data` argument provided by the sender for the transfer MUST be passed with its contents unaltered to the `ERC1155TokenReceiver` hook function(s) via their `_data` argument. - -**_TransferSingle and TransferBatch event rules:_** -* `TransferSingle` SHOULD be used to indicate a single balance transfer has occurred between a `_from` and `_to` pair. - - It MAY be emitted multiple times to indicate multiple balance changes in the transaction, but note that `TransferBatch` is designed for this to reduce gas consumption. - - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - - The `_from` argument MUST be the address of the holder whose balance is decreased. - - The `_to` argument MUST be the address of the recipient whose balance is increased. - - The `_id` argument MUST be the token type being transferred. - - The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. - - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). - - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). -* `TransferBatch` SHOULD be used to indicate multiple balance transfers have occurred between a `_from` and `_to` pair. - - It MAY be emitted with a single element in the list to indicate a singular balance change in the transaction, but note that `TransferSingle` is designed for this to reduce gas consumption. - - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - - The `_from` argument MUST be the address of the holder whose balance is decreased for each entry pair in `_ids` and `_values`. - - The `_to` argument MUST be the address of the recipient whose balance is increased for each entry pair in `_ids` and `_values`. - - The `_ids` array argument MUST contain the ids of the tokens being transferred. - - The `_values` array argument MUST contain the number of token to be transferred for each corresponding entry in `_ids`. - - `_ids` and `_values` MUST have the same length. - - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). - - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). -* The total value transferred from address 0x0 minus the total value transferred to 0x0 MAY be used by clients and exchanges to be added to the "circulating supply" for a given token ID. -* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the `TransferSingle` event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_value` of 0. -* All `TransferSingle` and `TransferBatch` events MUST be emitted to reflect all the balance changes that have occurred before any call(s) to `onERC1155Received` or `onERC1155BatchReceived`. - - To make sure event order is correct in the case of valid re-entry (e.g. if a receiver contract forwards tokens on receipt) state balance and events balance MUST match before calling an external contract. - -**_onERC1155Received rules:_** -- The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). -* The `_from` argument MUST be the address of the holder whose balance is decreased. - - `_from` MUST be 0x0 for a mint. -* The `_id` argument MUST be the token type being transferred. -* The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. -* The `_data` argument MUST contain the information provided by the sender for the transfer with its contents unaltered. - - i.e. it MUST pass on the unaltered `_data` argument sent via the `safeTransferFrom` or `safeBatchTransferFrom` call for this transfer. -* The recipient contract MAY accept an increase of its balance by returning the acceptance magic value `bytes4(keccak256("accept_erc1155_tokens()"))` - - If the return value is `bytes4(keccak256("accept_erc1155_tokens()"))` the transfer MUST be completed or MUST revert if any other conditions are not met for success. -* The recipient contract MAY reject an increase of its balance by calling revert. - - If recipient contract throws/reverts the transaction MUST be reverted. -* If the return value is anything other than `bytes4(keccak256("accept_erc1155_tokens()"))` the transaction MUST be reverted. -* `onERC1155Received` (and/or `onERC1155BatchReceived`) MAY be called multiple times in a single transaction and the following requirements must be met: - - All callbacks represent mutually exclusive balance changes. - - The set of all calls to `onERC1155Received` and `onERC1155BatchReceived` describes all balance changes that occurred during the transaction in the order submitted. - -**_onERC1155BatchReceived rules:_** -- The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). -* The `_from` argument MUST be the address of the holder whose balance is decreased. - - `_from` MUST be 0x0 for a mint. -* The `_ids` argument MUST be the list of tokens being transferred. -* The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in `_ids`) the holder balance is decreased by and match what the recipient balance is increased by. -* The `_data` argument MUST contain the information provided by the sender for the transfer with its contents unaltered. - - i.e. it MUST pass on the unaltered `_data` argument sent via the `safeBatchTransferFrom` call for this transfer. -* The recipient contract MAY accept an increase of its balance by returning the acceptance magic value `bytes4(keccak256("accept_batch_erc1155_tokens()"))` - - If the return value is `bytes4(keccak256("accept_batch_erc1155_tokens()"))` the transfer MUST be completed or MUST revert if any other conditions are not met for success. -* The recipient contract MAY reject an increase of its balance by calling revert. - - If recipient contract throws/reverts the transaction MUST be reverted. -* If the return value is anything other than `bytes4(keccak256("accept_batch_erc1155_tokens()"))` the transaction MUST be reverted. -* `onERC1155BatchReceived` (and/or `onERC1155Received`) MAY be called multiple times in a single transaction and the following requirements must be met: - - All callbacks represent mutually exclusive balance changes. - - The set of all calls to `onERC1155Received` and `onERC1155BatchReceived` describes all balance changes that occurred during the transaction in the order submitted. - -**_isERC1155TokenReceiver rules:_** -* The implementation of `isERC1155TokenReceiver` function SHOULD be as follows: - ``` - function isERC1155TokenReceiver() external view returns (bytes4) { - return 0x0d912442; // bytes4(keccak256("isERC1155TokenReceiver()")) - } - ``` -* The implementation MAY differ from the above but: - - It MUST return the same value. - - It MUST NOT consume more than 5,000 gas. - -**_Implementation specific transfer api rules:_** -* If implementation specific api functions are used to transfer 1155 tokens to a contract, the safeTransferFrom, or safeBatchTransferFrom (as appropriate) rules MUST be followed. - -###### A solidity example of the keccak256 generated constants for the return magic is: - - bytes4 constant public ERC1155_ACCEPTED = 0x4dc21a2f; // bytes4(keccak256("accept_erc1155_tokens()")) - - bytes4 constant public ERC1155_BATCH_ACCEPTED = 0xac007889; // bytes4(keccak256("accept_batch_erc1155_tokens()")) - -#### Compatibility with other standards - -There have been requirements during the design discussions to have this standard be compatible with existing standards when sending to contract addresses, specifically ERC-721 at time of writing. -To cater for this scenario, there is some leeway with the rejection logic should a contract not implement the `ERC1155TokenReceiver` as per "Safe Transfer Rules" section above, specifically "Scenario#3 : The receiver does not implement the necessary `ERC1155TokenReceiver` interface function(s)". - -Hence in a hybrid 1155 contract implementation an extra call MUST be made on the recipient contract and checked before any hook calls to `onERC1155Received` or `onERC1155BatchReceived` are made. -Order of operation MUST therefore be: -1. The implementation MUST call the function `isERC1155TokenReceiver` on the recipient, providing at least 5,000 gas. -2. If the function call succeeds and the return value is `bytes4(keccak256("isERC1155TokenReceiver()"))` the implementation proceeds as a regular 1155 implementation, with the call(s) to the `onERC1155Received` or `onERC1155BatchReceived` hooks and rules associated. -3. If the function call fails or the return value is NOT `bytes4(keccak256("isERC1155TokenReceiver()"))` the implementation can assume the contract recipient is not an `ERC1155TokenReceiver` and follow its other standard's rules for transfers. - -*__Note that a pure implementation of a single standard is recommended__* rather than a hybrid solution, but an example of a hybrid 1155+721 contract is linked in the references section under implementations. - -An important consideration is that even if the tokens are sent with another standard's rules the *__1155 transfer events MUST still be emitted.__* This is so the balances can still be determined via events alone as per 1155 standard rules. - - -### Metadata - -The URI value allows for ID substitution by clients. If the string `{id}` exists in any URI, clients MUST replace this with the actual token ID in hexadecimal form. This allows for large number of tokens to use the same on-chain string by defining a URI once, for a large collection of tokens. Example of such a URI: `https://token-cdn-domain/{id}.json` would be replaced with `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` if the client is referring to token ID 314592/0x4CCE0. - -The string format of the substituted hexadecimal ID MUST be lowercase alphanumeric: `[0-9a-f]` with no 0x prefix. -The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary. - -#### Metadata Extensions - -The following optional extensions can be identified with the (ERC-165 Standard Interface Detection)[https://eips.ethereum.org/EIPS/eip-165]. - -Changes to the URI MUST emit the `URI` event if the change can be expressed with an event (i.e. it isn't dynamic). If the optional ERC1155Metadata_URI extension is included, the 'uri' function SHOULD be used to retrieve values for which no event was emitted. The function MUST return the same value as the event if it was emitted. - -```solidity -pragma solidity ^0.5.8; - -/** - Note: The ERC-165 identifier for this interface is 0x0e89341c. -*/ -interface ERC1155Metadata_URI { - /** - @notice A distinct Uniform Resource Identifier (URI) for a given token. - @dev URIs are defined in RFC 3986. - The URI may point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". - @return URI string - */ - function uri(uint256 _id) external view returns (string memory); -} -``` - -#### ERC-1155 Metadata URI JSON Schema - -This JSON schema is loosely based on the "ERC721 Metadata JSON Schema", but includes optional formatting to allow for ID substitution by clients. If the string `{id}` exists in any JSON value, it MUST be replaced with the actual token ID, by all client software that follows this standard. - -The string format of the substituted hexadecimal ID MUST be lowercase alphanumeric: `[0-9a-f]` with no 0x prefix. - -```json -{ - "title": "Token Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents", - }, - "decimals": { - "type": "integer", - "description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation.", - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents", - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", - }, - "properties": { - "type": "object", - "description": "Arbitrary properties. Values may be strings, numbers, object or arrays.", - }, - } -} -``` - -An example of an ERC-1155 Metadata JSON file follows. The properties array proposes some SUGGESTED formatting for token-specific display properties and metadata. - -```json -{ - "name": "Asset Name", - "description": "Lorem ipsum...", - "image": "https:\/\/s3.amazonaws.com\/your-bucket\/images\/{id}.png", - "properties": { - "simple_property": "example value", - "rich_property": { - "name": "Name", - "value": "123", - "display_value": "123 Example Value", - "class": "emphasis", - "css": { - "color": "#ffffff", - "font-weight": "bold", - "text-decoration": "underline" - } - }, - "array_property": { - "name": "Name", - "value": [1,2,3,4], - "class": "emphasis" - } - } -} -``` - -##### Localization - -Metadata localization should be standardized to increase presentation uniformity across all languages. As such, a simple overlay method is proposed to enable localization. If the metadata JSON file contains a `localization` attribute, its content MAY be used to provide localized values for fields that need it. The `localization` attribute should be a sub-object with three attributes: `uri`, `default` and `locales`. If the string `{locale}` exists in any URI, it MUST be replaced with the chosen locale by all client software. - -##### JSON Schema - -```json -{ - "title": "Token Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents", - }, - "decimals": { - "type": "integer", - "description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation.", - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents", - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", - }, - "properties": { - "type": "object", - "description": "Arbitrary properties. Values may be strings, numbers, object or arrays.", - }, - "localization": { - "type": "object", - "required": ["uri", "default", "locales"], - "properties": { - "uri": { - "type": "string", - "description": "The URI pattern to fetch localized data from. This URI should contain the substring `{locale}` which will be replaced with the appropriate locale value before sending the request." - }, - "default": { - "type": "string", - "description": "The locale of the default data within the base JSON" - }, - "locales": { - "type": "array", - "description": "The list of locales for which data is available. These locales should conform to those defined in the Unicode Common Locale Data Repository (http://cldr.unicode.org/)." - } - } - }, - } -} -``` - -##### Localized Sample - -Base URI: -```json -{ - "name": "Advertising Space", - "description": "Each token represents a unique Ad space in the city.", - "localization": { - "uri": "ipfs://QmWS1VAdMD353A6SDk9wNyvkT14kyCiZrNDYAad4w1tKqT/{locale}.json", - "default": "en", - "locales": ["en", "es", "fr"] - } -} -``` - -es.json: -```json -{ - "name": "Espacio Publicitario", - "description": "Cada token representa un espacio publicitario único en la ciudad." -} -``` - -fr.json: -```json -{ - "name": "Espace Publicitaire", - "description": "Chaque jeton représente un espace publicitaire unique dans la ville." -} -``` - -### Approval - -The function `setApprovalForAll` allows an operator to manage one's entire set of tokens on behalf of the approver. To permit approval of a subset of token IDs, an interface such as [ERC-1761 Scoped Approval Interface](https://eips.ethereum.org/EIPS/eip-1761) is suggested. -The counterpart `isApprovedForAll` provides introspection into status set by `setApprovalForAll`. - -An owner SHOULD be assumed to always be able to operate on their own tokens regardless of approval status, so should SHOULD NOT have to call `setApprovalForAll` to approve themselves as an operator before they can operate on them. - -## Rationale - -### Metadata Choices - -The `symbol` function (found in the ERC-20 and ERC-721 standards) was not included as we do not believe this is a globally useful piece of data to identify a generic virtual item / asset and are also prone to collisions. Short-hand symbols are used in tickers and currency trading, but they aren't as useful outside of that space. - -The `name` function (for human-readable asset names, on-chain) was removed from the standard to allow the Metadata JSON to be the definitive asset name and reduce duplication of data. This also allows localization for names, which would otherwise be prohibitively expensive if each language string was stored on-chain, not to mention bloating the standard interface. While this decision may add a small burden on implementers to host a JSON file containing metadata, we believe any serious implementation of ERC-1155 will already utilize JSON Metadata. - -### Upgrades - -The requirement to emit `TransferSingle` or `TransferBatch` on balance change implies that a valid implementation of ERC-1155 redeploying to a new contract address MUST emit events from the new contract address to replicate the deprecated contract final state. It is valid to only emit a minimal number of events to reflect only the final balance and omit all the transactions that led to that state. The event emit requirement is to ensure that the current state of the contract can always be traced only through events. To alleviate the need to emit events when changing contract address, consider using the proxy pattern, such as described in ERC-1538. This will also have the added benefit of providing a stable contract address for users. - -### Design decision: Supporting non-batch - -The standard supports `safeTransferFrom` and `onERC1155Received` functions because they are significantly cheaper for single token-type transfers, which is arguably a common use case. - -### Design decision: Safe transfers only - -The standard only supports safe-style transfers, making it possible for receiver contracts to depend on `onERC1155Received` or `onERC1155BatchReceived` function to be always called at the end of a transfer. - -### Guaranteed log trace - -As the Ethereum ecosystem continues to grow, many dapps are relying on traditional databases and explorer API services to retrieve and categorize data. The ERC-1155 standard guarantees that event logs emitted by the smart contract will provide enough data to create an accurate record of all current token balances. A database or explorer may listen to events and be able to provide indexed and categorized searches of every ERC-1155 token in the contract. - -### Approval - -The function `setApprovalForAll` allows an operator to manage one's entire set of tokens on behalf of the approver. It enables frictionless interaction with exchange and trade contracts. - -Restricting approval to a certain set of token IDs, quantities or other rules MAY be done with an additional interface or an external contract. The rationale is to keep the ERC-1155 standard as generic as possible for all use-cases without imposing a specific approval scheme on implementations that may not need it. Standard token approval interfaces can be used, such as the suggested [ERC-1761 Scoped Approval Interface](https://github.com/ethereum/EIPs/issues/1761) which is compatible with ERC-1155. - -## Usage - -This standard can be used to represent multiple token types for an entire domain. Both Fungible and Non-Fungible tokens can be stored in the same smart-contract. - -### Batch Transfers - -The `safeBatchTransferFrom` function allows for batch transfers of multiple token ids and values. The design of ERC-1155 makes batch transfers possible without the need for a wrapper contract, as with existing token standards. This reduces gas costs when more than one token type is included in a batch transfer, as compared to single transfers with multiple transactions. - -Another advantage of standardized batch transfers is the ability for a smart contract to respond to the batch transfer in a single operation using `onERC1155BatchReceived`. - -### Batch Balance - -The `balanceOfBatch` function allows clients to retrieve balances of multiple owners and token ids with a single call. - -### Enumerating from events - -In order to keep storage requirements light for contracts implementing ERC-1155, enumeration (discovering the IDs and values of tokens) must be done using event logs. It is RECOMMENDED that clients such as exchanges and blockchain explorers maintain a local database containing the token ID, Supply, and URI at the minimum. This can be built from each TransferSingle, TransferBatch, and URI event, starting from the block the smart contract was deployed until the latest block. - -ERC-1155 contracts must therefore carefully emit `TransferSingle` or `TransferBatch` events in any instance where tokens are created, minted, or destroyed. - -### Non-Fungible Tokens - -The following strategy is an example of how to mix fungible and non-fungible tokens together in the same contract. The top 128 bits of the uint256 `_id` parameter in any ERC-1155 function could represent the base token ID, while the bottom 128 bits might be used for any extra data passed to the contract. - -Non-Fungible tokens can be interacted with using an index based accessor into the contract/token data set. Therefore to access a particular token set within a mixed data contract and particular NFT within that set, `_id` could be passed as ``. - -Inside the contract code the two pieces of data needed to access the individual NFT can be extracted with uint128(~0) and the same mask shifted by 128. - -### Example of split ID bits - -```solidity -uint256 baseToken = 12345 << 128; -uint128 index = 50; - -balanceOf(baseToken, msg.sender); // Get balance of the base token -balanceOf(baseToken + index, msg.sender); // Get balance of the Non-Fungible token index -``` - -## References - -**Standards** -- [ERC-721 Non-Fungible Token Standard](https://eips.ethereum.org/EIPS/eip-721) -- [ERC-165 Standard Interface Detection](https://eips.ethereum.org/EIPS/eip-165) -- [ERC-1538 Transparent Contract Standard](https://eips.ethereum.org/EIPS/eip-1538) -- [JSON Schema](https://json-schema.org/) -- [RFC 2119 Key words for use in RFCs to Indicate Requirement Levels](https://www.ietf.org/rfc/rfc2119.txt) - -**Implementations** -- [ERC-1155 Reference Implementation](https://github.com/enjin/erc-1155) -- [Horizon Games - Multi-Token Standard](https://github.com/horizon-games/multi-token-standard) -- [Enjin Coin](https://enjincoin.io) ([GitHub](https://github.com/enjin)) -- [The Sandbox - Dual ERC-1155/721 Contract](https://github.com/pixowl/thesandbox-contracts/tree/master/src/Asset) - -**Articles & Discussions** -- [Github - Original Discussion Thread](https://github.com/ethereum/EIPs/issues/1155) -- [ERC-1155 - The Crypto Item Standard](https://blog.enjincoin.io/erc-1155-the-crypto-item-standard-ac9cf1c5a226) -- [Here Be Dragons - Going Beyond ERC-20 and ERC-721 To Reduce Gas Cost by ~80%](https://medium.com/horizongames/going-beyond-erc20-and-erc721-9acebd4ff6ef) -- [Blockonomi - Ethereum ERC-1155 Token Perfect for Online Games, Possibly More](https://blockonomi.com/erc1155-gaming-token/) -- [Beyond Gaming - Exploring the Utility of ERC-1155 Token Standard!](https://blockgeeks.com/erc-1155-token/) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1155.md diff --git a/EIPS/eip-1167.md b/EIPS/eip-1167.md index 30154b6ad146df..c8ce36929836ca 100644 --- a/EIPS/eip-1167.md +++ b/EIPS/eip-1167.md @@ -1,126 +1,7 @@ --- eip: 1167 -title: Minimal Proxy Contract -author: Peter Murray (@yarrumretep), Nate Welch (@flygoing), Joe Messerman (@JAMesserman) -discussions-to: https://github.com/optionality/clone-factory/issues/10 -status: Final -type: Standards Track category: ERC -created: 2018-06-22 -requires: 211 +status: Moved --- - - -## Simple Summary - -To simply and cheaply clone contract functionality in an immutable way, this standard specifies a minimal bytecode implementation that delegates all calls to a known, fixed address. -## Abstract - -By standardizing on a known minimal bytecode redirect implementation, this standard allows users and third party tools (e.g. Etherscan) to (a) simply discover that a contract will always redirect in a known manner and (b) depend on the behavior of the code at the destination contract as the behavior of the redirecting contract. Specifically, tooling can interrogate the bytecode at a redirecting address to determine the location of the code that will run - and can depend on representations about that code (verified source, third-party audits, etc). This implementation forwards all calls and 100% of the gas to the implementation contract and then relays the return value back to the caller. In the case where the implementation reverts, the revert is passed back along with the payload data (for revert with message). - - -## Motivation - -This standard supports use-cases wherein it is desirable to clone exact contract functionality with a minimum of side effects (e.g. memory slot stomping) and with low gas cost deployment of duplicate proxies. - -## Specification - -The exact bytecode of the standard clone contract is this: `363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3` wherein the bytes at indices 10 - 29 (inclusive) are replaced with the 20 byte address of the master functionality contract. - -A reference implementation of this can be found at the [optionality/clone-factory](https://github.com/optionality/clone-factory) github repo. - -## Rationale - -The goals of this effort have been the following: -- inexpensive deployment (low gas to deploy clones) -- support clone initialization in creation transaction (through factory contract model) -- simple clone bytecode to encourage directly bytecode interrogation (see CloneProbe.sol in the clone-factory project) -- dependable, locked-down behavior - this is not designed to handle upgradability, nor should it as the representation we are seeking is stronger. -- small operational overhead - adds a single call cost to each call -- handles error return bubbling for revert messages - -## Backwards Compatibility - -There are no backwards compatibility issues. There may be some systems that are using earlier versions of the proxy contract bytecode. They will not be compliant with this standard. - -## Test Cases - -Test cases include: -- invocation with no arguments -- invocation with arguments -- invocation with fixed length return values -- invocation with variable length return values -- invocation with revert (confirming reverted payload is transferred) - -Tests for these cases are included in the reference implementation project. - -## Implementation - -Deployment bytecode is not included in this specification. One approach is defined in the proxy-contract reference implementation. - -### Standard Proxy -The disassembly of the standard deployed proxy contract code (from r2 and edited to include stack visualization) - -``` -| 0x00000000 36 calldatasize cds -| 0x00000001 3d returndatasize 0 cds -| 0x00000002 3d returndatasize 0 0 cds -| 0x00000003 37 calldatacopy -| 0x00000004 3d returndatasize 0 -| 0x00000005 3d returndatasize 0 0 -| 0x00000006 3d returndatasize 0 0 0 -| 0x00000007 36 calldatasize cds 0 0 0 -| 0x00000008 3d returndatasize 0 cds 0 0 0 -| 0x00000009 73bebebebebe. push20 0xbebebebe 0xbebe 0 cds 0 0 0 -| 0x0000001e 5a gas gas 0xbebe 0 cds 0 0 0 -| 0x0000001f f4 delegatecall suc 0 -| 0x00000020 3d returndatasize rds suc 0 -| 0x00000021 82 dup3 0 rds suc 0 -| 0x00000022 80 dup1 0 0 rds suc 0 -| 0x00000023 3e returndatacopy suc 0 -| 0x00000024 90 swap1 0 suc -| 0x00000025 3d returndatasize rds 0 suc -| 0x00000026 91 swap2 suc 0 rds -| 0x00000027 602b push1 0x2b 0x2b suc 0 rds -| ,=< 0x00000029 57 jumpi 0 rds -| | 0x0000002a fd revert -| `-> 0x0000002b 5b jumpdest 0 rds -\ 0x0000002c f3 return - -``` - -NOTE: as an effort to reduce gas costs as much as possible, the above bytecode depends on EIP-211 specification that `returndatasize` returns zero prior to any calls within the call-frame. `returndatasize` uses 1 less gas than `dup*`. - -### Vanity Address Optimization -Proxy deployment can be further optimized by installing the master contract at a vanity contract deployment address with leading zero-bytes. By generating a master contract vanity address that includes Z leading 0 bytes in its address, you can shorten the proxy bytecode by replacing the `push20` opcode with `pushN` (where N is 20 - Z) followed by the N non-zero address bytes. The revert jump address is decremented by Z in this case. Here is an example where Z = 4: -``` -| 0x00000000 36 calldatasize cds -| 0x00000001 3d returndatasize 0 cds -| 0x00000002 3d returndatasize 0 0 cds -| 0x00000003 37 calldatacopy -| 0x00000004 3d returndatasize 0 -| 0x00000005 3d returndatasize 0 0 -| 0x00000006 3d returndatasize 0 0 0 -| 0x00000007 36 calldatasize cds 0 0 0 -| 0x00000008 3d returndatasize 0 cds 0 0 0 -| 0x00000009 6fbebebebebe. push16 0xbebebebe 0xbebe 0 cds 0 0 0 -| 0x0000001a 5a gas gas 0xbebe 0 cds 0 0 0 -| 0x0000001b f4 delegatecall suc 0 -| 0x0000001c 3d returndatasize rds suc 0 -| 0x0000001d 82 dup3 0 rds suc 0 -| 0x0000001e 80 dup1 0 0 rds suc 0 -| 0x0000001f 3e returndatacopy suc 0 -| 0x00000020 90 swap1 0 suc -| 0x00000021 3d returndatasize rds 0 suc -| 0x00000022 91 swap2 suc 0 rds -| 0x00000023 6027 push1 0x27 0x27 suc 0 rds -| ,=< 0x00000025 57 jumpi 0 rds -| | 0x00000026 fd revert -| `-> 0x00000027 5b jumpdest 0 rds -\ 0x00000028 f3 return -``` -This saves 4 bytes of proxy contract size (savings on each deployment) and has zero impact on runtime gas costs. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1167.md diff --git a/EIPS/eip-1175.md b/EIPS/eip-1175.md index fa8cc102511807..6febb5f659e7d4 100644 --- a/EIPS/eip-1175.md +++ b/EIPS/eip-1175.md @@ -1,533 +1,7 @@ --- eip: 1175 -title: Wallet & shop standard for all tokens (erc20) -author: Jet Lim (@Nitro888) -discussions-to: https://github.com/ethereum/EIPs/issues/1182 -status: Draft -type: Standards Track category: ERC -created: 2018-06-21 -requires: 20 +status: Moved --- -# All tokens go to heaven -## Simple Summary -Make wallets and shops created from certified contracts make erc20 tokens easy to use for commerce. - -![wallet](https://user-images.githubusercontent.com/11692220/41762799-ee17c480-7636-11e8-9930-681be2c59b56.png) - -## Abstract -The mutual trust between the wallet and the shop created by the authenticated contract allows you to pay for and purchase items at a simple process. - -## Motivation -New standards with improvements have been released, but the majority of tokens currently being developed are erc20 tokens. So I felt I needed a proposal to use old tokens in commerce. - To use various erc20 tokens for trading, you need a custom contract. However, a single wallet with a variety of tokens, and a mutually trusted store, can make transactions that are simple and efficient. The erc20 token is traded through two calls, `approve (address _spender, uint256 _value)` and `transferFrom (address _from, address _to, uint256 _value)`, but when using the wallet contract, `paySafe (address _shop, uint256 _item)`will be traded only in one call. -And if you only reuse the store interface, you can also trade using `payUnsafe (address _shop, uint256 _item)`. - -## Specification -![workflow](https://user-images.githubusercontent.com/11692220/41841025-2ed6e024-78a2-11e8-9faf-2b43aeaa2303.png) -## WalletCenter -### Methods -#### createWallet -Create wallet contract and add to list. Returns the address of new wallet. - -``` js -function createWallet() public returns (address _wallet) -``` - -#### isWallet -Returns true or false value for test this address is a created by createWallet. - -``` js -function isWallet(address _wallet) public constant returns (bool) -``` - -#### createShop -Create Shop contract and add to list. Returns the address of new Shop with erc20 token address. - -``` js -function createShop(address _erc20) public returns (address _shop) -``` - -#### isShop -Returns true or false value for test this address is a created by createWallet. - -``` js -function isShop(address _shop) public constant returns (bool) -``` - -### Events -#### Wallet -Search for my wallet. -``` js -event Wallet(address indexed _owner, address indexed _wallet) -``` - -#### Shop -Search for my shop. -``` js -event Shop(address indexed _owner, address indexed _shop, address indexed _erc20) -``` - -## Wallet -Wallet must be created by wallet center. -### Methods -#### balanceOf -Returns the account balance of Wallet. -``` js -function balanceOf(address _erc20) public constant returns (uint256 balance) -``` - -#### withdrawal -withdrawal `_value` amount of `_erc20` token to `_owner`. -``` js -function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) -``` - -#### paySafe -Pay for safe shop (created by contract) item with item index `_item`. -``` js -function paySafe(address _shop, uint256 _item) onlyOwner onlyShop(_shop) public payable returns (bool success) -``` - -#### payUnsafe -Pay for unsafe shop (did not created by contract) item with item index `_item`. -``` js -function payUnsafe(address _shop, uint256 _item) onlyOwner public payable returns (bool success) -``` - -#### payCancel -Cancel pay and refund. (only weekly model) -``` js -function payCancel(address _shop, uint256 _item) onlyOwner public returns (bool success) -``` - -#### refund -Refund from shop with item index `_item`. -``` js -function refund(uint256 _item, uint256 _value) public payable returns (bool success) -``` - -### Events -#### Pay -``` js -event Pay(address indexed _shop, uint256 indexed _item, uint256 indexed _value) -``` - -#### Refund -``` js -event Refund(address indexed _shop, uint256 indexed _item, uint256 indexed _value) -``` - -## Shop -Shop is created by wallet center or not. but Shop that created by wallet center is called safe shop. -### Methods -#### balanceOf -Returns the account balance of Shop. -``` js -function balanceOf(address _erc20) public constant returns (uint256 balance) -``` - -#### withdrawal -withdrawal `_value` amount of `_erc20` token to `_owner`. -``` js -function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) -``` - -#### pay -Pay from buyer with item index `_item`. -``` js -function pay(uint256 _item) onlyWallet(msg.sender) public payable returns (bool success) -``` - -#### refund -refund token to `_to`. -``` js -function refund(address _buyer, uint256 _item, uint256 _value) onlyWallet(_buyer) onlyOwner public payable returns (bool success) -``` - -#### resister -Listing item for sell. -``` js -function resister(uint8 _category, uint256 _price, uint256 _stock) onlyOwner public returns (uint256 _itemId) -``` - -#### update -Update item state for sell. (change item `_price` or add item `_stock`) -``` js -function update(uint256 _item, uint256 _price, uint256 _stock) onlyOwner public -``` - -#### price -Get token address and price from buyer with item index `_item`. -``` js -function price(uint256 _item) public constant returns (address _erc20, uint256 _value) -``` - -#### canBuy -`_who` can Buy `_item`. -``` js -function canBuy(address _who, uint256 _item) public constant returns (bool _canBuy) -``` - -#### isBuyer -`_who` is buyer of `_item`. -``` js -function isBuyer(address _who, uint256 _item) public constant returns (bool _buyer) -``` - -#### info -Set shop information bytes. -``` js -function info(bytes _msgPack) -``` - -#### upVote -Up vote for this shop. -``` js -function upVote() -``` - -#### dnVote -Down vote for this shop. -``` js -function dnVote() -``` - -#### about -Get shop token, up vote and down vote. -``` js -function about() view returns (address _erc20, uint256 _up, uint256 _down) -``` - -#### infoItem -Set item information bytes. -``` js -function infoItem(uint256 _item, bytes _msgPack) -``` - -#### upVoteItem -Up vote for this item. -``` js -function upVoteItem(uint256 _item) -``` - -#### dnVoteItem -Down vote for this item. -``` js -function dnVoteItem(uint256 _item) -``` - -#### aboutItem -Get Item price, up vote and down vote. -``` js -function aboutItem(uint256 _item) view returns (uint256 _price, uint256 _up, uint256 _down) -``` - -### Events -#### Pay -``` js -event Pay(address indexed _buyer, uint256 indexed _item, uint256 indexed _value) -``` - -#### Refund -``` js -event Refund(address indexed _to, uint256 indexed _item, uint256 indexed _value) -``` - -#### Item -``` js -event Item(uint256 indexed _item, uint256 _price) -``` - -#### Info -``` js -event Info(bytes _msgPack) -``` - -#### InfoItem -``` js -event InfoItem(uint256 indexed _item, bytes _msgPack) -``` - -## Implementation -Sample token contract address is [0x393dd70ce2ae7b30501aec94727968c517f90d52](https://ropsten.etherscan.io/address/0x393dd70ce2ae7b30501aec94727968c517f90d52) - -WalletCenter contract address is [0x1fe0862a4a8287d6c23904d61f02507b5044ea31](https://ropsten.etherscan.io/address/0x1fe0862a4a8287d6c23904d61f02507b5044ea31) - -WalletCenter create shop contract address is [0x59117730D02Ca3796121b7975796d479A5Fe54B0](https://ropsten.etherscan.io/address/0x59117730D02Ca3796121b7975796d479A5Fe54B0) - -WalletCenter create wallet contract address is [0x39da7111844df424e1d0a0226183533dd07bc5c6](https://ropsten.etherscan.io/address/0x39da7111844df424e1d0a0226183533dd07bc5c6) - - -## Appendix -``` js -pragma solidity ^0.4.24; - -contract ERC20Interface { - function totalSupply() public constant returns (uint); - function balanceOf(address tokenOwner) public constant returns (uint balance); - function allowance(address tokenOwner, address spender) public constant returns (uint remaining); - function transfer(address to, uint tokens) public returns (bool success); - function approve(address spender, uint tokens) public returns (bool success); - function transferFrom(address from, address to, uint tokens) public returns (bool success); - - event Transfer(address indexed from, address indexed to, uint tokens); - event Approval(address indexed tokenOwner, address indexed spender, uint tokens); -} - -contract SafeMath { - function safeAdd(uint a, uint b) public pure returns (uint c) { - c = a + b; - require(c >= a); - } - function safeSub(uint a, uint b) public pure returns (uint c) { - require(b <= a); - c = a - b; - } - function safeMul(uint a, uint b) public pure returns (uint c) { - c = a * b; - require(a == 0 || c / a == b); - } - function safeDiv(uint a, uint b) public pure returns (uint c) { - require(b > 0); - c = a / b; - } -} - -contract _Base { - address internal owner; - address internal walletCenter; - - modifier onlyOwner { - require(owner == msg.sender); - _; - } - modifier onlyWallet(address _addr) { - require(WalletCenter(walletCenter).isWallet(_addr)); - _; - } - modifier onlyShop(address _addr) { - require(WalletCenter(walletCenter).isShop(_addr)); - _; - } - - function balanceOf(address _erc20) public constant returns (uint256 balance) { - if(_erc20==address(0)) - return address(this).balance; - return ERC20Interface(_erc20).balanceOf(this); - } - - function transfer(address _to, address _erc20, uint256 _value) internal returns (bool success) { - require((_erc20==address(0)?address(this).balance:ERC20Interface(_erc20).balanceOf(this))>=_value); - if(_erc20==address(0)) - _to.transfer(_value); - else - ERC20Interface(_erc20).approve(_to,_value); - return true; - } - - function withdrawal(address _erc20, uint256 _value) public returns (bool success); - - event Pay(address indexed _who, uint256 indexed _item, uint256 indexed _value); - event Refund(address indexed _who, uint256 indexed _item, uint256 indexed _value); - event Prize(address indexed _who, uint256 indexed _item, uint256 indexed _value); -} - -contract _Wallet is _Base { - constructor(address _who) public { - owner = _who; - walletCenter = msg.sender; - } - - function pay(address _shop, uint256 _item) private { - require(_Shop(_shop).canBuy(this,_item)); - - address _erc20; - uint256 _value; - (_erc20,_value) = _Shop(_shop).price(_item); - - transfer(_shop,_erc20,_value); - _Shop(_shop).pay(_item); - emit Pay(_shop,_item,_value); - } - - function paySafe(address _shop, uint256 _item) onlyOwner onlyShop(_shop) public payable returns (bool success) { - pay(_shop,_item); - return true; - } - function payUnsafe(address _shop, uint256 _item) onlyOwner public payable returns (bool success) { - pay(_shop,_item); - return true; - } - function payCancel(address _shop, uint256 _item) onlyOwner public returns (bool success) { - _Shop(_shop).payCancel(_item); - return true; - } - - function refund(address _erc20, uint256 _item, uint256 _value) public payable returns (bool success) { - require((_erc20==address(0)?msg.value:ERC20Interface(_erc20).allowance(msg.sender,this))==_value); - if(_erc20!=address(0)) - ERC20Interface(_erc20).transferFrom(msg.sender,this,_value); - emit Refund(msg.sender,_item,_value); - return true; - } - function prize(address _erc20, uint256 _item, uint256 _value) public payable returns (bool success) { - require((_erc20==address(0)?msg.value:ERC20Interface(_erc20).allowance(msg.sender,this))==_value); - if(_erc20!=address(0)) - ERC20Interface(_erc20).transferFrom(msg.sender,this,_value); - emit Prize(msg.sender,_item,_value); - return true; - } - - function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) { - require((_erc20==address(0)?address(this).balance:ERC20Interface(_erc20).balanceOf(this))>=_value); - if(_erc20==address(0)) - owner.transfer(_value); - else - ERC20Interface(_erc20).transfer(owner,_value); - return true; - } -} - -contract _Shop is _Base, SafeMath{ - address erc20; - constructor(address _who, address _erc20) public { - owner = _who; - walletCenter = msg.sender; - erc20 = _erc20; - } - - struct item { - uint8 category; // 0 = disable, 1 = non Stock, non Expire, 2 = can Expire (after 1 week), 3 = stackable - uint256 price; - uint256 stockCount; - - mapping(address=>uint256) customer; - } - - uint index; - mapping(uint256=>item) items; - - function pay(uint256 _item) onlyWallet(msg.sender) public payable returns (bool success) { - require(canBuy(msg.sender, _item)); - require((erc20==address(0)?msg.value:ERC20Interface(erc20).allowance(msg.sender,this))==items[_item].price); - - if(erc20!=address(0)) - ERC20Interface(erc20).transferFrom(msg.sender,this,items[_item].price); - - if(items[_item].category==1 || items[_item].category==2 && now > safeAdd(items[_item].customer[msg.sender], 1 weeks)) - items[_item].customer[msg.sender] = now; - else if(items[_item].category==2 && now < safeAdd(items[_item].customer[msg.sender], 1 weeks) ) - items[_item].customer[msg.sender] = safeAdd(items[_item].customer[msg.sender], 1 weeks); - else if(items[_item].category==3) { - items[_item].customer[msg.sender] = safeAdd(items[_item].customer[msg.sender],1); - items[_item].stockCount = safeSub(items[_item].stockCount,1); - } - - emit Pay(msg.sender,_item,items[_item].customer[msg.sender]); - return true; - } - - function payCancel(uint256 _item) onlyWallet(msg.sender) public returns (bool success) { - require (items[_item].category==2&&safeAdd(items[_item].customer[msg.sender],2 weeks)>now&&balanceOf(erc20)>=items[_item].price); - - items[_item].customer[msg.sender] = safeSub(items[_item].customer[msg.sender],1 weeks); - transfer(msg.sender, erc20, items[_item].price); - _Wallet(msg.sender).refund(erc20,_item,items[_item].price); - emit Refund(msg.sender,_item,items[_item].price); - - return true; - } - function refund(address _to, uint256 _item) onlyWallet(_to) onlyOwner public payable returns (bool success) { - require(isBuyer(_to,_item)&&items[_item].category>0&&(items[_item].customer[_to]>0||(items[_item].category==2&&safeAdd(items[_item].customer[_to],2 weeks)>now))); - require((erc20==address(0)?address(this).balance:ERC20Interface(erc20).balanceOf(this))>=items[_item].price); - - if(items[_item].category==1) - items[_item].customer[_to] = 0; - else if(items[_item].category==2) - items[_item].customer[_to] = safeSub(items[_item].customer[_to],1 weeks); - else - items[_item].customer[_to] = safeSub(items[_item].customer[_to],1); - - transfer(_to, erc20, items[_item].price); - _Wallet(_to).refund(erc20,_item,items[_item].price); - emit Refund(_to,_item,items[_item].price); - - return true; - } - - event Item(uint256 indexed _item, uint256 _price); - function resister(uint8 _category, uint256 _price, uint256 _stock) onlyOwner public returns (uint256 _itemId) { - require(_category>0&&_category<4); - require(_price>0); - items[index] = item(_category,_price,_stock); - index = safeAdd(index,1); - emit Item(index,_price); - return safeSub(index,1); - } - function update(uint256 _item, uint256 _price, uint256 _stock) onlyOwner public { - require(items[_item].category>0); - require(_price>0); - uint256 temp = items[_item].price; - items[_item].price = _price; - items[_item].stockCount = safeAdd(items[_item].stockCount,_stock); - - if(temp!=items[_item].price) - emit Item(index,items[_item].price); - } - - function price(uint256 _item) public constant returns (address _erc20, uint256 _value) { - return (erc20,items[_item].price); - } - - function canBuy(address _who, uint256 _item) public constant returns (bool _canBuy) { - return (items[_item].category>0) && - !(items[_item].category==1&&items[_item].customer[_who]>0) && - (items[_item].stockCount>0); - } - - function isBuyer(address _who, uint256 _item) public constant returns (bool _buyer) { - return (items[_item].category==1&&items[_item].customer[_who]>0)||(items[_item].category==2&&safeAdd(items[_item].customer[_who],1 weeks)>now)||(items[_item].category==3&&items[_item].customer[_who]>0); - } - - uint lastWithdrawal; - function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) { - require(safeAdd(lastWithdrawal,1 weeks)<=now); - require((_erc20==address(0)?address(this).balance:ERC20Interface(_erc20).balanceOf(this))>=_value); - if(_erc20==address(0)) - owner.transfer(_value); - else - ERC20Interface(_erc20).transfer(owner,_value); - lastWithdrawal = now; - return true; - } -} - -contract WalletCenter { - mapping(address=>bool) public wallet; - event Wallet(address indexed _owner, address indexed _wallet); - function createWallet() public returns (address _wallet) { - _wallet = new _Wallet(msg.sender); - wallet[_wallet] = true; - emit Wallet(msg.sender,_wallet); - return _wallet; - } - function isWallet(address _wallet) public constant returns (bool) { - return wallet[_wallet]; - } - mapping(address=>bool) public shop; - event Shop(address indexed _owner, address indexed _shop, address indexed _erc20); - function createShop(address _erc20) public returns (address _shop) { - _shop = new _Shop(msg.sender,_erc20); - shop[_shop] = true; - emit Shop(msg.sender,_shop,_erc20); - return _shop; - } - function isShop(address _shop) public constant returns (bool) { - return shop[_shop]; - } -} -``` -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1175.md diff --git a/EIPS/eip-1178.md b/EIPS/eip-1178.md index 017feebaa10548..ce8fc9b21156bc 100644 --- a/EIPS/eip-1178.md +++ b/EIPS/eip-1178.md @@ -1,164 +1,7 @@ --- eip: 1178 -title: Multi-class Token Standard -author: Albert Chon -discussions-to: https://github.com/ethereum/EIPs/issues/1179 -status: Draft -type: Standards Track category: ERC -created: 2018-06-22 +status: Moved --- - - -## Simple Summary - -A standard interface for multi-class fungible tokens. -## Abstract - -This standard allows for the implementation of a standard API for multi-class fungible tokens (henceforth referred to as "MCFTs") within smart contracts. This standard provides basic functionality to track and transfer ownership of MCFTs. -## Motivation - -Currently, there is no standard to support tokens that have multiple classes. In the real world, there are many situations in which defining distinct classes of the same token would be fitting (e.g. distinguishing between preferred/common/restricted shares of a company). Yet, such nuance cannot be supported in today's token standards. An ERC-20 token contract defines tokens that are all of one class while an ERC-721 token contract creates a class (defined by token_id) for each individual token. The ERC-1178 token standard proposes a new standard for creating multiple classes of tokens within one token contract. - -> Aside: In theory, while it is possible to implement tokens with classes using the properties of token structs in ERC-721 tokens, gas costs of implementing this in practice are prohibitive for any non-trivial application. - -## Specification -### ERC-20 Compatibility (partial) -**name** - -```solidity -function name() constant returns (string name) -``` - -*OPTIONAL - It is recommended that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.* - -Returns the name of the aggregate collection of MCFTs managed by this contract. - e.g. `"My Company Tokens"`. - -**class name** - -```solidity -function className(uint256 classId) constant returns (string name) -``` - -*OPTIONAL - It is recommended that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.* - -Returns the name of the class of MCFT managed by this contract. - e.g. `"My Company Preferred Shares Token"`. - -**symbol** -```solidity -function symbol() constant returns (string symbol) -``` - -*OPTIONAL - It is recommend that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.* - -Returns a short string symbol referencing the entire collection of MCFT managed in this contract. e.g. "MUL". This symbol SHOULD be short (3-8 characters is recommended), with no whitespace characters or new-lines and SHOULD be limited to the uppercase latin alphabet (i.e. the 26 letters used in English). - -**totalSupply** -```solidity -function totalSupply() constant returns (uint256 totalSupply) -``` -Returns the total number of all MCFTs currently tracked by this contract. - -**individualSupply** -```solidity -function individualSupply(uint256 _classId) constant returns (uint256 individualSupply) -``` -Returns the total number of MCFTs of class `_classId` currently tracked by this contract. - -**balanceOf** -```solidity -function balanceOf(address _owner, uint256 _classId) constant returns (uint256 balance) -``` - -Returns the number of MCFTs of token class `_classId` assigned to address `_owner`. - -**classesOwned** -```solidity -function classesOwned(address _owner) constant returns (uint256[] classes) -``` - -Returns an array of `_classId`'s of MCFTs that address `_owner` owns in the contract. -> NOTE: returning an array is supported by `pragma experimental ABIEncoderV2` - -## Basic Ownership - -**approve** -```solidity -function approve(address _to, uint256 _classId, uint256 quantity) -``` -Grants approval for address `_to` to take possession `quantity` amount of the MCFT with ID `_classId`. This method MUST `throw` if `balanceOf(msg.sender, _classId) < quantity`, or if `_classId` does not represent an MCFT class currently tracked by this contract, or if `msg.sender == _to`. - -Only one address can "have approval" at any given time for a given address and `_classId`. Calling `approve` with a new address and `_classId` revokes approval for the previous address and `_classId`. Calling this method with 0 as the `_to` argument clears approval for any address and the specified `_classId`. - -Successful completion of this method MUST emit an `Approval` event (defined below) unless the caller is attempting to clear approval when there is no pending approval. In particular, an Approval event MUST be fired if the `_to` address is zero and there is some outstanding approval. Additionally, an Approval event MUST be fired if `_to` is already the currently approved address and this call otherwise has no effect. (i.e. An `approve()` call that "reaffirms" an existing approval MUST fire an event.) - - - -**transfer** -```solidity -function transfer(address _to, uint256 _classId, uint256 quantity) -``` -Assigns the ownership of `quantity` MCFT's with ID `_classId` to `_to` if and only if `quantity == balanceOf(msg.sender, _classId)`. A successful transfer MUST fire the `Transfer` event (defined below). - -This method MUST transfer ownership to `_to` or `throw`, no other outcomes can be possible. Reasons for failure include (but are not limited to): - -* `msg.sender` is not the owner of `quantity` amount of tokens of `_classId`'s. -* `_classId` does not represent an MCFT class currently tracked by this contract - -A conforming contract MUST allow the current owner to "transfer" a token to themselves, as a way of affirming ownership in the event stream. (i.e. it is valid for `_to == msg.sender` if `balanceOf(msg.sender, _classId) >= balance`.) This "no-op transfer" MUST be considered a successful transfer, and therefore MUST fire a `Transfer` event (with the same address for `_from` and `_to`). - -## Advanced Ownership and Exchange -```solidity -function approveForToken(uint256 classIdHeld, uint256 quantityHeld, uint256 classIdWanted, uint256 quantityWanted) -``` -Allows holder of one token to allow another individual (or the smart contract itself) to approve the exchange of their tokens of one class for tokens of another class at their specified exchange rate (see sample implementation for more details). This is equivalent to posting a bid in a marketplace. - -```solidity -function exchange(address to, uint256 classIdPosted, uint256 quantityPosted, uint256 classIdWanted, uint256 quantityWanted) -``` -Allows an individual to fill an existing bid (see above function) and complete the exchange of their tokens of one class for another. In the sample implementation, this function call should fail unless the callee has already approved the contract to transfer their tokens. Of course, it is possible to create an implementation where calling this function implicitly assumes approval and the transfer is completed in one step. - -```solidity -transferFrom(address from, address to, uint256 classId) -``` -Allows a third party to initiate a transfer of tokens from `from` to `to` assuming the approvals have been granted. - -## Events -**Transfer** - -This event MUST trigger when MCFT ownership is transferred via any mechanism. - -Additionally, the creation of new MCFTs MUST trigger a Transfer event for each newly created MCFTs, with a `_from` address of 0 and a `_to` address matching the owner of the new MCFT (possibly the smart contract itself). The deletion (or burn) of any MCFT MUST trigger a Transfer event with a `_to` address of 0 and a `_from` address of the owner of the MCFT (now former owner!). - -NOTE: A Transfer event with `_from == _to` is valid. See the `transfer()` documentation for details. - -```solidity -event Transfer(address indexed _from, address indexed _to, uint256 _classId) -``` - -**Approval** -This event MUST trigger on any successful call to `approve(_to, _classId, quantity)` (unless the caller is attempting to clear approval when there is no pending approval). - -```solidity -event Approval(address indexed _owner, address indexed _approved, uint256 _classId) -``` -## Rationale - -### Current Limitations -The design of this project was motivated when I tried to create different classes of fungible ERC-721 tokens (an oxymoron) but ran into gas limits from having to create each tokens individually and maintain them in an efficient data structure for access. Using the maximum gas amount one can send with a transaction on Metamask (a popular web wallet), I was only able to create around 46 ERC-721 tokens before exhausting all gas. This experience motivated the creation of the multi-class fungible token standard. - - -## Backwards Compatibility - -Adoption of the MCFT standard proposal would not pose backwards compatibility issues as it defines a new standard for token creation. This standard follows the semantics of ERC-721 as closely as possible, but can't be entirely compatible with it due to the fundamental differences between multi-class fungible and non-fungible tokens. For example, the `ownerOf`, `takeOwnership`, and `tokenOfOwnerByIndex` methods in the ERC-721 token standard cannot be implemented in this standard. Furthermore, the function arguments to `balanceOf`, `approve`, and `transfer` differ as well. - -## Implementation - -A sample implementation can be found [here](https://github.com/achon22/ERC-1178/blob/master/erc1178-sample.sol) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1178.md diff --git a/EIPS/eip-1185.md b/EIPS/eip-1185.md index 9d8bf26b954f6f..eecb70b6494360 100644 --- a/EIPS/eip-1185.md +++ b/EIPS/eip-1185.md @@ -1,80 +1,7 @@ --- eip: 1185 -title: Storage of DNS Records in ENS -author: Jim McDonald -status: Draft -type: Standards Track category: ERC -created: 2018-06-26 -requires: 137 -discussions-to: https://ethereum-magicians.org/t/eip1185-dns-resolver-profile-for-ens/1589 +status: Moved --- - -## Abstract -This EIP defines a resolver profile for ENS that provides features for storage and lookup of DNS records. This allows ENS to be used as a store of authoritative DNS information. -## Motivation -ENS is a highly desirable store for DNS information. It provides the distributed authority of DNS without conflating ownership and authoritative serving of information. With ENS, the owner of a domain has full control over their own DNS records. Also, ENS has the ability (through smart contracts) for a domain's subdomains to be irrevocably assigned to another entity. - -## Specification - -The resolver profile to support DNS on ENS follows the resolver specification as defined in #137. - -Traditionally, DNS is a zone-based system in that all of the records for a zone are kept together in the same file. This has the benefit of simplicity and atomicity of zone updates, but when transposed to ENS can result in significant gas costs for simple changes. As a result, the resolver works on the basis of record sets. A record set is uniquely defined by the tuple (domain, name, resource record type), for example the tuple (example.com, www.example.com, A) defines the record set of A records for the name www.example.com in the domain example.com. A record set can contain 0 or more values, for example if www.example.com has A records 1.2.3.4 and 5.6.7.8 then the aforementioned tuple will have two values. - -The choice to work at the level of record sets rather than zones means that this specification cannot completely support some features of DNS, such as zone transfers and DNSSEC. It would be possible to build a different resolver profile that works at the zone level, however it would be very expensive to carry out updates and so is not considered further for this EIP. - -The DNS resolver interface consists of two functions to set DNS information and two functions to query DNS information. - -### setDNSRecords(bytes32 node, bytes data) - -`setDNSRecords()` sets, updates or clears 1 or more DNS records for a given node. It has function signature `0x0af179d7`. - -The arguments for the function are as follows: - - node: the namehash of the fully-qualified domain in ENS for which to set the records. Namehashes are defined in #137 - - data: 1 or more DNS records in DNS wire format. Any record that is supplied without a value will be cleared. Note that all records in the same RRset should be contiguous within the data; if not then the later RRsets will overwrite the earlier one(s) - -### clearDNSZone(bytes32 node) - -`clearDNSZone()` removes all DNS records for the domain. It has function signature `0xad5780af`. - -Although it is possible to clear records individually with `setDNSRecords()` as described above this requires the owner to know all of the records that have been set (as the resolver has no methods to iterate over the records for a given domain), and might require multiple transactions. `clearDNSZone()` removes all zone information in a single operation. - -The arguments for the function is as follows: - - node: the namehash of the fully-qualified domain in ENS for which to clear the records. Namehashes are defined in #137 - -### dnsRecords(bytes32 node, bytes32 name, uint16 resource) view returns (bytes) - -`dnsRecords()` obtains the DNS records for a given node, name and resource. It has function signature `0x2461e851`. - -The arguments for the function are as follows: - - node: the namehash of the fully-qualified domain in ENS for which to set the records. Namehashes are defined in #137 - - name: the `keccak256()` hash of the name of the record in DNS wire format. - - resource: the resource record ID. Resource record IDs are defined in https://en.wikipedia.org/wiki/List\_of\_DNS\_record\_types - -The function returns all matching records in DNS wire format. If there are no records present the function will return nothing. - -### hasDNSRecords(bytes32 node, bytes32 name) view returns (bool) - -`hasDNSRecords()` reports if there are any records for the provided name in the domain. It has function signature `0x4cbf6ba4`. - -This function is needed by DNS resolvers when working with wildcard resources as defined in https://tools.ietf.org/html/rfc4592 - -The arguments for the function are as follows: - - node: the namehash of the fully-qualified domain in ENS for which to set the records. Namehashes are defined in #137 - - name: the `keccak256()` hash of the name of the record in DNS wire format. - -The function returns `true` if there are any records for the provided node and name, otherwise `false`. - -## Backwards compatibility -Not applicable. - -## Implementation -The reference implementation of the DNS resolver is at https://github.com/wealdtech/wealdtech-solidity/blob/master/contracts/ens/DNSResolver.sol - -https://github.com/wealdtech/ethereal.git can be used to test the functionality of the resolver with the "dns set", "dns get" and "dns clear" commands. -## Test Cases -Test cases for the DNS resolver are at https://github.com/wealdtech/wealdtech-solidity/blob/master/test/ens/DNSResolver.js - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1185.md diff --git a/EIPS/eip-1186.md b/EIPS/eip-1186.md index 84f7442d016222..1a341c3f9b8094 100644 --- a/EIPS/eip-1186.md +++ b/EIPS/eip-1186.md @@ -1,31 +1,26 @@ --- eip: 1186 -title: RPC-Method to get Merkle Proofs - eth_getProof +title: RPC-Method to get Merkle Proofs - eth_getProof author: Simon Jentzsch , Christoph Jentzsch discussions-to: https://github.com/ethereum/EIPs/issues/1186 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2018-06-24 +requires: 1474 --- - - ## Simple Summary - One of the great features of Ethereum is the fact, that you can verify all data of the state. But in order to allow verification of accounts outside the client, we need an additional function delivering us the required proof. These proofs are important to secure Layer2-Technologies. - ## Abstract - -Ethereum uses a [Merkle Tree](https://github.com/ethereum/wiki/wiki/Patricia-Tree) to store the state of accounts and their storage. This allows verification of each value by simply creating a Merkle Proof. But currently, the standard RPC-Interface does not give you access to these proofs. This EIP suggests an additional RPC-Method, which creates Merkle Proofs for Accounts and Storage Values. +Ethereum uses a [Merkle Tree](https://github.com/ethereum/eth-wiki/blob/master/fundamentals/patricia-tree.md) to store the state of accounts and their storage. This allows verification of each value by simply creating a Merkle Proof. But currently, the standard RPC-Interface does not give you access to these proofs. This EIP suggests an additional RPC-Method, which creates Merkle Proofs for Accounts and Storage Values. Combined with a stateRoot (from the blockheader) it enables offline verification of any account or storage-value. This allows especially IOT-Devices or even mobile apps which are not able to run a light client to verify responses from an untrusted source only given a trusted blockhash. ## Motivation - In order to create a MerkleProof access to the full state db is required. The current RPC-Methods allow an application to access single values (`eth_getBalance`,`eth_getTransactionCount`,`eth_getStorageAt`,`eth_getCode`), but it is impossible to read the data needed for a MerkleProof through the standard RPC-Interface. (There are implementations using leveldb and accessing the data via filesystems, but this can not be used for production systems since it requires the client to be stopped first - See https://github.com/zmitton/eth-proof) @@ -35,7 +30,6 @@ Offering these already existing function through the RPC-Interface as well would ## Specification - As Part of the eth-Module, an additional Method called `eth_getProof` should be defined as follows: @@ -58,7 +52,7 @@ Returns the account- and storage-values of the specified account including the M - `nonce`: `QUANTITY`, - nonce of the account. See [`eth_getTransactionCount`](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactioncount) - `storageHash`: `DATA`, 32 Bytes - SHA3 of the StorageRoot. All storage will deliver a MerkleProof starting with this rootHash. - `accountProof`: `ARRAY` - Array of rlp-serialized MerkleTree-Nodes, starting with the stateRoot-Node, following the path of the SHA3 (address) as key. - - `storageProof`: `ARRAY` - Array of storage-entries as requested. Each entry is a object with these properties: + - `storageProof`: `ARRAY` - Array of storage-entries as requested. Each entry is an object with these properties: - `key`: `QUANTITY` - the requested storage key - `value`: `QUANTITY` - the storage value @@ -114,7 +108,6 @@ The result will look like this: ``` ## Rationale - This one Method actually returns 3 different important data points: @@ -134,22 +127,12 @@ In case an address or storage-value does not exist, the proof needs to provide e - in order to reduce data, the account-object may only provide the `accountProof` and `storageProof`. The Fields `balance`, `nonce`, `storageHash` and `codeHash` could be taken from the last Node in the proof by deserializing it. ## Backwards Compatibility - Since this only adds a new Method there are no issues with Backwards Compatibility. ## Test Cases - - -Tests still need to be implemented, but the core function creating the proof already exists inside the clients and are well tested. - -## Implementation - - -We implemented this function for: -- [x] [parity](https://github.com/paritytech/parity/pull/9001) (Status: pending pull request) - [Docker](https://hub.docker.com/r/slockit/parity-in3/tags/) -- [x] [geth](https://github.com/ethereum/go-ethereum/pull/17737) (Status: pending pull request) - [Docker](https://hub.docker.com/r/slockit/geth-in3/tags/) +TODO: Tests still need to be implemented, but the core function creating the proof already exists inside the clients and are well tested. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1191.md b/EIPS/eip-1191.md index 7b0149fe6d3789..9927c0a32159b5 100644 --- a/EIPS/eip-1191.md +++ b/EIPS/eip-1191.md @@ -1,97 +1,7 @@ --- -eip: 1191 -title: Add chain id to mixed-case checksum address encoding -author: Juliano Rizzo (@juli) -status: Draft -type: Standards Track +eip: 1191 category: ERC -created: 2018-03-18 -requires: 55, 155 -discussions-to: https://github.com/ethereum/EIPs/issues/1121 +status: Moved --- -## Simple Summary -This EIP extends EIP-55 by optionally adding a chain id defined by EIP-155 to the checksum calculation. -## Specification -Convert the address using the same algorithm defined by EIP-55 but if a registered chain id is provided, add it to the input of the hash function. If the chain id passed to the function belongs to a network that opted for using this checksum variant, prefix the address with the chain id and the `0x` separator before calculating the hash. Then convert the address to hexadecimal, but if the ith digit is a letter (ie. it's one of `abcdef`) print it in uppercase if the 4*ith bit of the calculated hash is 1 otherwise print it in lowercase. - -## Rationale - Benefits: - - By means of a minimal code change on existing libraries, users are protected from losing funds by mixing addresses of different Ethereum based networks. -## Backwards Compatibility -This proposal is fully backward compatible. The checksum calculation is changed only for new networks that choose to adopt this EIP and add their chain numbers to the Adoption Table included in this document. - -## Implementation -```python -#!/usr/bin/python3 -from sha3 import keccak_256 -import random -""" - addr (str): Hexadecimal address, 40 characters long with 2 characters prefix - chainid (int): chain id from EIP-155 """ -def eth_checksum_encode(addr, chainid=1): - adopted_eip1191 = [30, 31] - hash_input = str(chainid) + addr.lower() if chainid in adopted_eip1191 else addr[2:].lower() - hash_output = keccak_256(hash_input.encode('utf8')).hexdigest() - aggregate = zip(addr[2:].lower(),hash_output) - out = addr[:2] + ''.join([c.upper() if int(a,16) >= 8 else c for c,a in aggregate]) - return out -``` -## Test Cases -```python -eth_mainnet= [ -'0x88021160C5C792225E4E5452585947470010289D', -'0x27b1fdb04752bbc536007a920d24acb045561c26', -'0x52908400098527886E0F7030069857D2E4169EE7', -'0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed', -'0x8617E340B3D01FA5F11F306F4090FD50E238070D', -'0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb', -'0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB', -'0xde709f2102306220921060314715629080e2fb77', -'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359', -] -rsk_mainnet = [ -'0x6549F4939460DE12611948B3F82B88C3C8975323', -'0x27b1FdB04752BBc536007A920D24ACB045561c26', -'0x3599689E6292B81B2D85451025146515070129Bb', -'0x52908400098527886E0F7030069857D2E4169ee7', -'0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD', -'0x8617E340b3D01Fa5f11f306f4090fd50E238070D', -'0xD1220A0Cf47c7B9BE7a2e6ba89F429762E7B9adB', -'0xDBF03B407c01E7CD3cBea99509D93F8Dddc8C6FB', -'0xDe709F2102306220921060314715629080e2FB77', -'0xFb6916095cA1Df60bb79ce92cE3EA74c37c5d359', -] -rsk_testnet= [ -'0x42712D45473476B98452F434E72461577D686318', -'0x27B1FdB04752BbC536007a920D24acB045561C26', -'0x3599689e6292b81b2D85451025146515070129Bb', -'0x52908400098527886E0F7030069857D2e4169EE7', -'0x5aAeb6053F3e94c9b9A09F33669435E7EF1BEaEd', -'0x66f9664F97F2b50f62d13eA064982F936DE76657', -'0x8617e340b3D01fa5F11f306F4090Fd50e238070d', -'0xDE709F2102306220921060314715629080e2Fb77', -'0xFb6916095CA1dF60bb79CE92ce3Ea74C37c5D359', -'0xd1220a0CF47c7B9Be7A2E6Ba89f429762E7b9adB', -'0xdbF03B407C01E7cd3cbEa99509D93f8dDDc8C6fB', -] -test_cases = {30 : rsk_mainnet, 31 : rsk_testnet, 1 : eth_mainnet} - -for chainid, cases in test_cases.items(): - for addr in cases: - assert ( addr == eth_checksum_encode(addr,chainid) ) -``` -## Adoption -### Adoption Table -| Network | Chain id | Supports this EIP | -|--------------|----------|-------------------| -| RSK Mainnet | 30 | Yes | -| RSK Testnet | 31 | Yes | - -### Implementation Table -| Wallet | Adopted this EIP | Implementation | -|----------------|------------------| -------------- | -| MyCrypto | Yes | [JavaScript](https://github.com/MyCryptoHQ/MyCrypto/blob/develop/common/utils/formatters.ts#L126) | -| MyEtherWallet | Yes | [JavaScript](https://github.com/MyEtherWallet/MyEtherWallet/blob/73c4a24f8f67c655749ac990c5b62efd92a2b11a/src/helpers/addressUtils.js#L22) | -| Ledger | Yes | [C](https://github.com/LedgerHQ/ledger-app-eth/blob/master/src_common/ethUtils.c#L203) | -| Trezor | Yes | [Python](https://github.com/trezor/trezor-core/blob/270bf732121d004a4cd1ab129adaccf7346ff1db/src/apps/ethereum/get_address.py#L32) and [C](https://github.com/trezor/trezor-crypto/blob/4153e662b60a0d83c1be15150f18483a37e9092c/address.c#L62) | +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1191.md diff --git a/EIPS/eip-1193.md b/EIPS/eip-1193.md index 7398f75db8804c..ea5377a8956e5d 100644 --- a/EIPS/eip-1193.md +++ b/EIPS/eip-1193.md @@ -1,210 +1,524 @@ --- eip: 1193 title: Ethereum Provider JavaScript API -author: Fabian Vogelsteller (@frozeman), Ryan Ghods (@ryanio), Marc Garreau (@marcgarreau), Victor Maia (@MaiaVictor) -discussions-to: https://ethereum-magicians.org/t/eip-1193-ethereum-provider-javascript-api/640 -status: Draft +author: Fabian Vogelsteller (@frozeman), Ryan Ghods (@ryanio), Victor Maia (@MaiaVictor), Marc Garreau (@wolovim), Erik Marks (@rekmarks) +discussions-to: https://github.com/ethereum/EIPs/issues/2319 +status: Final type: Standards Track category: Interface created: 2018-06-30 +requires: 155, 695 --- ## Summary -This EIP formalizes an Ethereum Provider JavaScript API for consistency across clients and applications. The provider is designed to be minimal and is intended to be available on `window.ethereum` for cross environment compatibility. +A JavaScript Ethereum Provider API for consistency across clients and applications. -## API +## Abstract -### Send +A common convention in the Ethereum web application ("dapp") ecosystem is for key management software ("wallets") to expose their API via a JavaScript object in the web page. +This object is called "the Provider". -Ethereum API methods can be sent and received: +Historically, Provider implementations have exhibited conflicting interfaces and behaviors between wallets. +This EIP formalizes an Ethereum Provider API to promote wallet interoperability. +The API is designed to be minimal, event-driven, and agnostic of transport and RPC protocols. +Its functionality is easily extended by defining new RPC methods and `message` event types. -```js -ethereum.send(method: String, params?: Array): Promise; +Historically, Providers have been made available as `window.ethereum` in web browsers, but this convention is not part of the specification. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC-2119](https://www.ietf.org/rfc/rfc2119.txt). + +> Comments like this are non-normative. + +### Definitions + +_This section is non-normative._ + +- Provider + - A JavaScript object made available to a consumer, that provides access to Ethereum by means of a Client. +- Client + - An endpoint that receives Remote Procedure Call (RPC) requests from the Provider, and returns their results. +- Wallet + - An end-user application that manages private keys, performs signing operations, and acts as a middleware between the Provider and the Client. +- Remote Procedure Call (RPC) + - A Remote Procedure Call (RPC), is any request submitted to a Provider for some procedure that is to be processed by a Provider, its Wallet, or its Client. + +### Connectivity + +The Provider is said to be "connected" when it can service RPC requests to at least one chain. + +The Provider is said to be "disconnected" when it cannot service RPC requests to any chain at all. + +> To service an RPC request, the Provider must successfully submit the request to the remote location, and receive a response. +> In other words, if the Provider is unable to communicate with its Client, for example due to network issues, the Provider is disconnected. + +### API + +> The Provider API is specified using TypeScript. +> The authors encourage implementers to declare their own types and interfaces, using the ones in this section as a basis. +> +> For consumer-facing API documentation, see [Appendix I](#appendix-i-consumer-facing-api-documentation) + +The Provider **MUST** implement and expose the API defined in this section. +All API entities **MUST** adhere to the types and interfaces defined in this section. + +#### request + +> The `request` method is intended as a transport- and protocol-agnostic wrapper function for Remote Procedure Calls (RPCs). + +```typescript +interface RequestArguments { + readonly method: string; + readonly params?: readonly unknown[] | object; +} + +Provider.request(args: RequestArguments): Promise; ``` -Promise resolves with `result` or rejects with `Error`. +The Provider **MUST** identify the requested RPC method by the value of `RequestArguments.method`. -See the [available methods](https://github.com/ethereum/wiki/wiki/JSON-RPC#json-rpc-methods). +If the requested RPC method takes any parameters, the Provider **MUST** accept them as the value of `RequestArguments.params`. -#### eth_requestAccounts +RPC requests **MUST** be handled such that the returned Promise either resolves with a value per the requested RPC method's specification, or rejects with an error. -By default, the provider supplied to a new dapp has is a "read-only" provider with no accounts authenticated. See [EIP 1102: Opt-in account exposure](https://eips.ethereum.org/EIPS/eip-1102). +If resolved, the Promise **MUST** resolve with a result per the RPC method's specification. The Promise **MUST NOT** resolve with any RPC protocol-specific response objects, unless the RPC method's return type is so defined. -To request accounts, call `ethereum.send('eth_requestAccounts')`. This will ask the user which account(s) they would like to authenticate to the dapp. +If the returned Promise rejects, it **MUST** reject with a `ProviderRpcError` as specified in the [RPC Errors](#rpc-errors) section below. -Promise resolves with an array of the enabled account(s) addresses. +The returned Promise **MUST** reject if any of the following conditions are met: -### Events +- An error is returned for the RPC request. + - If the returned error is compatible with the `ProviderRpcError` interface, the Promise **MAY** reject with that error directly. +- The Provider encounters an error or fails to process the request for any reason. + +> If the Provider implements any kind of authorization logic, the authors recommend rejecting with a `4100` error in case of authorization failures. + +The returned Promise **SHOULD** reject if any of the following conditions are met: + +- The Provider is disconnected. + - If rejecting for this reason, the Promise rejection error `code` **MUST** be `4900`. +- The RPC request is directed at a specific chain, and the Provider is not connected to that chain, but is connected to at least one other chain. + - If rejecting for this reason, the Promise rejection error `code` **MUST** be `4901`. + +See the section [Connectivity](#connectivity) for the definitions of "connected" and "disconnected". + +### Supported RPC Methods -Events are emitted using [EventEmitter](https://nodejs.org/api/events.html). +A "supported RPC method" is any RPC method that may be called via the Provider. -#### notification +All supported RPC methods **MUST** be identified by unique strings. -All subscriptions from the node emit on "subscription type" (e.g. `eth_subscription`, or `ssh_subscription`). Attach listeners with: +Providers **MAY** support whatever RPC methods required to fulfill their purpose, standardized or otherwise. -```js -ethereum.on('eth_subscription', listener: (result: any) => void): this; +If an RPC method defined in a finalized EIP is not supported, it **SHOULD** be rejected with a `4200` error per the [Provider Errors](#provider-errors) section below, or an appropriate error per the RPC method's specification. + +#### RPC Errors + +```typescript +interface ProviderRpcError extends Error { + code: number; + data?: unknown; +} ``` -To create a subscription, call `ethereum.send('eth_subscribe')` or `ethereum.send('shh_subscribe')`. The subscription object will emit through the specific subscription type. +- `message` + - **MUST** be a human-readable string + - **SHOULD** adhere to the specifications in the [Error Standards](#error-standards) section below +- `code` + - **MUST** be an integer number + - **SHOULD** adhere to the specifications in the [Error Standards](#error-standards) section below +- `data` + - **SHOULD** contain any other useful information about the error + +##### Error Standards + +`ProviderRpcError` codes and messages **SHOULD** follow these conventions, in order of priority: + +1. The errors in the [Provider Errors](#provider-errors) section below + +2. Any errors mandated by the erroring RPC method's specification + +3. The [`CloseEvent` status codes](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes) + +#### Provider Errors + +| Status code | Name | Description | +| ----------- | --------------------- | ------------------------------------------------------------------------ | +| 4001 | User Rejected Request | The user rejected the request. | +| 4100 | Unauthorized | The requested method and/or account has not been authorized by the user. | +| 4200 | Unsupported Method | The Provider does not support the requested method. | +| 4900 | Disconnected | The Provider is disconnected from all chains. | +| 4901 | Chain Disconnected | The Provider is not connected to the requested chain. | + +> `4900` is intended to indicate that the Provider is disconnected from all chains, while `4901` is intended to indicate that the Provider is disconnected from a specific chain only. +> In other words, `4901` implies that the Provider is connected to other chains, just not the requested one. + +### Events -The result object will look as follows: +The Provider **MUST** implement the following event handling methods: -```js -{ - "subscription":"0xc3b33aa549fb9a60e95d21862596617c", - "result": {...} +- `on` +- `removeListener` + +These methods **MUST** be implemented per the Node.js [`EventEmitter` API](https://nodejs.org/api/events.html). + +> To satisfy these requirements, Provider implementers should consider simply extending the Node.js `EventEmitter` class and bundling it for the target environment. + +#### message + +> The `message` event is intended for arbitrary notifications not covered by other events. + +When emitted, the `message` event **MUST** be emitted with an object argument of the following form: + +```typescript +interface ProviderMessage { + readonly type: string; + readonly data: unknown; } ``` -See the [eth subscription methods](https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB#supported-subscriptions) and [shh subscription methods](https://github.com/ethereum/go-ethereum/wiki/Whisper-v6-RPC-API#shh_subscribe). +##### Subscriptions + +If the Provider supports Ethereum RPC subscriptions, e.g. [`eth_subscribe`](https://geth.ethereum.org/docs/rpc/pubsub), the Provider **MUST** emit the `message` event when it receives a subscription notification. + +If the Provider receives a subscription message from e.g. an `eth_subscribe` subscription, the Provider **MUST** emit a `message` event with a `ProviderMessage` object of the following form: + +```typescript +interface EthSubscription extends ProviderMessage { + readonly type: 'eth_subscription'; + readonly data: { + readonly subscription: string; + readonly result: unknown; + }; +} +``` #### connect -The provider emits `connect` on connect to a network. +See the section [Connectivity](#connectivity) for the definition of "connected". + +If the Provider becomes connected, the Provider **MUST** emit the event named `connect`. -```js -ethereum.on('connect', listener: () => void): this; +This includes when: + +- The Provider first connects to a chain after initialization. +- The Provider connects to a chain after the `disconnect` event was emitted. + +This event **MUST** be emitted with an object of the following form: + +```typescript +interface ProviderConnectInfo { + readonly chainId: string; +} ``` -You can detect which network by sending `net_version`: +`chainId` **MUST** specify the integer ID of the connected chain as a hexadecimal string, per the [`eth_chainId`](./eip-695.md) Ethereum RPC method. + +#### disconnect + +See the section [Connectivity](#connectivity) for the definition of "disconnected". + +If the Provider becomes disconnected from all chains, the Provider **MUST** emit the event named `disconnect` with value `error: ProviderRpcError`, per the interfaced defined in the [RPC Errors](#rpc-errors) section. The value of the error's `code` property **MUST** follow the [status codes for `CloseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes). + +#### chainChanged + +If the chain the Provider is connected to changes, the Provider **MUST** emit the event named `chainChanged` with value `chainId: string`, specifying the integer ID of the new chain as a hexadecimal string, per the [`eth_chainId`](./eip-695.md) Ethereum RPC method. + +#### accountsChanged + +If the accounts available to the Provider change, the Provider **MUST** emit the event named `accountsChanged` with value `accounts: string[]`, containing the account addresses per the `eth_accounts` Ethereum RPC method. + +The "accounts available to the Provider" change when the return value of `eth_accounts` changes. + +## Rationale + +The purpose of a Provider is to _provide_ a consumer with access to Ethereum. +In general, a Provider must enable an Ethereum web application to do two things: + +- Make Ethereum RPC requests +- Respond to state changes in the Provider's Ethereum chain, Client, and Wallet + +The Provider API specification consists of a single method and five events. +The `request` method and the `message` event alone, are sufficient to implement a complete Provider. +They are designed to make arbitrary RPC requests and communicate arbitrary messages, respectively. + +The remaining four events can be separated into two categories: + +- Changes to the Provider's ability to make RPC requests + - `connect` + - `disconnect` +- Common Client and/or Wallet state changes that any non-trivial application must handle + - `chainChanged` + - `accountsChanged` + +These events are included due to the widespread production usage of related patterns, at the time of writing. + +## Backwards Compatibility + +Many Providers adopted a draft version of this specification before it was finalized. +The current API is designed to be a strict superset of the legacy version, and this specification is in that sense fully backwards compatible. +See [Appendix III](#appendix-iii-legacy-provider-api) for the legacy API. + +Providers that only implement this specification will not be compatible with Ethereum web applications that target the legacy API. + +## Implementations + +At the time of writing, the following projects have working implementations: -```js -const network = await ethereum.send('net_version'); -> '1' +- [buidler.dev](https://github.com/nomiclabs/buidler/pull/608) +- [ethers.js](https://github.com/ethers-io/ethers.js/blob/56af4413b1dd1787db68985e0b612b63d86fdf7c/packages/providers/src.ts/web3-provider.ts) +- [eth-provider](https://www.npmjs.com/package/eth-provider) +- [MetaMask](https://github.com/MetaMask/inpage-provider) +- [WalletConnect](https://github.com/WalletConnect/walletconnect-monorepo/blob/d33fd2070d7a67f74de50fd10ca4217f4e2f22f3/packages/providers/web3-provider/README.md) +- [web3.js](https://web3js.readthedocs.io/) + +## Security Considerations + +The Provider is intended to pass messages between an Ethereum Client and an Ethereum application. +It is _not_ responsible for private key or account management; it merely processes RPC messages and emits events. +Consequently, account security and user privacy need to be implemented in middlewares between the Provider and its Ethereum Client. +In practice, we call these middleware applications "Wallets," and they usually manage the user's private keys and accounts. +The Provider can be thought of as an extension of the Wallet, exposed in an untrusted environment, under the control of some third party (e.g. a website). + +### Handling Adversarial Behavior + +Since it is a JavaScript object, consumers can generally perform arbitrary operations on the Provider, and all its properties can be read or overwritten. +Therefore, it is best to treat the Provider object as though it is controlled by an adversary. +It is paramount that the Provider implementer protects the user, Wallet, and Client by ensuring that: + +- The Provider does not contain any private user data. +- The Provider and Wallet programs are isolated from each other. +- The Wallet and/or Client rate-limit requests from the Provider. +- The Wallet and/or Client validate all data sent from the Provider. + +### Chain Changes + +Since all Ethereum operations are directed at a particular chain, it's important that the Provider accurately reflects the Client's configured chain, per the `eth_chainId` Ethereum RPC method (see [EIP-695](./eip-695.md)). + +This includes ensuring that `eth_chainId` has the correct return value, and that the `chainChanged` event is emitted whenever that value changes. + +### User Account Exposure and Account Changes + +Many Ethereum write operations (e.g. `eth_sendTransaction`) require a user account to be specified. +Provider consumers access these accounts via the `eth_accounts` RPC method, and by listening for the `accountsChanged` event. + +As with `eth_chainId`, it is critical that `eth_accounts` has the correct return value, and that the `accountsChanged` event is emitted whenever that value changes. + +The return value of `eth_accounts` is ultimately controlled by the Wallet or Client. +In order to protect user privacy, the authors recommend not exposing any accounts by default. +Instead, Providers should support RPC methods for explicitly requesting account access, such as `eth_requestAccounts` (see [EIP-1102](./eip-1102.md)) or `wallet_requestPermissions` (see [EIP-2255](./eip-2255.md)). + +## References + +- [Initial discussion in `ethereum/interfaces`](https://github.com/ethereum/interfaces/issues/16) +- [Deprecated Ethereum Magicians thread](https://ethereum-magicians.org/t/eip-1193-ethereum-provider-javascript-api/640) +- [Continuing discussion](https://github.com/ethereum/EIPs/issues/2319) +- Related EIPs + - [EIP-1102: Opt-in Account Exposure](./eip-1102.md) + - [EIP-1474: Remote Procedure Call Specification](./eip-1474.md) + - [EIP-1767: GraphQL Interface to Ethereum Node Data](./eip-1767.md) + - [EIP-2255: Wallet Permissions](./eip-2255.md) + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + +## Appendix I: Consumer-Facing API Documentation + +### request + +Makes an Ethereum RPC method call. + +```typescript +interface RequestArguments { + readonly method: string; + readonly params?: readonly unknown[] | object; +} + +Provider.request(args: RequestArguments): Promise; ``` -#### close +The returned Promise resolves with the method's result or rejects with a [`ProviderRpcError`](#errors). For example: -The provider emits `close` on disconnect from a network. +```javascript +Provider.request({ method: 'eth_accounts' }) + .then((accounts) => console.log(accounts)) + .catch((error) => console.error(error)); +``` -```js -ethereum.on('close', listener: (code: Number, reason: String) => void): this; +Consult each Ethereum RPC method's documentation for its `params` and return type. +You can find a list of common methods [here](./eip-1474.md). + +#### RPC Protocols + +Multiple RPC protocols may be available. For examples, see: + +- [EIP-1474](./eip-1474.md), the Ethereum JSON-RPC API +- [EIP-1767](./eip-1767.md), the Ethereum GraphQL schema + +### Events + +Events follow the conventions of the Node.js [`EventEmitter` API](https://nodejs.org/api/events.html). + +#### connect + +The Provider emits `connect` when it: + +- first connects to a chain after being initialized. +- first connects to a chain, after the `disconnect` event was emitted. + +```typescript +interface ProviderConnectInfo { + readonly chainId: string; +} + +Provider.on('connect', listener: (connectInfo: ProviderConnectInfo) => void): Provider; ``` -The event emits with `code` and `reason`. The code follows the table of [`CloseEvent` status codes](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes). +The event emits an object with a hexadecimal string `chainId` per the `eth_chainId` Ethereum RPC method, and other properties as determined by the Provider. -#### networkChanged +#### disconnect -The provider emits `networkChanged` on connect to a new network. +The Provider emits `disconnect` when it becomes disconnected from all chains. -```js -ethereum.on('networkChanged', listener: (networkId: String) => void): this; +```typescript +Provider.on('disconnect', listener: (error: ProviderRpcError) => void): Provider; ``` -The event emits with `networkId`, the new network returned from `net_version`. +This event emits a [`ProviderRpcError`](#errors). The error `code` follows the table of [`CloseEvent` status codes](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes). + +#### chainChanged + +The Provider emits `chainChanged` when connecting to a new chain. + +```typescript +Provider.on('chainChanged', listener: (chainId: string) => void): Provider; +``` + +The event emits a hexadecimal string `chainId` per the `eth_chainId` Ethereum RPC method. #### accountsChanged -The provider emits `accountsChanged` if the accounts returned from the provider (`eth_accounts`) changes. +The Provider emits `accountsChanged` if the accounts returned from the Provider (`eth_accounts`) change. -```js -ethereum.on('accountsChanged', listener: (accounts: Array) => void): this; +```typescript +Provider.on('accountsChanged', listener: (accounts: string[]) => void): Provider; ``` -The event emits with `accounts`, an array of the accounts' addresses. +The event emits with `accounts`, an array of account addresses, per the `eth_accounts` Ethereum RPC method. -## Examples +#### message -```js -const ethereum = window.ethereum; +The Provider emits `message` to communicate arbitrary messages to the consumer. +Messages may include JSON-RPC notifications, GraphQL subscriptions, and/or any other event as defined by the Provider. -// A) Set provider in web3.js -var web3 = new Web3(ethereum); +```typescript +interface ProviderMessage { + readonly type: string; + readonly data: unknown; +} + +Provider.on('message', listener: (message: ProviderMessage) => void): Provider; +``` +##### Subscriptions -// B) Use provider object directly -// Example 1: Log last block +[`eth_` subscription methods](https://geth.ethereum.org/docs/rpc/pubsub) and [`shh_` subscription methods](https://github.com/ethereum/go-ethereum/wiki/Whisper-v6-RPC-API#shh_subscribe) rely on this event to emit subscription updates. + +For e.g. `eth_subscribe` subscription updates, `ProviderMessage.type` will equal the string `'eth_subscription'`, and the subscription data will be the value of `ProviderMessage.data`. + +### Errors + +```typescript +interface ProviderRpcError extends Error { + message: string; + code: number; + data?: unknown; +} +``` + +## Appendix II: Examples + +These examples assume a web browser environment. + +```javascript +// Most Providers are available as window.ethereum on page load. +// This is only a convention, not a standard, and may not be the case in practice. +// Please consult the Provider implementation's documentation. +const ethereum = window.ethereum; + +// Example 1: Log chainId ethereum - .send('eth_getBlockByNumber', ['latest', 'true']) - .then(block => { - console.log(`Block ${block.number}:`, block); + .request({ method: 'eth_chainId' }) + .then((chainId) => { + console.log(`hexadecimal string: ${chainId}`); + console.log(`decimal number: ${parseInt(chainId, 16)}`); }) - .catch(error => { - console.error( - `Error fetching last block: ${error.message}. - Code: ${error.code}. Data: ${error.data}` - ); + .catch((error) => { + console.error(`Error fetching chainId: ${error.code}: ${error.message}`); }); - -// Example 2: Request accounts +// Example 2: Log last block ethereum - .send('eth_requestAccounts') - .then(accounts => { - if (accounts.length > 0) { - console.log(`Accounts enabled:\n${accounts.join('\n')}`); - } else { - console.error(`No accounts enabled.`); - } + .request({ + method: 'eth_getBlockByNumber', + params: ['latest', true], + }) + .then((block) => { + console.log(`Block ${block.number}:`, block); }) - .catch(error => { + .catch((error) => { console.error( - `Error requesting accounts: ${error.message}. - Code: ${error.code}. Data: ${error.data}` + `Error fetching last block: ${error.message}. + Code: ${error.code}. Data: ${error.data}` ); }); - // Example 3: Log available accounts ethereum - .send('eth_accounts') - .then(accounts => { + .request({ method: 'eth_accounts' }) + .then((accounts) => { console.log(`Accounts:\n${accounts.join('\n')}`); }) - .catch(error => { + .catch((error) => { console.error( `Error fetching accounts: ${error.message}. - Code: ${error.code}. Data: ${error.data}` + Code: ${error.code}. Data: ${error.data}` ); }); - // Example 4: Log new blocks -let subId; ethereum - .send('eth_subscribe', ['newHeads']) - .then(subscriptionId => { - subId = subscriptionId; - ethereum.on('eth_subscription', result => { - if (result.subscription === subscriptionId) { - if (result.result instanceof Error) { - const error = result.result; - console.error( - `Error from newHeads subscription: ${error.message}. - Code: ${error.code}. Data: ${error.data}` - ); - } else { - const block = result.result; - console.log(`New block ${block.number}:`, block); + .request({ + method: 'eth_subscribe', + params: ['newHeads'], + }) + .then((subscriptionId) => { + ethereum.on('message', (message) => { + if (message.type === 'eth_subscription') { + const { data } = message; + if (data.subscription === subscriptionId) { + if ('result' in data && typeof data.result === 'object') { + const block = data.result; + console.log(`New block ${block.number}:`, block); + } else { + console.error(`Something went wrong: ${data.result}`); + } } } }); }) - .catch(error => { + .catch((error) => { console.error( `Error making newHeads subscription: ${error.message}. Code: ${error.code}. Data: ${error.data}` ); }); - -// to unsubscribe -ethereum - .send('eth_unsubscribe', [subId]) - .then(result => { - console.log(`Unsubscribed newHeads subscription ${subId}`); - }) - .catch(error => { - console.error( - `Error unsubscribing newHeads subscription: ${error.message}. - Code: ${error.code}. Data: ${error.data}` - ); - }); - // Example 5: Log when accounts change -const logAccounts = accounts => { +const logAccounts = (accounts) => { console.log(`Accounts:\n${accounts.join('\n')}`); }; ethereum.on('accountsChanged', logAccounts); @@ -212,221 +526,51 @@ ethereum.on('accountsChanged', logAccounts); ethereum.removeListener('accountsChanged', logAccounts); // Example 6: Log if connection ends -ethereum.on('close', (code, reason) => { - console.log(`Ethereum provider connection closed: ${reason}. Code: ${code}`); +ethereum.on('disconnect', (code, reason) => { + console.log(`Ethereum Provider connection closed: ${reason}. Code: ${code}`); }); ``` -## Specification - -### Errors - -If the Ethereum Provider request returns an error property then the Promise **MUST** reject with an Error object containing the `error.message` as the Error message, `error.code` as a code property on the error and `error.data` as a data property on the error. - -If an error occurs during processing, such as an HTTP error or internal parsing error, then the Promise **MUST** reject with an `Error` object. - -If the request requires an account that is not yet authenticated, the Promise **MUST** reject with Error code 4100. - -#### eth_requestAccounts - -The provider supplied to a new dapp **MUST** be a "read-only" provider: authenticating no accounts by default, returning a blank array for `eth_accounts`, and rejecting any methods that require an account with Error code `4100`. - -If the dapp has been previously authenticated and remembered by the user, then the provider supplied on load **MAY** automatically be enabled with the previously authenticated accounts. - -If no accounts are authenticated, the `eth_requestAccounts` method **MUST** ask the user which account(s) they would like to authenticate to the dapp. If the request has been previously granted and remembered, the `eth_requestAccounts` method **MAY** immediately return. - -The `eth_requestAccounts` method **MUST** resolve with an array of the account(s) addresses or reject with an `Error`. If the account(s) enabled by the provider change, the `accountsChanged` event **MUST** also emit. - -For full specification of the `eth_requestAccounts` RPC method, see [EIP 1102: Opt-in account exposure](https://eips.ethereum.org/EIPS/eip-1102). - -### Events - -The provider **SHOULD** extend from `EventEmitter` to provide dapps flexibility in listening to events. In place of full `EventEmitter` functionality, the provider **MAY** provide as many methods as it can reasonably provide, but **MUST** provide at least `on`, `emit`, and `removeListener`. - -#### notification - -All subscriptions received from the node **MUST** emit the `subscription` property with the subscription ID and a `results` property. - -#### connect +## Appendix III: Legacy Provider API -If the network connects, the Ethereum Provider **MUST** emit an event named `connect`. +This section documents the legacy Provider API, which is extensively used in production at the time of writing. +As it was never fully standardized, significant deviations occur in practice. +The authors recommend against implementing it except to support legacy Ethereum applications. -#### close +### sendAsync (DEPRECATED) -If the network connection closes, the Ethereum Provider **MUST** emit an event named `close` with args `code: Number, reason: String` following the [status codes for `CloseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes). +This method is superseded by [`request`](#request). -#### networkChanged +`sendAsync` is like `request`, but with JSON-RPC objects and a callback. -If the network the provider is connected to changes, the provider **MUST** emit an event named `networkChanged` with args `networkId: String` containing the ID of the new network (using the Ethereum JSON-RPC call `net_version`). - -#### accountsChanged - -If the accounts connected to the Ethereum Provider change at any time, the Ethereum Provider **MUST** send an event with the name `accountsChanged` with args `accounts: Array` containing the accounts' addresses. - -### web3.js Backwards Compatibility - -If the implementing Ethereum Provider would like to be compatible with `web3.js` prior to `1.0.0-beta38`, it **MUST** provide the method: `sendAsync(payload: Object, callback: (error: any, result: any) => void): void`. - -### Error object and codes - -If an Error object is returned, it **MUST** contain a human readable string message describing the error and **SHOULD** populate the `code` and `data` properties on the error object with additional error details. - -Appropriate error codes **SHOULD** follow the table of [`CloseEvent` status codes](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes), along with the following table: - -| Status code | Name | Description | -| ----------- | ---------------------------- | --------------------------------------------------------------------- | -| 4001 | User Denied Request Accounts | User denied authorizing any accounts for the dapp. | -| 4010 | User Denied Create Account | User denied creating a new account. | -| 4100 | Unauthorized | The requested account has not been authorized by the user. | -| 4200 | Unsupported Method | The requested method is not supported by the given Ethereum Provider. | - -## Sample Class Implementation - -```js -class EthereumProvider extends EventEmitter { - constructor() { - // Call super for `this` to be defined - super(); - - // Init storage - this._nextJsonrpcId = 0; - this._promises = {}; - - // Fire the connect - this._connect(); +```typescript +Provider.sendAsync(request: Object, callback: Function): void; +``` - // Listen for jsonrpc responses - window.addEventListener('message', this._handleJsonrpcMessage.bind(this)); - } +Historically, the request and response object interfaces have followed the [Ethereum JSON-RPC specification](./eip-1474.md). - /* Methods */ +### send (DEPRECATED) - send(method, params = []) { - if (!method || typeof method !== 'string') { - return new Error('Method is not a valid string.'); - } +This method is superseded by [`request`](#request). - if (!(params instanceof Array)) { - return new Error('Params is not a valid array.'); - } +```typescript +Provider.send(...args: unknown[]): unknown; +``` - const id = this._nextJsonrpcId++; - const jsonrpc = '2.0'; - const payload = { jsonrpc, id, method, params }; +### Legacy Events - const promise = new Promise((resolve, reject) => { - this._promises[payload.id] = { resolve, reject }; - }); +#### close (DEPRECATED) - // Send jsonrpc request to Mist - window.postMessage( - { type: 'mistAPI_ethereum_provider_write', message: payload }, - targetOrigin - ); +This event is superseded by [`disconnect`](#disconnect). - return promise; - } - - /* Internal methods */ - - _handleJsonrpcMessage(event) { - // Return if no data to parse - if (!event || !event.data) { - return; - } - - let data; - try { - data = JSON.parse(event.data); - } catch (error) { - // Return if we can't parse a valid object - return; - } - - // Return if not a jsonrpc response - if (!data || !data.message || !data.message.jsonrpc) { - return; - } - - const message = data.message; - const { id, method, error, result } = message; - - if (typeof id !== 'undefined') { - const promise = this._promises[id]; - if (promise) { - // Handle pending promise - if (data.type === 'error') { - promise.reject(message); - } else if (message.error) { - promise.reject(error); - } else { - promise.resolve(result); - } - delete this._promises[id]; - } - } else { - if (method && method.indexOf('_subscription') > -1) { - // Emit subscription notification - this._emitNotification(message.params); - } - } - } +#### networkChanged (DEPRECATED) - /* Connection handling */ +The event `networkChanged` is superseded by [`chainChanged`](#chainchanged). - _connect() { - // Send to Mist - window.postMessage( - { type: 'mistAPI_ethereum_provider_connect' }, - targetOrigin - ); +For details, see [EIP-155: Simple replay attack protection](./eip-155.md) and [EIP-695: Create eth_chainId method for JSON-RPC](./eip-695.md). - // Reconnect on close - this.once('close', this._connect.bind(this)); - } - - /* Events */ - - _emitNotification(result) { - this.emit('notification', result); - } - - _emitConnect() { - this.emit('connect'); - } - - _emitClose(code, reason) { - this.emit('close', code, reason); - } - - _emitNetworkChanged(networkId) { - this.emit('networkChanged', networkId); - } - - _emitAccountsChanged(accounts) { - this.emit('accountsChanged', accounts); - } - - /* web3.js Provider Backwards Compatibility */ - - sendAsync(payload, callback) { - return this.send(payload.method, payload.params) - .then(result => { - const response = payload; - response.result = result; - callback(null, response); - }) - .catch(error => { - callback(error, null); - // eslint-disable-next-line no-console - console.error( - `Error from EthereumProvider sendAsync ${payload}: ${error}` - ); - }); - } -} -``` +#### notification (DEPRECATED) -## Copyright +This event is superseded by [`message`](#message). -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Historically, this event has been emitted with e.g. `eth_subscribe` subscription updates of the form `{ subscription: string, result: unknown }`. diff --git a/EIPS/eip-1202.md b/EIPS/eip-1202.md index a6de062f8f4a79..2868fbb772b93b 100644 --- a/EIPS/eip-1202.md +++ b/EIPS/eip-1202.md @@ -1,296 +1,7 @@ --- eip: 1202 -title: Voting Standard -author: Zainan Victor Zhou (@xinbenlv), Evan (@evbots), Yin Xu (@yingogobot) -type: Standards Track category: ERC -status: Draft -created: 2018-07-08 -discussions-to: https://github.com/ethereum/EIPs/issues/1202 +status: Moved --- -## Note to Readers - -1. We are still open to have co-author to collaborate, in particular, we are looking for co-authors of the -following category: - - standard designers who are experienced in application-layer standard design, or - - developers who have experience with blockchain-based voting system in practice - - researchers with research interest in crypto/zero-knowledge-proof voting - - -2. We have two discussion destinations: - - [Github Ethereum EIP Issue #1202](https://github.com/ethereum/EIPs/issues/1202) for long and more mature thoughts - - [Telegram Channel t.me/erc1202](https://t.me/erc1202) for real-time and related random chat. - -3. We are actively working on updating this draft as many feedbacks have come in since it merged into official EIP repo. -If you are viewing a snapshot of this draft, please be advised the latest dev version of ERC 1202 can be found [here](https://github.com/xinbenlv/eip-1202-draft/blob/master/EIP-1202.md) - -## Simple Summary -Propose a standard interface for voting. - -## Abstract -This proposal creates a standard API for implementing voting within smart contract. This standard provides functionalities to voting as well as to view the vote result and set voting status. - -## Motivation -Voting is one of the earliest example of EVM programming, and also a key to DAO/organizational governance process. We foresee many DAOs will ultimately need to leverage voting as one of the important part of their governance. By creating a voting standard for smart contract / token, we can have the following benefits - -### Benefits -1. Allow general UI and applications to be built on top of a standardized voting to allow more general user to participate, and encourage more DApp and DAO to think about their governance -2. Allow delegate voting / smart contract voting, automatic voting -3. Allow voting results to be recorded on-chain, in a standard way, and allow DAOs and DApps to honor the voting result programmatically. -4. Allow the compatibility with token standard such as [ERC-20](https://eips.ethereum.org/EIPS/eip-20) or other new standards([EIP-777](https://eips.ethereum.org/EIPS/eip-777)) and item standard such as [EIP-721](https://eips.ethereum.org/EIPS/eip-721) -5. Create massive potential for interoperability within Ethereum echo systems and other system. -6. Allow setting voting deadline, allow determine on single or multiple options. Allow requiring voting orders. (trade-off is interface complexity, we might need [ERC-20](https://eips.ethereum.org/EIPS/eip-20) approach and later a [EIP-777](https://eips.ethereum.org/EIPS/eip-777) for advanced voting) -7. Recording the voting with weights with token amount. -8. Possibly allow trust-worthy privacy-safe voting and anonymous voting (with either voter address being un-associated with the vote they cast, given a list of randomized/obfuscated voting options). -8 -9. Possibly allow result in reward by voting partitipation or voting result - -### Use-cases: -1. Determine on issuing new token, issuing more token or issuing sub-token -2. Determine on creating new item under [EIP-721](https://eips.ethereum.org/EIPS/eip-721) -3. Determine on election on certain person or smart contract to be delegated leader for project or subproject -4. Determine on auditing result ownership allowing migration of smart contract proxy address - -## Specifications - -### Simple Version -The simple version of specification makes the assumption that each smart contract voting standard is: *Single Issue*, *Single Selection* and *Single Outcome* - -```solidity -pragma solidity ^0.4.22; - - -/** - * - Single issue - * - Single selection - * - * Discussion: - * 1. Each address has a weight determined by other input decided by the actual implementation - * which is suggested to be set upon the initialization - * 2. Is there certain naming convention to follow? - */ -interface ERC1202 { - - // Vote with an option. The caller needs to handle success or not - function vote(uint option) external returns (bool success); - function setStatus(bool isOpen) external returns (bool success); - - function issueDescription() external view returns (string desc); - function availableOptions() external view returns (uint[] options); - function optionDescription(uint option) external view returns (string desc); - function ballotOf(address addr) external view returns (uint option); - function weightOf(address addr) external view returns (uint weight); - function getStatus() external view returns (bool isOpen); - function weightedVoteCountsOf(uint option) external view returns (uint count); - function winningOption() external view returns (uint option); - - event OnVote(address indexed _from, uint _value); - event OnStatusChange(bool newIsOpen); -} -``` - -### Advanced Version -```solidity -pragma solidity ^0.4.22; - - -/** - * - Multiple issue - * - Multiple selection - * - Ordered multiple result - * Discussion: - * 1. Each address has a weight determined by other input decided by the actual implementation - * which is suggested to be set upon the initialization - * 2. Is there certain naming convention to follow? - */ -contract AdvancedERC1202 { - - // Vote with an option. The caller needs to handle success or not - function vote(uint issueId, uint option) public returns (bool success); - function setStatus(uint issueId, bool isOpen) public returns (bool success); - - function issueDescription(uint issueId) public view returns (string desc); - function availableOptions(uint issueId) public view returns (uint[] options); - function optionDescription(uint issueId, uint option) public view returns (string desc); - function ballotOf(uint issueId, address addr) public view returns (uint option); - function weightOf(uint issueId, address addr) public view returns (uint weight); - function getStatus(uint issueId) public view returns (bool isOpen); - function weightedVoteCountsOf(uint issueId, uint option) public view returns (uint count); - function topOptions(uint issueId, uint limit) public view returns (uint[] topOptions_); - - event OnVote(uint issueId, address indexed _from, uint _value); - event OnStatusChange(uint issueId, bool newIsOpen); -} -``` - -## Rationale - -We made the following design decisions and here are the rationales. - - - **Granularity and Anonymity:**: We created a `view` function `ballotOf` primarily making it easier for people to check the vote from certain address. This has the following assumptions: - - * It's possible to check someone's vote directly given an address. If implementor don't want to make it so easiy, they can simply reject all calls to this function. We want to make sure that we support both anonymous voting an non-anonymous voting. However since all calls to a smart contract is logged in block history, there is really no secrecy unless done with cryptography tricks. I am not cryptography-savvy enough to comment on the possibility. Please see "Second Feedback Questions 2018" for related topic. - - * It's assumes for each individual address, they can only vote for one decision. They can distribute their available voting power into more granular level. If implementor wants allow this, they ask the user to create another wallet address and grant the new address certain power. For example, a token based voting where voting weight is determined by the amount of token held by a voter, a voter who wants to distribute its voting power in two different option(option set) can transfer some of the tokens to the new account and cast the votes from both accounts. - - - **Weight**: We assume there are `weight` of votes and can be checked by calling `weightOf(address addr)`, and the weight distribution is either internally determined or determined by constructor. However we have not been considering updating the weight distribution. Please comment on this design decision as we want to learn how likely an implementor would want to be able to update the voting weight distributions. - -### Security and Privacy of Voting -// TODO - -## Backward Compatibility -There is no backward compatibility issue we are aware of. - - -## Interactions with other ERCs -// TODO add interaction discussion for the following ERCs -ERC20, ERC721, ERC735, ERC780, ERC165 - - -## Simple Code Examples -### Example 1: Simplest Version: Single Issue Yes/No Question Per Smart Contract Address Per Non-Weighted Vote - - - [Source Code](https://github.com/xinbenlv/eip-1202-draft/blob/master/contracts/simple-version/SimplestVote1202.sol) - - [Deployment (Ropsten)](https://ropsten.etherscan.io/address/0x067e76ddd9c67f7ae606b18d881545512d4b680c#code) - -### Example 2: TokenVote with Simple Interface with Weight Assigned by Token and Pre-registered Snapshot of Token-Holders - - [Source Code](https://github.com/xinbenlv/eip-1202-draft/blob/master/contracts/simple-version/TokenVote1202.sol) - - [Deployment (Ropsten)](https://ropsten.etherscan.io/address/0x5bd007a224fe8820b19cc0bce8e241f4752ce74d#code) - -### Example 3: TokenVote with Advanced Interface - - [Source Code](https://github.com/xinbenlv/eip-1202-draft/blob/master/contracts/advanced-version/AdvancedTokenVote1202.sol) - - [Deployment (Ropsten)](https://ropsten.etherscan.io/address/0xfd8b3be5f9db4662d1c9269f948345b46e37fd26#code) - -## Comprehensive Application Examples - -### Example 1: Joint Wallet Account Spending Approval -// TODO - -### Example 2: Secret Vote -// TODO - -### Example 3: Token Re-issue -// TODO - -### Example 4: Multi-input Oracle -// TODO - - -## Case Study - -### Existing Voting Systems in Blockchain World -// TODO - -#### Carbon Vote -// TODO - -#### PLACE Voting -https://medium.com/@jameson.quinn/how-place-voting-works-617a5e8ac422 - -#### PLCR Voting -[PLCR Voting: ](https://github.com/ConsenSys/PLCRVoting) -https://medium.com/metax-publication/a-walkthrough-of-plcr-voting-in-solidity-92420bd5b87c - -#### - -### Exiting Voting Systems in Real World -// TODO - -#### Simple Majority Vote Requiring Quorum (e.g. Company Board) -// TODO, and a small variant: ZaiGeZaiGu function committee approval (1/2 as quorum, majority vote) - - -#### Two-tiered Shareholder Vote (e.g. GOOG, FB) -// TODO - -#### Jury Decision of US Federal Criminal Court (All Ayle for Guity, 5/5 for Tie) -// TODO - -#### US Presidential Election: Different Vote Time, Multi-Reginal, Two-level (General and Editorial(delegate)) -// TODO - -#### Super-Girl China 2005: Idol Ranking Vote, Multiple Votes Allowed -// TODO - - -## Summary of Discussions - -### Early Feedback Questions (2018-07-08) -Here are a few early questions I'd like to ask people here. -1. Have we had any duplicated EIPs that I overlooked. If not, have anyone attempted to do so, and why it did not continue to exist? -**Answer**: We concluded there is no duplicated efforts working on creating a voting standard. - -2. Should each issue have its own smart contract address (like individual item on [EIP-721](https://eips.ethereum.org/EIPS/eip-721)) or should it support multiple items in [EIP-1155](https://eips.ethereum.org/EIPS/eip-1155), or should it support multi-class voting in [EIP-1178](https://eips.ethereum.org/EIPS/eip-1178), [EIP-1203](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1203.md) (e.g. certain issue can override another issue) -**Answer**: We will provide examples of both and seek comments. - -3. Should the voting support proxy(e.g [EIP-897](https://eips.ethereum.org/EIPS/eip-897), [EIP-1167](https://eips.ethereum.org/EIPS/eip-1167)) and migration? What are potential security concerns -**Answer**: It shall not be determined by this ERC. - -4. Should it be proposed in a single phase standard or multiple separate into multiple phase, with earlier phase supporting easiest and simplest interface, and later phase supporting more advanced interfaces? (I intuitively believe it will be the latter, but not sure if it might be possible to do it all-at once.) -**Answer**: It will unavoidably require upgrade in the future, but supporting multiple issue multiple options will be good enough so far. - -1. Should it support or optionally support [EIP-165](https://eips.ethereum.org/EIPS/eip-165)? For public voting, support EIP-165 make it easier to discover, but for secret voting people might not want to disclose a voting for certain issue even exist. -**Answer**: It shall not be determined by this ERC. - -### Second Feedback Questions 2018-07-19 -1. Is it technically possible to achieve anonymous voting on current Ethereum/EVM setup, is it possible that people either hide their identity, or hide what selection they made in a vote given that for a smart contract the public states are visible from block history directly, and internal private state can be replied in any fullnode? - -2. number byte length: for simplicity we are using `uint` anywhere undecided. We need to decided what number byte length should we use for `weights` and `options`. - - -## Bibliography -### Related EIPs - - [EIP-20: ERC-20 Token Standard (a.k.a. ERC-20)](https://eips.ethereum.org/EIPS/eip-20) - - [EIP-165: Standard Interface Detection](https://eips.ethereum.org/EIPS/eip-165) - - [EIP-721: Non-Fungible Token Standard(a.k.a. ERC-721)](https://eips.ethereum.org/EIPS/eip-721) - - [EIP-735: ERC: Claim Holder](https://github.com/ethereum/EIPs/issues/735) - - [EIP-780: ERC: Ethereum Claims Registry](https://github.com/ethereum/EIPs/issues/780) - - [EIP-777: A New Advanced Token Standard](https://eips.ethereum.org/EIPS/eip-777) - - [EIP-897: ERC DelegateProxy](https://eips.ethereum.org/EIPS/eip-897) - - [EIP-1155: Crypto Item Standard](https://eips.ethereum.org/EIPS/eip-1155) - - [EIP-1178: Multi-class Token Standard](https://eips.ethereum.org/EIPS/eip-1178) - - [EIP-1167: Minimal Proxy Contract](https://eips.ethereum.org/EIPS/eip-1167) - - [EIP-1203: Multi-class Token Standard(ERC-20 Extension)](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1203.md) - -### Worthnoting Projects - - [Ethereum DAO: How to build a DEMOCRACY on the blockchain](https://www.ethereum.org/dao) - - [Carbon Vote](http://carbonvote.com/) - - [Paper: A Smart Contract for Boardroom Voting with Maximum Voter Privacy](https://eprint.iacr.org/2017/110.pdf) - *Suggested by @aodhgan* - - [Private Voting for TCR](https://blog.enigma.co/private-voting-for-tcrs-with-enigma-b441b5d4fa7b) - -### Worthnoting Academic Papers - - -## Request for Comment -We kindly request the community for comments, in particular, the following ERC and projects related authors: - - - ERC-20: @frozeman, @vbuterin - - ERC-721: @fulldecent, Dieter Shirley, Jacob Evans, Nastassia Sachs - - Carbon Vote: @lgn21st, @Aaaaaashu - - Alex Van de Sande (Mist) and Nick Johnson (ENS) * - suggested by Fabian (@frozeman)* - - Will Warren, 0xProject a project who cares a lot about governance. * - nominated by Evan()@evanbots)* - -Your comments and suggestions will be greatly appreciated. - -## Acknowledgement -The authors of EIP 1202 greatly appreciate the valuable input from distinguished community members including: @frozeman, @fulldecent, @bingen, @aodhgan. - -## EIP Work Logs - -- 2018-07-08: (@xinbenlv) Created early feedback request. Asked around discussion channels suggested in [EIP-1](https://eips.ethereum.org/EIPS/eip-1), such as [Ethereum-Magicians](https://ethereum-magicians.org/t/eip-x-voting-standard-early-feedback-wanted/670/2), [Gitter](https://gitter.im/ethereum/EIPs), [Reddit](https://www.reddit.com/r/ethereum/comments/8x6k11/early_feedback_request_for_eipx_voting_standard/) -- 2018-07-09: (@xinbenlv)Added examples outline. Request for co-author. -- 2018-07-17: (@xinbenlv)Added co-author. @evbots, added two simple examples. -- 2018-07-19: (@xinbenlv)Added interface-like specification. Moved content from [issue](https://github.com/ethereum/EIPs/issues/1202) to [xinbenlv's Github repo](https://github.com/xinbenlv/eip-1202-draft/blob/master/EIP-1202.md) . Added TokenVote example. -- 2018-07-20: (@xinbenlv)Added advanced token vote example. -- 2018-07-22: (@xinbenlv)Moved official discussion thread from [github issue](https://github.com/ethereum/EIPs/issues/1202) to [ethereum-magicians](https://ethereum-magicians.org/t/erc-1202-voting-standard-official-discussion-thread/670) - moved back as it's ok to use GitHub issue as official discussion thread. -- 2018-07-23: (@xinbenlv) - - added co-author Yin Xu (@yingogobot) - - added outline for a few applications and case studies for further drafting. - - added citation of ERC-735 and ERC-780 -- 2018-07-25: (@xinbenlv) Added input from @fulldecent, @bingen, @aodhgan to mention the privacy casting, PLCR etc, and -added placeholders for related session. - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1202.md diff --git a/EIPS/eip-1203.md b/EIPS/eip-1203.md index d4e30c9e877415..5d4e6d6f3a9d51 100644 --- a/EIPS/eip-1203.md +++ b/EIPS/eip-1203.md @@ -1,230 +1,7 @@ --- eip: 1203 -title: ERC-1203 Multi-Class Token Standard (ERC-20 Extension) -author: Jeff Huang , Min Zu -discussions-to: https://github.com/ethereum/EIPs/issues/1203 -status: Draft -type: Standards Track category: ERC -created: 2018-07-01 +status: Moved --- -## Simple Summary - -A standard interface for multi-class tokens (MCTs). - -## Abstract - -The following standard allows for the implementation of a standard API for MCTs within smart contracts. This standard provides basic functionality to track, transfer, and convert MCTs. - -## Motivation - -This standard is heavily inspired by ERC-20 Token Standard and ERC-721 Non-Fungible Token Standard. However, whereas these standards are chiefly concerned with representation of items/value in a single class, fungible or note, this proposed standard focus on that of a more complexed, multi-class system. It is fair to think of MCTs as a hybrid of fungible tokens (FT) and non-fungible tokens (NFTs), that is tokens are fungible within the same class but non-fungible with that from a different class. And conversions between classes may be optionally supported. - -MCTs are useful in representing various structures with heterogeneous components, such as: - -- **Abstract Concepts:** A company may have different classes of stocks (e.g. senior preferred, junior preferred, class A common, class B common) that together make up its outstanding equities. A shareholder's position of such company composites of zero or more shares in each class. - -- **Virtual Items:** A sandbox computer game may have many types of resources (e.g. rock, wood, berries, cows, meat, knife, etc.) that together make up that virtual world. A player's inventory has any combination and quantity of these resources - -- **Physical Items:** A supermarket may have many SKUs it has available for purchase (e.g. eggs, milk, beef jerky, beer, etc.). Things get added or removed from a shopper's cart as it moves down the aisle. - -It's sometimes possible, especially with regard to abstract concepts or virtual items, to convert from one class to another, at a specified conversion ratio. When it comes to physical items, such conversion essentially is the implementation of bartering. Though it might generally be easier to introduce a common intermediary class, i.e. money. - -## Specification - -```solidity -contract ERC20 { - function totalSupply() public view returns (uint256); - function balanceOf(address _owner) public view returns (uint256); - function transfer(address _to, uint256 _value) public returns (bool); - function approve(address _spender, uint256 _value) public returns (bool); - function allowance(address _owner, address _spender) public view returns (uint256); - function transferFrom(address _from, address _to, uint256 _value) public returns (bool); - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -} - -contract ERC1203 is ERC20 { - function totalSupply(uint256 _class) public view returns (uint256); - function balanceOf(address _owner, uint256 _class) public view returns (uint256); - function transfer(address _to, uint256 _class, uint256 _value) public returns (bool); - function approve(address _spender, uint256 _class, uint256 _value) public returns (bool); - function allowance(address _owner, address _spender, uint256 _class) public view returns (uint256); - function transferFrom(address _from, address _to, uint256 _class, uint256 _value) public returns (bool); - - function fullyDilutedTotalSupply() public view returns (uint256); - function fullyDilutedBalanceOf(address _owner) public view returns (uint256); - function fullyDilutedAllowance(address _owner, address _spender) public view returns (uint256); - function convert(uint256 _fromClass, uint256 _toClass, uint256 _value) public returns (bool); - - event Transfer(address indexed _from, address indexed _to, uint256 _class, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _class, uint256 _value); - event Convert(uint256 indexed _fromClass, uint256 indexed _toClass, uint256 _value); -} -``` - -### ERC-20 Methods and Events (fully compatible) - -Please see [ERC-20 Token Standard](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md) for detailed specifications. Do note that these methods and events only work on the "default" class of an MCT. - -```solidity - function totalSupply() public view returns (uint256); - function balanceOf(address _owner) public view returns (uint256); - function transfer(address _to, uint256 _value) public returns (bool); - function approve(address _spender, uint256 _value) public returns (bool); - function allowance(address _owner, address _spender) public view returns (uint256); - function transferFrom(address _from, address _to, uint256 _value) public returns (bool); - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -``` - -### Tracking and Transferring - -**totalSupply** - -Returns the total number of tokens in the specified `_class` - -```solidity - function totalSupply(uint256 _class) public view returns (uint256); -``` - -**balanceOf** - -Returns the number of tokens of a specified `_class` that the `_owner` has - -```solidity - function balanceOf(address _owner, uint256 _class) public view returns (uint256); -``` - -**transfer** - -Transfer `_value` tokens of `_class` to address specified by `_to`, return `true` if successful - -```solidity - function transfer(address _to, uint256 _class, uint256 _value) public returns (bool); -``` - -**approve** - -Grant `_spender` the right to transfer `_value` tokens of `_class`, return `true` if successful - -```solidity - function approve(address _spender, uint256 _class, uint256 _value) public returns (bool); -``` - -**allowance** - -Return the number of tokens of `_class` that `_spender` is authorized to transfer on the behalf of `_owner` - -```solidity - function allowance(address _owner, address _spender, uint256 _class) public view returns (uint256); -``` - -**transferFrom** - -Transfer `_value` tokens of `_class` from address specified by `_from` to address specified by `_to` as previously approved, return `true` if successful - -```solidity - function transferFrom(address _from, address _to, uint256 _class, uint256 _value) public returns (bool); -``` - -**Transfer** - -Triggered when tokens are transferred or created, including zero value transfers - -```solidity - event Transfer(address indexed _from, address indexed _to, uint256 _class, uint256 _value); -``` - -**Approval** - -Triggered on successful `approve` - -```solidity - event Approval(address indexed _owner, address indexed _spender, uint256 _class, uint256 _value); -``` - -### Conversion and Dilution - -**fullyDilutedTotalSupply** - -Return the total token supply as if all converted to the lowest common denominator class - -```solidity - function fullyDilutedTotalSupply() public view returns (uint256); -``` - -**fullyDilutedBalanceOf** - -Return the total token owned by `_owner` as if all converted to the lowest common denominator class - -```solidity - function fullyDilutedBalanceOf(address _owner) public view returns (uint256); -``` - -**fullyDilutedAllowance** - -Return the total token `_spender` is authorized to transfer on behalf of `_owner` as if all converted to the lowest common denominator class - -```solidity - function fullyDilutedAllowance(address _owner, address _spender) public view returns (uint256); -``` - -**convert** - -Convert `_value` of `_fromClass` to `_toClass`, return `true` if successful - -```solidity - function convert(uint256 _fromClass, uint256 _toClass, uint256 _value) public returns (bool); -``` - -**Conversion** - -Triggered on successful `convert` - -```solidity - event Conversion(uint256 indexed _fromClass, uint256 indexed _toClass, uint256 _value); -``` - -## Rationale -This standard purposely extends ERC-20 Token Standard so that new MCTs following or existing ERC-20 tokens extending this standard are fully compatible with current wallets and exchanges. In addition, new methods and events are kept as closely to ERC-20 conventions as possible for ease of adoption. - -We have considered alternative implementations to support the multi-class structure, as discussed below, and we found current token standards incapable or inefficient in deal with such structures. - -**Using multiple ERC-20 tokens** - -It is certainly possible to create an ERC-20 token for each class, and a separate contract to coordinate potential conversions, but the short coming in this approach is clearly evident. The rationale behind this standard is to have a single contract to manage multiple classes of tokens. - -**Shoehorning ERC-721 token** - -Treating each token as unique, the non-fungible token standard offers maximum representational flexibility arguably at the expense of convenience. The main challenge of using ERC-721 to represent multi-class token is that separate logic is required to keep track of which tokens belongs to which class, a hacky and unnecessary endeavor. - -**Using ERC-1178 token** - -We came across ERC-1178 as we were putting final touches on our own proposal. The two ERCs look very similar on the surface but we believe there're a few key advantages this one has over ERC-1178. - -- ERC-1178 offers no backward compatibility whereas this proposal is an extension of ERC-20 and therefore fully compatible with all existing wallets and exchanges -- By the same token, existing ERC-20 contracts can extend themselves to adopt this standard and support additional classes without affecting their current behaviors -- This proposal introduces the concept of cross class conversion and dilution, making each token class integral part of a whole system rather than many silos - -## Backwards Compatibility -This EIP is fully compatible with the mandatory methods of ERC20 Token Standard so long as the implementation includes a "lowest common denominator" class, which may be class B common/gold coin/money in the abstract/virtual/physical examples above respectively. Where it is not possible to implement such class, then the implementation should specify a default class for tracking or transferring unless otherwise specified, e.g. US dollar is transferred unless other currency is explicitly specified. - -We find it contrived to require the optional methods of ERC20 Token Standard, `name()`, `symbol()`, and `decimals()`, but developers are certainly free to implement these as they wish. - -## Test Cases -The repository at [jeffishjeff/ERC-1203](https://github.com/jeffishjeff/ERC-1203) contains the [sample test cases](https://github.com/jeffishjeff/ERC-1203/blob/master/token.test.js). - -## Implementation -The repository at [jeffishjeff/ERC-1203](https://github.com/jeffishjeff/ERC-1203) contains the [sample implementation](https://github.com/jeffishjeff/ERC-1203/blob/master/token.sol). - -## References -- ERC-20 Token Standard. https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md -- ERC-721 Non-Fungible Token Standard. https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md -- ERC-1178 Multi-class Token Standard. https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1178.md - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1203.md diff --git a/EIPS/eip-1207.md b/EIPS/eip-1207.md index 5f769b7564a307..867e74672a09f4 100644 --- a/EIPS/eip-1207.md +++ b/EIPS/eip-1207.md @@ -1,169 +1,7 @@ --- eip: 1207 -title: DAuth Access Delegation Standard -author: Xiaoyu Wang (@wxygeek), Bicong Wang (@Wangbicong) -discussions-to: https://github.com/ethereum/EIPs/issues/1207 -status: Draft -type: Standards Track category: ERC -created: 2018-07-10 +status: Moved --- -DAuth Access Delegation Standard -===== - -## Simple Summary -DAuth is a standard interface for accessing authorization delegation between smart contracts and users. - -## Abstract -The DAuth protocol defines a set of standard API allowing identity delegations between smart contracts without the user's private key. Identity delegations include accessing and operating a user's data and assets contained in the delegated contracts. - -## Motivation -The inspiration for designing DAuth comes from OAuth protocol that is extensively used in web applications. But unlike the centralized authorization of OAuth, DAuth works in a distributed manner, thus providing much more reliability and generality. - -## Specification -![Rationale](../assets/eip-1207/rationale.png) - -**Resource owner**: the authorizer - -**Resource contract**: the contract providing data and operators - -**API**: the resource contract APIs that the grantee contract can invoke - -**Client contract**: the grantee contract using authorization to access and operate the data - -**Grantee request**: the client contract calls the resource contract with the authorizer authorization - - -**AuthInfo** -``` js -struct AuthInfo { - string[] funcNames; - uint expireAt; -} -``` -Required - The struct contains user authorization information -* `funcNames`: a list of function names callable by the granted contract -* `expireAt`: the authorization expire timestamp in seconds - -**userAuth** -``` js -mapping(address => mapping(address => AuthInfo)) userAuth; -``` -Required - userAuth maps (authorizer address, grantee contract address) pair to the user’s authorization AuthInfo object - -**callableFuncNames** -``` js -string[] callableFuncNames; -``` -Required - All methods that are allowed other contracts to call -* The callable function MUST verify the grantee’s authorization - -**updateCallableFuncNames** -``` js -function updateCallableFuncNames(string _invokes) public returns (bool success); -``` -Optional - Update the callable function list for the client contract by the resource contract's administrator -* `_invokes`: the invoke methods that the client contract can call -* return: Whether the callableFuncNames is updated or not -* This method MUST return success or throw, no other outcomes can be possible - -**verify** -``` js -function verify(address _authorizer, string _invoke) internal returns (bool success); -``` -Required - check the invoke method authority for the client contract -* `_authorizer`: the user address that the client contract agents -* `_invoke`: the invoke method that the client contract wants to call -* return: Whether the grantee request is authorized or not -* This method MUST return success or throw, no other outcomes can be possible - -**grant** -``` js -function grant(address _grantee, string _invokes, uint _expireAt) public returns (bool success); -``` -Required - delegate a client contract to access the user's resource -* `_grantee`: the client contract address -* `_invokes`: the callable methods that the client contract can access. It is a string which contains all function names split by spaces -* `_expireAt`: the authorization expire timestamp in seconds -* return: Whether the grant is successful or not -* This method MUST return success or throw, no other outcomes can be possible -* A successful grant MUST fire the Grant event(defined below) - -**regrant** -``` js -function regrant(address _grantee, string _invokes, uint _expireAt) public returns (bool success); -``` -Optional - alter a client contract's delegation - -**revoke** -``` js -function revoke(address _grantee) public returns (bool success); -``` -Required - delete a client contract's delegation -* `_grantee`: the client contract address -* return: Whether the revoke is successful or not -* A successful revoke MUST fire the Revoke event(defined below). - -**Grant** -``` js -event Grant(address _authorizer, address _grantee, string _invokes, uint _expireAt); -``` -* This event MUST trigger when the authorizer grant a new authorization when `grant` or `regrant` processes successfully - -**Revoke** -``` js -event Revoke(address _authorizer, address _grantee); -``` -* This event MUST trigger when the authorizer revoke a specific authorization successfully - -**Callable Resource Contract Functions** - -All public or external functions that are allowed the grantee to call MUST use overload to implement two functions: The First one is the standard method that the user invokes directly, the second one is the grantee methods of the same function name with one more authorizer address parameter. - -Example: -``` js -function approve(address _spender, uint256 _value) public returns (bool success) { - return _approve(msg.sender, _spender, _value); -} - -function approve(address _spender, uint256 _value, address _authorizer) public returns (bool success) { - verify(_authorizer, "approve"); - - return _approve(_authorizer, _spender, _value); -} - -function _approve(address sender, address _spender, uint256 _value) internal returns (bool success) { - allowed[sender][_spender] = _value; - emit Approval(sender, _spender, _value); - return true; -} -``` - -## Rationale - -**Current Limitations** - -The current design of many smart contracts only considers the user invokes the smart contract functions by themselves using the private key. However, in some case, the user wants to delegate other client smart contracts to access and operate their data or assets in the resource smart contract. There isn’t a common protocol to provide a standard delegation approach. - -**Rationale** - -On the Ethereum platform, all storage is transparent and the `msg.sender` is reliable. Therefore, the DAuth don't need an `access_token` like OAuth. DAuth just recodes the users' authorization for the specific client smart contract's address. It is simple and reliable on the Ethereum platform. - -## Backwards Compatibility -This EIP introduces no backward compatibility issues. In the future, the new version protocol has to keep these interfaces. - -## Implementation -Following is the DAuth Interface implementation. Furthermore, the example implementations of EIP20 Interface and ERC-DAuth Interface are also provided. Developers can easily implement their own contracts with ERC-DAuth Interface and other EIP. - -* ERC-DAuth Interface implementation is available at: - - https://github.com/DIA-Network/ERC-DAuth/blob/master/ERC-DAuth-Interface.sol - -* Example implementation with EIP20 Interface and ERC-DAuth Interface is available at: - - https://github.com/DIA-Network/ERC-DAuth/blob/master/eip20-dauth-example/EIP20DAuth.sol - - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1207.md diff --git a/EIPS/eip-1227.md b/EIPS/eip-1227.md index 6bc6da904bb204..f731b13d77bba3 100644 --- a/EIPS/eip-1227.md +++ b/EIPS/eip-1227.md @@ -3,7 +3,7 @@ eip: 1227 title: Defuse Difficulty Bomb and Reset Block Reward author: SmeargleUsedFly (@SmeargleUsedFly) discussions-to: https://github.com/ethereum/EIPs/issues/1227 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-07-18 @@ -17,13 +17,13 @@ This EIP proposes to permanently disable the "difficulty bomb" and reset the blo Starting with `FORK_BLKNUM` the client will calculate the difficulty without the additional exponential component. Furthermore, block rewards will be adjusted to a base of 5 ETH, uncle and nephew rewards will be adjusted accordingly. ## Motivation -Due to the "difficulty bomb" (also known as the "ice age"), introduced in EIP [#2](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md), an artificial exponential increase in difficulty until chain freeze, users may find it much more challenging to remain on the unforked chain after a hard-fork. This is a desirable effect of the ice age (in fact, its only stated purpose) in the case of a scheduled network upgrade, but is especially problematic when a hard-fork includes a controversial change. +Due to the "difficulty bomb" (also known as the "ice age"), introduced in EIP [#2](./eip-2.md), an artificial exponential increase in difficulty until chain freeze, users may find it much more challenging to remain on the unforked chain after a hard-fork. This is a desirable effect of the ice age (in fact, its only stated purpose) in the case of a scheduled network upgrade, but is especially problematic when a hard-fork includes a controversial change. -This situation has already been observed: during the Byzantium hard-fork users were given the "choice" of following the upgraded side of the chain or remaining on the original chain, the latter already experiencing block times greater than 30 seconds. In reality one will find that organizing a disperse and decentralized set of individuals to keep the original, soon-to-be-dead chain alive under such conditions impossible. This is exacerbated when a controversial change, such as EIP [#649](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-649.md), is merged in so close to the hard-fork date, as users cannot be organized to take an educated stance for or against the change on such short notice. +This situation has already been observed: during the Byzantium hard-fork users were given the "choice" of following the upgraded side of the chain or remaining on the original chain, the latter already experiencing block times greater than 30 seconds. In reality one will find that organizing a disperse and decentralized set of individuals to keep the original, soon-to-be-dead chain alive under such conditions impossible. This is exacerbated when a controversial change, such as EIP [#649](./eip-649.md), is merged in so close to the hard-fork date, as users cannot be organized to take an educated stance for or against the change on such short notice. Ultimately, the difficulty bomb serves but a single purpose: make it more difficult to keep the original chain alive after a hard-fork. This is unacceptable if the only way the community can make their voice heard is running/not running client software, and not through the EIP process, since they effectively have no choice and therefore no power. This EIP proposes to completely eliminate the difficulty bomb, returning some measure of power over Ethereum's governance process to the users, to the community. -Given the controversy surrounding the directly relevant EIP [#649](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-649.md), the issuance should also be reset to pre-Byzantium levels. It may be reduced again at a later time via a new hard-fork, only this time users would actually have a meaningful choice in accepting the change or not. Note: the issuance reduction is not the focus of this proposal, and is optional; the defusing of the difficulty bomb is of primary concern. +Given the controversy surrounding the directly relevant EIP [#649](./eip-649.md), the issuance should also be reset to pre-Byzantium levels. It may be reduced again at a later time via a new hard-fork, only this time users would actually have a meaningful choice in accepting the change or not. Note: the issuance reduction is not the focus of this proposal, and is optional; the defusing of the difficulty bomb is of primary concern. ## Specification #### Remove Exponential Component of Difficulty Adjustment @@ -49,7 +49,7 @@ The nephew reward for `block.number >= FORK_BLKNUM` is This is the existing pre-Byzantium formula for nephew rewards, simply adjusted with `new_block_reward`. ## Rationale -This will permanently, without further changes, disable the "ice age." It will also reset the block reward to pre-Byzantium levels. Both of these changes are specified similarly to EIP [#649](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-649.md), so they should require only minimal changes from client developers. +This will permanently, without further changes, disable the "ice age." It will also reset the block reward to pre-Byzantium levels. Both of these changes are specified similarly to EIP [#649](./eip-649.md), so they should require only minimal changes from client developers. ## Backwards Compatibility This EIP is not forward compatible and introduces backwards incompatibilities in the difficulty calculation, as well as the block, uncle and nephew reward structure. However, it may be controversial in nature among different sections of the userbase—the very problem this EIP is made to address. Therefore, it should not be included in a scheduled hardfork at a certain block number. It is suggested to implement this EIP in an isolated hard-fork before the second of the two Metropolis hard-forks. @@ -61,4 +61,4 @@ Forthcoming. Forthcoming. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1234.md b/EIPS/eip-1234.md index 5cf44307ef3793..b303473e3c9b18 100644 --- a/EIPS/eip-1234.md +++ b/EIPS/eip-1234.md @@ -46,7 +46,7 @@ This is the existing pre-Constantinople formula for nephew rewards, simply adjus ## Rationale This will delay the ice age by 29 million seconds (approximately 12 months), so the chain would be back at 30 second block times in winter 2019. An alternate proposal was to add special rules to the difficulty calculation to effectively _pause_ the difficulty between different blocks. This would lead to similar results. -This was previously discussed at All Core Devs Meeting [#42](https://github.com/ethereum/pm/blob/master/All%20Core%20Devs%20Meetings/Meeting%2042.md) and subsequent meetings; and accepted in the Constantinople Session [#1](https://github.com/ethereum/pm/issues/55). +This was previously discussed at All Core Devs Meeting [#42](https://github.com/ethereum/pm/blob/6dbd82303bfcb697eaf9a76de37f5fa570e6379d/AllCoreDevs-EL-Meetings/Meeting%2042.md) and subsequent meetings; and accepted in the Constantinople Session [#1](https://github.com/ethereum/pm/issues/55). ## Backwards Compatibility This EIP is not forward compatible and introduces backwards incompatibilities in the difficulty calculation, as well as the block, uncle and nephew reward structure. Therefore, it should be included in a scheduled hardfork at a certain block number. It's suggested to include this EIP in the second Metropolis hard-fork, _Constantinople_. @@ -55,7 +55,7 @@ This EIP is not forward compatible and introduces backwards incompatibilities in Test cases shall be created once the specification is to be accepted by the developers or implemented by the clients. ## Implementation -The implementation in it's logic does not differ from [EIP-649](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-649.md); an implementation for Parity-Ethereum is available in [parity-ethereum#9187](https://github.com/paritytech/parity-ethereum/pull/9187). +The implementation in it's logic does not differ from [EIP-649](./eip-649.md); an implementation for Parity-Ethereum is available in [parity-ethereum#9187](https://github.com/paritytech/parity-ethereum/pull/9187). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1240.md b/EIPS/eip-1240.md index 03290c3bebd491..e9c787cc4866f7 100644 --- a/EIPS/eip-1240.md +++ b/EIPS/eip-1240.md @@ -5,7 +5,7 @@ author: Micah Zoltu (@MicahZoltu) discussions-to: https://ethereum-magicians.org/t/difficulty-bomb-removal/832 type: Standards Track category: Core -status: Draft +status: Withdrawn created: 2018-07-21 --- @@ -37,4 +37,4 @@ Test cases shall be created once the specification is to be accepted by the deve The yellow paper implements this change in https://github.com/ethereum/yellowpaper/pull/710 ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1261.md b/EIPS/eip-1261.md index 75dd50da28c7fb..ba3f868fa31714 100644 --- a/EIPS/eip-1261.md +++ b/EIPS/eip-1261.md @@ -1,390 +1,7 @@ --- eip: 1261 -title: Membership Verification Token (MVT) -author: Chaitanya Potti (@chaitanyapotti), Partha Bhattacharya (@pb25193) -type: Standards Track category: ERC -status: Draft -created: 2018-07-14 -requires: 165, 173 -discussions-to: https://github.com/ethereum/EIPs/issues/1261 +status: Moved --- -## Simple Summary - -A standard interface for Membership Verification Token(MVT). - -## Abstract - -The following standard allows for the implementation of a standard API for Membership Verification Token within smart contracts(called entities). This standard provides basic functionality to track membership of individuals in certain on-chain ‘organizations’. This allows for several use cases like automated compliance, and several forms of governance and membership structures. - -We considered use cases of MVTs being assigned to individuals which are non-transferable and revocable by the owner. MVTs can represent proof of recognition, proof of membership, proof of right-to-vote and several such otherwise abstract concepts on the blockchain. The following are some examples of those use cases, and it is possible to come up with several others: - -- Voting: Voting is inherently supposed to be a permissioned activity. So far, onchain voting systems are only able to carry out voting with coin balance based polls. This can now change and take various shapes and forms. -- Passport issuance, social benefit distribution, Travel permit issuance, Drivers licence issuance are all applications which can be abstracted into membership, that is belonging of an individual to a small set, recognized by some authority as having certain entitlements, without needing any individual specific information(right to welfare, freedom of movement, authorization to operate vehicles, immigration) -- Investor permissioning: Making regulatory compliance a simple on chain process. Tokenization of securities, that are streamlined to flow only to accredited addresses, tracing and certifying on chain addresses for AML purposes. -- Software licencing: Software companies like game developers can use the protocol to authorize certain hardware units(consoles) to download and use specific software(games) - -In general, an individual can have different memberships in his day to day life. The protocol allows for the creation of software that puts everything all at one place. His identity can be verified instantly. Imagine a world where you don't need to carry a wallet full of identity cards (Passport, gym membership, SSN, Company ID etc) and organizations can easily keep track of all its members. Organizations can easily identify and disallow fake identities. - -Attributes are a huge part of ERC-1261 which help to store identifiable information regarding its members. Polls can make use of attributes to calculate the voterbase. -E.g: Users should belong to USA entity and not belong to Washington state attribute to be a part of a poll. - -There will exist a mapping table that maps attribute headers to an array of all possible attributes. This is done in order to subdivide entities into subgroups which are exclusive and exhaustive. For example, -header: blood group alphabet -Array: [ o, a, b, ab ] -header: blood group sign -Array: [ +, - ] - -NOT an example of exclusive exhaustive: -Header: video subscription -Array: [ Netflix, HBO, Amazon ] -Because a person is not necessitated to have EXACTLY one of the elements. He or she may have none or more than one. - -## Motivation - -A standard interface allows any user,applications to work with any MVT on Ethereum. We provide for simple ERC-1261 smart contracts. Additional applications are discussed below. - -This standard is inspired from the fact that voting on the blockchain is done with token balance weights. This has been greatly detrimental to the formation of flexible governance systems on the blockchain, despite the tremendous governance potential that blockchains offer. The idea was to create a permissioning system that allows organizations to vet people once into the organization on the blockchain, and then gain immense flexibility in the kind of governance that can be carried out. - -We have also reviewed other Membership EIPs including EIP-725/735 Claim Registry. A significant difference between #735 claims and #1261 MVTs is information ownership. In #735 the Claim Holder owns any claims made about themselves. The problem with this is that there is no way for a Claim Issuer to revoke or alter a claim once it has been issued. While #735 does specify a removeClaim method, a malicious implementation could simply ignore that method call, because they own the claim. - -Imagine that SafeEmploy™, a background checking company, issues a claim about Timmy. The claim states that Timmy has never been convicted of any felonies. Timmy makes some bad decisions, and now that claim is no longer true. SafeEmploy™ executes removeClaim, but Timmy's #735 contract just ignores it, because Timmy wants to stay employed (and is crypto-clever). #1261 MVTs do not have this problem. Ownership of a badge/claim is entirely determined by the contract issuing the badges, not the one receiving them. The issuer is free to remove or change those badges as they see fit. - -**Trade-off between trustlessness and usability:** -To truly understand the value of the protocol, it is important to understand the trade-off we are treading on. The MVT contract allows the creator to revoke the token, and essentially confiscate the membership of the member in question. To some, this might seem like an unacceptable flaw, however this is a design choice, and not a flaw. -The choice may seem to place a great amount of trust in the individuals who are managing the entity contract(entity owners). If the interests of the entity owner conflict with the interests of the members, the owner may resort to addition of fake addresses(to dominate consensus) or evicting members(to censor unfavourable decisions). At first glance this appears to be a major shortcomings, because the blockchain space is used to absolute removal of authority in most cases. Even the official definition of a dapp requires the absence of any party that manages the services provided by the application. However, the trust in entity owners is not misplaced, if it can be ensured that the interests of entity owners are aligned with the interests of members. -Another criticism of such a system would be that the standard edge of blockchain intermediation - “you cannot bribe the system if you don’t know who to bribe” - no longer holds. It is possible to bribe an entity owner into submission, and get them to censor or fake votes. There are several ways to respond to this argument. First of all, all activities, such as addition of members, and removal of members can be tracked on the blockchain and traces of such activity cannot be removed. It is not difficult to build analytics tools to detect malicious activity(adding 100 fake members suddenly who vote in the direction/sudden removal of a number of members voting in a certain direction). Secondly, the entity owners’ power is limited to the addition and removal of members. This means that they cannot tamper any votes. They can only alter the counting system to include fake voters or remove real voters. Any sensible auditor can identify the malicious/victim addresses and create an open source audit tool to find out the correct results. The biggest loser in this attack will be the entity owner, who has a reputation to lose. -Finally, one must understand why we are taking a step away from trustlessness in this trade-off. The answer is usability. Introducing a permissioning system expands the scope of products and services that can be delivered through the blockchain, while leveraging other aspects of the blockchain(cheap, immutable, no red-tape, secure). Consider the example of the driver licence issuing agency using the ERC-1300 standard. This is a service that simply cannot be deployed in a completely trustless environment. The introduction of permissioned systems expanded the scope of services on the blockchain to cover this particular service. Sure, they have the power to revoke a person’s licence for no reason. But will they? Who stands to lose the most, if the agency acts erratically? The agency itself. Now consider the alternative, the way licences(not necessarily only drivers licence, but say shareholder certificates and so on) are issued, the amount of time consumed, the complete lack of transparency. One could argue that if the legacy systems providing these services really wanted to carry out corruption and nepotism in the execution of these services, the present systems make it much easier to do so. Also, they are not transparent, meaning that there is no way to even detect if they act maliciously. -All that being said, we are very excited to share our proposal with the community and open up to suggestions in this space. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Every ERC-1261 compliant contract must implement the `ERC1261`, `ERC173` and `ERC165` interfaces** (subject to "caveats" below): - -```solidity -/// @title ERC-1261 MVT Standard -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1261.md -/// The constructor should define the attribute set for this MVT. -/// Note: the ERC-165 identifier for this interface is 0x1d8362cf. -interface IERC1261 {/* is ERC173, ERC165 */ - /// @dev This emits when a token is assigned to a member. - event Assigned(address indexed _to, uint[] attributeIndexes); - - /// @dev This emits when a membership is revoked. - event Revoked(address indexed _to); - - /// @dev This emits when a user forfeits his membership - event Forfeited(address indexed _to); - - /// @dev This emits when a membership request is accepted - event ApprovedMembership(address indexed _to, uint[] attributeIndexes); - - /// @dev This emits when a membership is requested by an user - event RequestedMembership(address indexed _to); - - /// @dev This emits when data of a member is modified. - /// Doesn't emit when a new membership is created and data is assigned. - event ModifiedAttributes(address indexed _to, uint attributeIndex, uint attributeValueIndex); - - /// @notice Adds a new attribute (key, value) pair to the set of pre-existing attributes. - /// @dev Adds a new attribute at the end of the array of attributes and maps it to `values`. - /// Contract can set a max number of attributes and throw if limit is reached. - /// @param _name Name of the attribute which is to be added. - /// @param values List of values of the specified attribute. - function addAttributeSet(bytes32 _name, bytes32[] values) external; - - /// @notice Modifies the attribute value of a specific attribute for a given `_to` address. - /// @dev Use appropriate checks for whether a user/admin can modify the data. - /// Best practice is to use onlyOwner modifier from ERC173. - /// @param _to The address whose attribute is being modified. - /// @param _attributeIndex The index of attribute which is being modified. - /// @param _modifiedValueIndex The index of the new value which is being assigned to the user attribute. - function modifyAttributeByIndex(address _to, uint _attributeIndex, uint _modifiedValueIndex) external; - - /// @notice Requests membership from any address. - /// @dev Throws if the `msg.sender` already has the token. - /// The individual `msg.sender` can request for a membership if some existing criteria are satisfied. - /// When a membership is requested, this function emits the RequestedMembership event. - /// dev can store the membership request and use `approveRequest` to assign membership later - /// dev can also oraclize the request to assign membership later - /// @param _attributeIndexes the attribute data associated with the member. - /// This is an array which contains indexes of attributes. - function requestMembership(uint[] _attributeIndexes) external payable; - - /// @notice User can forfeit his membership. - /// @dev Throws if the `msg.sender` already doesn't have the token. - /// The individual `msg.sender` can revoke his/her membership. - /// When the token is revoked, this function emits the Revoked event. - function forfeitMembership() external payable; - - /// @notice Owner approves membership from any address. - /// @dev Throws if the `_user` doesn't have a pending request. - /// Throws if the `msg.sender` is not an owner. - /// Approves the pending request - /// Make oraclize callback call this function - /// When the token is assigned, this function emits the `ApprovedMembership` and `Assigned` events. - /// @param _user the user whose membership request will be approved. - function approveRequest(address _user) external; - - /// @notice Owner discards membership from any address. - /// @dev Throws if the `_user` doesn't have a pending request. - /// Throws if the `msg.sender` is not an owner. - /// Discards the pending request - /// Make oraclize callback call this function if criteria are not satisfied - /// @param _user the user whose membership request will be discarded. - function discardRequest(address _user) external; - - /// @notice Assigns membership of an MVT from owner address to another address. - /// @dev Throws if the member already has the token. - /// Throws if `_to` is the zero address. - /// Throws if the `msg.sender` is not an owner. - /// The entity assigns the membership to each individual. - /// When the token is assigned, this function emits the Assigned event. - /// @param _to The address to which the token is assigned. - /// @param _attributeIndexes The attribute data associated with the member. - /// This is an array which contains indexes of attributes. - function assignTo(address _to, uint[] _attributeIndexes) external; - - /// @notice Only Owner can revoke the membership. - /// @dev This removes the membership of the user. - /// Throws if the `_from` is not an owner of the token. - /// Throws if the `msg.sender` is not an owner. - /// Throws if `_from` is the zero address. - /// When transaction is complete, this function emits the Revoked event. - /// @param _from The current owner of the MVT. - function revokeFrom(address _from) external; - - /// @notice Queries whether a member is a current member of the organization. - /// @dev MVT's assigned to the zero address are considered invalid, and this - /// function throws for queries about the zero address. - /// @param _to An address for whom to query the membership. - /// @return Whether the member owns the token. - function isCurrentMember(address _to) external view returns (bool); - - /// @notice Gets the value collection of an attribute. - /// @dev Returns the values of attributes as a bytes32 array. - /// @param _name Name of the attribute whose values are to be fetched - /// @return The values of attributes. - function getAttributeExhaustiveCollection(bytes32 _name) external view returns (bytes32[]); - - /// @notice Returns the list of all past and present members. - /// @dev Use this function along with isCurrentMember to find wasMemberOf() in Js. - /// It can be calculated as present in getAllMembers() and !isCurrentMember(). - /// @return List of addresses who have owned the token and currently own the token. - function getAllMembers() external view returns (address[]); - - /// @notice Returns the count of all current members. - /// @dev Use this function in polls as denominator to get percentage of members voted. - /// @return Count of current Members. - function getCurrentMemberCount() external view returns (uint); - - /// @notice Returns the list of all attribute names. - /// @dev Returns the names of attributes as a bytes32 array. - /// AttributeNames are stored in a bytes32 Array. - /// Possible values for each attributeName are stored in a mapping(attributeName => attributeValues). - /// AttributeName is bytes32 and attributeValues is bytes32[]. - /// Attributes of a particular user are stored in bytes32[]. - /// Which has a single attributeValue for each attributeName in an array. - /// Use web3.toAscii(data[0]).replace(/\u0000/g, "") to convert to string in JS. - /// @return The names of attributes. - function getAttributeNames() external view returns (bytes32[]); - - /// @notice Returns the attributes of `_to` address. - /// @dev Throws if `_to` is the zero address. - /// Use web3.toAscii(data[0]).replace(/\u0000/g, "") to convert to string in JS. - /// @param _to The address whose current attributes are to be returned. - /// @return The attributes associated with `_to` address. - function getAttributes(address _to) external view returns (bytes32[]); - - /// @notice Returns the `attribute` stored against `_to` address. - /// @dev Finds the index of the `attribute`. - /// Throws if the attribute is not present in the predefined attributes. - /// Returns the attributeValue for the specified `attribute`. - /// @param _to The address whose attribute is requested. - /// @param _attributeIndex The attribute Index which is required. - /// @return The attribute value at the specified name. - function getAttributeByIndex(address _to, uint _attributeIndex) external view returns (bytes32); -} - -interface ERC173 /* is ERC165 */ { - /// @dev This emits when ownership of a contract changes. - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - /// @notice Get the address of the owner - /// @return The address of the owner. - function owner() view external; - - /// @notice Set the address of the new owner of the contract - /// @param _newOwner The address of the new owner of the contract - function transferOwnership(address _newOwner) external; -} - -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -The **metadata extension** is OPTIONAL for ERC-1261 smart contracts (see "caveats", below). This allows your smart contract to be interrogated for its name and for details about the organization which your MV tokens represent. - -```solidity -/// @title ERC-1261 MVT Standard, optional metadata extension -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1261.md -interface ERC1261Metadata /* is ERC1261 */ { - /// @notice A descriptive name for a collection of MVTs in this contract - function name() external view returns (string _name); - - /// @notice An abbreviated name for MVTs in this contract - function symbol() external view returns (string _symbol); -} -``` - -This is the "ERC1261 Metadata JSON Schema" referenced above. - -```json -{ - "title": "Organization Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the organization to which this MVT represents" - }, - "description": { - "type": "string", - "description": "Describes the organization to which this MVT represents" - } - } -} -``` - -### Caveats - -The 0.4.24 Solidity interface grammar is not expressive enough to document the ERC-1261 standard. A contract which complies with ERC-1261 MUST also abide by the following: - -- Solidity issue #3412: The above interfaces include explicit mutability guarantees for each function. Mutability guarantees are, in order weak to strong: `payable`, implicit nonpayable, `view`, and `pure`. Your implementation MUST meet the mutability guarantee in this interface and you MAY meet a stronger guarantee. For example, a `payable` function in this interface may be implemented as nonpayble (no state mutability specified) in your contract. We expect a later Solidity release will allow your stricter contract to inherit from this interface, but a workaround for version 0.4.24 is that you can edit this interface to add stricter mutability before inheriting from your contract. -- Solidity issue #3419: A contract that implements `ERC1261Metadata` SHALL also implement `ERC1261`. -- Solidity issue #2330: If a function is shown in this specification as `external` then a contract will be compliant if it uses `public` visibility. As a workaround for version 0.4.24, you can edit this interface to switch to `public` before inheriting from your contract. -- Solidity issues #3494, #3544: Use of `this.*.selector` is marked as a warning by Solidity, a future version of Solidity will not mark this as an error. - -_If a newer version of Solidity allows the caveats to be expressed in code, then this EIP MAY be updated and the caveats removed, such will be equivalent to the original specification._ - -## Rationale - -There are many potential uses of Ethereum smart contracts that depend on tracking membership. Examples of existing or planned MVT systems are Vault, a DAICO platform, and Stream, a security token framework. Future uses include the implementation of direct democracy, in-game memberships and badges, licence and travel document issuance, electronic voting machine trails, software licencing and many more. - -**MVT Word Choice:** - -Since the tokens are non transferable and revocable, they function like membership cards. Hence the word membership verification token. - -**Transfer Mechanism** - -MVTs can't be transferred. This is a design choice, and one of the features that distinguishes this protocol. -Any member can always ask the issuer to revoke the token from an existing address and assign to a new address. -One can think of the set of MVTs as identifying a user, and you cannot split the user into parts and have it be the same user, but you can transfer a user to a new private key. - -**Assign and Revoke mechanism** - -The assign and revoke functions' documentation only specify conditions when the transaction MUST throw. Your implementation MAY also throw in other situations. This allows implementations to achieve interesting results: - -- **Disallow additional memberships after a condition is met** — Sample contract available on Github -- **Blacklist certain address from receiving MV tokens** — Sample contract available on Github -- **Disallow additional memberships after a certain time is reached** — Sample contract available on Github -- **Charge a fee to user of a transaction** — require payment when calling `assign` and `revoke` so that condition checks from external sources can be made - -**ERC-173 Interface** - -We chose Standard Interface for Ownership (ERC-173) to manage the ownership of a ERC-1261 contract. - -A future EIP/ Zeppelin may create a multi-ownable implementation for ownership. We strongly support such an EIP and it would allow your ERC-1261 implementation to implement `ERC1261Metadata`, or other interfaces by delegating to a separate contract. - -**ERC-165 Interface** - -We chose Standard Interface Detection (ERC-165) to expose the interfaces that a ERC-1261 smart contract supports. - -A future EIP may create a global registry of interfaces for contracts. We strongly support such an EIP and it would allow your ERC-1261 implementation to implement `ERC1261Metadata`, or other interfaces by delegating to a separate contract. - -**Gas and Complexity** (regarding the enumeration extension) - -This specification contemplates implementations that manage a few and _arbitrarily large_ numbers of MVTs. If your application is able to grow then avoid using for/while loops in your code. These indicate your contract may be unable to scale and gas costs will rise over time without bound - -**Privacy** - -Personal information: The protocol does not put any personal information on to the blockchain, so there is no compromise of privacy in that respect. -Membership privacy: The protocol by design, makes it public which addresses are/aren’t members. Without making that information public, it would not be possible to independently audit governance activity or track admin(entity owner) activity. - -**Metadata Choices** (metadata extension) - -We have required `name` and `symbol` functions in the metadata extension. Every token EIP and draft we reviewed (ERC-20, ERC-223, ERC-677, ERC-777, ERC-827) included these functions. - -We remind implementation authors that the empty string is a valid response to `name` and `symbol` if you protest to the usage of this mechanism. We also remind everyone that any smart contract can use the same name and symbol as _your_ contract. How a client may determine which ERC-1261 smart contracts are well-known (canonical) is outside the scope of this standard. - -A mechanism is provided to associate MVTs with URIs. We expect that many implementations will take advantage of this to provide metadata for each MVT system. The URI MAY be mutable (i.e. it changes from time to time). We considered an MVT representing membership of a place, in this case metadata about the organization can naturally change. - -Metadata is returned as a string value. Currently this is only usable as calling from `web3`, not from other contracts. This is acceptable because we have not considered a use case where an on-blockchain application would query such information. - -_Alternatives considered: put all metadata for each asset on the blockchain (too expensive), use URL templates to query metadata parts (URL templates do not work with all URL schemes, especially P2P URLs), multiaddr network address (not mature enough)_ - -**Community Consensus** - -We have been very inclusive in this process and invite anyone with questions or contributions into our discussion. However, this standard is written only to support the identified use cases which are listed herein. - -## Backwards Compatibility - -We have adopted `name` and `symbol` semantics from the ERC-20 specification. - -Example MVT implementations as of July 2018: - -- Membership Verification Token(https://github.com/chaitanyapotti/MembershipVerificationToken) - -## Test Cases - -Membership Verification Token ERC-1261 Token includes test cases written using Truffle. - -## Implementations - -Membership Verification Token ERC1261 -- a reference implementation - -- MIT licensed, so you can freely use it for your projects -- Includes test cases -- Also available as a npm package - npm i membershipverificationtoken - -## References - -**Standards** - -1. ERC-20 Token Standard. https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md -1. ERC-165 Standard Interface Detection. https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md -1. ERC-725/735 Claim Registry https://github.com/ethereum/EIPs/blob/master/EIPS/eip-725.md -1. ERC-173 Owned Standard. https://github.com/ethereum/EIPs/issues/173 -1. JSON Schema. https://json-schema.org/ -1. Multiaddr. https://github.com/multiformats/multiaddr -1. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt - -**Issues** - -1. The Original ERC-1261 Issue. https://github.com/ethereum/eips/issues/1261 -1. Solidity Issue \#2330 -- Interface Functions are Axternal. https://github.com/ethereum/solidity/issues/2330 -1. Solidity Issue \#3412 -- Implement Interface: Allow Stricter Mutability. https://github.com/ethereum/solidity/issues/3412 -1. Solidity Issue \#3419 -- Interfaces Can't Inherit. https://github.com/ethereum/solidity/issues/3419 - -**Discussions** - -1. Gitter #EIPs (announcement of first live discussion). https://gitter.im/ethereum/EIPs?at=5b5a1733d2f0934551d37642 -1. ERC-1261 (announcement of first live discussion). https://github.com/ethereum/eips/issues/1261 - -**MVT Implementations and Other Projects** - -1. Membership Verification Token ERC-1261 Token. https://github.com/chaitanyapotti/MembershipVerificationToken - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1261.md diff --git a/EIPS/eip-1271.md b/EIPS/eip-1271.md index a76c905d608968..2a1649d5b0f11f 100644 --- a/EIPS/eip-1271.md +++ b/EIPS/eip-1271.md @@ -1,95 +1,7 @@ --- eip: 1271 -title: Standard Signature Validation Method for Contracts -author: Francisco Giordano (@frangio), Matt Condon (@shrugs), Philippe Castonguay (@PhABC), Amir Bandeali (@abandeali1), Jorge Izquierdo (@izqui), Bertrand Masius (@catageek) -discussions-to: https://github.com/ethereum/EIPs/issues/1271 -status: Draft -type: Standards Track category: ERC -created: 2018-07-25 +status: Moved --- - - -## Simple Summary - -Many blockchain based applications allow users to sign off-chain messages instead of directly requesting users to do an on-chain transaction. This is the case for decentralized exchanges with off-chain orderbooks like [0x](https://0xproject.com/) and [etherdelta](https://etherdelta.com/). These applications usually assume that the message will be signed by the same address that owns the assets. However, one can hold assets directly in their regular account (controlled by a private key) *or* in a smart contract that acts as a wallet (e.g. a multisig contract). The current design of many smart contracts prevent contract based accounts from interacting with them, since contracts do not possess private keys and therefore can not directly sign messages. The proposal here outlines a standard way for contracts to verify if a provided signature is valid when the account is a contract. - -## Abstract - -Externally Owned Accounts (EOA) can sign messages with their associated private keys, but currently contracts cannot. This is a problem for many applications that implement signature based off-chain methods, since contracts can't easily interact with them as they do not possess a private key. Here, we propose a standard way for any contracts to verify whether a signature on a behalf of a given contract is valid. - -## Motivation - - -In the future, it is likely that many users will hold their assets in a smart contract instead of holding them in their externally owned account directly since contracts can improve user experience significantly while providing extra security. This means that contracts using signature based functions should not assume that a given address can provide ECDSA signatures. Otherwise, identity based contracts and contracts holding assets may not be able to interact with functions requiring ECDSA signatures directly. - -Here, we use the term *smart account* to refer to any contract that acts as an account, which can include identity based methods (e.g. [ERC-725](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-725.md) & [ERC-1078](https://github.com/alexvandesande/EIPs/blob/ee2347027e94b93708939f2e448447d030ca2d76/EIPS/eip-1078.md)), asset ownership (e.g. Multisigs, proxy contracts) and/or executable signed messages methods (e.g. [ERC-1077)](https://github.com/alexvandesande/EIPs/blob/ee2347027e94b93708939f2e448447d030ca2d76/EIPS/eip-1077.md). This terminology is important for the reader to better distinguish a contract that acts as an account (e.g. a multisig, wallet or [Gnosis Safe](https://github.com/gnosis/safe-contracts) contract) and a contract that does not act as an account but requires signatures. - -One example of an application that requires addresses to provide signatures would be decentralized exchanges with off-chain orderbook, where buy/sell orders are signed messages (see [0x](https://0xproject.com/) and [etherdelta](https://etherdelta.com/) for examples). In these applications, EOAs sign orders, signaling their desire to buy/sell a given asset and giving explicit permissions to the exchange smart contracts to conclude a trade via an ECDSA signature. When it comes to contracts however, ECDSA signature is not possible since contracts do not possess a private key. In the first version of the 0x protocol, smart contracts could not generate buy/sell orders for this very reason, as the `maker` needed to both own the assets *and* sign the order via ECDSA method. This was revised in their protocol version 2 (see below). - - - -## Specification - - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt). - -```javascript -pragma solidity ^0.5.0; - -contract ERC1271 { - - // bytes4(keccak256("isValidSignature(bytes,bytes)") - bytes4 constant internal MAGICVALUE = 0x20c13b0b; - - /** - * @dev Should return whether the signature provided is valid for the provided data - * @param _data Arbitrary length data signed on the behalf of address(this) - * @param _signature Signature byte array associated with _data - * - * MUST return the bytes4 magic value 0x20c13b0b when function passes. - * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) - * MUST allow external calls - */ - function isValidSignature( - bytes memory _data, - bytes memory _signature) - public - view - returns (bytes4 magicValue); -} -``` - -`isValidSignature` can call arbitrary methods to validate a given signature, which could be context dependent (e.g. time based or state based), EOA dependent (e.g. signers authorization level within smart wallet), signature scheme Dependent (e.g. ECDSA, multisig, BLS), etc. - - - -## Rationale - - -Such a function is important because it allows *other contracts* to validate signed messages on the behalf of the smart wallet. This is necessary because not all signed messages will first pass by the smart wallet as in ERC-1077, since signatures can be requested by independent contracts. Action based signed messages do not require this method for external contracts since the action is `smart wallet A -> Contract C` (e.g. owner of smart wallet `A` wants to transfer tokens `T` to contract `C`), but when the action is in the opposite direction (`Contract A -> SmartAccount`) this external function is necessary (e.g. `contract A` requires smart wallet `A` to transfer tokens `T` when event `E` is triggered). - -We believe the name of the proposed function to be appropriate considering that an *authorized* signers providing proper signatures for a given data would see their signature as "valid" by the smart wallet. Hence, an signed action message is only valid when the signer is authorized to perform a given action on the behalf of a smart wallet. - -Two arguments are provided for simplicity of separating the data from the signature, but both could be concatenated in a single byte array if community prefers this. - -`isValidSignature()` should not be able to modify states in order to prevent `GasToken` minting or similar attack vectors. A gas limit being passed is being considered, but could prevent some interesting use cases like large multisignatures or more costly validation and cryptographic schemes. - - - -## Backwards Compatibility - - -This EIP is backward compatible with previous work on signature validation since this method is specific to contract based signatures and not EOA signatures. - -## Implementation - - -Existing implementations : - -* The 0x project [implemented this method](https://github.com/0xProject/0x-monorepo/blob/05b35c0fdcbca7980d4195e96ec791c1c2d13398/packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol#L187) in their protocol version 2. -* Zeppelin is [in the process](https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1104) of implementing this method. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1271.md diff --git a/EIPS/eip-1276.md b/EIPS/eip-1276.md index 2225ad3d9790c2..f13ba7e3bd2f70 100644 --- a/EIPS/eip-1276.md +++ b/EIPS/eip-1276.md @@ -5,7 +5,7 @@ author: EOS Classic (@eosclassicteam) discussions-to: https://ethereum-magicians.org/t/eip-1276-eliminate-difficulty-bomb-and-adjust-block-reward-on-constantinople-shift/908 type: Standards Track category: Core -status: Draft +status: Stagnant created: 2018-07-31 --- @@ -48,7 +48,7 @@ This is the existing pre-Constantinople formula for nephew rewards, simply adjus ## Rationale This will completely remove the difficulty bomb on difficulty adjustment algorithm without delaying the difficulty bomb again, therefore it is possible to prevent network delay on the beginning of 2019. -This EIP-1276 opposes directly the intent of [EIP-1234](https://github.com/ethereum/EIPs/issues/1234) which should be also considered in discussions. +This EIP-1276 opposes directly the intent of [EIP-1234](./eip-1234.md) which should be also considered in discussions. ## Backwards Compatibility This EIP is not forward compatible and introduces backwards incompatibilities in the difficulty calculation, as well as the block, uncle and nephew reward structure. Therefore, it should be included in a scheduled hardfork at a certain block number. It's suggested to include this EIP in the second Metropolis hard-fork, _Constantinople_. @@ -60,4 +60,4 @@ Test cases shall be created once the specification is to be accepted by the deve The implementation shall be created once the specification is to be accepted by the developers or implemented by the clients. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1283.md b/EIPS/eip-1283.md index 38df50bc111a02..2a56a5607af599 100644 --- a/EIPS/eip-1283.md +++ b/EIPS/eip-1283.md @@ -11,9 +11,9 @@ created: 2018-08-01 ## Abstract -This EIP proposes net gas metering changes for SSTORE opcode, enabling +This EIP proposes net gas metering changes for `SSTORE` opcode, enabling new usages for contract storage, and reducing excessive gas costs -where it doesn't match how most implementation works. +where it doesn't match how most implementations work. This acts as an alternative for EIP-1087, where it tries to be friendlier to implementations that use different optimization @@ -23,7 +23,7 @@ strategies for storage change caches. This EIP proposes a way for gas metering on SSTORE (as an alternative for EIP-1087 and EIP-1153), using information that is more universally -available to most implementations, and require as little change in +available to most implementations, and requires as little change in implementation structures as possible. * *Storage slot's original value*. @@ -50,7 +50,7 @@ Definitions of terms are as below: * *Storage slot's new value*: This is the value of the storage after SSTORE operation happens. -Replace SSTORE opcode gas cost calculation (including refunds) with +Replace `SSTORE` opcode gas cost calculation (including refunds) with the following logic: * If *current value* equals *new value* (this is a no-op), 200 gas is @@ -91,7 +91,7 @@ implementation details: ## Explanation -The new gas cost scheme for SSTORE is divided into three different +The new gas cost scheme for `SSTORE` is divided into three different types: * **No-op**: the virtual machine does not need to do anything. This is @@ -109,11 +109,11 @@ We can see that the above three types cover all possible variations of **No-op** is a trivial operation. Below we only consider cases for **Fresh** and **Dirty**. -All initial (not-**No-op**) SSTORE on a particular storage slot starts +All initial (not-**No-op**) `SSTORE` on a particular storage slot starts with **Fresh**. After that, it will become **Dirty** if the value has been changed. When going from **Fresh** to **Dirty**, we charge the gas cost the same as current scheme. A **Dirty** storage slot can be -reset back to **Fresh** via a SSTORE opcode. This will trigger a +reset back to **Fresh** via a `SSTORE` opcode. This will trigger a refund. When a storage slot remains at **Dirty**, we charge 200 gas. In this @@ -178,7 +178,7 @@ concept of "dirty maps", or an extra storage struct. refactoring on this. Nonetheless, no extra memory or processing cost is needed on runtime. -Regarding SSTORE gas cost and refunds, see Appendix for proofs of +Regarding `SSTORE` gas cost and refunds, see Appendix for proofs of properties that this EIP satisfies. * For *absolute gas used* (that is, actual *gas used* minus *refund*), @@ -207,7 +207,7 @@ anticipated, and many contracts will see gas reduction. Below we provide 17 test cases. 15 of them covering consecutive two `SSTORE` operations are based on work [by @chfast](https://github.com/ethereum/tests/issues/483). Two additional -case with three `SSTORE` operations is used to test the case when a +cases with three `SSTORE` operations is used to test the case when a slot is reset and then set again. | Code | Used Gas | Refund | Original | 1st | 2nd | 3rd | @@ -332,4 +332,4 @@ We always start at state X. The first SSTORE can: ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1285.md b/EIPS/eip-1285.md index 3522a6cf14942e..7d6d20525b5360 100644 --- a/EIPS/eip-1285.md +++ b/EIPS/eip-1285.md @@ -1,27 +1,24 @@ --- eip: 1285 -title: Increase Gcallstipend gas in the CALL OPCODE +title: Increase Gcallstipend gas in the CALL opcode author: Ben Kaufman , Adam Levi discussions-to: https://ethereum-magicians.org/t/eip-1285-increase-gcallstipend-gas-in-the-call-opcode/941 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-08-01 --- ## Simple Summary - -Increase the ``Gcallstipend`` fee parameter in the ``CALL`` OPCODE from ``2,300`` to ``3,500`` gas units. +Increase the ``Gcallstipend`` fee parameter in the ``CALL`` opcode from ``2,300`` to ``3,500`` gas units. ## Abstract - -Currently, the ``CALL`` OPCODE forwards a stipend of ``2,300`` gas units for a non zero value ``CALL`` operations where a contract is called. This stipend is given to the contract to allow execution of its ``fallback`` function. The stipend given is intentionally small in order to prevent the called contract from spending the call gas or performing an attack (like re-entrancy). -While the stipend is small it should still give the sufficient gas required for some cheap OPCODES like ``LOG``, but it's not enough for some more complex and modern logics to be implemented. +Currently, the ``CALL`` opcode forwards a stipend of ``2,300`` gas units for a non zero value ``CALL`` operations where a contract is called. This stipend is given to the contract to allow execution of its ``fallback`` function. The stipend given is intentionally small in order to prevent the called contract from spending the call gas or performing an attack (like re-entrancy). +While the stipend is small it should still give the sufficient gas required for some cheap opcodes like ``LOG``, but it's not enough for some more complex and modern logics to be implemented. This EIP proposes to increase the given stipend from ``2,300`` to ``3,500`` to increase the usability of the ``fallback`` function. ## Motivation - The main motivation behind this EIP is to allow simple fallback functions to be implemented for contracts following the ``"Proxy"`` pattern. Simply explained, a ``"Proxy Contract"`` is a contract which use ``DELEGATECALL`` in its ``fallback`` function to behave according to the logic of another contract and serve as an independent instance for the logic of the contract it points to. This pattern is very useful for saving gas per deployment (as Proxy contracts are very lean) and it opens the ability to experiment with upgradability of contracts. On average, the ``DELEGATECALL`` functionality of a proxy contract costs about ``1,000`` gas units. @@ -29,20 +26,17 @@ When a contract transfers ETH to a proxy contract, the proxy logic will consume By slightly increasing the gas units given in the stipend we allow proxy contracts have proper ``fallback`` logic without increasing the attack surface of the calling contract. ## Specification - -Increase the ``Gcallstipend`` fee parameter in the ``CALL`` OPCODE from ``2,300`` to ``3,500`` gas unit. +Increase the ``Gcallstipend`` fee parameter in the ``CALL`` opcode from ``2,300`` to ``3,500`` gas unit. The actual change to the Ethereum clients would be to change the ``CallStipend`` they store as a constant. For an implementation example you can find a Geth client implementation linked [here](https://github.com/ben-kaufman/go-ethereum/tree/eip-1285). The actual change to the code can be found [here](https://github.com/ben-kaufman/go-ethereum/blob/eip-1285/params/protocol_params.go#L41). ## Rationale - The rational for increasing the ``Gcallstipend`` gas parameter by ``1,200`` gas units comes from the cost of performing ``DELEGATECALL`` and ``SLOAD`` with a small margin for some small additional operations. All while still keeping the stipend relatively small and insufficient for accessing the storage or changing the state. ## Backwards Compatibility - -This EIP requires a backwards incompatible change for the ``Gcallstipend`` gas parameter in the ``CALL`` OPCODE. +This EIP requires a backwards incompatible change for the ``Gcallstipend`` gas parameter in the ``CALL`` opcode. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1295.md b/EIPS/eip-1295.md index 9ced783cd23706..4eb207482cdd5d 100644 --- a/EIPS/eip-1295.md +++ b/EIPS/eip-1295.md @@ -3,26 +3,22 @@ eip: 1295 title: Modify Ethereum PoW Incentive Structure and Delay Difficulty Bomb author: Brian Venturo (@atlanticcrypto) discussions-to: https://github.com/atlanticcrypto/Discussion/issues/1 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-08-05 --- - ## Simple Summary - Network security and overall ecosystem maturity warrants the continued incentivization of Proof of Work participation but may allow for a reduction in ancillary ETH issuance and the delay of the Difficulty Bomb. This EIP proposes a reduction of Uncle and removal of Nephew rewards while delaying the Difficulty Bomb with the Constantinople hard fork. ## Abstract - Starting with CNSTNTNPL_FORK_BLKNUM the client will calculate the difficulty based on a fake block number suggesting the client that the difficulty bomb is adjusting around 6 million blocks later than previously specified with the Homestead fork. Furthermore, Uncle rewards will be adjusted and Nephew rewards will be removed to eliminate excess ancillary ETH issuance. The current ETH block reward of 3 ETH will remain constant. ## Motivation - Network scalability and security are at the forefront of risks to the Ethereum protocol. With great strides being made towards on and off chain scalability, the existence of an artificial throughput limiting device in the protocol is not warranted. Removing the risk of reducing throughput through the initialization of the Difficulty Bomb is "low-hanging-fruit" to ensure continued operation at a minimum of current throughput through the next major hard fork (scheduled for late 2019). The security layer of the Ethereum network is and should remain robust. Incentives for continued operation of the security of the growing ecosystem are paramount. @@ -30,7 +26,6 @@ The security layer of the Ethereum network is and should remain robust. Incentiv At the same time, the ancillary issuance benefits of the Ethereum protocol can be adjusted to reduce the overall issuance profile. Aggressively adjusting Uncle and removing Nephew rewards will reduce the inflationary aspect of ETH issuance, while keeping the current block reward constant at 3 ETH will ensure top line incentives stay in place. ## Specification - #### Relax Difficulty with Fake Block Number For the purposes of `calc_difficulty`, simply replace the use of `block.number`, as used in the exponential ice age component, with the formula: @@ -50,7 +45,6 @@ The nephew reward for `block.number >= CNSTNTNPL_FORK_BLKNUM` is This is a removal of all rewards for Nephew blocks. ## Rationale - The security layer of the Ethereum network is and should remain robust. Incentives for continued operation of the growing ecosystem’s security are paramount. @@ -83,16 +77,13 @@ With a reduction to the Uncle and removal of the Nephew reward, ancillary ETH is Paired with the diffusal of the Difficulty Bomb, this proposal strikes a balance between ensuring status quo network throughput, reducing overall ETH issuance, and continuing top line incentives for investment in infrastructure and efficiencies to continue operating the Ethereum network’s security layer. ## Backwards Compatibility - This EIP is not forward compatible and introduces backwards incompatibilities in the difficulty calculation, as well as the block, uncle and nephew reward structure. Therefore, it should be included in a scheduled hardfork at a certain block number. It's suggested to include this EIP in the second Metropolis hard-fork, Constantinople. ## Test Cases - Test cases shall be created once the specification is to be accepted by the developers or implemented by the clients. ## Implementation - Forthcoming. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1319.md b/EIPS/eip-1319.md index e51788eefd4ee0..f2692ae66c1298 100644 --- a/EIPS/eip-1319.md +++ b/EIPS/eip-1319.md @@ -1,176 +1,7 @@ --- eip: 1319 -title: Smart Contract Package Registry Interface -author: Piper Merriam , Christopher Gewecke , g. nicholas d'andrea , Nick Gheorghita -type: Standards Track category: ERC -status: Draft -created: 2018-08-13 -discussions-to: https://github.com/ethereum/EIPs/issues/1319 +status: Moved --- -## Simple Summary -A standard interface for smart contract package registries. - -## Abstract -This EIP specifies an interface for publishing to and retrieving assets from smart contract package registries. It is a companion EIP to [1123](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1123.md) which defines a standard for smart contract package manifests. - -## Motivation -The goal is to establish a framework that allows smart contract publishers to design and deploy code registries with arbitrary business logic while exposing a set of common endpoints that tooling can use to retrieve assets for contract consumers. - -A clear standard would help the existing EthPM Package Registry evolve from a centralized, single-project community resource into a decentralized multi-registry system whose constituents are bound together by the proposed interface. In turn, these registries could be ENS name-spaced, enabling installation conventions familiar to users of `npm` and other package managers. - -**Examples** -```shell -$ ethpm install packages.zeppelin.eth/Ownership -``` - -```javascript -const SimpleToken = await web3.packaging - .registry('packages.ethpm.eth') - .getPackage('simple-token') - .getVersion('^1.1.5'); -``` - -## Specification -The specification describes a small read/write API whose components are mandatory. It allows registries to manage versioned releases using the conventions of [semver](https://semver.org/) without imposing this as a requirement. It assumes registries will share the following structure and conventions: - -+ a **registry** is a deployed contract which manages a collection of **packages**. -+ a **package** is a collection of **releases** -+ a **package** is identified by a unique string name and unique bytes32 **packageId** within a given **registry** -+ a **release** is identified by a `bytes32` **releaseId** which must be unique for a given package name and release version string pair. -+ a **releaseId** maps to a set of data that includes a **manifestURI** string which describes the location of an [EIP 1123 package manifest](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1123.md). This manifest contains data about the release including the location of its component code assets. -+ a **manifestURI** is a URI as defined by [RFC3986](https://tools.ietf.org/html/rfc3986) which can be used to retrieve the contents of the package manifest. In addition to validation against RFC3986, each **manifestURI** must also contain a hash of the content as specified in the [EIP 1123](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1123.md). - -### Examples - -**Package Names / Release Versions** - -```shell -"simple-token" # package name -"1.0.1" # version string -``` - -**Release IDs** - -Implementations are free to choose any scheme for generating a **releaseId**. A common approach would be to hash the strings together as below: - -```solidity -// Hashes package name and a release version string -function generateReleaseId(string packageName, string version) - public - view - returns (bytes32 releaseId) - { - return keccak256(abi.encodePacked(packageName, version)); - } -``` -Implementations **must** expose this id generation logic as part of their public `read` API so -tooling can easily map a string based release query to the registry's unique identifier for that release. - -**Manifest URIs** - -Any IPFS or Swarm URI meets the definition of **manifestURI**. - -Another example is content on GitHub addressed by its SHA-1 hash. The Base64 encoded content at this hash can be obtained by running: -```shell -$ curl https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha - -# Example -$ curl https://api.github.com/repos/rstallman/hello/git/blobs/ce013625030ba8dba906f756967f9e9ca394464a -``` - -The string "hello" can have its GitHub SHA-1 hash independently verified by comparing it to the output of: -```shell -$ printf "blob 6\000hello\n" | sha1sum -> ce013625030ba8dba906f756967f9e9ca394464a -``` - -### Write API Specification -The write API consists of a single method, `release`. It passes the registry the package name, a -version identifier for the release, and a URI specifying the location of a manifest which -details the contents of the release. -```solidity -function release(string packageName, string version, string manifestURI) public - returns (bytes32 releaseId); -``` - -### Events - -#### VersionRelease -MUST be triggered when `release` is successfully called. - -```solidity -event VersionRelease(string packageName, string version, string manifestURI) -``` - -### Read API Specification - -The read API consists of a set of methods that allows tooling to extract all consumable data from a registry. - -```solidity -// Retrieves a slice of the list of all unique package identifiers in a registry. -// `offset` and `limit` enable paginated responses / retrieval of the complete set. (See note below) -function getAllPackageIds(uint offset, uint limit) public view - returns ( - bytes32[] packageIds, - uint pointer - ); - -// Retrieves the unique string `name` associated with a package's id. -function getPackageName(bytes32 packageId) public view returns (string packageName); - -// Retrieves the registry's unique identifier for an existing release of a package. -function getReleaseId(string packageName, string version) public view returns (bytes32 releaseId); - -// Retrieves a slice of the list of all release ids for a package. -// `offset` and `limit` enable paginated responses / retrieval of the complete set. (See note below) -function getAllReleaseIds(string packageName, uint offset, uint limit) public view - returns ( - bytes32[] releaseIds, - uint pointer - ); - -// Retrieves package name, release version and URI location data for a release id. -function getReleaseData(bytes32 releaseId) public view - returns ( - string packageName, - string version, - string manifestURI - ); - -// Retrieves the release id a registry *would* generate for a package name and version pair -// when executing a release. -function generateReleaseId(string packageName, string version) - public - view - returns (bytes32 releaseId); - -// Returns the total number of unique packages in a registry. -function numPackageIds() public view returns (uint totalCount); - -// Returns the total number of unique releases belonging to the given packageName in a registry. -function numReleaseIds(string packageName) public view returns (uint totalCount); -``` -**Pagination** - -`getAllPackageIds` and `getAllReleaseIds` support paginated requests because it's possible that the return values for these methods could become quite large. The methods should return a `pointer` that points to the next available item in a list of all items such that a caller can use it to pick up from where the previous request left off. (See [here](https://mixmax.com/blog/api-paging-built-the-right-way) for a discussion of the merits and demerits of various pagination strategies.) The `limit` parameter defines the maximum number of items a registry should return per request. - -## Rationale -The proposal hopes to accomplish the following: - -+ Define the smallest set of inputs necessary to allow registries to map package names to a set of -release versions while allowing them to use any versioning schema they choose. -+ Provide the minimum set of getter methods needed to retrieve package data from a registry so that registry aggregators can read all of their data. -+ Define a standard query that synthesizes a release identifier from a package name and version pair so that tooling can resolve specific package version requests without needing to query a registry about all of a package's releases. - -Registries may offer more complex `read` APIs that manage requests for packages within a semver range or at `latest` etc. This EIP is agnostic about how tooling or registries might implement these. It recommends that registries implement [EIP 165](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) and avail themselves of resources to publish more complex interfaces such as [EIP 926](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-926.md). - -## Backwards Compatibility -No existing standard exists for package registries. The package registry currently deployed by EthPM would not comply with the standard since it implements only one of the method signatures described in the specification. - -## Implementation -A reference implementation of this proposal is in active development at the EthPM organization on Github [here](https://github.com/ethpm/escape-truffle). - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1319.md diff --git a/EIPS/eip-1328.md b/EIPS/eip-1328.md index 63d61278f0fafd..6038084aa2162c 100644 --- a/EIPS/eip-1328.md +++ b/EIPS/eip-1328.md @@ -1,54 +1,7 @@ --- eip: 1328 -title: WalletConnect Standard URI Format -author: ligi , Pedro Gomes -type: Standards Track category: ERC -status: Draft -created: 2018-08-15 -discussions-to: https://ethereum-magicians.org/t/wallet-connect-eip/850 +status: Moved --- -## Simple Summary - -A standard to create WalletConnect URIs to initiate connections between applications and wallets. - -## Abstract - -This standard defines how the data to connect some application and a wallet can be encoded with a URI. This URI can then be shown either as a QR code or for mobile to mobile as a link. - -## Specification - -### Syntax - -WalletConnect request URI with the following parameters: - - request = "wc" ":" topic [ "@" version ][ "?" parameters ] - topic = STRING - version = 1*DIGIT - parameters = parameter *( "&" parameter ) - parameter = key "=" value - key = "bridge" / "key" - value = STRING - -### Semantics - -Required parameters are dependent on the Walletconnect protocol version which currently includes the `key`, hex string of symmetric key, and `bridge`, encoded url of the bridge used for establishing the connection. - -### Example - -``` -wc:8a5e5bdc-a0e4-4702-ba63-8f1a5655744f@1?bridge=https%3A%2F%2Fbridge.walletconnect.org&key=41791102999c339c844880b23950704cc43aa840f3739e365323cda4dfa89e7a -``` - -## Rationale - -The need for this ERC stems from the discussion to move away from JSON format used in the alpha version of the WalletConnect protocol which makes for very inneficient parsing of the intent of the QR code, making it easier to create better QR code parsers APIs for Wallets to implement. Also by using a URI instead of a JSON inside the QR-Code the Android Intent system can be leveraged. - -## References - -1. WalletConnect Technical Specification, https://docs.walletconnect.org/tech-spec - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1328.md diff --git a/EIPS/eip-1337.md b/EIPS/eip-1337.md new file mode 100644 index 00000000000000..8d201b25cb9b2f --- /dev/null +++ b/EIPS/eip-1337.md @@ -0,0 +1,7 @@ +--- +eip: 1337 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1337.md diff --git a/EIPS/eip-1344.md b/EIPS/eip-1344.md index 291930300c1041..02e46aebc80e6e 100644 --- a/EIPS/eip-1344.md +++ b/EIPS/eip-1344.md @@ -5,20 +5,21 @@ author: Richard Meissner (@rmeissner), Bryant Eisenbach (@fubuloubu) discussions-to: https://ethereum-magicians.org/t/add-chain-id-opcode-for-replay-protection-when-handling-signed-messages-in-contracts/1131 category: Core type: Standards Track -requires: 155 -status: Last Call +status: Final created: 2018-08-22 -review-period-end: 2019-04-30 +requires: 155 --- ## Abstract This EIP adds an opcode that returns the current chain's EIP-155 unique identifier. ## Motivation -[EIP-155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md) proposes to use the chain ID to prevent replay attacks between different chains. It would be a great benefit to have the same possibility inside smart contracts when handling signatures, especially for Layer 2 signature schemes using [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md). +[EIP-155](./eip-155.md) proposes to use the chain ID to prevent replay attacks between different chains. It would be a great benefit to have the same possibility inside smart contracts when handling signatures, especially for Layer 2 signature schemes using [EIP-712](./eip-712.md). ## Specification -Adds a new opcode `CHAINID` at 0x46, which uses 0 stack arguments. It pushes the current chain ID onto the stack. The operation costs `G_base` to execute. +Adds a new opcode `CHAINID` at 0x46, which uses 0 stack arguments. It pushes the current chain ID onto the stack. Chain ID is a 256-bit value. The operation costs `G_base` to execute. + +The value of the current chain ID is obtained from the chain ID configuration, which should match the EIP-155 unique identifier a client will accept from incoming transactions. Please note that per EIP-155, it is not *required* that a transaction have an EIP-155 unique identifier, but in that scenario this opcode will still return the configured chain ID and not a default. ## Rationale The current approach proposed by EIP-712 is to specify the chain ID at compile time. Using this approach will result in problems after a hardfork, as well as human error that may lead to loss of funds or replay attacks on signed messages. @@ -28,17 +29,23 @@ Currently, there is no specification for how chain ID is set for a particular ne In order to mitigate this situation, users of the proposed `CHAINID` opcode **must** ensure that their application can handle a potential update to the value of chain ID during their usage of their application in case this does occur, if required for the continued use of the application. A Trustless Oracle that logs the timestamp when a change is made to chain ID can be implemented either as an application-level feature inside the application contract system, or referenced as a globally standard contract. Failure to provide a mitigation for this scenario could lead to a sudden loss of legitimacy of previously signed off-chain messages, which could be an issue during settlement periods and other longer-term verification events for these types of messages. Not all applications of this opcode may need mitigations to handle this scenario, but developers should provide reasoning on a case-by-case basis. +One example of a scenario where it would not make sense to leverage a global oracle is with the Plasma L2 paradigm. In the Plasma paradigm, an operator or group of operators submit blocks from the L2 network to the base chain (in this case Ethereum) summarizing transactions that have occurred on that chain. The submission of these blocks may not perfectly align with major events on the mainchain, such as a split causing an update of chain ID, which may cause a significant insecurity in the protocol if chain ID is utilized in signing messages. If the operators are not allowed to control the update of chain ID they will not be able to perfectly synchronize the update with their block submissions, and certain past transactions may be rejected because they do not align with the update. This is one example of the unintended consequences of trying to specify too much of the behavior of chain ID during a contentious split, and why having a simple opcode for access is most optimal, versus a more complicated precompile or contract. + +This proposed opcode would be the simplest possible way to implement this functionality, and allows developers the flexibility to implement their own global or local handling of chain ID changes, if required. + ## Backwards Compatibility This EIP is fully backwards compatible with all chains which implement EIP-155 chain ID domain separator for transaction signing. ## References -This was previously suggested as part of [EIP901](https://github.com/ethereum/EIPs/issues/901). +This was previously suggested as part of [EIP-901](https://github.com/ethereum/EIPs/issues/901). ## Test Cases -TBD +Test Cases added to [ethereum/tests](https://github.com/ethereum/tests/pull/627) ## Implementation -A sample implementation was attempted here: https://github.com/fubuloubu/py-evm/commit/eaab5ffa2164d4cc06ae5c855a49d030965be828 +A reference implementation for the Trinity Python client is [here](https://github.com/ethereum/py-evm/pull/1803). + +An example implementation of a trustless chain ID oracle was implemented [here](https://github.com/fubuloubu/chain-id-oracle/blob/master/ChainIdOracle.vy). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1352.md b/EIPS/eip-1352.md index 11416bbad847a2..55c1a52a3ebd80 100644 --- a/EIPS/eip-1352.md +++ b/EIPS/eip-1352.md @@ -3,7 +3,7 @@ eip: 1352 title: Specify restricted address range for precompiles/system contracts author: Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/eip-1352-specify-restricted-address-range-for-precompiles-system-contracts/1151 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-07-27 @@ -37,4 +37,4 @@ N/A N/A ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1355.md b/EIPS/eip-1355.md index 3dbd4df3f61d18..60cfe2010d0d1d 100644 --- a/EIPS/eip-1355.md +++ b/EIPS/eip-1355.md @@ -1,9 +1,9 @@ --- eip: 1355 title: Ethash 1a -author: Paweł Bylica (@chfast) , Jean M. Cyr (@jean-m-cyr) +author: Paweł Bylica (@chfast), Jean M. Cyr (@jean-m-cyr) discussions-to: https://ethereum-magicians.org/t/eip-1355-ethash-1a/1167 -status: Draft +status: Withdrawn type: Standards Track category: Core created: 2018-08-26 @@ -22,7 +22,7 @@ Provide minimal set of changes to Ethash algorithm to hinder and delay the adopt ``` where `FNV1A_PRIME` is 16777499 or 16777639. 2. Change the hash function that determines the DAG item index in Ethash algorithm from `fnv()` to new `fnv1a()`. - In [Main Loop](https://github.com/ethereum/wiki/wiki/Ethash#main-loop) change + In [Main Loop](https://github.com/ethereum/eth-wiki/blob/master/concepts/ethash/ethash.md#main-loop) change ```python p = fnv(i ^ s[0], mix[i % w]) % (n // mixhashes) * mixhashes ``` diff --git a/EIPS/eip-1363.md b/EIPS/eip-1363.md new file mode 100644 index 00000000000000..8c0100cab26161 --- /dev/null +++ b/EIPS/eip-1363.md @@ -0,0 +1,7 @@ +--- +eip: 1363 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1363.md diff --git a/EIPS/eip-137.md b/EIPS/eip-137.md index cc873744bc4feb..71ad10879546df 100644 --- a/EIPS/eip-137.md +++ b/EIPS/eip-137.md @@ -1,386 +1,7 @@ --- eip: 137 -title: Ethereum Domain Name Service - Specification -author: Nick Johnson -status: Final -type: Standards Track category: ERC -created: 2016-04-04 +status: Moved --- -# Abstract - -This draft EIP describes the details of the Ethereum Name Service, a proposed protocol and ABI definition that provides flexible resolution of short, human-readable names to service and resource identifiers. This permits users and developers to refer to human-readable and easy to remember names, and permits those names to be updated as necessary when the underlying resource (contract, content-addressed data, etc) changes. - -The goal of domain names is to provide stable, human-readable identifiers that can be used to specify network resources. In this way, users can enter a memorable string, such as 'vitalik.wallet' or 'www.mysite.swarm', and be directed to the appropriate resource. The mapping between names and resources may change over time, so a user may change wallets, a website may change hosts, or a swarm document may be updated to a new version, without the domain name changing. Further, a domain need not specify a single resource; different record types allow the same domain to reference different resources. For instance, a browser may resolve 'mysite.swarm' to the IP address of its server by fetching its A (address) record, while a mail client may resolve the same address to a mail server by fetching its MX (mail exchanger) record. -# Motivation - -Existing [specifications](https://github.com/ethereum/wiki/wiki/Registrar-ABI) and [implementations](https://ethereum.gitbooks.io/frontier-guide/content/registrar_services.html) for name resolution in Ethereum provide basic functionality, but suffer several shortcomings that will significantly limit their long-term usefulness: -- A single global namespace for all names with a single 'centralised' resolver. -- Limited or no support for delegation and sub-names/sub-domains. -- Only one record type, and no support for associating multiple copies of a record with a domain. -- Due to a single global implementation, no support for multiple different name allocation systems. -- Conflation of responsibilities: Name resolution, registration, and whois information. - -Use-cases that these features would permit include: -- Support for subnames/sub-domains - eg, live.mysite.tld and forum.mysite.tld. -- Multiple services under a single name, such as a DApp hosted in Swarm, a Whisper address, and a mail server. -- Support for DNS record types, allowing blockchain hosting of 'legacy' names. This would permit an Ethereum client such as Mist to resolve the address of a traditional website, or the mail server for an email address, from a blockchain name. -- DNS gateways, exposing ENS domains via the Domain Name Service, providing easier means for legacy clients to resolve and connect to blockchain services. - -The first two use-cases, in particular, can be observed everywhere on the present-day internet under DNS, and we believe them to be fundamental features of a name service that will continue to be useful as the Ethereum platform develops and matures. - -The normative parts of this document does not specify an implementation of the proposed system; its purpose is to document a protocol that different resolver implementations can adhere to in order to facilitate consistent name resolution. An appendix provides sample implementations of resolver contracts and libraries, which should be treated as illustrative examples only. - -Likewise, this document does not attempt to specify how domains should be registered or updated, or how systems can find the owner responsible for a given domain. Registration is the responsibility of registrars, and is a governance matter that will necessarily vary between top-level domains. - -Updating of domain records can also be handled separately from resolution. Some systems, such as swarm, may require a well defined interface for updating domains, in which event we anticipate the development of a standard for this. -# Specification -## Overview - -The ENS system comprises three main parts: -- The ENS registry -- Resolvers -- Registrars - -The registry is a single contract that provides a mapping from any registered name to the resolver responsible for it, and permits the owner of a name to set the resolver address, and to create subdomains, potentially with different owners to the parent domain. - -Resolvers are responsible for performing resource lookups for a name - for instance, returning a contract address, a content hash, or IP address(es) as appropriate. The resolver specification, defined here and extended in other EIPs, defines what methods a resolver may implement to support resolving different types of records. - -Registrars are responsible for allocating domain names to users of the system, and are the only entities capable of updating the ENS; the owner of a node in the ENS registry is its registrar. Registrars may be contracts or externally owned accounts, though it is expected that the root and top-level registrars, at a minimum, will be implemented as contracts. - -Resolving a name in ENS is a two-step process. First, the ENS registry is called with the name to resolve, after hashing it using the procedure described below. If the record exists, the registry returns the address of its resolver. Then, the resolver is called, using the method appropriate to the resource being requested. The resolver then returns the desired result. - -For example, suppose you wish to find the address of the token contract associated with 'beercoin.eth'. First, get the resolver: - -``` -var node = namehash("beercoin.eth"); -var resolver = ens.resolver(node); -``` - -Then, ask the resolver for the address for the contract: - -``` -var address = resolver.addr(node); -``` - -Because the `namehash` procedure depends only on the name itself, this can be precomputed and inserted into a contract, removing the need for string manipulation, and permitting O(1) lookup of ENS records regardless of the number of components in the raw name. -## Name Syntax - -ENS names must conform to the following syntax: - -
<domain> ::= <label> | <domain> "." <label>
-<label> ::= any valid string label per [UTS46](https://unicode.org/reports/tr46/)
-
- -In short, names consist of a series of dot-separated labels. Each label must be a valid normalised label as described in [UTS46](https://unicode.org/reports/tr46/) with the options `transitional=false` and `useSTD3AsciiRules=true`. For Javascript implementations, a [library](https://www.npmjs.com/package/idna-uts46) is available that normalises and checks names. - -Note that while upper and lower case letters are allowed in names, the UTS46 normalisation process case-folds labels before hashing them, so two names with different case but identical spelling will produce the same namehash. - -Labels and domains may be of any length, but for compatibility with legacy DNS, it is recommended that labels be restricted to no more than 64 characters each, and complete ENS names to no more than 255 characters. For the same reason, it is recommended that labels do not start or end with hyphens, or start with digits. - -## namehash algorithm - -Before being used in ENS, names are hashed using the 'namehash' algorithm. This algorithm recursively hashes components of the name, producing a unique, fixed-length string for any valid input domain. The output of namehash is referred to as a 'node'. - -Pseudocode for the namehash algorithm is as follows: - -``` -def namehash(name): - if name == '': - return '\0' * 32 - else: - label, _, remainder = name.partition('.') - return sha3(namehash(remainder) + sha3(label)) -``` - -Informally, the name is split into labels, each label is hashed. Then, starting with the last component, the previous output is concatenated with the label hash and hashed again. The first component is concatenated with 32 '0' bytes. Thus, 'mysite.swarm' is processed as follows: - -``` -node = '\0' * 32 -node = sha3(node + sha3('swarm')) -node = sha3(node + sha3('mysite')) -``` - -Implementations should conform to the following test vectors for namehash: - - namehash('') = 0x0000000000000000000000000000000000000000000000000000000000000000 - namehash('eth') = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae - namehash('foo.eth') = 0xde9b09fd7c5f901e23a3f19fecc54828e9c848539801e86591bd9801b019f84f - -## Registry specification - -The ENS registry contract exposes the following functions: - -``` -function owner(bytes32 node) constant returns (address); -``` - -Returns the owner (registrar) of the specified node. - -``` -function resolver(bytes32 node) constant returns (address); -``` - -Returns the resolver for the specified node. - -``` -function ttl(bytes32 node) constant returns (uint64); -``` - -Returns the time-to-live (TTL) of the node; that is, the maximum duration for which a node's information may be cached. - -``` -function setOwner(bytes32 node, address owner); -``` - -Transfers ownership of a node to another registrar. This function may only be called by the current owner of `node`. A successful call to this function logs the event `Transfer(bytes32 indexed, address)`. - -``` -function setSubnodeOwner(bytes32 node, bytes32 label, address owner); -``` - -Creates a new node, `sha3(node, label)` and sets its owner to `owner`, or updates the node with a new owner if it already exists. This function may only be called by the current owner of `node`. A successful call to this function logs the event `NewOwner(bytes32 indexed, bytes32 indexed, address)`. - -``` -function setResolver(bytes32 node, address resolver); -``` - -Sets the resolver address for `node`. This function may only be called by the owner of `node`. A successful call to this function logs the event `NewResolver(bytes32 indexed, address)`. - -``` -function setTTL(bytes32 node, uint64 ttl); -``` - -Sets the TTL for a node. A node's TTL applies to the 'owner' and 'resolver' records in the registry, as well as to any information returned by the associated resolver. -## Resolver specification - -Resolvers may implement any subset of the record types specified here. Where a record types specification requires a resolver to provide multiple functions, the resolver MUST implement either all or none of them. Resolvers MUST specify a fallback function that throws. - -Resolvers have one mandatory function: - -``` -function supportsInterface(bytes4 interfaceID) constant returns (bool) -``` - -The `supportsInterface` function is documented in [EIP 165](https://github.com/ethereum/EIPs/issues/165), and returns true if the resolver implements the interface specified by the provided 4 byte identifier. An interface identifier consists of the XOR of the function signature hashes of the functions provided by that interface; in the degenerate case of single-function interfaces, it is simply equal to the signature hash of that function. If a resolver returns `true` for `supportsInterface()`, it must implement the functions specified in that interface. - -`supportsInterface` must always return true for `0x01ffc9a7`, which is the interface ID of `supportsInterface` itself. - - Currently standardised resolver interfaces are specified in the table below. - -The following interfaces are defined: - -| Interface name | Interface hash | Specification | -| --- | --- | --- | -| `addr` | 0x3b3b57de | [Contract address](#addr) | -| `name` | 0x691f3431 | #181 | -| `ABI` | 0x2203ab56 | #205 | -| `pubkey` | 0xc8690233 | #619 | - -EIPs may define new interfaces to be added to this registry. - -###
Contract Address Interface - -Resolvers wishing to support contract address resources must provide the following function: - -``` -function addr(bytes32 node) constant returns (address); -``` - -If the resolver supports `addr` lookups but the requested node does not have an addr record, the resolver MUST return the zero address. - -Clients resolving the `addr` record MUST check for a zero return value, and treat this in the same manner as a name that does not have a resolver specified - that is, refuse to send funds to or interact with the address. Failure to do this can result in users accidentally sending funds to the 0 address. - -Changes to an address MUST trigger the following event: - -``` -event AddrChanged(bytes32 indexed node, address a); -``` -# Appendix A: Registry Implementation - -``` -contract ENS { - struct Record { - address owner; - address resolver; - uint64 ttl; - } - - mapping(bytes32=>Record) records; - - event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); - event Transfer(bytes32 indexed node, address owner); - event NewResolver(bytes32 indexed node, address resolver); - - modifier only_owner(bytes32 node) { - if(records[node].owner != msg.sender) throw; - _ - } - - function ENS(address owner) { - records[0].owner = owner; - } - - function owner(bytes32 node) constant returns (address) { - return records[node].owner; - } - - function resolver(bytes32 node) constant returns (address) { - return records[node].resolver; - } - - function ttl(bytes32 node) constant returns (uint64) { - return records[node].ttl; - } - - function setOwner(bytes32 node, address owner) only_owner(node) { - Transfer(node, owner); - records[node].owner = owner; - } - - function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) { - var subnode = sha3(node, label); - NewOwner(node, label, owner); - records[subnode].owner = owner; - } - - function setResolver(bytes32 node, address resolver) only_owner(node) { - NewResolver(node, resolver); - records[node].resolver = resolver; - } - - function setTTL(bytes32 node, uint64 ttl) only_owner(node) { - NewTTL(node, ttl); - records[node].ttl = ttl; - } -} -``` -# Appendix B: Sample Resolver Implementations -### Built-in resolver - -The simplest possible resolver is a contract that acts as its own name resolver by implementing the contract address resource profile: - -``` -contract DoSomethingUseful { - // Other code - - function addr(bytes32 node) constant returns (address) { - return this; - } - - function supportsInterface(bytes4 interfaceID) constant returns (bool) { - return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7; - } - - function() { - throw; - } -} -``` - -Such a contract can be inserted directly into the ENS registry, eliminating the need for a separate resolver contract in simple use-cases. However, the requirement to 'throw' on unknown function calls may interfere with normal operation of some types of contract. - -### Standalone resolver - -A basic resolver that implements the contract address profile, and allows only its owner to update records: - -``` -contract Resolver { - event AddrChanged(bytes32 indexed node, address a); - - address owner; - mapping(bytes32=>address) addresses; - - modifier only_owner() { - if(msg.sender != owner) throw; - _ - } - - function Resolver() { - owner = msg.sender; - } - - function addr(bytes32 node) constant returns(address) { - return addresses[node]; - } - - function setAddr(bytes32 node, address addr) only_owner { - addresses[node] = addr; - AddrChanged(node, addr); - } - - function supportsInterface(bytes4 interfaceID) constant returns (bool) { - return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7; - } - - function() { - throw; - } -} -``` - -After deploying this contract, use it by updating the ENS registry to reference this contract for a name, then calling `setAddr()` with the same node to set the contract address it will resolve to. -### Public resolver - -Similar to the resolver above, this contract only supports the contract address profile, but uses the ENS registry to determine who should be allowed to update entries: - -``` -contract PublicResolver { - event AddrChanged(bytes32 indexed node, address a); - event ContentChanged(bytes32 indexed node, bytes32 hash); - - ENS ens; - mapping(bytes32=>address) addresses; - - modifier only_owner(bytes32 node) { - if(ens.owner(node) != msg.sender) throw; - _ - } - - function PublicResolver(address ensAddr) { - ens = ENS(ensAddr); - } - - function addr(bytes32 node) constant returns (address ret) { - ret = addresses[node]; - } - - function setAddr(bytes32 node, address addr) only_owner(node) { - addresses[node] = addr; - AddrChanged(node, addr); - } - - function supportsInterface(bytes4 interfaceID) constant returns (bool) { - return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7; - } - - function() { - throw; - } -} -``` -# Appendix C: Sample Registrar Implementation - -This registrar allows users to register names at no cost if they are the first to request them. - -``` -contract FIFSRegistrar { - ENS ens; - bytes32 rootNode; - - function FIFSRegistrar(address ensAddr, bytes32 node) { - ens = ENS(ensAddr); - rootNode = node; - } - - function register(bytes32 subnode, address owner) { - var node = sha3(rootNode, subnode); - var currentOwner = ens.owner(node); - if(currentOwner != 0 && currentOwner != msg.sender) - throw; - - ens.setSubnodeOwner(rootNode, subnode, owner); - } -} -``` +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-137.md diff --git a/EIPS/eip-1380.md b/EIPS/eip-1380.md index f8476e1f4673b6..9f32f1b5737a2e 100644 --- a/EIPS/eip-1380.md +++ b/EIPS/eip-1380.md @@ -3,7 +3,7 @@ eip: 1380 title: Reduced gas cost for call to self author: Alex Beregszaszi (@axic), Jacques Wagener (@jacqueswww) discussions-to: https://ethereum-magicians.org/t/eip-1380-reduced-gas-cost-for-call-to-self/1242 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-08-31 @@ -11,9 +11,11 @@ requires: 150 --- ## Abstract + Reduce the gas cost for call instructions, when the goal is to run a new instance of the currently loaded contract. ## Motivation + The current gas cost of 700 for all call types (`CALL`, `DELEGATECALL`, `CALLCODE` and `STATICCALL`) does not take into account that a call to a contract itself does not need to perform additional I/O operations, because the current contract code has already been loaded into memory. @@ -26,32 +28,38 @@ must be swapped in and out of the calling functions context. A desired feature i them through `JUMP` requires a bigger effort from the compiler as opposed to being able to use `CALL`s. Using call-to-self provides the guarantee that when making an internal call the function can rely on a clear reset state of memory or context, benefiting both -contract writers and contract consumers against potentially undetetected edge cases were memory could poison the context of the internal function. +contract writers and contract consumers against potentially undetected edge cases were memory could poison the context of the internal function. -Because of the `JUMP` usage for internal functions a smart contract languages are also at risk of reaching the stack depth limit considerbly faster, if nested +Because of the `JUMP` usage for internal functions a smart contract languages are also at risk of reaching the stack depth limit considerably faster, if nested function calls with many in and/or outputs are required. Reducing the gas cost, and thereby incentivising of using call-to-self instead of `JUMP`s for the internal function implementation will also benefit static analyzers and tracers. ## Specification + If `block.number >= FORK_BLKNUM`, then decrease the cost of `CALL`, `DELEGATECALL`, `CALLCODE` and `STATICCALL` from 700 to 40, if and only if, the destination address of the call equals to the address of the caller. ## Rationale + EIP150 has increased the cost of these instructions from 40 to 700 to more fairly charge for loading new contracts from disk, e.g. to reflect the I/O charge more closely. By assuming that 660 is the cost of loading a contract from disk, one can assume that the original 40 gas is a fair cost of creating a new VM instance of an already loaded contract code. ## Backwards Compatibility + This should pose no risk to backwards compatibility. Currently existing contracts should not notice the difference, just see cheaper execution. With EIP150 contract (and language) developers had a lesson that relying on strict gas costs is not feasible as costs may change. The impact of this EIP is even less that of EIP150 because the costs are changing downwards and not upwards. ## Test Cases + TBA ## Implementation + TBA ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1386.md b/EIPS/eip-1386.md index 94d678514fdcb5..0eb45ced7e50e3 100644 --- a/EIPS/eip-1386.md +++ b/EIPS/eip-1386.md @@ -1,88 +1,7 @@ --- eip: 1386 -title: Attestation management contract -author: Weiwu Zhang , James Sangalli -discussions-to: https://github.com/ethereum/EIPs/issues/1386 -status: Draft -type: Standards Track category: ERC -created: 2018-09-08 +status: Moved --- -### Introduction - -Very often, we will need to use Attestations like "Alice lives in Australia" on the blockchain; that is issued by a valid issuer off chain for privacy reasons and is revokable inside a smart contract. - -An issuer can create a smart contract where he revokes multiple attestations in one go by building a bloom filter of all the hashes of the revoked attestations. - -An issuer can also put the validation method in their smart contract that can be called by other smart contracts who need to validate attestations issued by them. This allows each attestor to update their attestation format separately. - -### Purpose - -This ERC provides an interface for attestation issuers to manage their attestation signing keys and the attestations that are issued off chain for actions such as revocation and validation. - -In our draft implementation we include functions to hold cryptographic attestations, change the issuing contracts of attestations, revoke attestations and verify the authenticity of a cryptographic attestation. - -### Example use cases - -Let's say that our friend, Alice, wants to buy a bottle of wine to consume with her friends. She wants to do the order online and have it delivered to her home address whilst paying for it with Ether. - -Alice has a cryptographic attestation from her local road and maritime services who attests to her age, date of birth, country of residence and ability to drive. - -Alice is able to split up this attestation (see merkle tree attestations ERC [here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/lib/MerkleTreeAttestation.sol)) and provides only the leaf that states she is over the age of 21. - -Alice goes to buy the wine through the wine vendors smart contract and feeds in the merkle tree attestation proving that she is above 21 and can thus buy the wine, whilst attaching the appropriate amount of ether to complete the purchase. - -The issuer smart contract is able to validate her attestation, check that the issuer contract is valid and capable of performing such an attestation to her age. In this case it would have to be from someone like a driver's licence authority, as attestations to age from a school ID are not of a high enough capacity. - -The wine vendors smart contract validates the attestation, checks the payment amount is correct and credits Alice with the wine tokens she needs to complete the sale and deliver the wine. - -When the wine vendor shows up to her apartment with the wine, there is no need to prove her age again. - -### Draft interface -``` -/* each attestation issuer should provide their own verify() for the - * attestations they issued. There are two reasons for this. First, we - * need to leave room for new attestation methods other than the - * Merkle Tree format we are recommending. Second, the validity of the - * attestation may depend on the context that only the attestor - * knows. For example, a ticket as an attestation issued on a - * successful redemption of an American Express credit */ - -contract Issuer { - struct Attestation - { - bytes32[] merklePath; - bool valid; - uint8 v; - bytes32 r; - bytes32 s; - address attestor; - address recipient; - bytes32 salt; - bytes32 key; - bytes32 val; - }` - /* Verify the authenticity of an attestation */ - function verify(Attestation attestation); - function addattestorKey(address newAttestor, string capacity, uint expiry); - - /* this should call the revoke first */ - function replaceKey(address attestorToReplace, string capacity, uint expiry, address newAttestor); - - /* this revokes a single key */ - function removeKey(address attestor); - - /* if the key exists with such capacity and isn't revoked or expired */ - function validateKey(address attestor, string capacity) returns (bool); - - /* revoke an attestation by replace the bloom filter, this helps preserve privacy */ - function revokeAttestations(Bloomfilter b); - -} -``` - -Please click [here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/example-james-squire/james-squire.sol) to see a draft implementation of this interface - -### Related ERC's -#1388 #1387 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1386.md diff --git a/EIPS/eip-1387.md b/EIPS/eip-1387.md index 8aceee77e8ee3e..cdb744a8ac774f 100644 --- a/EIPS/eip-1387.md +++ b/EIPS/eip-1387.md @@ -1,49 +1,7 @@ --- eip: 1387 -title: Merkle Tree Attestations with Privacy enabled -author: Weiwu Zhang , James Sangalli -discussions-to: https://github.com/ethereum/EIPs/issues/1387 -status: Draft -type: Standards Track category: ERC -created: 2018-09-08 +status: Moved --- -### Introduction - -It's often needed that an Ethereum smart contract must verify a claim (I live in Australia) attested by a valid attester. - -For example, an ICO contract might require that the participant, Alice, lives in Australia before she participates. Alice's claim of residency could come from a local Justice of the Peace who could attest that "Alice is a resident of Australia in NSW". - -Unlike previous attempts, we assume that the attestation is signed and issued off the blockchain in a Merkle Tree format. Only a part of the Merkle tree is revealed by Alice at each use. Therefore we avoid the privacy problem often associated with issuing attestations on chain. We also assume that Alice has multiple signed Merkle Trees for the same factual claim to avoid her transactions being linkable. - -## Purpose -This ERC provides an interface and reference implementation for smart contracts that need users to provide an attestation and validate it. - -### Draft implementation -``` -contract MerkleTreeAttestationInterface { - struct Attestation - { - bytes32[] merklePath; - bool valid; - uint8 v; - bytes32 r; - bytes32 s; - address attester; - address recipient; - bytes32 salt; - bytes32 key; - bytes32 val; - } - - function validate(Attestation attestation) public returns(bool); -} - -``` -### Relevant implementation examples -[Here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/lib/MerkleTreeAttestation.sol) is an example implementation of the MerkleTreeAttestationInterface -[Here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/example-james-squire/james-squire.sol) is an example service which would use such a merkle tree attestation - -### Related ERC's -#1388 #1386 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1387.md diff --git a/EIPS/eip-1388.md b/EIPS/eip-1388.md index 6bf1ca4ec8bee5..1d931981050c35 100644 --- a/EIPS/eip-1388.md +++ b/EIPS/eip-1388.md @@ -1,87 +1,7 @@ --- eip: 1388 -title: Attestation Issuers Management List -author: Weiwu Zhang , James Sangalli -discussions-to: https://github.com/ethereum/EIPs/issues/1388 -status: Draft -type: Standards Track category: ERC -created: 2018-09-08 +status: Moved --- -### Introduction - -In smart contracts, we will need methods to handle cryptographic attestations to a users identifier or abilities. Let's say we have a real estate agent, KiwiRealtors, that provides an "expression of interest" function though a smart contract and requires the users to provide an attestation that they are a resident of New Zealand or Australia, as a legal requirement. This has actually happened in the New Zealand property market and it is the perfect example of a need to handle such attestations. - -However, it is not practical for a smart contract to explicitly trust an attestation issuer. There are multiple issuers who can provide an attestation to a person's residency - a local Justice of the Peace, the land title office, local police, passport authority etc. We envision a model where the effort to manage the list of qualified issuers is practically outsourced to a list. - -Anyone can publish a list of issuers. Only the most trusted and carefully maintained lists gets popular use. - -### Purpose -This ERC provides a smart contract interface for anyone to manage a list of attestation issuers. A smart contract would explicitly trust a list, and therefore all attestations issued by the issuers on the list. - -### Draft implementation - ``` - /* The purpose of this contract is to manage the list of attestation - * issuer contracts and their capacity to fulfill requirements - */ - contract ManagedListERC - { - /* a manager is the steward of a list. Only he/she/it can change the - * list by removing/adding attestation issuers to the list. - - * An issuer in the list is represented by their contract - * addresses, not by the attestation signing keys managed by such a - * contract. - */ - struct List - { - string name; - string description; // short description of what the list entails - string capacity; // serves as a filter for the attestation signing keys - /* if a smart contract specifies a list, only attestation issued - * by issuers on that list is accepted. Furthermore, if that - * list has a non-empty capacity, only attestations signed by a - * signing key with that capacity is accepted. */ - - address[] issuerContracts; // all these addresses are contracts, no signing capacity - uint expiry; - } - - // find which list the sender is managing, then add an issuer to it - function addIssuer(address issuerContractAddress) public; - - //return false if the list identified by the sender doesn't have this issuer in the list - function removeIssuer(address issuerContractAddress, List listToRemoveIssuerFrom) public returns(bool); - - /* called by services, e.g. Kiwi Properties or James Squire */ - /* loop through all issuer's contract and execute validateKey() on - * every one of them in the hope of getting a hit, return the - * contract address of the first hit. Note that there is an attack - * method for one issuer to claim to own the key of another which - * is mitigated by later design. */ - //loop through the issuers array, calling validate on the signingKeyOfAttestation - function getIssuerCorrespondingToAttestationKey(bytes32 list_id, address signingKeyOfAttestation) public returns (address); - - /* for simplicity we use sender's address as the list ID, - * accepting these consequences: a) if one user wish to maintain - * several lists with different capacity, he or she must use a - * different sender address for each. b) if the user replaced the - * sender's key, either because he or she suspects the key is - * compromised or that it is lost and reset through special means, - * then the list is still identified by the first sender's - * address. - */ - - function createList(List list) public; - - /* replace list manager's key with the new key */ - function replaceListIndex(List list, address manager) public returns(bool); - - } -``` - -Click [here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/trustlist/ManagedList.sol) to see an example implementation of this ERC - -### Related ERC's -#1387 #1386 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1388.md diff --git a/EIPS/eip-140.md b/EIPS/eip-140.md index 8469cb072dfe44..e907550930fe6a 100644 --- a/EIPS/eip-140.md +++ b/EIPS/eip-140.md @@ -55,4 +55,4 @@ should: ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-141.md b/EIPS/eip-141.md index 2cc65835cd9301..429e38acef1e66 100644 --- a/EIPS/eip-141.md +++ b/EIPS/eip-141.md @@ -26,4 +26,4 @@ This instruction was never used and therefore has no effect on past contracts. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1417.md b/EIPS/eip-1417.md index f30735effc242a..1338778eb0dfad 100644 --- a/EIPS/eip-1417.md +++ b/EIPS/eip-1417.md @@ -1,283 +1,7 @@ --- eip: 1417 -title: Poll Standard -author: Chaitanya Potti (@chaitanyapotti), Partha Bhattacharya (@pb25193) -type: Standards Track category: ERC -status: Draft -created: 2018-09-16 -requires: 165, 1261 -discussions-to: https://github.com/ethereum/EIPs/issues/1417 +status: Moved --- -## Note to Readers - -1. We have created a couple of implementations of polls for varied use cases. - Please refer to them [here](https://github.com/chaitanyapotti/Voting) - -## Simple Summary - -A standard interface for Polls to be used with EIP-1261 (MVT). - -## Abstract - -The following standard allows for the implementation of a standard API for polls to be used with MVTs (refer [EIP-1261](https://eips.ethereum.org/EIPS/eip-1261)). The standard provides basic functionality to vote, unvote, tally votes, get voter turnout, and a lot more. The poll standard attempts to modularize blockchain voting by breaking down a poll into 4 crucial building blocks: voterbase qualification, vote weight calculation, vote consequences, and vote tallying. By creating a common interface for polls that have different kinds of building blocks, the poll standard makes it possible to make interactive front end applications which can seamlessly get data from a poll contract in order to bring transparency into consensus and decision making on the blockchain. - -We considered the usage of polls with MVTs because MVTs serve as a permissioning mechanism. The manual permissioning of polls allows for vote weightage functions to take up several shapes and forms. Hence the voterbase function applies several logical checks on the vote sender to confirm that they are member(see EIP 1261) of a certain entity or combination of entities. For the specification of the nature of voting, we define the vote weight function. The vote weight function decides how much of vote share each voter will receive and this can be based on several criteria, some of which are listed below in this article. There are certain kinds of polls that enforce certain consequences on the voter, for example a poll may require a voter to lock in a certain amount of tokens, or require the voter to pay a small fee. These on-chain consequences can be coded into the consequence module of the poll standard. Finally, the last module is where the votes are added. A ballot for each candidate is updated whenever relevant, depending on the vote value, and the corresponding NoV count(number of voters). This module is common for most polls, and is the most straightforward. Polls may be time bound, ie. having a finish time, after which no votes are recorded, or be unbound, such that there is no finish time. The following are some examples of specific polls which leverage the flexibility of the poll standard, and it is possible to come up with several others: - -- Plurality Voting: The simplest form of voting is when you want all eligible voters to have one vote per person. This is the simplest to code, as the vote weight is 1, and there is no vote consequence. The only relevant module here is the voterbase, which can be categorized by one or more MVT contracts. -- Token proportional voting: This kind of a poll is actually possible without the use of a voterbase function, because the vote weight function having token proportionality automatically rules out addresses which don't hold the appropriate ERC - 20/ ERC - 777 token. However the voterbase function may be leveraged to further permission the system and give voting rights only to a fixed subset of token holders. -- Capped Token Proportional Voting: This is a modified version of the previous example, where each voter is given proportional vote share only until a certain limit of token ownership. After exceeding that limit, holding more coins does not add more vote share. This format leverages the voterbase module effectively, disallowing people from spreading their coins across multiple addresses by allowing the admin to control which addresses can vote. -- Delegated Voting: Certain polls may allow voters to delegate their votes to other voters. This is known as delegated voting or liquid democracy. For such a poll, a complicated vote weight function is needed, and a data structure concerning the voterbase is also required. A consequence of voting here would be that a user cannot delegate, and a consequence of delegating is that a user cannot vote. Sample implementation of polls contains an example of this vote scheme. -- Karma Based Voting: A certain form of poll may be based on weightage from digital respect. This digital respect would be like a simple upvote from one member of voterbase to another. A mapping of mappings along with an appropriate vote weight function can serve this purpose. Sample implementation has an example. -- Quadratic voting: A system where each vote is associated with a fee, and the fee is proportional to the square of the vote weight that the voter wants. This can be designed by applying a vote weight based on the transaction message, and then charging a fee in the vote consequence module. - -The poll standard is intended to be a smart contract standard that makes poll deployment flexible, transparent and accessible. - -## Motivation - -A standard interface allows any user or applications to work with any Poll contract on Ethereum. We provide for simple ERC-1417 smart contracts. Additional applications are discussed below. - -This standard is inspired by the lack of governance tools in the blockchain space. Whenever there is a consensus collection exercise, someone goes ahead and deploys some kind of poll, and there is no standard software for accessing the data on the poll. For an end user who is not a developer, this is a real problem. The poll, which might be fully transparent, appears to be completely opaque to a common user who does not understand blockchain. In order for developers to build applications for interacting with and accessing poll data, and for poll deployers to have ready application level support, there must be a standardization of poll interfaces. - -This realization happened while conducting market research on DAICOs. The first ever DAICO, Abyss, had far from optimal user experience, and abysmal transparency. Since then, we have been working on a poll standard. During the process, we came across EIP 1202, the voting standard, and found that the discussion there had already diverged from our thoughts to an extent that it made sense to publish a separate proposal altogether. Some of the benefits brought by the poll standard - EIP 1417 aims to offer some additional benefits. - -1. Modularization: EIP 1417 modularizes the code present in the poll standard into 4 major building blocks based on functionality. These are: voterbase logic, vote weight calculation, vote consequence processing, and tallying module. This makes it easy for developers to change parts of a poll without disrupting other parts, and also helps people understand better, code written in the same format by other people. - -2. Permissioning: Permissioning is an important aspect of polls, and is missing in most poll proposals so far, on the blockchain. For some reason, most blockchain based polls seem to consider token holding as the only way to permission a poll. However this hampers flexibility, and hence our poll standard is leveraging EIP 1261 in order to clear the permissioning hurdle. Not only does it allow for more creative poll structures in terms of vote weightage, but even improves the flexibility in permissioning by allowing developers to combine several entities and read attributes from entities. - -3. Flexibility: The vote weight module of the poll standard can be used effectively to design various kinds of poll contracts which function differently and are suited to different environments. Some examples are quadratic voting, karma voting, delegated voting, token based voting, and one person one vote systems. These schemes are possible due to the separation of voterbase creation and vote weight calculation. - -4. NoV Counts: Several weighted polls have struggled to provide proper transparency because they only show the final result without enough granularity. This is because they do not store the number of voters that have voted for each proposal, and only store the total accrued vote for each option. EIP 1417 solves this by additionally recording number of voters(NoV) in each proposal. This NoV count is redundant in the case of one person one vote, but elsewhere, it is helpful in figuring out concentration of power. This ensures that malicious parties can be traced to a larger extent. - -5. Event Logging: The poll standard logs an event during a successful vote, unsuccessful vote, and a successful unvote. This is being done so that in the event of a malicious admin removing real members or adding fake members, communities can build tools in order to perform advanced audits and simulate results in the absence of the malicious attack. Such advanced features are completely absent in most polls, and hence, it is hard to investigate such polls. - -6. Pollscan.io: The Electus foundation is working on a web based application for accessing and interacting with poll data on the blockchain, it will be deployed on the domain name www.pollscan.io in the coming months. - -All that being said, we are very excited to share our proposal with the community and open up to suggestions in this space. - -### Benefits - -1. Building applications (pollscan.io) on top of a standardized voting interface enables transparency and encourage more DAO/DAICO's to act responsibly in terms of governance -2. Create Action contracts which take actions programmatically based on the result of a poll -3. Allow the compatibility with token standard such as [ERC-20](https://eips.ethereum.org/EIPS/eip-20) or (https://eips.ethereum.org/EIPS/eip-777)) and membership standard such as [EIP-1261](https://eips.ethereum.org/EIPS/eip-1261) -4. Flexibility allows for various voting schemes including but not limited to modern schemes such as PLCR Voting - -### Use-cases: - -Polls are useful in any context of collective decision making, which include but aren't limited to: - -1. Governing public resources, like ponds, playgrounds, streets etc -2. Maintaining fiscal policy in a transparent consensus driven manner -3. Governing crowdfunded projects - refer DAICO, Vitalik Buterin -4. Implementation of Futarchy -5. Decision making in political parties, and municipal corporations -6. Governing expenditure of a cryptocurrency community - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Every ERC-1417 compliant contract must implement the `ERC1417` and `ERC165` interfaces** (subject to "caveats" below): - -```solidity -/// @title ERC-1417 Poll Standard -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1417.md -/// Note: the ERC-165 identifier for this interface is 0x4fad898b. -interface IPoll { - /// @dev This emits when a person tries to vote without permissions. Useful for auditing purposes. - /// E.g.: To prevent an admin to revoke permissions; calculate the result had they not been removed. - /// @param _from User who tried to vote - /// @param _to the index of the proposal he voted to - /// @param voteWeight the weight of his vote - event TriedToVote(address indexed _from, uint8 indexed _to, uint voteWeight); - - /// @dev This emits when a person votes successfully - /// @param _from User who successfully voted - /// @param _to the index of the proposal he voted to - /// @param voteWeight the weight of his vote - event CastVote(address indexed _from, uint8 indexed _to, uint voteWeight); - - /// @dev This emits when a person revokes his vote - /// @param _from User who successfully unvoted - /// @param _to the index of the proposal he unvoted - /// @param voteWeight the weight of his vote - event RevokedVote(address indexed _from, uint8 indexed _to, uint voteWeight); - - /// @notice Handles the vote logic - /// @dev updates the appropriate data structures regarding the vote. - /// stores the proposalId against the user to allow for unvote - /// @param _proposalId the index of the proposal in the proposals array - function vote(uint8 _proposalId) external; - - /// @notice Handles the unvote logic - /// @dev updates the appropriate data structures regarding the unvote - function revokeVote() external; - - /// @notice gets the proposal names - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the proposal list - /// @return the list of names of proposals - function getProposals() external view returns (bytes32[]); - - /// @notice returns a boolean specifying whether the user can vote - /// @dev implement logic to enable checks to determine whether the user can vote - /// if using eip-1261, use protocol addresses and interface (IERC1261) to enable checking with attributes - /// @param _to the person who can vote/not - /// @return a boolean as to whether the user can vote - function canVote(address _to) external view returns (bool); - - /// @notice gets the vote weight of the proposalId - /// @dev returns the current cumulative vote weight of a proposal - /// @param _proposalId the index of the proposal in the proposals array - /// @return the cumulative vote weight of the specified proposal - function getVoteTally(uint _proposalId) external view returns (uint); - - /// @notice gets the no. of voters who voted for the proposal - /// @dev use a struct to keep a track of voteWeights and voterCount - /// @param _proposalId the index of the proposal in the proposals array - /// @return the voter count of the people who voted for the specified proposal - function getVoterCount(uint _proposalId) external view returns (uint); - - /// @notice calculates the vote weight associated with the person `_to` - /// @dev use appropriate logic to determine the vote weight of the individual - /// For sample implementations, refer to end of the eip - /// @param _to the person whose vote weight is being calculated - /// @return the vote weight of the individual - function calculateVoteWeight(address _to) external view returns (uint); - - /// @notice gets the leading proposal at the current time - /// @dev calculate the leading proposal at the current time - /// For practical reasons, limit proposal count to 32. - /// @return the index of the proposal which is leading - function winningProposal() external view returns (uint8); - - /// @notice gets the name of the poll e.g.: "Admin Election for Autumn 2018" - /// @dev Set the name in the constructor of the poll - /// @return the name of the poll - function getName() external view returns (bytes32); - - /// @notice gets the type of the Poll e.g.: Token (XYZ) weighted poll - /// @dev Set the poll type in the constructor of the poll - /// @return the type of the poll - function getPollType() external view returns (bytes32); - - /// @notice gets the logic to be used in a poll's `canVote` function - /// e.g.: "XYZ Token | US & China(attributes in erc-1261) | Developers(attributes in erc-1261)" - /// @dev Set the Voterbase logic in the constructor of the poll - /// @return the voterbase logic - function getVoterBaseLogic() external view returns (bytes32); - - /// @notice gets the start time for the poll - /// @dev Set the start time in the constructor of the poll as Unix Standard Time - /// @return start time as Unix Standard Time - function getStartTime() external view returns (uint); - - /// @notice gets the end time for the poll - /// @dev Set the end time in the constructor of the poll as Unix Time or specify duration in constructor - /// @return end time as Unix Standard Time - function getEndTime() external view returns (uint); - - /// @notice returns the list of entity addresses (eip-1261) used for perimissioning purposes. - /// @dev addresses list can be used along with IERC1261 interface to define the logic inside `canVote()` function - /// @return the list of addresses of entities - function getProtocolAddresses() external view returns (address[]); - - /// @notice gets the vote weight against all proposals - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the vote tally list - /// @return the list of vote weights against all proposals - function getVoteTallies() external view returns (uint[]); - - /// @notice gets the no. of people who voted against all proposals - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the vote count list - /// @return the list of voter count against all proposals - function getVoterCounts() external view returns (uint[]); - - /// @notice For single proposal polls, returns the total voterbase count. - /// For multi proposal polls, returns the total vote weight against all proposals - /// this is used to calculate the percentages for each proposal - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the voter base denominator - /// @return an integer which specifies the above mentioned amount - function getVoterBaseDenominator() external view returns (uint); -} -``` - -### Caveats - -The 0.4.24 Solidity interface grammar is not expressive enough to document the ERC-1417 standard. A contract which complies with ERC-1417 MUST also abide by the following: - -- Solidity issue #3412: The above interfaces include explicit mutability guarantees for each function. Mutability guarantees are, in order weak to strong: `payable`, implicit nonpayable, `view`, and `pure`. Your implementation MUST meet the mutability guarantee in this interface and you MAY meet a stronger guarantee. For example, a `payable` function in this interface may be implemented as nonpayble (no state mutability specified) in your contract. We expect a later Solidity release will allow your stricter contract to inherit from this interface, but a workaround for version 0.4.24 is that you can edit this interface to add stricter mutability before inheriting from your contract. -- Solidity issue #2330: If a function is shown in this specification as `external` then a contract will be compliant if it uses `public` visibility. As a workaround for version 0.4.24, you can edit this interface to switch to `public` before inheriting from your contract. - -_If a newer version of Solidity allows the caveats to be expressed in code, then this EIP MAY be updated and the caveats removed, such will be equivalent to the original specification._ - -## Rationale - -As the poll standard is built with the intention of creating a system that allows for more transparency and accessibility of governance data, the design choices in the poll standard are driven by this motivator. In this section we go over some of the major design choices, and why these choices were made: - -1. Event logging: The logic behind maintaining event logs in the cases of: - - - Cast Vote - - Unvote - - Failed Vote - is to ensure that in the event of a manipulated voterbase, simple off chain checks can be performed to audit the integrity of the poll result. - -2. No poll finish trigger: There was a consideration of adding functions in the poll which execute after completion of the poll to carry out some pre-decided logic. However this was deemed to be unnecessary - because such an action can be deployed in a separate contract which simply reads the result of a given poll, and against the spirit of modularity, because no actions can be created after the poll has been deployed. Also, such functions would not be able to combine the results of polls, and definitely would not fit into polls that do not have an end time. - -3. Allow for unbound polls: The poll standard, unlike other voting standard proposals, does not force polls to have an end time. This becomes relevant in some cases where the purpose of a poll is to have a live register of ongoing consensus. Some other use cases come into picture when you want to deploy a set of action contracts which read from the poll, and want to be able to execute the action contract whenever a poll reaches a certain threshold, rather than waiting for the end of the poll. - -4. Modularization: There have been opinions in the Ethereum community that there cannot exist a voting standard, because voting contracts can be of various types, and have several shapes and forms. However we disagree, and make the case that modularization is the solution. While different polls may need different logic, they all need consistent end points. All polls need to give out results along with headcounts, all polls should have event logs, all polls should be examinable with frontend tools, and so on. The poll standard is not a statement saying “all polls should be token based” or any such specific system. However the poll standard is a statement saying that all polls should have a common access and modification protocol - this will enable more apps to include governance without having to go through the trouble of making customers start using command line. - -Having explained our rationale, we are looking forward to hearing from the community some thoughts on how this can be made more useful or powerful. - -**Gas and Complexity** (regarding the enumeration for proposal count) - -This specification contemplates implementations that contain a sample of 32 proposals (max up to blockgaslimit). If your application is able to grow and needs more than 32 proposals, then avoid using for/while loops in your code. These indicate your contract may be unable to scale and gas costs will rise over time without bound - -**Privacy** - -Personal information: The standard does not put any personal information on to the blockchain, so there is no compromise of privacy in that respect. - -**Community Consensus** - -We have been very inclusive in this process and invite anyone with questions or contributions into our discussion. However, this standard is written only to support the identified use cases which are listed herein. - -## Test Cases - -Voting Standard includes test cases written using Truffle. - -## Implementations - -Voting Standard -- a reference implementation - -- MIT licensed, so you can freely use it for your projects -- Includes test cases -- Also available as a npm package - npm i electusvoting - -## References - -**Standards** - -- [EIP-20: ERC-20 Token Standard (a.k.a. ERC-20)](https://eips.ethereum.org/EIPS/eip-20) -- [EIP-165: Standard Interface Detection](https://eips.ethereum.org/EIPS/eip-165) -- [EIP-721: Non-Fungible Token Standard(a.k.a. ERC-721)](https://eips.ethereum.org/EIPS/eip-721) -- [ERC-1261 MV Token Standard](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1261.md) -- [RFC 2119 Key words for use in RFCs to Indicate Requirement Levels](https://www.ietf.org/rfc/rfc2119.txt) - -**Issues** - -1. The Original ERC-1417 Issue. https://github.com/ethereum/eips/issues/1417 -1. Solidity Issue \#2330 -- Interface Functions are Axternal. https://github.com/ethereum/solidity/issues/2330 -1. Solidity Issue \#3412 -- Implement Interface: Allow Stricter Mutability. https://github.com/ethereum/solidity/issues/3412 -1. Solidity Issue \#3419 -- Interfaces Can't Inherit. https://github.com/ethereum/solidity/issues/3419 - -**Discussions** - -1. ERC-1417 (announcement of first live discussion). https://github.com/ethereum/eips/issues/1417 - -**Voting Implementations and Other Projects** - -- [Voting Implementations](https://github.com/chaitanyapotti/Voting) - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1417.md diff --git a/EIPS/eip-1418.md b/EIPS/eip-1418.md index 398adaa3f87e09..ac932f21780b58 100644 --- a/EIPS/eip-1418.md +++ b/EIPS/eip-1418.md @@ -1,53 +1,48 @@ --- eip: 1418 title: Blockchain Storage Rent Payment +description: At each block, deduct value from every account based on the quantity of storage used by that account. author: William Entriken (@fulldecent) -discussions-to: https://github.com/ethereum/EIPs/issues/1418 -status: Draft +discussions-to: https://ethereum-magicians.org/t/eip-1418-storage-rent/10737 +status: Stagnant type: Standards Track category: Core created: 2018-09-16 +requires: 1559 --- -# Simple Summary +## Abstract -At each block, deduct an amount of value from every account based on the quantity of storage used by that account. +At each block, deduct an amount of value ("rent") from every account based on the quantity of storage used by that account. -# Abstract +## Motivation -The most naive implementation would be to simply loop through every account on each block and deduct a certain fee. We show that a better implementation could achieve reasonable performance. Also we review practical considerations of switching to a fee-based rent system. - -In other words, `product=0; while(factor1--)product+= factor2;` is slow, but equivalently `product = factor1 * factor2` is fast. And we can reason about both at the same time. +Ethereum is a public utility and we are underpricing the long-term costs of storage. Storage cost can be approximately modeled as bytes × time. -# Motivation +## Specification -Ethereum is a public utility and we are underpricing the long-term costs of storage. Storage cost can be approximately modeled as bytes × time. +**Updated transaction type** -# Specification +A new transaction type is introduced. Whereas [EIP-1559](./eip-1559.md) introduced warm access for contract state, this new type introduces warm access for contract code. **New state variables (per account)** -* rent -- σ[a]_r -- an amount of value, in Wei -* rentLastPaid -- σ[a]_p -- a block number that is set when: - * Value is transferred into an account - * Code is set for an account (CREATE) - * An account's storage is updated (SSTORE) -* storageWords -- σ[a]_w -- number of words in storage -* rentEvictBlock -- σ[a]_e -- the block number when this account will be destructed - * Note: it is possible that a client could implement the Yellow Paper without storing this value explicitly. It can be calculated simply on demand. +* **σ[a]_rent** -- an amount of value, in Wei, this is a signed value +* **σ[a]_storageWords** -- number of words in storage **New constants** -* RENT_WORD_COST -- The rent cost, in Wei, paid for each word-block -* RENT_ACCOUNT_COST -- The rent cost, in Wei, paid for each account-block -* RENT_STIPEND -- The amount of rent, in Wei, given to accounts when touched +* **`RENT_WORD_COST`** -- The rent cost, in Wei, paid for each word-block +* **`RENT_ACCOUNT_COST`** -- The rent cost, in Wei, paid for each account-block +* **`FORK_BLOCK`** – When implementation starts **New opcodes** -* RENTBALANCE(address) -- G_BALANCE -- Similar to BALANCE -* SENDRENT(address, amount) -- G_BASE -- Convert value to rent and send to account - 1. σ[account]_rent += amount - 2. σ[msg.sender]_balance -= amount +* **`RENTBALANCE(address)`** -- G_BALANCE -- Similar to `BALANCE` + * This returns the logical `σ[a]_rent` value which is defined to reduce each block. It is possible for the implementation to calculate this value using the recommended implementation variables, rather than storing and updating `σ[a]_rent` every block for every account. +* **`SENDRENT(address, amount)`** -- G_BASE -- Convert value to rent and send to account + 1. `σ[account]_rent` += amount + 2. `σ[msg.sender]_balance` -= amount **Updated opcodes** @@ -55,64 +50,76 @@ A new subroutine, paying for rent, is established as such: ```pseudocode PAYRENT(account) - ASSERT(σ[account]_rentEviction >= NUMBER) // TODO: I'm not sure if should be > or >= blocks_to_pay = NUMBER - σ[account]_rentLastPaid - cost_per_block = RENT_ACCOUNT_COST + RENT_WORD_COST * ⌈∥σ[account]_code∥ / 32⌉ + RENT_WORD_COST * σ[a]_storageWords + cost_per_block = RENT_ACCOUNT_COST + RENT_WORD_COST * (⌈∥σ[account]_code∥ / 32⌉ + * σ[a]_storageWords) rent_to_pay = blocks_to_pay * cost_per_block σ[account]_rent -= rent_to_pay + if σ[account]_rent < 0 + σ[account]_value += σ[account]_rent + σ[account]_rent = 0 + end + if σ[account]_value < 0 + σ[account]_rent = σ[account]_value + σ[account]_value = 0 + end σ[account]_rentLastPaid = NUMBER σ[account]_rentEvictBlock = NUMBER + ⌊σ[account]_rent / cost_per_block⌋ END PAYRENT ``` -* SSTORE(account, key, value) +* **`SSTORE(account, key, value)`** * Perform PAYRENT(account) - * Set σ[account]_rent = MAX(σ[account]_rent, RENT_STIPEND) + * If `account` is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless using the new transaction type and sufficient proofs are included to validate the old storage root and calculate the new root. * Do normal SSTORE operation - * If the old value was zero for this [account, key] and the new value is non-zero, then σ[account]_storageSize++ - * If the old value was non-zero for this [account, key] and the new value is zero, then σ[account]_storageSize-- -* CALL (and derivatives) - * If value > 0 then perform PAYRENT(account) + * If the old value was zero for this [account, key] and the new value is non-zero, then `σ[account]_storageWords++` + * If the old value was non-zero for this [account, key] and the new value is zero, then `σ[account]_storageWords--`, and if the result is negative then set to zero +* **`SLOAD(account, key)`** + * If `account` is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless using the new transaction type and sufficient proofs are included to validate the existing storage root and the existing storage value. + * Do normal SLOAD operation. +* **`CALL (and derivatives)`** + * If the target block is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless using the new transaction type and sufficient proof is included to validate the existing code. * Do normal CALL operation -* CREATE - * Set σ[account]_rent = MAX(σ[account]_rent, RENT_STIPEND) - * Set σ[account]_rentLastPaid = HEIGHT +* **`CREATE`** + * Set σ[account]_rentLastPaid = NUMBER * Do normal CREATE operation + * `σ[account]_storageWord = 0` * Note: it is possible there is a pre-existing rent balance here -**Updated substate** - -The substate tuple is defined as: +**New built-in contract** -> A ≡ (As, Al, At, Ar) +* `PAYRENT(address, amount)` -- Calls `PAYRENT` opcode + * This is a convenience for humans to send Ether from their accounts and turn it into rent. Note that simple accounts (CODESIZE == 0) cannot call arbitrary opcodes, they can only call CREATE or CALL. + * The gas cost of PAYRENT will be 10,000 or lower if possible. -This includes A_t, "the set of touched accounts, of which the empty ones are deleted at the end of a transaction". +**Calculating `σ[account]_storageWord` for existing accounts** -This definition is updated to: "the set of touched accounts, of which the empty ones or evicted ones (BLOCK >= σ[a]_rentEvictBlock) are deleted at the end of a transaction" +DRAFT... -// TODO: I'm not sure if that should be > or >= +It is not an acceptable upgrade if on the fork block it is necessary for only archive nodes to participate which know the full storage amount for each account. -**New built-in contract** +An acceptable upgrade will be if the required `σ[account]_storageWord` can be calculated (or estimated) incrementally based on new transaction activity. -* PAYRENT(address, amount) -- Calls PAYRENT opcode +DRAFT: I think it is possible to make such an acceptable upgrade using an unbiased estimator -*This is a convenience for humans to send Ether from their accounts and turn it into rent. Note that simple accounts (CODESIZE == 0) cannot call arbitrary opcodes, they can only call CREATE or CALL.* +* add one bit of storage per `SSTORE` for legacy accounts on the first access of a given key +* add log(n) bits for each trie level +* assume that storage keys are a random variable -The gas cost of PAYRENT will be 10,000. +To think more about... **No changes to current opcode gas costs.** -# Rationale +## Rationale **No call** -A contract will not know or react to the receipt of rent. This is okay. Workaround: if a contract really needed to know who provided rent payments then it could create a function in its ABI to attribute these payments. It is already possible to send payments to a contract without attribution by using SELFDESTRUCT. +A contract will not know or react to the receipt of rent. This is okay. Workaround: if a contract really needed to know who provided rent payments then it could create a function in its ABI to attribute these payments. It is already possible to send payments to a contract without attribution by using `SELFDESTRUCT`. Other blockchains like TRON allow to transfer value to a contract without performing a call. **Eviction responsibility / lazy evaluation** -The specification gives responsibility for eviction to the consensus clients. This is the most predictable behavior because it happens exactly when it should. Also there need not be any incentive mechanism (refund gas, bounty) for outside participants (off chain) to monitor accounts and request removal. +The specification gives responsibility for eviction to the consensus clients. This is the most predictable behavior because it happens exactly when it should. Also there need not be any incentive mechanism (refund gas, bounty) for outside participants (off-chain) to monitor accounts and request removal. -This adds a computational responsibility to the clients to track eviction dates. This is possible in efficient time (at double the memory) using a double-ended priority queue (one for addressing by account address, the other for addressing by eviction date). There may be other ways of implementing this with different time-memory guarantees. +It is possible that an arbitrary number of accounts will be evicted in one block. That doesn't matter. Client implementations do not need to track which accounts are evicted, consensus is achieved just by agreeing on the conditions under which an account would be evicted. **No converting rent to value** @@ -120,67 +127,69 @@ Ether converted to rent cannot be converted back. Anybody that works in accounti **Accounts pay rent** -Yes, they pay rent. It costs money to keep their balances so we charge them rent. +Yes, they pay rent. It costs resources to account for their balances so we charge them rent. -**You can lose all your money** +**Why do you need a separate rent account?** -Yes, if you do not pay rent for your account or contract then you lose it all. User education is required. +Because anybody/everybody can contribute to the rent account. If you depend on a contract, you should contribute to its rent. -Alternative: spend value (Ether balance) when rent is depleted - * Rename rentEvictBlock to rentUsingValueBlock - * Update eviction calculation to include RENT + VALUE. Also update CALL (and friends) operations to recalculate eviction date when value is transferred. This is the new rentEvictBlock. - * Update CALL (and friends), RENTBALANCE and SENDRENT operations. If HEIGHT >= rentUsingValueBlock then proceed as if rent started paying using value. +But the contract can spend all of its value. -This alternative is a good idea, if there is support I can include this part formally in the specification. The specification is a little complicated so I like the informal definition above until we have some consent around it. +By maintaining a separate rent and value balance, this allows people to contribute to the rent while being confident that this is allowing the contract to stay around. -Alternative2: do not have a separate rent account -- directly deduct rent from value - * Every time the state is updated (including receiving value) you get a rent subsidity - * Need to review invariants of existing contracts to see what problems and broken assumptions this will cause in real life +NOTE: cloning. With this EIP, it may become feasible to allow storage cloning. Yes really. Because the new clone will be paying rent. See other EIP, I think made by Augur team. -**Permanent removal** +### Economics & constants -All state about an account is destructed during eviction. The data cannot be recovered. That's the point. +An `SSTORE` executed in 2015 cost 20,000 gas and has survived about 6 million blocks. The gas price has been around 1 ~ 50 Gwei. So basically 4,000 Wei per block per word so far. Maybe storing an account is 10 times more intensive than storing a word. But actually `G_transaction` is 21,000 and `G_sstore` is 20,000 so these are similar and they can both create new accounts / words. -Hint to implementers: make sure this works: +How about: -1. Send value to a new account (gets stipend) -2. Pay rent to that account -3. Wait until after the rent expires (account is gone) -4. Send value to that account (gets stipend again) -5. Deploy a contract (CREATE) to that account (stipend gets topped off) +* `RENT_WORD_COST` -- 4,000 Wei +* `RENT_ACCOUNT_COST` -- 4,000 Wei +* `FORK_BLOCK` – when implementation starts -# Rationale -- economics & constants +The rent is priced in cold, hard Ether. It is not negotiated by clients, it is not dynamic. -An `SSTORE` executed in 2015 cost 20,000 gas and has survived about 6 million blocks. The gas price has been around 1 ~ 50 Gwei. So basically 4,000 Wei per block per word so far. Maybe storing an account is 10 times more intensive than storing a word. But actually G_transaction is 21,000 and G_sstore is 20,000 so these are similar and they can both create new accounts / words. +A future EIP may change this pricing to be dynamic. For example to notarize a block, notaries may be required to prove they have the current storage dataset (excluding evictions). Additionally, they may also prove they have the dataset plus evictions to earn an additional fee. The relative storage of the evicted accounts, and the other accounts versus the value of the additional fee may be used as a feedback mechanism to set a market price for storage. -How about: +FYI, there are about 15B words in the Ethereum Mainnet dataset and about 100M total Ether mined. This means if all Ether was spent on storage at current proposed prices it would be 400 terabyte-years of storage. I'm not sure if it is helpful to look at it that way. -* RENT_WORD_COST -- 4,000 Wei -* RENT_ACCOUNT_COST -- 4,000 Wei -* RENT_STIPEND -- 4,000 Wei * 360 days worth of blocks +## Backwards Compatibility -The rent is priced in cold, hard Ether. It is not negotiated by clients, it is not dynamic. It is linear. Why is this a good idea? Because right now Ethereum is a system with multiple free variables -- Ether/gas price, gas/opcodes costs, Ether/block reward. [Add some note here about reducing a system of equations...] So the end result is that we can peg one of the values and it will be okay. +EIP-1559 already introduces a mechanism for nodes to participate without recording the full network state and for clients to warm cache with storage data in their type 2 transactions. -By setting the RENT price in Ether and by having the existing gas prices set based on the floating rate, there is an implicit price of ~4 gwei set into the Yellow Paper. In other words, if in the future the price of gas goes to 1 Ether then people will be upset because they will say "I paid 20,000 gas for an SSTORE" but I only got 360 days of stipend. If I paid for the rent directly I would have gotten enough rent to last until the Sun explodes." I acknowledge this complaint and do not think it is sufficient to warrant dismissing this proposal. - -Q: There is a finite-ish amount of Ether and this proposal introduces a word-price in Ether, do math for me. A: The current size of Ethereum is about ~1 TB, maybe half of that is branch nodes. So that's like 15B words. There is about 100M Ether mined. The answer is that all the Ether can be spent on 400,000 terabyte-years of storage. I'm not sure if it is helpful to look at it that way. +Users will need to be educated. -# Backwards compatibility +Many smart contracts allow anybody to use an arbitrary amount of storage in them. This can limit the usefulness of deploying this proposal on an existing chain. -There is a 360-day transition period (related to the RENT_STIPEND). This requires a hard fork. On the block of the fork, every account is immediately funded with enough rent to pay for ~ 360 days' worth of their current storage requirements. The formal implementation is that this new rule is applied if any existing account has σ[account]_rentLastPaid = 0. Therefore this can be implemented by clients lazily or eagerly. +**Recommended implementation variables (per account)** -Preexisting accounts which increase their storage needs will evict sooner than 360 days. +* **σ[a]_rentLastPaid** -- a block number that is set when: + * Value is transferred into an account (`CREATE`, `CALL`, `SELFDESTRUCT`) + * Code is set for an account (`CREATE`) + * An account's storage is updated (`SSTORE`) + * This begins with a logical value of `FORK_BLOCK` for all accounts -Users will need to be educated. +* **σ[a]_rentEvictBlock** -- the block number when this account will be evicted -# Test Cases +**Storage note** -TO BE ADDED +For every account that is evicted, clients may choose to delete that storage from disk. A future EIP may make an incentive to keep this extra data for a fee. A future EIP may create a mechanism for clients to exchange information about these storage states. -# Implementation +## Security Considerations -TO BE ADDED +Many smart contracts allow anybody to use an arbitrary amount of storage in them. -# Copyright +## Copyright Copyright and related rights waived via CC0. + + diff --git a/EIPS/eip-1438.md b/EIPS/eip-1438.md index b9e4f30cdfe1f7..3f46c40d2adf45 100644 --- a/EIPS/eip-1438.md +++ b/EIPS/eip-1438.md @@ -1,142 +1,7 @@ --- eip: 1438 -title: dApp Components (avatar) & Universal Wallet -author: Jet Lim (@Nitro888) -discussions-to: https://ethresear.ch/t/avatar-system-and-universal-wallet-for-ethereum-address/3473 -status: Draft -type: Standards Track category: ERC -created: 2018-09-21 +status: Moved --- -## Simple Summary -Contracts are open source based. And most developers use the public contracts at the start of the project to modify or simply include them. This is project-oriented centralized development and I think it is a waste of resources. Therefore, we propose to make dApp or contracts component-ready for use in other services. - -## Abstract -There have been suggestions for modified tokens based on erc20, but since many tokens have already been built on erc20, it is necessary to increase the utilization of already developed erc20 tokens. Therefore, we propose a universal wallet that can use erc20 tokens universally. We also propose a component dApp that allows you to create and save your avatar (& social badge system), and use it immediately in other services. All of the dApps suggested in this document are based on decentralized development and use that anyone can create and participate in. - -## Motivation -While many projects are under development in an open source way, they are simply adding and deploy with open sources to their projects. This means that you are developing a centralized service that uses your own dApp-generated information on your own. In order to improve the block chain ecosystem, all resources created by dApp and placed in the public block chain must be reusable in another dApp. This means that you can enhance your service by exchanging the generated information with other dApp. Likewise, ERC20 Tokens require Universal Wallet standards to be easy to use for direct transactions. - -### Seeds for improvement of the blockchain ecosystem. -- Synergy - With other dApps and resources. -- Enhanced interface - For ERC20 tokens. -- Easy & Decentralized - Everyone should be able to add to their services easily, without censorship. - - -#### The following avatar store, badge system, and universal wallet are kind of examples about component dApp. -![intro](https://user-images.githubusercontent.com/11692220/45585539-ef51af00-b920-11e8-876b-ec7ee91c2cc6.png) - -## Specification -### 1. Avatar -#### 1.1. Avatar Shop -- The avatar store is created after ERC20 currency is set. -- You can customize asset category & viewer script. - -#### 1.2. Upload asset & user data -The avatar's information & assets are stored in the event log part of the block chain. -- Assets are SVG format. (compressed with gzip) -- avatar information data is json (compressed with msgpack) - -![avatar](https://user-images.githubusercontent.com/11692220/45530825-820e2300-b827-11e8-8468-fc3a9ae51ed8.png) -** The avatar assets from [Avataaars](https://github.com/fangpenlin/avataaars) developed by [Fang-Pen Lin](https://twitter.com/fangpenlin), the original avatar is designed by [Pablo Stanley](https://twitter.com/pablostanley). - -### 2. Universal Wallet -![wallet](https://user-images.githubusercontent.com/11692220/45146088-1b708000-b1fd-11e8-9b57-30ea7491de0b.png) -#### 2.1. ERC20 interface -``` js -contract ERC20Interface { - function totalSupply() public constant returns (uint); - function balanceOf(address tokenOwner) public constant returns (uint balance); - function allowance(address tokenOwner, address spender) public constant returns (uint remaining); - function transfer(address to, uint tokens) public returns (bool success); - function approve(address spender, uint tokens) public returns (bool success); - function transferFrom(address from, address to, uint tokens) public returns (bool success); - - event Transfer(address indexed from, address indexed to, uint tokens); - event Approval(address indexed tokenOwner, address indexed spender, uint tokens); -} -``` - -#### 2.2. Fixed ERC20 contract for receive approval and execute function in one call -``` js -function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { - allowed[msg.sender][spender] = tokens; - emit Approval(msg.sender, spender, tokens); - ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); - return true; -} -``` - -#### 2.3. And ApproveAndCallFallBack contract for Fixed ERC20. -However, many ERC20 tokens are not prepared. -``` js -contract ApproveAndCallFallBack { - function receiveApproval(address from, uint256 tokens, address token, bytes data) public; -} -``` -#### 2.4. Universal Wallet -We propose a Universal Wallet to solve this problem. - -``` js -contract UniversalWallet is _Base { - - constructor(bytes _msgPack) _Base(_msgPack) public {} - function () public payable {} - - //------------------------------------------------------- - // erc20 interface - //------------------------------------------------------- - function balanceOf(address _erc20) public constant returns (uint balance) { - if(_erc20==address(0)) - return address(this).balance; - return _ERC20Interface(_erc20).balanceOf(this); - } - function transfer(address _erc20, address _to, uint _tokens) onlyOwner public returns (bool success) { - require(balanceOf(_erc20)>=_tokens); - if(_erc20==address(0)) - _to.transfer(_tokens); - else - return _ERC20Interface(_erc20).transfer(_to,_tokens); - return true; - } - function approve(address _erc20, address _spender, uint _tokens) onlyOwner public returns (bool success) { - require(_erc20 != address(0)); - return _ERC20Interface(_erc20).approve(_spender,_tokens); - } - - //------------------------------------------------------- - // pay interface - //------------------------------------------------------- - function pay(address _store, uint _tokens, uint256[] _options) onlyOwner public { - address erc20 = _ApproveAndCallFallBack(_store).erc20(); - address spender = _ApproveAndCallFallBack(_store).spender(); - if(erc20 == address(0)) { - transfer(erc20,spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_options); - } else { - _ERC20Interface(erc20).approve(spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_options); - } - } - function pay(address _store, uint _tokens, bytes _msgPack) onlyOwner public { - address erc20 = _ApproveAndCallFallBack(_store).erc20(); - address spender = _ApproveAndCallFallBack(_store).spender(); - if(erc20 == address(0)) { - transfer(erc20,spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_msgPack); - } else { - _ERC20Interface(erc20).approve(spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_msgPack); - } - } -} -``` - -## Test Cases -- https://www.nitro888.com -- https://github.com/Nitro888/nitro888.github.io -- https://github.com/Nitro888/dApp-Alliance - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1438.md diff --git a/EIPS/eip-1444.md b/EIPS/eip-1444.md index b46d4f58e7dcae..4c40d99448fcd6 100644 --- a/EIPS/eip-1444.md +++ b/EIPS/eip-1444.md @@ -1,322 +1,7 @@ --- eip: 1444 -title: Localized Messaging with Signal-to-Text -author: Brooklyn Zelenka (@expede), Jennifer Cooper (@jenncoop) -discussions-to: https://ethereum-magicians.org/t/eip-1444-localized-messaging-with-signal-to-text/ -status: Draft -type: Standards Track category: ERC -created: 2018-09-23 +status: Moved --- -## Simple Summary - -A method of converting machine codes to human-readable text in any language and phrasing. - -## Abstract - -An on-chain system for providing user feedback by converting machine-efficient codes into human-readable strings in any language or phrasing. The system does not impose a list of languages, but rather lets users create, share, and use the localizated text of their choice. - -## Motivation - -There are many cases where an end user needs feedback or instruction from a smart contact. Directly exposing numeric codes does not make for good UX or DX. If Ethereum is to be a truly global system usable by experts and lay persons alike, systems to provide feedback on what happened during a transaction are needed in as many languages as possible. - -Returning a hard-coded string (typically in English) only serves a small segment of the global population. This standard proposes a method to allow users to create, register, share, and use a decentralized collection of translations, enabling richer messaging that is more culturally and linguistically diverse. - -There are several machine efficient ways of representing intent, status, state transition, and other semantic signals including booleans, enums and [ERC-1066 codes](https://eips.ethereum.org/EIPS/eip-1066). By providing human-readable messages for these signals, the developer experience is enhanced by returning easier to consume information with more context (ex. `revert`). End user experience is enhanced by providing text that can be propagated up to the UI. - -## Specification - -### Contract Architecture - -Two types of contract: `LocalizationPreferences`, and `Localization`s. - -The `LocalizationPreferences` contract functions as a proxy for `tx.origin`. - -```diagram - +--------------+ - | | - +------> | Localization | - | | | - | +--------------+ - | - | -+-----------+ +-------------------------+ | +--------------+ -| | | | <------+ | | -| Requestor | <------> | LocalizationPreferences | <-------------> | Localization | -| | | | <------+ | | -+-----------+ +-------------------------+ | +--------------+ - | - | - | +--------------+ - | | | - +------> | Localization | - | | - +--------------+ -``` - -### `Localization` - -A contract that holds a simple mapping of codes to their text representations. - -```solidity -interface Localization { - function textFor(bytes32 _code) external view returns (string _text); -} -``` - -#### `textFor` - -Fetches the localized text representation. - -```solidity -function textFor(bytes32 _code) external view returns (string _text); -``` - -### `LocalizationPreferences` - -A proxy contract that allows users to set their preferred `Localization`. Text lookup is delegated to the user's preferred contract. - -A fallback `Localization` with all keys filled MUST be available. If the user-specified `Localization` has not explicitly set a loalization (ie. `textFor` returns `""`), the `LocalizationPreferences` MUST redelegate to the fallback `Localization`. - -```solidity -interface LocalizationPreferences { - function set(Localization _localization) external returns (bool); - function textFor(bytes32 _code) external view returns (bool _wasFound, string _text); -} -``` - -#### `set` - -Registers a user's preferred `Localization`. The registering user SHOULD be considered `tx.origin`. - -```solidity -function set(Localization _localization) external; -``` - -#### `textFor` - -Retrieve text for a code found at the user's preferred `Localization` contract. - -The first return value (`bool _wasFound`) represents if the text is available from that `Localization`, or if a fallback was used. If the fallback was used in this context, the `textFor`'s first return value MUST be set to `false`, and is `true` otherwise. - -```solidity -function textFor(bytes32 _code) external view returns (bool _wasFound, string _text); -``` - -### String Format - -All strings MUST be encoded as [UTF-8](https://www.ietf.org/rfc/rfc3629.txt). - -```solidity -"Špeĉiäl chârãçtérs are permitted" -"As are non-Latin characters: アルミ缶の上にあるみかん。" -"Emoji are legal: 🙈🙉🙊🎉" -"Feel free to be creative: (ノ◕ヮ◕)ノ*:・゚✧" -``` - -### Templates - -Template strings are allowed, and MUST follow the [ANSI C `printf`](https://pubs.opengroup.org/onlinepubs/009696799/utilities/printf.html) conventions. - -```solidity -"Satoshi's true identity is %s" -``` - -Text with 2 or more arguments SHOULD use the POSIX parameter field extension. - -```solidity -"Knock knock. Who's there? %1$s. %1$s who? %2$s!" -``` - -## Rationale - -### `bytes32` Keys - -`bytes32` is very efficient since it is the EVM's base word size. Given the enormous number of elements (card(A) > 1.1579 × 1077), it can embed nearly any practical signal, enum, or state. In cases where an application's key is longer than `bytes32`, hashing that long key can map that value into the correct width. - -Designs that use datatypes with small widths than `bytes32` (such as `bytes1` in [ERC-1066](https://eips.ethereum.org/EIPS/eip-1066)) can be directly embedded into the larger width. This is a trivial one-to-one mapping of the smaller set into the the larger one. - -### Local vs Globals and Singletons - -This spec has opted to not _force_ a single global registry, and rather allow any contract and use case deploy their own system. This allows for more flexibility, and does not restrict the community for opting to use singleton `LocalizationPreference` contracts for common use cases, share `Localization`s between different proxys, delegate translations between `Localization`s, and so on. - -There are many practical uses of agreed upon singletons. For instance, translating codes that aim to be fairly universal and integrated directly into the broader ecosystem (wallets, frameworks, debuggers, and the like) will want to have a single `LocalizationPreference`. - -Rather the dispersing several `LocalizationPreference`s for different use cases and codes, one could imagine a global "registry of registries". While this approach allows for a unified lookups of all translations in all use cases, it is antithetical to the spirit of decentralization and freedom. Such a system also increases the lookup complexity, places an onus on getting the code right the first time (or adding the overhead of an upgradable contract), and need to account for use case conflicts with a "unified" or centralized numbering system. Further, lookups should be lightweight (especially in cases like looking up revert text). - -For these reasons, this spec chooses the more decentralized, lightweight, free approach, at the cost of on-chain discoverability. A registry could still be compiled, but would be difficult to enforce, and is out of scope of this spec. - -### Off Chain Storage - -A very viable alternative is to store text off chain, with a pointer to the translations on-chain, and emit or return a `bytes32` code for another party to do the lookup. It is difficult to guarantee that off-chain resources will be available, and requires coordination from some other system like a web server to do the code-to-text matching. This is also not compatible with `revert` messages. - -### ASCII vs UTF-8 vs UTF-16 - -UTF-8 is the most widely used encoding at time of writing. It contains a direct embedding of ASCII, while providing characters for most natural languages, emoji, and special characters. - -Please see the [UTF-8 Everywhere Manifesto](https://utf8everywhere.org/) for more information. - -### When No Text is Found - -Returning a blank string to the requestor fully defeats the purpose of a localization system. The two options for handling missing text are: - -1. A generic "text not found" message in the preferred language -2. The actual message, in a different language - -#### Generic Option - -This designed opted to not use generic fallback text. It does not provide any useful information to the user other than to potentially contact the `Localization` maintainer (if one even exists and updating is even possible). - -#### Fallback Option - -The design outlined in this proposal is to providing text in a commonly used language (ex. English or Mandarin). First, this is the language that will be routed to if the user has yet to set a preference. Second, there is a good chance that a user may have _some_ proficiency with the language, or at least be able to use an automated translation service. - -Knowing that the text fell back via `textFor`s first return field boolean is _much_ simpler than attempting language detection after the fact. This information is useful for certain UI cases. for example where there may be a desire to explain why localization fell back. - -### Decentralized Text Crowdsourcing - -In order for Ethereum to gain mass adoption, users must be able to interact with it in the language, phrasing, and level of detail that they are most comfortable with. Rather than imposing a fixed set of translations as in a traditional, centralized application, this EIP provides a way for anyone to create, curate, and use translations. This empowers the crowd to supply culturally and linguistically diverse messaging, leading to broader and more distributed access to information. - -### `printf`-style Format Strings - -C-style `printf` templates have been the de facto standard for some time. They have wide compatibility across most languages (either in standard or third-party libraries). This makes it much easier for the consuming program to interpolate strings with low developer overhead. - -#### Parameter Fields - -The POSIX parameter field extension is important since languages do not share a common word order. Parameter fields enable the reuse and rearrangement of arguments in different localizations. - -```solidity -("%1$s is an element with the atomic number %2$d!", "Mercury", 80); -// => "Mercury is an element with the atomic number 80!" -``` - -#### Simplified Localizations - -Localization text does not require use of all parameters, and may simply ignore values. This can be useful for not exposing more technical information to users that would otherwise find it confusing. - -```ruby -#!/usr/bin/env ruby - -sprintf("%1$s é um elemento", "Mercurio", 80) -# => "Mercurio é um elemento" -``` - -```clojure -#!/usr/bin/env clojure - -(format "Element #%2$s" "Mercury" 80) -;; => Element #80 -``` - -### Interpolation Strategy - -Please note that it is highly advisable to return the template string _as is_, with arguments as multiple return values or fields in an `event`, leaving the actual interpolation to be done off chain. - - -```solidity -event AtomMessage { - bytes32 templateCode; - bytes32 atomCode; - uint256 atomicNumber; -} -``` - -```javascript -#!/usr/bin/env node - -var printf = require('printf'); - -const { returnValues: { templateCode, atomCode, atomicNumber } } = eventResponse; - -const template = await AppText.textFor(templateCode); -// => "%1$s ist ein Element mit der Ordnungszahl %2$d!" - -const atomName = await PeriodicTableText.textFor(atomCode); -// => "Merkur" - -printf(template, atomName, 80); -// => "Merkur ist ein Element mit der Ordnungszahl 80!" -``` - -### Unspecified Behaviour - -This spec does not specify: - -* Public or private access to the default `Localization` -* Who may set text - * Deployer - * `onlyOwner` - * Anyone - * Whitelisted users - * and so on -* When text is set - * `constructor` - * Any time - * Write to empty slots, but not overwrite existing text - * and so on - -These are intentionally left open. There are many cases for each of these, and restricting any is fully beyond the scope of this proposal. - -## Implementation - -```solidity -pragma solidity ^0.4.25; - -contract Localization { - mapping(bytes32 => string) private dictionary_; - - constructor() public {} - - // Currently overwrites anything - function set(bytes32 _code, string _message) external { - dictionary_[_code] = _message; - } - - function textFor(bytes32 _code) external view returns (string _message) { - return dictionary_[_code]; - } -} - -contract LocalizationPreference { - mapping(address => Localization) private registry_; - Localization public defaultLocalization; - - bytes32 private empty_ = keccak256(abi.encodePacked("")); - - constructor(Localization _defaultLocalization) public { - defaultLocalization = _defaultLocalization; - } - - function set(Localization _localization) external returns (bool) { - registry_[tx.origin] = _localization; - return true; - } - - function get(bytes32 _code) external view returns (bool, string) { - return get(_code, tx.origin); - } - - // Primarily for testing - function get(bytes32 _code, address _who) public view returns (bool, string) { - string memory text = getLocalizationFor(_who).textFor(_code); - - if (keccak256(abi.encodePacked(text)) != empty_) { - return (true, text); - } else { - return (false, defaultLocalization.textFor(_code)); - } - } - - function getLocalizationFor(address _who) internal view returns (Localization) { - if (Localization(registry_[_who]) == Localization(0)) { - return Localization(defaultLocalization); - } else { - return Localization(registry_[tx.origin]); - } - } -} -``` - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1444.md diff --git a/EIPS/eip-145.md b/EIPS/eip-145.md index 55ae9c39cebce8..be0aca3e57f1ee 100644 --- a/EIPS/eip-145.md +++ b/EIPS/eip-145.md @@ -1,17 +1,14 @@ --- eip: 145 title: Bitwise shifting instructions in EVM +description: To Provide native bitwise shifting with cost on par with other arithmetic operations. author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast) +status: Final type: Standards Track category: Core -status: Final created: 2017-02-13 --- -## Simple Summary - -To provide native bitwise shifting with cost on par with other arithmetic operations. - ## Abstract Native bitwise shifting instructions are introduced, which are more efficient processing wise on the host and are cheaper to use by a contract. @@ -33,6 +30,7 @@ The `SHL` instruction (shift left) pops 2 values from the stack, first `arg1` an ``` Notes: + - The value (`arg2`) is interpreted as an unsigned number. - The shift amount (`arg1`) is interpreted as an unsigned number. - If the shift amount (`arg1`) is greater or equal 256 the result is 0. @@ -47,6 +45,7 @@ floor(arg2 / 2^arg1) ``` Notes: + - The value (`arg2`) is interpreted as an unsigned number. - The shift amount (`arg1`) is interpreted as an unsigned number. - If the shift amount (`arg1`) is greater or equal 256 the result is 0. @@ -61,6 +60,7 @@ floor(arg2 / 2^arg1) ``` Notes: + - The value (`arg2`) is interpreted as a signed number. - The shift amount (`arg1`) is interpreted as an unsigned number. - If the shift amount (`arg1`) is greater or equal 256 the result is 0 if `arg2` is non-negative or -1 if `arg2` is negative. @@ -70,7 +70,7 @@ The cost of the shift instructions is set at `verylow` tier (3 gas). ## Rationale -Instruction operands were chosen to fit the more natural use case of shifting a value already on the stack. This means the operand order is swapped compared to most arithmetic insturctions. +Instruction operands were chosen to fit the more natural use case of shifting a value already on the stack. This means the operand order is swapped compared to most arithmetic instructions. ## Backwards Compatibility @@ -87,6 +87,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 2. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x01 @@ -94,6 +95,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000002 ``` + 3. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0xff @@ -101,6 +103,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x8000000000000000000000000000000000000000000000000000000000000000 ``` + 4. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x0100 @@ -108,6 +111,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 5. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x0101 @@ -115,6 +119,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 6. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x00 @@ -122,6 +127,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 7. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -129,6 +135,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe ``` + 8. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -136,6 +143,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x8000000000000000000000000000000000000000000000000000000000000000 ``` + 9. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -143,6 +151,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 10. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -150,6 +159,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 11. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -158,7 +168,6 @@ The newly introduced instructions have no effect on bytecode created in the past 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe ``` - ### `SHR` (logical shift right) 1. ``` @@ -168,6 +177,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 2. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x01 @@ -175,6 +185,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 3. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -182,6 +193,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x4000000000000000000000000000000000000000000000000000000000000000 ``` + 4. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0xff @@ -189,6 +201,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 5. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0100 @@ -196,6 +209,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 6. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0101 @@ -203,6 +217,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 7. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x00 @@ -210,6 +225,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 8. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -217,6 +233,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 9. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -224,6 +241,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 10. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -231,6 +249,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 11. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -248,6 +267,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 2. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x01 @@ -255,6 +275,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 3. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -262,6 +283,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xc000000000000000000000000000000000000000000000000000000000000000 ``` + 4. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0xff @@ -269,6 +291,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 5. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0100 @@ -276,6 +299,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 6. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0101 @@ -283,6 +307,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 7. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x00 @@ -290,6 +315,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 8. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -297,6 +323,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 9. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -304,6 +331,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 10. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -311,6 +339,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 11. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -318,6 +347,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 12. ``` PUSH 0x4000000000000000000000000000000000000000000000000000000000000000 PUSH 0xfe @@ -325,6 +355,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 13. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xf8 @@ -332,6 +363,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x000000000000000000000000000000000000000000000000000000000000007f ``` + 14. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xfe @@ -339,6 +371,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 15. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -346,6 +379,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 16. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -353,25 +387,28 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` - - -## Implementation + +### Implementation Client support: + - cpp-ethereum: https://github.com/ethereum/cpp-ethereum/pull/4054 Compiler support: + - Solidity/LLL: https://github.com/ethereum/solidity/pull/2541 -## Tests +### Tests Sources: + - https://github.com/ethereum/tests/tree/develop/src/GeneralStateTestsFiller/stShift Filled Tests: + - https://github.com/ethereum/tests/tree/develop/GeneralStateTests/stShift - https://github.com/ethereum/tests/tree/develop/BlockchainTests/GeneralStateTests/stShift ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1450.md b/EIPS/eip-1450.md index ddbb8ba157f4a3..9650ebb2ee5350 100644 --- a/EIPS/eip-1450.md +++ b/EIPS/eip-1450.md @@ -1,326 +1,7 @@ --- eip: 1450 -title: ERC-1450 -author: John Shiple (@johnshiple), Howard Marks , David Zhang -discussions-to: https://ethereum-magicians.org/t/erc-proposal-ldgrtoken-a-compatible-security-token-for-issuing-and-trading-sec-compliant-securities/1468 -status: Draft -type: Standards Track category: ERC -created: 2018-09-25 +status: Moved --- -# ERC-1450 - A compatible security token for issuing and trading SEC-compliant securities - -## Simple Summary -`ERC-1450` is an `ERC-20` compatible token that enables issuing tokens representing securities that are required to comply with one or more of the following [Securities Act Regulations: Regulation Crowdfunding, Regulation D, and Regulation A](https://www.sec.gov/smallbusiness/exemptofferings). - -## Abstract -`ERC-1450` facilitates the recording of ownership and transfer of securities sold in compliance with the [Securities Act Regulations CF, D and A](https://www.sec.gov/smallbusiness/exemptofferings). The issuance and trading of securities is subject to the Securities Exchange Commission (SEC) and specific U.S. state blue sky laws and regulations. - -`ERC-1450` manages securities ownership during issuance and trading. The Issuer is the only role that should create a `ERC-1450` and assign the RTA. The RTA is the only role that is allowed to execute `ERC-1450`’s `mint`, `burnFrom`, and `transferFrom` functions. No role is allowed to execute `ERC-1450`’s `transfer` function. - -## Motivation -With the advent of the [JOBS Act](https://www.sec.gov/spotlight/jobs-act.shtml) in 2012 and the launch of Regulation Crowdfunding and the amendments to Regulation A and Regulation D in 2016, there has been an expansion in the exemptions available to Issuers and Investors to sell and purchase securities that have not been "registered" with the SEC under the Securities Act of 1933. - -There are currently no token standards that expressly facilitate conformity to securities law and related regulations. ERC-20 tokens do not support the regulated roles of Funding Portal, Broker Dealer, RTA, and Investor and do not support the [Bank Secrecy Act/USA Patriot Act KYC and AML requirements](https://www.occ.treas.gov/topics/compliance-bsa/bsa/index-bsa.html). Other improvements (notably [EIP-1404 (Simple Restricted Token Standard)](https://github.com/ethereum/EIPs/issues/1404) have tried to tackle KYC and AML regulatory requirement. This approach is novel because the RTA is solely responsible for performing KYC and AML and should be solely responsible for `transferFrom`, `mint`, and `burnFrom`. - -## Specification -`ERC-1450` extends `ERC-20`. - -### `ERC-1450` -`ERC-1450` requires that only the Issuer can create a token representing the security that only the RTA manages. Instantiating the `ERC-1450` requires the `Owned` and `IssuerControlled` modifiers, and only the Issuer should execute the `ERC-1450` constructor for a compliant token. `ERC-1450` extends the general `Ownable` modifier to describe a specific subset of owners that automate and decentralize compliance through the contract modifiers `Owned` and `IssuerControlled` and the function modifiers `onlyOwner` and `onlyIssuerTransferAgent`. The `Owned` contract modifier instantiates the `onlyOwner` modifier for functions. The `IssuerControlled` modifier instantiates the `onlyIssuerTransferAgent` modifier for functions. - -`ERC-1450` must prevent anyone from executing the `transfer`, `allowance`, and `approve` functions and/or implement these functions to always fail. `ERC-1450` updates the `transferFrom`, `mint`, and `burnFrom` functions. `transferFrom`, `mint`, and `burnFrom` may only be executed by the RTA and are restricted with the `onlyIssuerTransferAgent` modifier. Additionally, `ERC-1450` defines the functions `transferOwnership`, `setTransferAgent`, `setPhysicalAddressOfOperation`, and `isTransferAgent`. Only the issuer may call the `transferOwnership`, `setTransferAgent`, and `setPhysicalAddressOfOperation` functions. Anyone may call the `isTransferAgent` function. - -### Issuers and RTAs -For compliance reasons, the `ERC-1450` constructor must specify the issuer (the `owner`), the RTA (`transferAgent`), the security’s `name`, and the security’s `symbol`. - -#### Issuer Owned -`ERC-1450` must specify the `owner` in its constructor, apply the `Owned` modifier, and instantiate the `onlyOwner` modifier to enable specific functions to permit only the Issuer’s `owner` address to execute them. `ERC-1450` also defines the function `transferOwnership` which transfers ownership of the Issuer to the new `owner`’s address and can only be called by the `owner`. `transferOwnership` triggers the `OwnershipTransferred` event. - -#### Issuer Controlled -`IssuerControlled` maintains the Issuer’s ownership of their securities by owning the contract and enables the Issuer to set and update the RTA for the Issuer’s securities. `ERC-1450`‘s constructor must have an `IssuerControlled` modifier with the issuer specified in its `ERC-1450` constructor. `IssuerControlled` instantiates the `onlyIssuerTransferAgent` modifier for `ERC-1450` to enable specific functions (`setPhysicalAddressOfOperation` and `setTransferAgent`) to permit only the Issuer to execute these functions. - -#### Register Transfer Agent Controlled -`ERC-1450` defines the `setTransferAgent` function (to change the RTA) and `setPhysicalAddressOfOperation` function (to change the Issuer’s address) and must restrict execution to the Issuer’s owner with the `onlyOwner` modifier. `setTransferAgent` must emit the `TransferAgentUpdated` event. `setPhysicalAddressOfOperation` must emit the `PhysicalAddressOfOperationUpdated` event. - -`ERC-1450` must specify the `transferAgent` in its constructor and instantiate the `onlyIssuerTransferAgent` modifier to enable specific functions (`transferFrom`, `mint`, and `burnFrom`) to permit only the Issuer’s `transferAgent` address to execute them. `ERC-1450` also defines the public function `isTransferAgent` to lookup and identify the Issuer’s RTA. - -#### Securities -`ERC-1450` updates the `transferFrom`, `mint`, and `burnFrom` functions by applying the `onlyIssuerTransferAgent` to enable the issuance, re-issuance, and trading of securities. - -### ERC-20 Extension -`ERC-20` tokens provide the following functionality: - -``` -contract ERC20 { - function totalSupply() public view returns (uint256); - function balanceOf(address who) public view returns (uint256); - function transfer(address to, uint256 value) public returns (bool); - function allowance(address owner, address spender) public view returns (uint256); - function transferFrom(address from, address to, uint256 value) public returns (bool); - function approve(address spender, uint256 value) public returns (bool); - event Approval(address indexed owner, address indexed spender, uint256 value); - event Transfer(address indexed from, address indexed to, uint256 value); -} -``` - -`ERC-20` is extended as follows: - -``` -/** - * ERC-1450 is an ERC-20 compatible token that facilitates compliance with one or more of Securities Act Regulations CF, D and A. - * - * Implementations of the ERC-1450 standard must define the following optional ERC-20 - * fields: - * - * name - The name of the security - * symbol - The symbol of the security - * - * Implementations of the ERC-1450 standard must specify the following constructor - * arguments: - * - * _owner - the address of the owner - * _transferAgent - the address of the transfer agent - * _name - the name of the security - * _symbol - the symbol of the security - * - * Implementations of the ERC-1450 standard must implement the following contract - * modifiers: - * - * Owned - Only the address of the security’s issuer is permitted to execute the - * token’s constructor. This modifier also sets up the onlyOwner function modifier. - * IssuerControlled - This modifier sets up the onlyIssuerTransferAgent function modifier. - * - * Implementations of the ERC-1450 standard must implement the following function - * modifiers: - * - * onlyOwner - Only the address of the security’s issuer is permitted to execute the - * functions transferOwnership, setTransferAgent, and setPhysicalAddressOfOperation. - * onlyIssuerTransferAgent - Only the address of the issuer’s Registered Transfer - * Agent is permitted to execute the functions transferFrom, mint, and burnFrom. - * - * Implementations of the ERC-1450 standard must implement the following required ERC-20 - * event to always fail: - * - * Approval - Should never be called as the functions that emit this event must be - * implemented to always fail. - * - * Implementations of the ERC-1450 standard must implement the following required - * ERC-20 functions to always fail: - * - * transfer - Not a legal, regulated call for transferring securities because - * the token holder initiates the token transfer. The function must be implemented to - * always fail. - * allowance - Not a legal, regulated call for transferring securities because - * the token holder may not allow third parties to initiate token transfers. The - * function must be implemented to always fail. - * approve - Not a legal, regulated call for transferring securities because - * the token holder may not allow third parties to initiate token transfers. The - * function must be implemented to always fail. - * - * Implementations of the ERC-1450 standard must implement the following optional - * ERC-20 function: - * decimals - Must return '0' because securities are indivisible entities. - * - * Implementations of the ERC-1450 standard must implement the following functions: - * - * mint - Only the address of the issuer's Registered Transfer Agent may create new - * securities. - * burnFrom - Only the address of the issuer’s Registered Transfer Agent may burn or - * destroy securities. - */ - -Contract ERC-1450 is Owned, IssuerControlled { - - /** - * The constructor must implement a modifier (Owned) that creates the onlyOwner modifier - * to allow only the address of the issuer (the owner) to execute the transferOwnership, - * setTransferAgent, and setPhysicalAddressOfOperation functions. The construct must also - * implement a modifier (TransferAgentControlled) that creates the onlyIssuerTransferAgent - * modifier to allow only the address of the issuer’s Registered Transfer Agent to execute - * the functions transferFrom, mint, and burnFrom). - */ - constructor(address _owner, address _transferAgent, string _name, string _symbol) - Owned(_issuer) TransferAgentControlled(_transferAgent) public; - - /** - * Specify that only the owner (issuer) may execute a function. - * - * onlyOwner requires the msg.sender to be the owner’s address. - */ - modifier onlyOwner(); - - /** - * Specify that only the issuer’s transferAgent may execute a function. - * - * onlyIssuerTransferAgent requires the msg.sender to be the transferAgent’s address. - */ - modifier onlyIssuerTransferAgent(); - - /** - * Transfer ownership of a security from one issuer to another issuer. - * - * transferOwnership must implement the onlyOwner modifier to only allow the - * address of the issuer’s owner to transfer ownership. - * transferOwnership requires the _newOwner address to be the address of the new - * issuer. - */ - function transferOwnership(address _newOwner) public onlyOwner; - - /** - * Triggered after transferOwnership is executed. - */ - event OwnershipTransferred() - - /** - * Sets the transfer agent for the security. - * - * setTransferAgent must implement the onlyOwner modifier to only allow the - * address of the issuer’s specify the security’s transfer agent. - * setTransferAgent requires the _newTransferAgent address to be the address of the - * new transfer agent. - */ - function setTransferAgent(address _newTransferAgent) public onlyOwner; - - /** - * Triggered after setTransferAgent is executed. - */ - event TransferAgentUpdated(address indexed previousTransferAgent, address indexed - newTransferAgent); - - /** - * Sets the issuers physical address of operation. - * - * setPhysicalAddressOfOperation must implement the onlyOwner modifier to only allow - * the address of the issuer’s owner to transfer ownership. - * setPhysicalAddressOfOperation requires the _newPhysicalAddressOfOperation address - * to be the new address of the issuer. - */ - function setPhysicalAddressOfOperation(string _newPhysicalAddressOfOperation) public - onlyOwner; - - /** - * Triggered after setPhysicalAddressOfOperation is executed. - */ - event PhysicalAddressOfOperationUpdated(string previousPhysicalAddressOfOperation, - string newPhysicalAddressOfOperation); - - /** - * Look up the security’s transfer agent. - * - * isTransferAgent is a public function. - * isTransferAgent requires the _lookup address to determine if that address - * is the security’s transfer agent. - */ - function isTransferAgent(address _lookup) public view returns (bool); - - /** - * transfer is not a legal, regulated call and must be implemented to always fail. - */ - transfer(address to, uint tokens) public returns (bool success); - - /** - * Approval does not have to be implemented. This event should never be triggered as - * the functions that emit this even are not legal, regulated calls. - */ - event Approval(address indexed tokenOwner, address indexed spender, uint tokens); - - /** - * allowance is not a legal, regulated call and must be implemented to always fail. - */ - allowance(address tokenOwner, address spender) public constant returns (uint remaining); - - /** - * approve is not a legal, regulated call and must be implemented to always fail. - */ - approve(address spender, uint tokens) public returns (bool success); - - /** - * Transfer securities. - * - * transferFrom must implement the onlyIssuerTransferAgent modifier to only allow the - * address of the issuer’s Registered Transfer Agent to transfer `ERC-1450`s. - * transferFrom requires the _from address to have _value tokens. - * transferFrom requires that the _to address must not be 0 because securities must - * not destroyed in this manner. - */ - function transferFrom(address _from, address _to, uint256 _value) public - onlyIssuerTransferAgent returns (bool); - - /** - * Create new securities. - * - * mint must implement the onlyIssuerTransferAgent modifier to only allow the address - * of the issuer’s Registered Transfer Agent to mint `ERC-1450` tokens. - * mint requires that the _to address must not be 0 because securities must - * not destroyed in this manner. - * mint must add _value tokens to the _to address and increase the totalSupply by - * _value. - * mint must emit the Transfer event. - */ - function mint(address _to, uint256 _value) public onlyIssuerTransferAgent returns - (bool); - - /** - * Burn or destroy securities. - * - * burnFrom must implement the onlyIssuerTransferAgent modifier to only allow the - * address of the issuer’s Registered Transfer Agent to burn `ERC-1450`s. - * burnFrom requires the _from address to have _value tokens. - * burnFrom must subtract _value tokens from the _from address and decrease the - * totalSupply by _value. - * burnFrom must emit the Transfer event. - */ - function burnFrom(address _who, uint256 _value) public onlyIssuerTransferAgent returns - (bool); -} -``` - -### Securities Exchange Commission Requirements -The SEC has very strict requirements as to the specific roles that are allowed to perform specific actions. Specifically, only the RTA may `mint` and `transferFrom` securities. - -Implementers must maintain off-chain services and databases that record and track the Investor’s name, physical address, Ethereum address, and security ownership amount. The implementers and the SEC must be able to access the Investor’s private information on an as needed basis. Issuers and the RTA must be able to produce a current list of all Investors, including the names, addresses, and security ownership levels for every security at any given moment. Issuers and the RTA must be able to re-issue securities to Investors for a variety of regulated reasons. - -Private Investor information must never be publicly exposed on a public blockchain. - -### Managing Investor Information -Special care and attention must be taken to ensure that the personally identifiable information of Investors is never exposed or revealed to the public. - -### Issuers who lost access to their address or private keys -There is no recourse if the Issuer loses access to their address to an existing instance of their securities. Special care and efforts must be made by the Issuer to secure and safely store their address and associated private key. The Issuer can reassign ownership to another Issuer but not in the case where the Issuer loses their private key. - -If the Issuer loses access, the Issuer’s securities must be rebuilt using off-chain services. The Issuer must create (and secure) a new address. The RTA can read the existing Issuer securities, and the RTA can `mint` Investor securities accordingly under a new `ERC-1450` smart contract. - -### Registered Transfer Agents who lost access to their address or private keys -If the RTA loses access, the RTA can create a new Ethereum address, and the Issuer can execute the `setTransferAgent` function to reassign the RTA. - -### Handling Investors (security owners) who lost access to their addresses or private keys -Investors may “lose” their credentials for a number of reasons: they simply “lost” their credentials, they were hacked or the victim of fraud, they committed securities-related fraud, or a life event (like death) occurred. Because the RTA manages the Issuer’s securities, the RTA may authorize ownership related changes of securities (as long as they are properly notarized and verified). - -If an Investor (or, say, the Investor’s heir) loses their credentials, the Investor must go through a notarized process to notify the RTA of the situation and supply a new Investor address. From there, the RTA can `mint` the “lost” securities to the new Investor address and `burnFrom` the old Investor address (because the RTA knows all Investors’ addresses). - -## Rationale -The are currently no token standards that facilitate compliance with SEC regulations. The closest token is [ERC-884 (Delaware General Corporations Law (DGCL) compatible share token)](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-884.md) which states that SEC requirements are out of scope. [EIP-1404 (Simple Restricted Token Standard)](https://github.com/ethereum/EIPs/issues/1404) does not go far enough to address SEC requirements around re-issuing securities to Investors. - -## Backwards Compatibility -`ERC-1450` maintains compatibility with ERC-20 tokens with the following stipulations: -* `function allowance(address tokenOwner, address spender) public constant returns (uint remaining);` - * Must be implemented to always fail because allowance is not a legal, regulated call for a security. -* `function transfer(address to, uint tokens) public returns (bool success);` - * As the token holder initiates the transfer, must be implemented to always fail because transfer is not a legal, regulated call for a security. -* `function approve(address spender, uint tokens) public returns (bool success);` - * Must be implemented to always fail because approve is not a legal, regulated call for a security -* `function transferFrom(address from, address to, uint tokens) public returns (bool success);` - * Must be implemented so that only the Issuer’s RTA can perform this action -* `event Approval(address indexed tokenOwner, address indexed spender, uint tokens);` - * Does not have to be implemented. Approval should never be called as the functions that emit this event must be implemented to always fail - -## Test Cases -Test cases are available at [https://github.com/StartEngine/ldgr_smart_contracts/tree/master/test](https://github.com/StartEngine/ldgr_smart_contracts/tree/master/test). - -## Implementations -A reference implementation is available at [https://github.com/StartEngine/ldgr_smart_contracts](https://github.com/StartEngine/ldgr_smart_contracts). - -## Copyright Waiver -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1450.md diff --git a/EIPS/eip-1459.md b/EIPS/eip-1459.md index 4c05b41fab20c7..dc84e58c8e8c17 100644 --- a/EIPS/eip-1459.md +++ b/EIPS/eip-1459.md @@ -1,21 +1,22 @@ --- eip: 1459 title: Node Discovery via DNS -author: Felix Lange , Péter Szilágyi +description: Scheme for authenticated updateable Ethereum node lists via DNS. +author: Felix Lange (@fjl), Péter Szilágyi (@karalabe) +discussions-to: https://github.com/ethereum/devp2p/issues/50 +status: Stagnant type: Standards Track category: Networking -status: Draft created: 2018-09-26 requires: 778 -discussions-to: https://github.com/ethereum/devp2p/issues/50 --- -# Abstract +## Abstract -This document describes a scheme for authenticated, updateable Ethereum node lists -retrievable via DNS. +This document describes a scheme for authenticated, updateable Ethereum node +lists retrievable via DNS. -# Motivation +## Motivation Many Ethereum clients contain hard-coded bootstrap node lists. Updating those lists requires a software update. The current lists are small, giving the client @@ -24,88 +25,105 @@ maintain larger node lists containing hundreds of nodes, and update them regularly. The scheme described here is a replacement for client bootstrap node lists with -equivalent security and many additional benefits. DNS node lists may also be -useful to Ethereum peering providers because their customers can configure the -client to use the provider's list. Finally, the scheme serves as a fallback -option for nodes which can't join the node discovery DHT. +equivalent security and many additional benefits. Large lists populated by +traversing the node discovery DHT can serve as a fallback option for nodes which +can't join the DHT due to restrictive network policy. DNS-based node lists may +also be useful to Ethereum peering providers because their customers can +configure the client to use the provider's list. + +## Specification + +A 'node list' is a list of 'node records' [as defined by EIP-778](./eip-778.md) +of arbitrary length. Lists +may refer to other lists using links. The entire list is signed using a +secp256k1 private key. The corresponding public key must be known to the client +in order to verify the list. + +To refer to a DNS node list, clients use a URL with 'enrtree' scheme. The URL +contains the DNS name on which the list can be found as well as the public key +that signed the list. The public key is contained in the username part of the +URL and is the base32 encoding (RFC-4648) of the compressed 32-byte binary public key. + +Example: + + enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@nodes.example.org -# Specification +This URL refers to a node list at the DNS name 'nodes.example.org' and is signed +by the public key +`0x049f88229042fef9200246f49f94d9b77c4e954721442714e85850cb6d9e5daf2d880ea0e53cb3ac1a75f9923c2726a4f941f7d326781baa6380754a360de5c2b6` ### DNS Record Structure -Node lists are encoded as TXT records. The records form a merkle tree. The root -of the tree is a record with content: +The nodes in a list are encoded as a merkle tree for distribution via the DNS +protocol. Entries of the merkle tree are contained in DNS TXT records. The root +of the tree is a TXT record with the following content: - enrtree-root=v1 hash= seq= sig= + enrtree-root:v1 e= l= seq= sig= -`roothash` is the abbreviated root hash of the tree in base32 encoding. `seqnum` -is the tree's update sequence number, a decimal integer. `signature` is a -65-byte secp256k1 EC signature over the keccak256 hash of the record content, -encoded as URL-safe base64. +where -Further TXT records on subdomains map hashes to one of three entry types. The -subdomain name of any entry is the base32 encoding of the abbreviated keccak256 -hash of its text content. +- `enr-root` and `link-root` refer to the root hashes of subtrees containing + nodes and links subtrees. +- `sequence-number` is the tree's update sequence number, a decimal integer. +- `signature` is a 65-byte secp256k1 EC signature over the keccak256 hash of the + record content, excluding the `sig=` part, encoded as URL-safe base64 (RFC-4648). -- `enrtree=,,...,` is an intermediate tree containing further hash - subdomains. -- `enrtree-link=@` is a leaf pointing to a different list located at - another fully qualified domain name. The key is the expected signer of the - remote list, a base32 encoded secp256k1 public key, -- `enr=` is a leaf containing a node record [as defined in EIP-778][eip-778]. - The node record is encoded as a URL-safe base64 string. +Further TXT records on subdomains map hashes to one of three entry types. The +subdomain name of any entry is the base32 encoding of the (abbreviated) +keccak256 hash of its text content. + +- `enrtree-branch:,,...,` is an intermediate tree entry containing + hashes of subtree entries. +- `enrtree://@` is a leaf pointing to a different list located at + another fully qualified domain name. Note that this format matches the URL + encoding. This type of entry may only appear in the subtree pointed to by + `link-root`. +- `enr:` is a leaf containing a node record. The node record is + encoded as a URL-safe base64 string. Note that this type of entry matches the + canonical ENR text encoding. It may only appear in the `enr-root` subtree. No particular ordering or structure is defined for the tree. Whenever the tree is updated, its sequence number should increase. The content of any TXT record should be small enough to fit into the 512 byte limit imposed on UDP DNS -packets. This limits the number of hashes that can be placed into a `enrtree=` -entry. +packets. This limits the number of hashes that can be placed into an +`enrtree-branch` entry. Example in zone file format: -```text -; name ttl class type content -@ 60 IN TXT "enrtree-root=v1 hash=TO4Q75OQ2N7DX4EOOR7X66A6OM seq=3 sig=N-YY6UB9xD0hFx1Gmnt7v0RfSxch5tKyry2SRDoLx7B4GfPXagwLxQqyf7gAMvApFn_ORwZQekMWa_pXrcGCtwE=" -TO4Q75OQ2N7DX4EOOR7X66A6OM 86900 IN TXT "enrtree=F4YWVKW4N6B2DDZWFS4XCUQBHY,JTNOVTCP6XZUMXDRANXA6SWXTM,JGUFMSAGI7KZYB3P7IZW4S5Y3A" -F4YWVKW4N6B2DDZWFS4XCUQBHY 86900 IN TXT "enr=-H24QI0fqW39CMBZjJvV-EJZKyBYIoqvh69kfkF4X8DsJuXOZC6emn53SrrZD8P4v9Wp7NxgDYwtEUs3zQkxesaGc6UBgmlkgnY0gmlwhMsAcQGJc2VjcDI1NmsxoQPKY0yuDUmstAHYpMa2_oxVtw0RW_QAdpzBQA8yWM0xOA==" -JTNOVTCP6XZUMXDRANXA6SWXTM 86900 IN TXT "enr=-H24QDquAsLj8mCMzJh8ka2BhVFg3n4V9efBJBiaXHcoL31vRJJef-lAseMhuQBEVpM_8Zrin0ReuUXJE7Fs8jy9FtwBgmlkgnY0gmlwhMYzZGOJc2VjcDI1NmsxoQLtfC0F55K2s1egRhrc6wWX5dOYjqla-OuKCELP92O3kA==" -JGUFMSAGI7KZYB3P7IZW4S5Y3A 86900 IN TXT "enrtree-link=AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org" -``` - -### Referencing Trees by URL - -When referencing a record tree, e.g. in source code, the preferred form is a -URL. References should use the scheme `enrtree://` and encode the DNS domain in -the hostname. The expected public key that signs the tree should be encoded in -33-byte compressed form as a base32 string in the username portion of the URL. - -Example: - -```text -enrtree://AP62DT7WOTEQZGQZOU474PP3KMEGVTTE7A7NPRXKX3DUD57TQHGIA@nodes.example.org -``` + ; name ttl class type content + @ 60 IN TXT enrtree-root:v1 e=JWXYDBPXYWG6FX3GMDIBFA6CJ4 l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=1 sig=o908WmNp7LibOfPsr4btQwatZJ5URBr2ZAuxvK4UWHlsB9sUOTJQaGAlLPVAhM__XJesCHxLISo94z5Z2a463gA + C7HRFPF3BLGF3YR4DY5KX3SMBE 86900 IN TXT enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org + JWXYDBPXYWG6FX3GMDIBFA6CJ4 86900 IN TXT enrtree-branch:2XS2367YHAXJFGLZHVAWLQD4ZY,H4FHT4B454P6UXFD7JCYQ5PWDY,MHTDO6TMUBRIA2XWG5LUDACK24 + 2XS2367YHAXJFGLZHVAWLQD4ZY 86900 IN TXT enr:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA + H4FHT4B454P6UXFD7JCYQ5PWDY 86900 IN TXT enr:-HW4QAggRauloj2SDLtIHN1XBkvhFZ1vtf1raYQp9TBW2RD5EEawDzbtSmlXUfnaHcvwOizhVYLtr7e6vw7NAf6mTuoCgmlkgnY0iXNlY3AyNTZrMaECjrXI8TLNXU0f8cthpAMxEshUyQlK-AM0PW2wfrnacNI + MHTDO6TMUBRIA2XWG5LUDACK24 86900 IN TXT enr:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfhcGCvSElSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwdufn1S1o ### Client Protocol To find nodes at a given DNS name, say "mynodes.org": 1. Resolve the TXT record of the name and check whether it contains a valid - "enrtree-root=v1" entry. Let's say the root hash contained in the entry is - "CFZUWDU7JNQR4VTCZVOJZ5ROV4". -2. Optionally verify the signature on the root against a known public key and - check whether the sequence number is larger than or equal to any previous - number seen for that name. -3. Resolve the TXT record of the hash subdomain, e.g. "CFZUWDU7JNQR4VTCZVOJZ5ROV4.mynodes.org" - and verify whether the content matches the hash. + "enrtree-root=v1" entry. Let's say the `enr-root` hash contained in the entry + is "CFZUWDU7JNQR4VTCZVOJZ5ROV4". +2. Verify the signature on the root against the known public key and check + whether the sequence number is larger than or equal to any previous number + seen for that name. +3. Resolve the TXT record of the hash subdomain, e.g. + "CFZUWDU7JNQR4VTCZVOJZ5ROV4.mynodes.org" and verify whether the content + matches the hash. 4. The next step depends on the entry type found: - - for `enrtree`: parse the list of hashes and continue resolving those (step 3). - - for `enrtree-link`: continue traversal on the linked domain (step 1). + - for `enrtree-branch`: parse the list of hashes and continue resolving them (step 3). - for `enr`: decode, verify the node record and import it to local node storage. -During traversal, the client should track hashes and domains which are already -resolved to avoid going into an infinite loop. +During traversal, the client must track hashes and domains which are already +resolved to avoid going into an infinite loop. It's in the client's best +interest to traverse the tree in random order. + +Client implementations should avoid downloading the entire tree at once during +normal operation. It's much better to request entries via DNS when-needed, i.e. +at the time when the client is looking for peers. -# Rationale +## Rationale ### Why DNS? @@ -131,20 +149,24 @@ basic UDP DNS is available. The tree format also works well with caching resolvers: only the root of the tree needs a short TTL. Intermediate entries and leaves can be cached for days. -### Why does `enrtree-link` exist? +### Why does the link subtree exist? Links between lists enable federation and web-of-trust functionality. The operator of a large list can delegate maintenance to other list providers. If two node lists link to each other, users can use either list and get nodes from both. -# References +The link subtree is separate from the tree containing ENRs. This is done to +enable client implementations to sync these trees independently. A client +wanting to get as many nodes as possible will sync the link tree first and add +all linked names to the sync horizon. -1. The base64 and base32 encodings used to represent binary data are defined in - RFC 4648 (https://tools.ietf.org/html/rfc4648). No padding is used for base32. +## Security Considerations -[eip-778]: https://eips.ethereum.org/EIPS/eip-778 +Discovery via DNS is less secure than via DHT, because it relies on a trusted +party to publish the records regularly. The actor could easily eclipse +bootstrapping nodes by only publishing node records that it controls. -# Copyright +## Copyright -Copyright and related rights waived via CC0. +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1462.md b/EIPS/eip-1462.md index 59713317ba9d98..9f12e73031aa79 100644 --- a/EIPS/eip-1462.md +++ b/EIPS/eip-1462.md @@ -1,117 +1,7 @@ --- eip: 1462 -title: Base Security Token -author: Maxim Kupriianov , Julian Svirsky -discussions-to: https://ethereum-magicians.org/t/erc-1462-base-security-token/1501 -status: Draft -type: Standards Track category: ERC -created: 2018-10-01 -requires: 20, 1066 +status: Moved --- -## Simple Summary - -An extension to ERC-20 standard token that provides compliance with securities regulations and legal enforceability. - -## Abstract - -This EIP defines a minimal set of additions to the default token standard such as [ERC-20](https://eips.ethereum.org/EIPS/eip-20), that allows for compliance with domestic and international legal requirements. Such requirements include KYC (Know Your Customer) and AML (Anti Money Laundering) regulations, and the ability to lock tokens for an account, and restrict them from transfer due to a legal dispute. Also the ability to attach additional legal documentation, in order to set up a dual-binding relationship between the token and off-chain legal entities. - -The scope of this standard is being kept as narrow as possible to avoid restricting potential use-cases of this base security token. Any additional functionality and limitations not defined in this standard may be enforced on per-project basis. - -## Motivation - -There are several security token standards that have been proposed recently. Examples include [ERC-1400/ERC-1411](https://github.com/ethereum/EIPs/issues/1411), also [ERC-1450](https://github.com/ethereum/EIPs/issues/1450). We have concerns about each of them, mostly because the scope of each of these EIPs contains many project-specific or market-specific details. Since many EIPs are coming from the respective backing companies, they capture many niche requirements that are excessive for a general case. - -For instance, ERC-1411 uses dependency on [ERC-1410](https://github.com/ethereum/eips/issues/1410) but it falls out of the "security tokens" scope. Also its dependency on [ERC-777](https://github.com/ethereum/eips/issues/777]) will block the adoption for a quite period of time before ERC-777 is finalized, but the integration guidelines for existing ERC-20 workflows are not described in that EIP, yet. Another attempt to make a much simpler base standard [ERC-1404](https://github.com/ethereum/EIPs/issues/1404) is missing a few important points, specifically it doesn't provide enough granularity to distinguish between different ERC-20 transfer functions such as `transfer` and `transferFrom`. It also doesn't provide a way to bind legal documentation to the issued tokens. - -What we propose in this EIP is a simple and very modular solution for creating a base security token for the widest possible scope of applications, so it can be used by other issuers to build upon. The issuers should be able to add more restrictions and policies to the token, using the functions and implementation proposed below, but they must not be limited in any way while using this ERC. - -## Specification - -The ERC-20 token provides the following basic features: - -```solidity -contract ERC20 { - function totalSupply() public view returns (uint256); - function balanceOf(address who) public view returns (uint256); - function transfer(address to, uint256 value) public returns (bool); - function allowance(address owner, address spender) public view returns (uint256); - function transferFrom(address from, address to, uint256 value) public returns (bool); - function approve(address spender, uint256 value) public returns (bool); - event Approval(address indexed owner, address indexed spender, uint256 value); - event Transfer(address indexed from, address indexed to, uint256 value); -} -``` - -This will be extended as follows: - -```solidity -interface BaseSecurityToken /* is ERC-20 */ { - // Checking functions - function checkTransferAllowed (address from, address to, uint256 value) public view returns (byte); - function checkTransferFromAllowed (address from, address to, uint256 value) public view returns (byte); - function checkMintAllowed (address to, uint256 value) public view returns (byte); - function checkBurnAllowed (address from, uint256 value) public view returns (byte); - - // Documentation functions - function attachDocument(bytes32 _name, string _uri, bytes32 _contentHash) external; - function lookupDocument(bytes32 _name) external view returns (string, bytes32); -} -``` - -### Transfer Checking Functions - -We introduce four new functions that should be used to check that the actions are allowed for the provided inputs. The implementation details of each function are left for the token issuer, it is the issuer's responsibility to add all necessary checks that will validate an operation in accordance with KYC/AML policies and legal requirements set for a specific token asset. - -Each function must return a status code from the common set of Ethereum status codes (ESC), according to [ERC-1066](https://eips.ethereum.org/EIPS/eip-1066). Localization of these codes is out of the scope of this proposal and may be optionally solved by adopting [ERC-1444](https://github.com/ethereum/EIPs/pull/1444) on the application level. If the operation is allowed by a checking function, the return status code must be `0x11` (Allowed) or an issuer-specific code with equivalent but more precise meaning. If the operation is not allowed by a checking function, the status must be `0x10` (Disallowed) or an issuer-specific code with equivalent but more precise meaning. Upon an internal error, the function must return the most relevant code from the general code table or an issuer-specific equivalent, example: `0xF0` (Off-Chain Failure). - -**For [ERC-20](https://eips.ethereum.org/EIPS/eip-20) based tokens,** -* It is required that transfer function must be overridden with logic that checks the corresponding checkTransferAllowed return status code. -* It is required that `transferFrom` function must be overridden with logic that checks the corresponding `checkTransferFromAllowed` return status code. -* It is required that `approve` function must be overridden with logic that checks the corresponding `checkTransferFromAllowed` return status code. -* Other functions such as `mint` and `burn` must be overridden, if they exist in the token implementation, they should check `checkMintAllowed` and `checkBurnAllowed` status codes accordingly. - -**For [ERC-777](https://eips.ethereum.org/EIPS/eip-777) based tokens,** -* It is required that `send` function must be overridden with logic that checks the corresponding return status codes: - - `checkTransferAllowed` return status code, if transfer happens on behalf of the tokens owner; - - `checkTransferFromAllowed` return status code, if transfer happens on behalf of an operator (i.e. delegated transfer). -* It is required that `burn` function must be overridden with logic that checks the corresponding `checkBurnAllowed` return status code. -* Other functions, such as `mint` must be overridden, if they exist in the token implementation, e.g. if the security token is mintable. `mint` function must call `checkMintAllowed` ad check it return status code. - -For both cases, - -* It is required for guaranteed compatibility with ERC-20 and ERC-777 wallets that each checking function returns `0x11` (Allowed) if not overridden with the issuer's custom logic. -* It is required that all overridden checking functions must revert if the action is not allowed or an error occurred, according to the returned status code. - -Inside checker functions the logic is allowed to use any feature available on-chain: perform calls to registry contracts with whitelists/blacklists, use built-in checking logic that is defined on the same contract, or even run off-chain queries through an oracle. - -### Documentation Functions - -We also introduce two new functions that should be used for document management purposes. Function `attachDocument` adds a reference pointing to an off-chain document, with specified name, URI and contents hash. The hashing algorithm is not specified within this standard, but the resulting hash must not be longer than 32 bytes. Function `lookupDocument` gets the referenced document by its name. - -* It is not required to use documentation functions, they are optional and provided as a part of a legal framework. -* It is required that if `attachDocument` function has been used, the document reference must have a unique name, overwriting the references under same name is not allowed. All implementations must check if the reference under the given name is already existing. - -## Rationale - -This EIP targets both ERC-20 and ERC-777 based tokens, although the most emphasis is given to ERC-20 due to its widespread adoption. However, this extension is designed to be compatible with the forthcoming ERC-777 standard, as well. - -All checking functions are named with prefixes `check` since they return check status code, not booleans, because that is important to facilitate the debugging and tracing process. It is responsibility of the issuer to implement the logic that will handle the return codes appropriately. Some handlers will simply throw errors, other handlers would log information for future process mining. More rationale for status codes can be seen in [ERC-1066](https://eips.ethereum.org/EIPS/eip-1066). - -We require two different transfer validation functions: `checkTransferAllowed` and `checkTransferFromAllowed` since the corresponding `transfer` and `transferFrom` are usually called in different contexts. Some token standards such as [ERC-1450](https://github.com/ethereum/EIPs/issues/1450) explicitly disallow use of `transfer`, while allowing only `transferFrom`. There might be also different complex scenarios, where `transfer` and `transferFrom` should be treated differently. ERC-777 is relying on its own `send` for transferring tokens, so it is reasonable to switch between checker functions based on its call context. We decided to omit the `checkApprove` function since it would be used in exactly the same context as `checkTransferFromAllowed`. In many cases it is required not only regulate securities transfers, but also restrict burn and `mint` operations, and additional checker functions have been added for that. - -The documentation functions that we propose here are a must-have tool to create dual-bindings with off-chain legal documents, a great example of this can be seen in [Neufund's Employee Incentive Options Plan](https://medium.com/@ZoeAdamovicz/37376fd0384a) legal framework that implements full legal enforceability: the smart contract refers to printed ESOP Terms & Conditions Document, which itself refers back to smart contract. This is becoming a widely adopted practice even in cases where there are no legal requirements to reference the documents within the security token. However they're almost always required, and it's a good way to attach useful documentation of various types. - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of ERC-20 and ERC-777 tokens. - -## Implementation - -* https://github.com/AtlantPlatform/BaseSecurityToken - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1462.md diff --git a/EIPS/eip-1470.md b/EIPS/eip-1470.md index d6f9dffc24f455..2436f43e3cf419 100644 --- a/EIPS/eip-1470.md +++ b/EIPS/eip-1470.md @@ -1,21 +1,18 @@ --- eip: 1470 title: Smart Contract Weakness Classification (SWC) -author: Gerhard Wagner (@thec00n) +author: Gerhard Wagner (@thec00n) discussions-to: https://github.com/ethereum/EIPs/issues/1469 -status: Draft +status: Stagnant type: Informational created: 2018-09-18 --- - - ## Simple Summary This EIP proposes a classification scheme for security weaknesses in Ethereum smart contracts. ## Abstract - The SWC is a smart contract specific software weakness classification scheme for developers, tool vendors and security practitioners. The SWC is loosely aligned to the terminologies and structure used in the [Common Weakness Enumeration - CWE](https://cwe.mitre.org) scheme while overlaying a wide range of weakness variants that are specific to smart contracts. @@ -28,7 +25,6 @@ The goals of the SWC scheme are as follows: ## Motivation - In the software security industry, it is a widely accepted practice to use a common terminology and to classify security related bugs and errors with a standardized scheme. While this has not stopped vulnerabilities from appearing in software, it has helped communities focusing on web applications, network protocols, IOT devices and various other fields to educate users and developers to understand the nature of security related issues in their software. It has also allowed the security community to quickly understand vulnerabilities that occur in production systems to perform root cause analysis or triage findings from various security analysis sources. In recent years various organizations and companies also published vulnerability data to find the most widespread security issues based on collected vulnerability data. Two examples that are widely used and referred to are the [SANS TOP 25 Most Dangerous Software Errors](https://www.sans.org/top25-software-errors) and the [OWASP TOP 10](https://www.owasp.org/index.php/Top_10-2017_Top_10). None of those publications would have been possible without a common classification scheme. @@ -39,13 +35,12 @@ At present no such weakness classification scheme exists for weaknesses specific While recognizing the current gap, the SWC does not aim to reinvent the wheel in regards to classification of security weaknesses. It rather proposes to build on top of what has worked well in other parts of the software security community - specifically the Common Weakness Enumeration (CWE), a list of software vulnerability types that stands out in terms of adoption and breadth of coverage. While CWE does not describe any weaknesses specific to smart contracts, it does describe related weaknesses at higher abstraction layers. This EIP proposes to create smart contract specific variants while linking back to the larger spectrum of software errors and mistakes listed in the CWE that different platforms and technologies have in common. ## Specification - Before discussing the SWC specification it is important to describe the terminology used: - Weakness: A software error or mistake that in the right conditions can by itself or coupled with other weaknesses lead to a vulnerability. - Vulnerability: A weakness or multiple weaknesses which directly or indirectly lead to an undesirable state in a smart contract system. -- Variant: A specific weakness that is described in a very low detail specific to Ethereum smart contracts. Each variant is assigned an unique SWC ID. +- Variant: A specific weakness that is described in a very low detail specific to Ethereum smart contracts. Each variant is assigned a unique SWC ID. - Relationships: CWE has a wide range of _Base_ and _Class_ types that group weaknesses on higher abstraction layers. The CWE uses _Relationships_ to link SWC smart contract weakness variants to existing _Base_ or _Class_ CWE types. _Relationships_ are used to provide context on how SWCs are linked to the wider group of software security weaknesses and to be able to generate useful visualisations and insights through issue data sets. In its current revision it is proposed to link a SWC to its closest parent in the CWE. - SWC ID: A numeric identifier linked to a variant (e.g. SWC-101). - Test Case: A test case constitutes a micro-sample or real-world smart contract that demonstrates concrete instances of one or multiple SWC variants. Test cases serve as the basis for meaningful weakness classification and are useful to security analysis tool developers. @@ -102,9 +97,8 @@ properties: ``` ## Implementation - -The Smart Contract Weakness Classification registry located in this [Github repository](https://github.com/SmartContractSecurity/SWC-registry) uses the SWC scheme proposed in this EIP. A Github Pages rendered version is also available [here](https://smartcontractsecurity.github.io/SWC-registry/). +The Smart Contract Weakness Classification registry located in this [GitHub repository](https://github.com/SmartContractSecurity/SWC-registry) uses the SWC scheme proposed in this EIP. A GitHub Pages rendered version is also available [here](https://smartcontractsecurity.github.io/SWC-registry/). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1474.md b/EIPS/eip-1474.md index 8eefc1bf5d0f12..9a1aa362800a0f 100644 --- a/EIPS/eip-1474.md +++ b/EIPS/eip-1474.md @@ -1,9 +1,9 @@ --- eip: 1474 title: Remote procedure call specification -author: Paul Bouchon +author: Paul Bouchon , Erik Marks (@rekmarks) discussions-to: https://ethereum-magicians.org/t/eip-remote-procedure-call-specification/1537 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2018-10-02 @@ -45,6 +45,8 @@ If an Ethereum RPC method encounters an error, the `error` member included on th |-32002|Resource unavailable|Requested resource not available|non-standard| |-32003|Transaction rejected|Transaction creation failed|non-standard| |-32004|Method not supported|Method is not implemented|non-standard| +|-32005|Limit exceeded|Request exceeds defined limit|non-standard| +|-32006|JSON-RPC version not supported|Version of JSON-RPC protocol is not supported|non-standard| Example error response: @@ -82,6 +84,25 @@ Examples `Quantity` values: |0x0400|`invalid`|leading zeroes not allowed| |ff|`invalid`|values must be prefixed| +##### `Block Identifier` + +The RPC methods below take a default block identifier as a parameter. +- `eth_getBalance` +- `eth_getStorageAt` +- `eth_getTransactionCount` +- `eth_getCode` +- `eth_call` +- `eth_getProof` + +Since there is no way to clearly distinguish between a `Data` parameter and a `Quantity` parameter, [EIP-1898](./eip-1898.md) provides a format to specify a block either using the block hash or block number. The block identifier is a JSON `object` with the following fields: + +|Property|Type|Description| +|-|-|-| +|`[blockNumber]`|{[`Quantity`](#quantity)}|The block in the canonical chain with this number| +|OR `[blockHash]`|{[`Data`](#data)}|The block uniquely identified by this hash. The `blockNumber` and `blockHash` properties are mutually exclusive; exactly one of them must be set.| +|`requireCanonical`|{`boolean`}|(optional) Whether or not to throw an error if the block is not in the canonical chain as described below. Only allowed in conjunction with the `blockHash` tag. Defaults to `false`.| + +If the block is not found, the callee SHOULD raise a JSON-RPC error (the recommended error code is `-32001: Resource not found`. If the tag is `blockHash` and `requireCanonical` is `true`, the callee SHOULD additionally raise a JSON-RPC error if the block is not in the canonical chain (the recommended error code is `-32000: Invalid input` and in any case should be different than the error code for the block not found case so that the caller can distinguish the cases). The block-not-found check SHOULD take precedence over the block-is-canonical check, so that if the block is not found the callee raises block-not-found rather than block-not-canonical. ##### `Data` @@ -107,22 +128,21 @@ New Ethereum RPC methods and changes to existing methods **MUST** be proposed vi ### Methods -
-web3_clientVersion +#### web3_clientVersion -#### Description +##### Description Returns the version of the current client -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {`string`} - client version -#### Example +##### Example ```sh # Request @@ -141,26 +161,24 @@ curl -X POST --data '{ } ``` --- -
-
-web3_sha3 +#### web3_sha3 -#### Description +##### Description Hashes data using the Keccak-256 algorithm -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|data to hash| -#### Returns +##### Returns {[`Data`](#data)} - Keccak-256 hash of the given data -#### Example +##### Example ```sh # Request @@ -179,24 +197,22 @@ curl -X POST --data '{ } ``` --- -
-
-net_listening +#### net_listening -#### Description +##### Description Determines if this client is listening for new network connections -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {`boolean`} - `true` if listening is active or `false` if listening is not active -#### Example +##### Example ```sh # Request @@ -215,24 +231,22 @@ curl -X POST --data '{ } ``` --- -
-
-net_peerCount +#### net_peerCount -#### Description +##### Description Returns the number of peers currently connected to this client -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of connected peers -#### Example +##### Example ```sh # Request curl -X POST --data '{ @@ -250,20 +264,18 @@ curl -X POST --data '{ } ``` --- -
-
-net_version +#### net_version -#### Description +##### Description Returns the chain ID associated with the current network -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {`string`} - chain ID associated with the current network @@ -274,17 +286,17 @@ Common chain IDs: - `"4"` - Rinkeby testnet - `"42"` - Kovan testnet -**Note:** See EIP-155 for a [complete list](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md#list-of-chain-ids) of possible chain IDs. +**Note:** See EIP-155 for a [complete list](./eip-155.md#list-of-chain-ids) of possible chain IDs. -#### Example +##### Example ```sh # Request curl -X POST --data '{ - "id": 1337 + "id": 1337, "jsonrpc": "2.0", "method": "net_version", - "params": [], + "params": [] }' # Response @@ -295,24 +307,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_accounts +#### eth_accounts -#### Description +##### Description Returns a list of addresses owned by this client -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {[`Data[]`](#data)} - array of addresses -#### Example +##### Example ```sh # Request @@ -331,24 +341,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_blockNumber +#### eth_blockNumber -#### Description +##### Description Returns the number of the most recent block seen by this client -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of the latest block -#### Example +##### Example ```sh # Request @@ -367,27 +375,25 @@ curl -X POST --data '{ } ``` --- -
-
-eth_call +#### eth_call -#### Description +##### Description Executes a new message call immediately without submitting a transaction to the network -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{`object`}|@property {[`Data`](#data)} `[from]` - transaction sender
@property {[`Data`](#data)} `to` - transaction recipient or `null` if deploying a contract
@property {[`Quantity`](#quantity)} `[gas]` - gas provided for transaction execution
@property {[`Quantity`](#quantity)} `[gasPrice]` - price in wei of each gas used
@property {[`Quantity`](#quantity)} `[value]` - value in wei sent with this transaction
@property {[`Data`](#data)} `[data]` - contract code or a hashed method call with encoded args| -|2|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| +|2|{[`Quantity`](#quantity)\|`string`\|[`Block Identifier`](#block-identifier)}|block number, or one of `"latest"`, `"earliest"` or `"pending"`, or a block identifier as described in [`Block Identifier`](#block-identifier)| -#### Returns +##### Returns {[`Data`](#data)} - return value of executed contract -#### Example +##### Example ```sh # Request @@ -413,24 +419,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_coinbase +#### eth_coinbase -#### Description +##### Description Returns the coinbase address for this client -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {[`Data`](#data)} - coinbase address -#### Example +##### Example ```sh # Request @@ -449,29 +453,27 @@ curl -X POST --data '{ } ``` --- -
-
-eth_estimateGas +#### eth_estimateGas -#### Description +##### Description Estimates the gas necessary to complete a transaction without submitting it to the network **Note:** The resulting gas estimation may be significantly more than the amount of gas actually used by the transaction. This is due to a variety of reasons including EVM mechanics and node performance. -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{`object`}|@property {[`Data`](#data)} `[from]` - transaction sender
@property {[`Data`](#data)} `[to]` - transaction recipient
@property {[`Quantity`](#quantity)} `[gas]` - gas provided for transaction execution
@property {[`Quantity`](#quantity)} `[gasPrice]` - price in wei of each gas used
@property {[`Quantity`](#quantity)} `[value]` - value in wei sent with this transaction
@property {[`Data`](#data)} `[data]` - contract code or a hashed method call with encoded args| |2|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| -#### Returns +##### Returns {[`Quantity`](#quantity)} - amount of gas required by transaction -#### Example +##### Example ```sh # Request @@ -497,24 +499,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_gasPrice +#### eth_gasPrice -#### Description +##### Description Returns the current price of gas expressed in wei -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {[`Quantity`](#quantity)} - current gas price in wei -#### Example +##### Example ```sh # Request @@ -533,27 +533,25 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getBalance +#### eth_getBalance -#### Description +##### Description Returns the balance of an address in wei -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|address to query for balance| -|2|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| +|2|{[`Quantity`](#quantity)\|`string`\|[`Block Identifier`](#block-identifier)}|block number, or one of `"latest"`, `"earliest"` or `"pending"`, or a block identifier as described in [`Block Identifier`](#block-identifier)| -#### Returns +##### Returns {[`Quantity`](#quantity)} - balance of the provided account in wei -#### Example +##### Example ```sh # Request @@ -572,23 +570,21 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getBlockByHash +#### eth_getBlockByHash -#### Description +##### Description Returns information about a block specified by hash -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash of a block| |2|{`boolean`}|`true` will pull full transaction objects, `false` will pull transaction hashes| -#### Returns +##### Returns {`null|object`} - `null` if no block is found, otherwise a block object with the following members: @@ -598,7 +594,7 @@ Returns information about a block specified by hash - {[`Data`](#data)} `miner` - address that received this block's mining rewards - {[`Data`](#data)} `nonce` - proof-of-work hash or `null` if pending - {[`Data`](#data)} `parentHash` - parent block hash -- {[`Data`](#data)} `receiptsRoot` -root of the this block's receipts trie +- {[`Data`](#data)} `receiptsRoot` -root of this block's receipts trie - {[`Data`](#data)} `sha3Uncles` - SHA3 of the uncles data in this block - {[`Data`](#data)} `stateRoot` - root of this block's final state trie - {[`Data`](#data)} `transactionsRoot` - root of this block's transaction trie @@ -612,7 +608,7 @@ Returns information about a block specified by hash - {`Array`} `transactions` - list of transaction objects or hashes - {`Array`} `uncles` - list of uncle hashes -#### Example +##### Example ```sh # Request @@ -643,30 +639,28 @@ curl -X POST --data '{ "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", "timestamp": "0x54e34e8e" "totalDifficulty": "0x027f07", - "transactions": [] + "transactions": [] "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "uncles": ["0x1606e5...", "0xd5145a9..."] } } ``` --- -
-
-eth_getBlockByNumber +#### eth_getBlockByNumber -#### Description +##### Description Returns information about a block specified by number -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| |2|{`boolean`}|`true` will pull full transaction objects, `false` will pull transaction hashes| -#### Returns +##### Returns {`null|object`} - `null` if no block is found, otherwise a block object with the following members: @@ -676,7 +670,7 @@ Returns information about a block specified by number - {[`Data`](#data)} `miner` - address that received this block's mining rewards - {[`Data`](#data)} `nonce` - proof-of-work hash or `null` if pending - {[`Data`](#data)} `parentHash` - parent block hash -- {[`Data`](#data)} `receiptsRoot` -root of the this block's receipts trie +- {[`Data`](#data)} `receiptsRoot` -root of this block's receipts trie - {[`Data`](#data)} `sha3Uncles` - SHA3 of the uncles data in this block - {[`Data`](#data)} `stateRoot` - root of this block's final state trie - {[`Data`](#data)} `transactionsRoot` - root of this block's transaction trie @@ -690,7 +684,7 @@ Returns information about a block specified by number - {`Array`} `transactions` - list of transaction objects or hashes - {`Array`} `uncles` - list of uncle hashes -#### Example +##### Example ```sh # Request @@ -721,33 +715,31 @@ curl -X POST --data '{ "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", "timestamp": "0x54e34e8e" "totalDifficulty": "0x027f07", - "transactions": [] + "transactions": [] "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "uncles": ["0x1606e5...", "0xd5145a9..."] } } ``` --- -
-
-eth_getBlockTransactionCountByHash +#### eth_getBlockTransactionCountByHash -#### Description +##### Description Returns the number of transactions in a block specified by block hash -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash of a block| -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of transactions in the specified block -#### Example +##### Example ```sh # Request @@ -766,26 +758,24 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getBlockTransactionCountByNumber +#### eth_getBlockTransactionCountByNumber -#### Description +##### Description Returns the number of transactions in a block specified by block number -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of transactions in the specified block -#### Example +##### Example ```sh # Request @@ -804,27 +794,25 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getCode +#### eth_getCode -#### Description +##### Description Returns the contract code stored at a given address -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|address to query for code| -|2|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| +|2|{[`Quantity`](#quantity)\|`string`\|[`Block Identifier`](#block-identifier)}|block number, or one of `"latest"`, `"earliest"` or `"pending"`, or a block identifier as described in [`Block Identifier`](#block-identifier)| -#### Returns +##### Returns {[`Data`](#data)} - code from the specified address -#### Example +##### Example ```sh # Request @@ -843,22 +831,20 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getFilterChanges +#### eth_getFilterChanges -#### Description +##### Description Returns a list of all logs based on filter ID since the last log retrieval -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)}|ID of the filter| -#### Returns +##### Returns {`Array`} - array of log objects with the following members: @@ -874,7 +860,7 @@ Returns a list of all logs based on filter ID since the last log retrieval **Note:** The return value of `eth_getFilterChanges` when retrieving logs from `eth_newBlockFilter` and `eth_newPendingTransactionFilter` filters will be an array of hashes, not an array of Log objects. -#### Example +##### Example ```sh # Request @@ -902,22 +888,20 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getFilterLogs +#### eth_getFilterLogs -#### Description +##### Description Returns a list of all logs based on filter ID -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)}|ID of the filter| -#### Returns +##### Returns {`Array`} - array of log objects with the following members: @@ -933,7 +917,7 @@ Returns a list of all logs based on filter ID **Note:** The return value of `eth_getFilterLogs` when retrieving logs from `eth_newBlockFilter` and `eth_newPendingTransactionFilter` filters will be an array of hashes, not an array of Log objects. -#### Example +##### Example ```sh # Request @@ -961,16 +945,14 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getLogs +#### eth_getLogs -#### Description +##### Description Returns a list of all logs based on a filter object -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| @@ -978,7 +960,7 @@ Returns a list of all logs based on a filter object **Note:** If `blockhash` is passed, neither `fromBlock` nor `toBlock` are allowed or respected. -#### Returns +##### Returns {`Array`} - array of log objects with the following members: @@ -992,9 +974,7 @@ Returns a list of all logs based on a filter object - {[`Data`](#data)} `topics` - list of order-dependent topics - {`boolean`} `removed` - `true` if this filter has been destroyed and is invalid -**Note:** The return value of `eth_getLogs` when retrieving logs from `eth_newBlockFilter` and `eth_newPendingTransactionFilter` filters will be an array of hashes, not an array of Log objects. - -#### Example +##### Example ```sh # Request @@ -1024,28 +1004,26 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getStorageAt +#### eth_getStorageAt -#### Description +##### Description Returns the value from a storage position at an address -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|address of stored data| |2|{[`Quantity`](#quantity)}|index into stored data| -|3|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| +|3|{[`Quantity`](#quantity)\|`string`\|[`Block Identifier`](#block-identifier)}|block number, or one of `"latest"`, `"earliest"` or `"pending"`, or a block identifier as described in [`Block Identifier`](#block-identifier)| -#### Returns +##### Returns {[`Data`](#data)} - value stored at the given address and data index -#### Example +##### Example ```sh # Request @@ -1064,23 +1042,21 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getTransactionByBlockHashAndIndex +#### eth_getTransactionByBlockHashAndIndex -#### Description +##### Description Returns information about a transaction specified by block hash and transaction index -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash of a block| |2|{[`Quantity`](#quantity)}|index of a transaction in the specified block| -#### Returns +##### Returns {`null|object`} - `null` if no transaction is found, otherwise a transaction object with the following members: @@ -1099,7 +1075,7 @@ Returns information about a transaction specified by block hash and transaction - {[`Quantity`](#quantity)} `transactionIndex` - index of this transaction in the block or `null` if pending - {[`Quantity`](#quantity)} `value` - value in wei sent with this transaction -#### Example +##### Example ```sh # Request @@ -1133,23 +1109,21 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getTransactionByBlockNumberAndIndex +#### eth_getTransactionByBlockNumberAndIndex -#### Description +##### Description Returns information about a transaction specified by block number and transaction index -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| |2|{[`Quantity`](#quantity)}|index of a transaction in the specified block| -#### Returns +##### Returns {`null|object`} - `null` if no transaction is found, otherwise a transaction object with the following members: @@ -1168,7 +1142,7 @@ Returns information about a transaction specified by block number and transactio - {[`Quantity`](#quantity)} `transactionIndex` - index of this transaction in the block or `null` if pending - {[`Quantity`](#quantity)} `value` - value in wei sent with this transaction -#### Example +##### Example ```sh # Request @@ -1202,22 +1176,20 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getTransactionByHash +#### eth_getTransactionByHash -#### Description +##### Description Returns information about a transaction specified by hash -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash of a transaction| -#### Returns +##### Returns {`null|object`} - `null` if no transaction is found, otherwise a transaction object with the following members: @@ -1236,7 +1208,7 @@ Returns information about a transaction specified by hash - {[`Quantity`](#quantity)} `transactionIndex` - index of this transaction in the block or `null` if pending - {[`Quantity`](#quantity)} `value` - value in wei sent with this transaction -#### Example +##### Example ```sh # Request @@ -1270,27 +1242,25 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getTransactionCount +#### eth_getTransactionCount -#### Description +##### Description Returns the number of transactions sent from an address -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|address to query for sent transactions| -|2|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| +|2|{[`Quantity`](#quantity)\|`string`\|[`Block Identifier`](#block-identifier)}|block number, or one of `"latest"`, `"earliest"` or `"pending"`, or a block identifier as described in [`Block Identifier`](#block-identifier)| -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of transactions sent from the specified address -#### Example +##### Example ```sh # Request @@ -1309,24 +1279,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getTransactionReceipt +#### eth_getTransactionReceipt -#### Description +##### Description Returns the receipt of a transaction specified by hash **Note:** Transaction receipts are unavailable for pending transactions. -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash of a transaction| -#### Returns +##### Returns {`null|object`} - `null` if no transaction is found, otherwise a transaction receipt object with the following members: @@ -1343,7 +1311,7 @@ Returns the receipt of a transaction specified by hash - {[`Quantity`](#quantity)} `transactionIndex` - index of this transaction in the block - {`Array`} `logs` - list of log objects generated by this transaction -#### Example +##### Example ```sh # Request @@ -1373,23 +1341,21 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getUncleByBlockHashAndIndex +#### eth_getUncleByBlockHashAndIndex -#### Description +##### Description Returns information about an uncle specified by block hash and uncle index position -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash of a block| |2|{[`Quantity`](#quantity)}|index of uncle| -#### Returns +##### Returns {`null|object`} - `null` if no block or uncle is found, otherwise an uncle object with the following members: @@ -1399,7 +1365,7 @@ Returns information about an uncle specified by block hash and uncle index posit - {[`Data`](#data)} `miner` - address that received this block's mining rewards - {[`Data`](#data)} `nonce` - proof-of-work hash or `null` if pending - {[`Data`](#data)} `parentHash` - parent block hash -- {[`Data`](#data)} `receiptsRoot` -root of the this block's receipts trie +- {[`Data`](#data)} `receiptsRoot` -root of this block's receipts trie - {[`Data`](#data)} `sha3Uncles` - SHA3 of the uncles data in this block - {[`Data`](#data)} `stateRoot` - root of this block's final state trie - {[`Data`](#data)} `transactionsRoot` - root of this block's transaction trie @@ -1412,7 +1378,7 @@ Returns information about an uncle specified by block hash and uncle index posit - {[`Quantity`](#quantity)} `totalDifficulty` - total difficulty of the chain until this block - {`Array`} `uncles` - list of uncle hashes -#### Example +##### Example ```sh # Request @@ -1428,37 +1394,42 @@ curl -X POST --data '{ "id": 1337, "jsonrpc": "2.0", "result": { - "blockHash": '0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b', - "blockNumber": '0xb', - "contractAddress": '0xb60e8dd61c5d32be8058bb8eb970870f07233155', - "cumulativeGasUsed": '0x33bc', - "gasUsed": '0x4dc', - "logs": [], - "logsBloom": "0x00...0", - "status": "0x1", - "transactionHash": '0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238', - "transactionIndex": '0x1' + "difficulty": "0x027f07", + "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", + "gasLimit": "0x9f759", + "gasUsed": "0x9f759", + "hash": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "logsBloom": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "miner": "0x4e65fda2159562a496f9f3522f89122a3088497a", + "nonce": "0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2", + "number": "0x1b4", + "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5", + "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": "0x027f07", + "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", + "timestamp": "0x54e34e8e" + "totalDifficulty": "0x027f07", + "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "uncles": [] } } ``` --- -
-
-eth_getUncleByBlockNumberAndIndex +#### eth_getUncleByBlockNumberAndIndex -#### Description +##### Description Returns information about an uncle specified by block number and uncle index position -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| |2|{[`Quantity`](#quantity)}|index of uncle| -#### Returns +##### Returns {`null|object`} - `null` if no block or uncle is found, otherwise an uncle object with the following members: @@ -1468,7 +1439,7 @@ Returns information about an uncle specified by block number and uncle index pos - {[`Data`](#data)} `miner` - address that received this block's mining rewards - {[`Data`](#data)} `nonce` - proof-of-work hash or `null` if pending - {[`Data`](#data)} `parentHash` - parent block hash -- {[`Data`](#data)} `receiptsRoot` -root of the this block's receipts trie +- {[`Data`](#data)} `receiptsRoot` -root of this block's receipts trie - {[`Data`](#data)} `sha3Uncles` - SHA3 of the uncles data in this block - {[`Data`](#data)} `stateRoot` - root of this block's final state trie - {[`Data`](#data)} `transactionsRoot` - root of this block's transaction trie @@ -1481,7 +1452,7 @@ Returns information about an uncle specified by block number and uncle index pos - {[`Quantity`](#quantity)} `totalDifficulty` - total difficulty of the chain until this block - {`Array`} `uncles` - list of uncle hashes -#### Example +##### Example ```sh # Request @@ -1497,40 +1468,45 @@ curl -X POST --data '{ "id": 1337, "jsonrpc": "2.0", "result": { - "blockHash": '0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b', - "blockNumber": '0xb', - "contractAddress": '0xb60e8dd61c5d32be8058bb8eb970870f07233155', - "cumulativeGasUsed": '0x33bc', - "gasUsed": '0x4dc', - "logs": [], - "logsBloom": "0x00...0", - "status": "0x1", - "transactionHash": '0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238', - "transactionIndex": '0x1' + "difficulty": "0x027f07", + "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", + "gasLimit": "0x9f759", + "gasUsed": "0x9f759", + "hash": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "logsBloom": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "miner": "0x4e65fda2159562a496f9f3522f89122a3088497a", + "nonce": "0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2", + "number": "0x1b4", + "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5", + "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": "0x027f07", + "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", + "timestamp": "0x54e34e8e" + "totalDifficulty": "0x027f07", + "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "uncles": [] } } ``` --- -
-
-eth_getUncleCountByBlockHash +#### eth_getUncleCountByBlockHash -#### Description +##### Description Returns the number of uncles in a block specified by block hash -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash of a block| -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of uncles in the specified block -#### Example +##### Example ```sh # Request @@ -1549,26 +1525,24 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getUncleCountByBlockNumber +#### eth_getUncleCountByBlockNumber -#### Description +##### Description Returns the number of uncles in a block specified by block number -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)\|`string`}|block number, or one of `"latest"`, `"earliest"` or `"pending"`| -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of uncles in the specified block -#### Example +##### Example ```sh # Request @@ -1587,20 +1561,18 @@ curl -X POST --data '{ } ``` --- -
-
-eth_getWork +#### eth_getWork -#### Description +##### Description Returns a list containing relevant information for proof-of-work -#### Parameters +##### Parameters _none_ -#### Returns +##### Returns {[`Data[]`](#data)} - array with the following items: @@ -1608,7 +1580,7 @@ _none_ 1. {[`Data`](#data)} - seed hash used for the DAG 1. {[`Data`](#data)} - boundary condition ("target"), 2^256 / difficulty -#### Example +##### Example ```sh # Request @@ -1631,24 +1603,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_hashrate +#### eth_hashrate -#### Description +##### Description Returns the number of hashes-per-second this node is mining at -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {[`Quantity`](#quantity)} - number of hashes-per-second -#### Example +##### Example ```sh # Request @@ -1667,24 +1637,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_mining +#### eth_mining -#### Description +##### Description Determines if this client is mining new blocks -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {`boolean`} - `true` if this client is mining or `false` if it is not mining -#### Example +##### Example ```sh # Request @@ -1703,24 +1671,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_newBlockFilter +#### eth_newBlockFilter -#### Description +##### Description Creates a filter to listen for new blocks that can be used with `eth_getFilterChanges` -#### Parameters +##### Parameters _none_ -#### Returns +##### Returns {[`Quantity`](#quantity)} - ID of the newly-created filter that can be used with `eth_getFilterChanges` -#### Example +##### Example ```sh # Request @@ -1739,16 +1705,14 @@ curl -X POST --data '{ } ``` --- -
-
-eth_newFilter +#### eth_newFilter -#### Description +##### Description Creates a filter to listen for specific state changes that can then be used with `eth_getFilterChanges` -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| @@ -1761,11 +1725,11 @@ Creates a filter to listen for specific state changes that can then be used with - `[A, B]` - "A in first position AND B in second position (and anything after)" - `[[A, B], [A, B]]` - "(A OR B) in first position AND (A OR B) in second position (and anything after)" -#### Returns +##### Returns {[`Quantity`](#quantity)} - ID of the newly-created filter that can be used with `eth_getFilterChanges` -#### Example +##### Example ```sh # Request @@ -1786,24 +1750,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_newPendingTransactionFilter +#### eth_newPendingTransactionFilter -#### Description +##### Description Creates a filter to listen for new pending transactions that can be used with `eth_getFilterChanges` -#### Parameters +##### Parameters _none_ -#### Returns +##### Returns {[`Quantity`](#quantity)} - ID of the newly-created filter that can be used with `eth_getFilterChanges` -#### Example +##### Example ```sh # Request @@ -1822,24 +1784,22 @@ curl -X POST --data '{ } ``` --- -
-
-eth_protocolVersion +#### eth_protocolVersion -#### Description +##### Description Returns the current Ethereum protocol version -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {`string`} - current Ethereum protocol version -#### Example +##### Example ```sh # Request curl -X POST --data '{ @@ -1857,26 +1817,24 @@ curl -X POST --data '{ } ``` --- -
-
-eth_sendRawTransaction +#### eth_sendRawTransaction -#### Description +##### Description Sends and already-signed transaction to the network -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|signed transaction data| -#### Returns +##### Returns {[`Data`](#data)} - transaction hash, or the zero hash if the transaction is not yet available -#### Example +##### Example ```sh # Request @@ -1895,26 +1853,24 @@ curl -X POST --data '{ } ``` --- -
-
-eth_sendTransaction +#### eth_sendTransaction -#### Description +##### Description Creates, signs, and sends a new transaction to the network -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{`object`}|@property {[`Data`](#data)} `from` - transaction sender
@property {[`Data`](#data)} `[to]` - transaction recipient
@property {[`Quantity`](#quantity)} `[gas="0x15f90"]` - gas provided for transaction execution
@property {[`Quantity`](#quantity)} `[gasPrice]` - price in wei of each gas used
@property {[`Quantity`](#quantity)} `[value]` - value in wei sent with this transaction
@property {[`Data`](#data)} `[data]` - contract code or a hashed method call with encoded args
@property {[`Quantity`](#quantity)} `[nonce]` - unique number identifying this transaction| -#### Returns +##### Returns {[`Data`](#data)} - transaction hash, or the zero hash if the transaction is not yet available -#### Example +##### Example ```sh # Request @@ -1940,27 +1896,25 @@ curl -X POST --data '{ } ``` --- -
-
-eth_sign +#### eth_sign -#### Description +##### Description Calculates an Ethereum-specific signature in the form of `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))` -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|address to use for signing| |2|{[`Data`](#data)}|data to sign| -#### Returns +##### Returns {[`Data`](#data)} - signature hash of the provided data -#### Example +##### Example ```sh # Request @@ -1979,26 +1933,24 @@ curl -X POST --data '{ } ``` --- -
-
-eth_signTransaction +#### eth_signTransaction -#### Description +##### Description Signs a transaction that can be submitted to the network at a later time using with `eth_sendRawTransaction` -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{`object`}|@property {[`Data`](#data)} `from` - transaction sender
@property {[`Data`](#data)} `[to]` - transaction recipient
@property {[`Quantity`](#quantity)} `[gas="0x15f90"]` - gas provided for transaction execution
@property {[`Quantity`](#quantity)} `[gasPrice]` - price in wei of each gas used
@property {[`Quantity`](#quantity)} `[value]` - value in wei sent with this transaction
@property {[`Data`](#data)} `[data]` - contract code or a hashed method call with encoded args
@property {[`Quantity`](#quantity)} `[nonce]` - unique number identifying this transaction| -#### Returns +##### Returns {[`Data`](#data)} - signature hash of the transaction object -#### Example +##### Example ```sh # Request @@ -2024,29 +1976,27 @@ curl -X POST --data '{ } ``` --- -
-
-eth_signTypedData +#### eth_signTypedData -#### Description +##### Description Calculates an Ethereum-specific signature in the form of `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))` -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|address to use for signing| |2|{[`Data`](#data)}|message to sign containing type information, a domain separator, and data| -**Note:** Client developers should refer to EIP-712 for complete semantics around [encoding and signing data](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification). Dapp developers should refer to EIP-712 for the expected structure of [RPC method input parameters](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#parameters). +**Note:** Client developers should refer to EIP-712 for complete semantics around [encoding and signing data](./eip-712.md#specification). Dapp developers should refer to EIP-712 for the expected structure of [RPC method input parameters](./eip-712.md#parameters). -#### Returns +##### Returns {[`Data`](#data)} - signature hash of the provided message -#### Example +##### Example ```sh # Request @@ -2116,27 +2066,25 @@ curl -X POST --data '{ } ``` --- -
-
-eth_submitHashrate +#### eth_submitHashrate -#### Description +##### Description Submit a mining hashrate -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Data`](#data)}|hash rate| |2|{[`Data`](#data)}|random ID identifying this node| -#### Returns +##### Returns {`boolean`} - `true` if submitting went through successfully, `false` otherwise -#### Example +##### Example ```sh # Request @@ -2158,16 +2106,14 @@ curl -X POST --data '{ } ``` --- -
-
-eth_submitWork +#### eth_submitWork -#### Description +##### Description Submit a proof-of-work solution -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| @@ -2175,11 +2121,11 @@ Submit a proof-of-work solution |2|{[`Data`](#data)}|header's pow-hash| |3|{[`Data`](#data)}|mix digest| -#### Returns +##### Returns {`boolean`} - `true` if the provided solution is valid, `false` otherwise -#### Example +##### Example ```sh # Request @@ -2202,21 +2148,18 @@ curl -X POST --data '{ } ``` --- -
- -
-eth_syncing +#### eth_syncing -#### Description +##### Description Returns information about the status of this client's network synchronization -#### Parameters +##### Parameters _(none)_ -#### Returns +##### Returns {`boolean|object`} - `false` if this client is not syncing with the network, otherwise an object with the following members: @@ -2224,7 +2167,7 @@ _(none)_ - {[`Quantity`](#quantity)} `highestBlock` - number of latest block on the network - {[`Quantity`](#quantity)} `startingBlock` - block number at which syncing started -#### Example +##### Example ```sh # Request @@ -2247,28 +2190,26 @@ curl -X POST --data '{ } ``` --- -
-
-eth_uninstallFilter +#### eth_uninstallFilter -#### Description +##### Description Destroys a filter based on filter ID **Note:** This should only be called if a filter and its notifications are no longer needed. This will also be called automatically on a filter if its notifications are not retrieved using `eth_getFilterChanges` for a period of time. -#### Parameters +##### Parameters |#|Type|Description| |-|-|-| |1|{[`Quantity`](#quantity)}|ID of the filter to destroy| -#### Returns +##### Returns {`boolean`} - `true` if the filter is found and successfully destroyed or `false` if it is not -#### Example +##### Example ```sh # Request @@ -2287,7 +2228,6 @@ curl -X POST --data '{ } ``` --- -
## Rationale @@ -2311,4 +2251,4 @@ The current generation of Ethereum clients includes several implementations that ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1482.md b/EIPS/eip-1482.md index b133bc6302f7c2..90b8bfa20d201d 100644 --- a/EIPS/eip-1482.md +++ b/EIPS/eip-1482.md @@ -3,7 +3,7 @@ eip: 1482 title: Define a maximum block timestamp drift author: Maurelian (@Maurelian) discussions-to: https://ethereum-magicians.org/t/define-a-maximum-block-timestamp-drift/1556 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-10-09 @@ -41,12 +41,10 @@ Both [Geth](https://github.com/ethereum/go-ethereum/blob/4e474c74dc2ac1d26b339c3 ## Backwards Compatibility - It may be necessary to relax this requirement for blocks which were mined early in the main chain's history, if they would be considered invalid. ## Test Cases - These would be important to have. @@ -54,8 +52,7 @@ These would be important to have. ## Implementation - _The implementations must be completed before any EIP is given status "Final", but it need not be completed before the EIP is accepted. While there is merit to the approach of reaching consensus on the specification and rationale before writing code, the principle of "rough consensus and running code" is still useful when it comes to resolving many discussions of API details. _ ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1484.md b/EIPS/eip-1484.md index ebe60637774e65..ad952a72f854b9 100644 --- a/EIPS/eip-1484.md +++ b/EIPS/eip-1484.md @@ -1,544 +1,7 @@ --- eip: 1484 -title: Digital Identity Aggregator -author: Anurag Angara , Andy Chorlian , Shane Hampton , Noah Zinsmeister -discussions-to: https://github.com/ethereum/EIPs/issues/1495 -status: Draft -type: Standards Track category: ERC -created: 2018-10-12 -requires: 191 +status: Moved --- -## Simple Summary -A protocol for aggregating digital identity information that's broadly interoperable with existing, proposed, and hypothetical future digital identity standards. - -## Abstract -This EIP proposes an identity management and aggregation framework on the Ethereum blockchain. It allows entities to claim an `Identity` via a singular `Identity Registry` smart contract, associate it with Ethereum addresses in a variety of meaningful ways, and use it to interact with smart contracts. This enables arbitrarily complex identity-related functionality. Notably (among other features) ERC-1484 `Identities`: are self-sovereign, can natively support [ERC-725](https://github.com/NoahZinsmeister/ERC-1484/tree/master/contracts/examples/Resolvers/ERC725) and [ERC-1056](https://github.com/NoahZinsmeister/ERC-1484/tree/master/contracts/examples/Resolvers/ERC1056) identities, are [DID compliant](https://github.com/NoahZinsmeister/ERC-1484/blob/master/best-practices/DID-Method.md), and can be fully powered by [meta-transactions](https://github.com/NoahZinsmeister/ERC-1484/tree/master/contracts/examples/Providers/MetaTransactions). - -## Motivation -Emerging identity standards and related frameworks proposed by the Ethereum community (including ERCs/EIPs [725](https://github.com/ethereum/EIPs/issues/725), [735](https://github.com/ethereum/EIPs/issues/735), [780](https://github.com/ethereum/EIPs/issues/780), [1056](https://github.com/ethereum/EIPs/issues/1056), etc.) define and instrumentalize digital identity in a variety of ways. As existing approaches mature, new standards emerge, and isolated, non-standard approaches to identity develop, coordinating on identity will become increasingly burdensome for blockchain users and developers, and involve the unnecessary duplication of work. - -The proliferation of on-chain identity solutions can be traced back to the fact that each codifies a notion of identity and links it to specific aspects of Ethereum (claims protocols, per-identity smart contracts, signature verification schemes, etc.). This proposal eschews that approach, instead introducing a protocol layer in between the Ethereum network and individual identity applications. This solves identity management and interoperability challenges by enabling any identity-driven application to leverage an un-opinionated identity management protocol. - -## Definitions -- `Identity Registry`: A single smart contract which is the hub for all `Identities`. The primary responsibility of the `Registry` is to define and enforce the rules of a global namespace for `Identities`, which are individually denominated by Ethereum Identification Numbers (EINs). - -- `Identity`: A data structure containing all the core information relevant to an identity, namely: a `Recovery Address`, an `Associated Addresses` set, a `Providers` set, and a `Resolvers` set. `Identities` are denominated by EINs (incrementing `uint` identifiers starting at 1), which are unique but otherwise uninformative. Each `Identity` is a Solidity struct: - -```solidity -struct Identity { - address recoveryAddress; - AddressSet.Set associatedAddresses; - AddressSet.Set providers; - AddressSet.Set resolvers; -} -``` - -- `Associated Address`: An Ethereum address publicly associated with an `Identity`. In order for an address to become an `Associated Address`, an `Identity` must either transact from or produce an appropriately signed message from the candidate address and an existing `Associated Address`, indicating intent to associate. An `Associated Address` can be removed from an `Identity` by transacting/producing a signature indicating intent to disassociate. A given address may only be an `Associated Address` for one `Identity` at any given time. - -- `Provider`: An Ethereum address (typically but not by definition a smart contract) authorized to act on behalf of `Identities` who have authorized them to do so. This includes but is not limited to managing the `Associated Address`, `Provider`, and `Resolver` sets for an `Identity`. `Providers` exist to facilitate user adoption by making it easier to manage `Identities`. - -- `Resolver`: A smart contract containing arbitrary information pertaining to `Identities`. A resolver may implement an identity standard, such as ERC-725, or may consist of a smart contract leveraging or declaring identifying information about `Identities`. These could be simple attestation structures or more sophisticated financial dApps, social media dApps, etc. Each `Resolver` added to an `Identity` makes the `Identity` more informative. - -- `Recovery Address`: An Ethereum address (either an account or smart contract) that can be used to recover lost `Identities` as outlined in the [Recovery](#recovery) section. - -- `Destruction`: In the event of irrecoverable loss of control of an `Identity`, `Destruction` is a contingency measure to permanently disable the `Identity`. It removes all `Associated Addresses`, `Providers`, and optionally `Resolvers` while preserving the `Identity`. Evidence of the existence of the `Identity` persists, while control over the `Identity` is nullified. - -## Specification -A digital identity in this proposal can be viewed as an omnibus account, containing more information about an identity than any individual identity application could. This omnibus identity is resolvable to an unlimited number of sub-identities called `Resolvers`. This allows an atomic entity, the `Identity`, to be resolvable to abstract data structures, the `Resolvers`. `Resolvers` recognize `Identities` by any of their `Associated Addresses`, or by their `EIN`. - -The protocol revolves around claiming an `Identity` and managing `Associated Addresses`, `Providers` and `Resolvers`. Identities can delegate much or all of this responsibility to one or more `Providers`, or perform it directly from an `Associated Address`. `Associated Addresses`/`Providers` may add and remove `Resolvers` and `Providers` indiscriminately. `Associated Addresses` may only be added or removed with the appropriate permission. - -### Identity Registry -The `Identity Registry` contains functionality to create new `Identities` and for existing `Identities` to manage their `Associated Addresses`, `Providers`, and `Resolvers`. It is important to note that this registry fundamentally requires transactions for every aspect of building out an `Identity`. However, recognizing the importance of accessibility to dApps and identity applications, we empower `Providers` to build out `Identities` on the behalf of users, without requiring users to pay gas costs. An example of this pattern, often referred to as a meta transactions, can be [seen in the reference implementation](https://github.com/NoahZinsmeister/ERC-1484/tree/master/contracts/examples/Providers/MetaTransactions). - -Due to the fact that multiple addresses can be associated with a given identity (though not the reverse), `Identities` are denominated by `EIN`. This `uint` identifier can be encoded in QR format or mapped to more user-friendly formats, such as a `string`, in registries at the `Provider` or `Resolver` level. - -### Address Management -The address management function consists of trustlessly connecting multiple user-owned `Associated Addresses` to an `Identity`. It does not give special status to any particular `Associated Address`, rather leaving this (optional) specification to identity applications built on top of the protocol - for instance, `management`, `action`, `claim` and `encryption` keys denominated in the ERC-725 standard, or `identifiers` and `delegates` as denominated in ERC-1056. This allows a user to access common identity data from multiple wallets while still: - -- retaining the ability to interact with contracts outside of their identity -- taking advantage of address-specific permissions established at the application layer of a user's identity. - -Trustlessness in the address management function is achieved through a robust permissioning scheme. To add an `Associated Address` to an `Identity`, implicit permission from a transaction sender or explicit permission from a signature is required from 1) an address already within the registry and 2) an address to be claimed. Importantly, the transaction need not come from any particular address, as long as permission is established, which allows not only users but third parties (companies, governments, etc.) to bear the overhead of managing identities. To prevent a compromised `Associated Address` from unilaterally removing other `Associated Addresses`, it's only possible to remove an `Associated Address` by transacting or producing a signature from it. - -All signatures required in ERC-1484 are designed per the [ERC-191](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-191.md) v0 specification. To avoid replay attacks, all signatures must include a timestamp within a rolling lagged window of the current `block.timestamp`. For more information, see this [best practices document](https://github.com/NoahZinsmeister/ERC-1484/blob/master/best-practices/VerifyingSignatures.md) in the reference implementation. - -### Provider Management -While the protocol allows users to directly call identity management functions, it also aims to be more robust and future-proof by allowing `Providers`, typically smart contracts, to perform identity management functions on a user's behalf. A `Provider` set by an `Identity` can perform address management and resolver management functions by passing a user's `EIN` in function calls. - -### Resolver Management -A `Resolver` is any smart contract that encodes information which resolves to an `Identity`. We remain agnostic about the specific information that can be encoded in a resolver and the functionality that this enables. The existence of `Resolvers` is primarily what makes this ERC an identity *protocol* rather than an identity *application*. `Resolvers` resolve abstract data in smart contracts to an atomic entity, the `Identity`. - -### Recovery -If users lose control over an `Associated Address`, the `Recovery Address` provides a fallback mechanism. Upon `Identity` creation, a `Recovery Address` is passed as a parameter by the creator. Recovery functionality is triggered in three scenarios: - -**1. Changing Recovery Address**: If a recovery key is lost, an `Associated Address`/`Provider` can [triggerRecoveryAddressChange](#triggerRecoveryAddressChange)/[triggerRecoveryAddressChangeFor](#triggerRecoveryAddressChangeFor). To prevent malicious behavior from someone who has gained control of an `Associated Address` or `Provider` and is changing the `Recovery Address` to one under their control, this action triggers a 14 day challenge period during which the old `Recovery Address` may reject the change by [triggering recovery](#triggerRecovery). If the `Recovery Address` does not reject the change within 14 days, the `Recovery Address` is changed. - -**2. Recovery**: Recovery occurs when a user recognizes that an `Associated Address` or the `Recovery Address` belonging to the user is lost or stolen. In this instance the `Recovery Address` must call [triggerRecovery](#triggerRecovery). This removes all `Associated Addresses` and `Providers` from the corresponding `Identity` and replaces them with an address passed in the function call. The `Identity` and associated `Resolvers` maintain integrity. The user is now responsible for adding the appropriate un-compromised addresses back to their `Identity`. - -*Importantly, the `Recovery Address` can be a user-controlled wallet or another address, such as a multisig wallet or smart contract. This allows for arbitrarily sophisticated recovery logic! This includes the potential for recovery to be fully compliant with standards such as [DID](https://decentralized.id/).* - -**3. Destruction** -The Recovery scheme offers considerable power to a `Recovery Address`; accordingly, `Destruction` is a nuclear option to combat malicious control over an `Identity` when a `Recovery Address` is compromised. If a malicious actor compromises a user's `Recovery Address` and triggers recovery, any address removed in the `Recovery` process can call [triggerDestruction](#triggerDestruction) within 14 days to permanently disable the `Identity`. The user would then need to create a new `Identity`, and would be responsible for engaging in recovery schemes for any identity applications built in the `Resolver` or `Provider` layers. - -#### Alternative Recovery Considerations -We considered many possible alternatives when devising the Recovery process outlined above. We ultimately selected the scheme that was most un-opinionated, modular, and consistent with the philosophy behind the `Associated Address`, `Provider`, and `Resolver` components. Still, we feel that it is important to highlight some of the other recovery options we considered, to provide a rationale as to how we settled on what we did. - -**High Level Concerns** -Fundamentally, a Recovery scheme needs to be resilient to a compromised address taking control of a user's `Identity`. A secondary concern is preventing a compromised address from maliciously destroying a user's identity due to off-chain utility, which is not an optimal scenario, but is strictly better than if they've gained control. - -**Alternative 1: Nuclear Option** -This approach would allow any `Associated Address` to destroy an `Identity` whenever another `Associated Address` is compromised. While this may seem severe, we strongly considered it because this ERC is an identity *protocol*, not an identity *application*. This means that though a user's compromised `Identity` is destroyed, they should still have recourse to whatever restoration mechanisms are available in each of their actual identities at the `Resolver` and/or `Provider` level. We ultimately dismissed this approach for two main reasons: - -- It is not robust in cases where a user has only one `Associated Address` -- It would increase the frequency of recovery requests to identity applications due to its unforgiving nature. - -**Alternative 2: Unilateral Address Removal via Providers** -This would allow `Associated Addresses`/`Providers` to remove `Associated Addresses` without a signature from said address. This implementation would allow `Providers` to include arbitrarily sophisticated schemes for removing a rogue address - for instance, multi-sig requirements, centralized off-chain verification, user controlled master addresses, deferral to a jurisdictional contract, and more. To prevent a compromised `Associated Address` from simply setting a malicious `Provider` to remove un-compromised addresses, it would have required a waiting period between when a `Provider` is set and when they would be able to remove an `Associated Address`. We dismissed this approach because we felt it placed too high of a burden on `Providers`. If a `Provider` offered a sophisticated range of functionality to a user, but post-deployment a threat was found in the Recovery logic of the provider, `Provider`-specific infrastructure would need to be rebuilt. We also considered including a flag that would allow a user to decide whether or not a `Provider` may remove `Associated Addresses` unilaterally. Ultimately, we concluded that only allowing removal of `Associated Addresses` via the `Recovery Address` enables equally sophisticated recovery logic while separating the functionality from `Providers`, leaving less room for users to relinquish control to potentially flawed implementations. - -## Rationale -We find that at a protocol layer, identities should not rely on specific claim or attestation structures, but should instead be a part of a trustless framework upon which arbitrarily sophisticated claim and attestation structures may be built. - -The main criticism of existing identity solutions is that they're overly restrictive. We aim to limit requirements, keep identities modular and future-proof, and remain un-opinionated regarding any functionality a particular identity component may have. This proposal gives users the option to interact on the blockchain using an robust `Identity` rather than just an address. - -## Implementation -**The reference implementation for ERC-1484 may be found in [NoahZinsmeister/ERC-1484](https://github.com/NoahZinsmeister/ERC-1484).** - -#### identityExists - -Returns a `bool` indicating whether or not an `Identity` denominated by the passed `EIN` exists. - -```solidity -function identityExists(uint ein) public view returns (bool); -``` - -#### hasIdentity - -Returns a `bool` indicating whether or not the passed `_address` is associated with an `Identity`. - -```solidity -function hasIdentity(address _address) public view returns (bool); -``` - -#### getEIN - -Returns the `EIN` associated with the passed `_address`. Throws if the address is not associated with an `EIN`. - -```solidity -function getEIN(address _address) public view returns (uint ein); -``` - -#### isAssociatedAddressFor - -Returns a `bool` indicating whether or not the passed `_address` is associated with the passed `EIN`. - -```solidity -function isAssociatedAddressFor(uint ein, address _address) public view returns (bool); -``` - -#### isProviderFor - -Returns a `bool` indicating whether or not the passed `provider` has been set by the passed `EIN`. - -```solidity -function isProviderFor(uint ein, address provider) public view returns (bool); -``` - -#### isResolverFor - -Returns a `bool` indicating whether or not the passed `resolver` has been set by the passed `EIN`. - -```solidity -function isResolverFor(uint ein, address resolver) public view returns (bool); -``` - -#### getIdentity - -Returns the `recoveryAddress`, `associatedAddresses`, `providers` and `resolvers` of the passed `EIN`. - -```solidity -function getIdentity(uint ein) public view - returns ( - address recoveryAddress, - address[] memory associatedAddresses, address[] memory providers, address[] memory resolvers - ); -``` - -#### createIdentity - -Creates an `Identity`, setting the `msg.sender` as the sole `Associated Address`. Returns the `EIN` of the new `Identity`. - -```solidity -function createIdentity(address recoveryAddress, address[] memory providers, address[] memory resolvers) - public returns (uint ein); -``` - -Triggers event: [IdentityCreated](#identitycreated) - -#### createIdentityDelegated - -Performs the same logic as `createIdentity`, but can be called by any address. This function requires a signature from the `associatedAddress` to ensure their consent. - -```solidity -function createIdentityDelegated( - address recoveryAddress, address associatedAddress, address[] memory providers, address[] memory resolvers, - uint8 v, bytes32 r, bytes32 s, uint timestamp -) - public returns (uint ein); -``` - -Triggers event: [IdentityCreated](#identitycreated) - -#### addAssociatedAddress - -Adds the `addressToAdd` to the `EIN` of the `approvingAddress`. The `msg.sender` must be either of the `approvingAddress` or the `addressToAdd`, and the signature must be from the other one. - -```solidity -function addAssociatedAddress( - address approvingAddress, address addressToAdd, uint8 v, bytes32 r, bytes32 s, uint timestamp -) - public -``` - -Triggers event: [AssociatedAddressAdded](#associatedaddressadded) - -#### addAssociatedAddressDelegated - -Adds the `addressToAdd` to the `EIN` of the `approvingAddress`. Requires signatures from both the `approvingAddress` and the `addressToAdd`. - -```solidity -function addAssociatedAddressDelegated( - address approvingAddress, address addressToAdd, - uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s, uint[2] memory timestamp -) - public -``` - -Triggers event: [AssociatedAddressAdded](#associatedaddressadded) - -#### removeAssociatedAddress - -Removes the `msg.sender` as an `Associated Address` from its `EIN`. - -```solidity -function removeAssociatedAddress() public; -``` - -Triggers event: [AssociatedAddressRemoved](#associatedaddressremoved) - - -#### removeAssociatedAddressDelegated - -Removes the `addressToRemove` from its associated `EIN`. Requires a signature from the `addressToRemove`. - -```solidity -function removeAssociatedAddressDelegated(address addressToRemove, uint8 v, bytes32 r, bytes32 s, uint timestamp) - public; -``` - -Triggers event: [AssociatedAddressRemoved](#associatedaddressremoved) - -#### addProviders - -Adds an array of `Providers` to the `Identity` of the `msg.sender`. - -```solidity -function addProviders(address[] memory providers) public; -``` - -Triggers event: [ProviderAdded](#provideradded) - -#### addProvidersFor - -Performs the same logic as `addProviders`, but must be called by a `Provider`. - -```solidity -function addProvidersFor(uint ein, address[] memory providers) public; -``` - -Triggers event: [ProviderAdded](#provideradded) - -#### removeProviders - -Removes an array of `Providers` from the `Identity` of the `msg.sender`. - -```solidity -function removeProviders(address[] memory providers) public; -``` - -Triggers event: [ProviderRemoved](#providerremoved) - - -#### removeProvidersFor - -Performs the same logic as `removeProviders`, but is called by a `Provider`. - -```solidity -function removeProvidersFor(uint ein, address[] memory providers) public; -``` - -Triggers event: [ProviderRemoved](#providerremoved) - - -#### addResolvers - -Adds an array of `Resolvers` to the `EIN` of the `msg.sender`. - -```solidity -function addResolvers(address[] memory resolvers) public; -``` - -Triggers event: [ResolverAdded](#resolveradded) - -#### addResolversFor - -Performs the same logic as `addResolvers`, but must be called by a `Provider`. - -```solidity -function addResolversFor(uint ein, address[] memory resolvers) public; -``` - -Triggers event: [ResolverAdded](#resolveradded) - -#### removeResolvers - -Removes an array of `Resolvers` from the `EIN` of the `msg.sender`. - -```solidity -function removeResolvers(address[] memory resolvers) public; -``` - -Triggers event: [ResolverRemoved](#resolverremoved) - -#### removeResolversFor - -Performs the same logic as `removeResolvers`, but must be called by a `Provider`. - -```solidity -function removeResolversFor(uint ein, address[] memory resolvers) public; -``` - -Triggers event: [ResolverRemoved](#resolverremoved) - -#### triggerRecoveryAddressChange - -Initiates a change in the current `recoveryAddress` for the `EIN` of the `msg.sender`. - -```solidity -function triggerRecoveryAddressChange(address newRecoveryAddress) public; -``` - -Triggers event: [RecoveryAddressChangeTriggered](#RecoveryAddressChangeTriggered) - -#### triggerRecoveryAddressChangeFor - -Initiates a change in the current `recoveryAddress` for a given `EIN`. - -```solidity -function triggerRecoveryAddressChangeFor(uint ein, address newRecoveryAddress) public; -``` - -Triggers event: [RecoveryAddressChangeTriggered](#RecoveryAddressChangeTriggered) - -#### triggerRecovery - -Triggers `EIN` recovery from the current `recoveryAddress`, or the old `recoveryAddress` if changed within the last 2 weeks. - -```solidity -function triggerRecovery(uint ein, address newAssociatedAddress, uint8 v, bytes32 r, bytes32 s, uint timestamp) public; -``` - -Triggers event: [RecoveryTriggered](#RecoveryTriggered) - -#### triggerDestruction - -Triggers destruction of an `EIN`. This renders the `Identity` permanently unusable. - -```solidity -function triggerDestruction(uint ein, address[] memory firstChunk, address[] memory lastChunk, bool clearResolvers) - public; -``` - -Triggers event: [IdentityDestroyed](#IdentityDestroyed) - -### Events - -#### IdentityCreated - -MUST be triggered when an `Identity` is created. - -```solidity -event IdentityCreated( - address indexed initiator, uint indexed ein, - address recoveryAddress, address associatedAddress, address[] providers, address[] resolvers, bool delegated -); -``` - -#### AssociatedAddressAdded - -MUST be triggered when an address is added to an `Identity`. - -```solidity -event AssociatedAddressAdded( - address indexed initiator, uint indexed ein, address approvingAddress, address addedAddress, bool delegated -); -``` - -#### AssociatedAddressRemoved - -MUST be triggered when an address is removed from an `Identity`. - -```solidity -event AssociatedAddressRemoved(address indexed initiator, uint indexed ein, address removedAddress, bool delegated); -``` - -#### ProviderAdded - -MUST be triggered when a provider is added to an `Identity`. - -```solidity -event ProviderAdded(address indexed initiator, uint indexed ein, address provider, bool delegated); -``` - -#### ProviderRemoved - -MUST be triggered when a provider is removed. - -```solidity -event ProviderRemoved(address indexed initiator, uint indexed ein, address provider, bool delegated); -``` - -#### ResolverAdded - -MUST be triggered when a resolver is added. - -```solidity -event ResolverAdded(address indexed initiator, uint indexed ein, address resolvers, bool delegated); -``` - -#### ResolverRemoved - -MUST be triggered when a resolver is removed. - -```solidity -event ResolverRemoved(address indexed initiator, uint indexed ein, address resolvers, bool delegated); -``` - -#### RecoveryAddressChangeTriggered - -MUST be triggered when a recovery address change is triggered. - -```solidity -event RecoveryAddressChangeTriggered( - address indexed initiator, uint indexed ein, - address oldRecoveryAddress, address newRecoveryAddress, bool delegated -); -``` - -#### RecoveryTriggered - -MUST be triggered when recovery is triggered. - -```solidity -event RecoveryTriggered( - address indexed initiator, uint indexed ein, address[] oldAssociatedAddresses, address newAssociatedAddress -); -``` - -#### IdentityDestroyed - -MUST be triggered when an `Identity` is destroyed. - -```solidity -event IdentityDestroyed(address indexed initiator, uint indexed ein, address recoveryAddress, bool resolversReset); -``` - -### Solidity Interface -```solidity -interface IdentityRegistryInterface { - function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) - external pure returns (bool); - - // Identity View Functions ///////////////////////////////////////////////////////////////////////////////////////// - function identityExists(uint ein) external view returns (bool); - function hasIdentity(address _address) external view returns (bool); - function getEIN(address _address) external view returns (uint ein); - function isAssociatedAddressFor(uint ein, address _address) external view returns (bool); - function isProviderFor(uint ein, address provider) external view returns (bool); - function isResolverFor(uint ein, address resolver) external view returns (bool); - function getIdentity(uint ein) external view returns ( - address recoveryAddress, - address[] memory associatedAddresses, address[] memory providers, address[] memory resolvers - ); - - // Identity Management Functions /////////////////////////////////////////////////////////////////////////////////// - function createIdentity(address recoveryAddress, address[] calldata providers, address[] calldata resolvers) - external returns (uint ein); - function createIdentityDelegated( - address recoveryAddress, address associatedAddress, address[] calldata providers, address[] calldata resolvers, - uint8 v, bytes32 r, bytes32 s, uint timestamp - ) external returns (uint ein); - function addAssociatedAddress( - address approvingAddress, address addressToAdd, uint8 v, bytes32 r, bytes32 s, uint timestamp - ) external; - function addAssociatedAddressDelegated( - address approvingAddress, address addressToAdd, - uint8[2] calldata v, bytes32[2] calldata r, bytes32[2] calldata s, uint[2] calldata timestamp - ) external; - function removeAssociatedAddress() external; - function removeAssociatedAddressDelegated(address addressToRemove, uint8 v, bytes32 r, bytes32 s, uint timestamp) - external; - function addProviders(address[] calldata providers) external; - function addProvidersFor(uint ein, address[] calldata providers) external; - function removeProviders(address[] calldata providers) external; - function removeProvidersFor(uint ein, address[] calldata providers) external; - function addResolvers(address[] calldata resolvers) external; - function addResolversFor(uint ein, address[] calldata resolvers) external; - function removeResolvers(address[] calldata resolvers) external; - function removeResolversFor(uint ein, address[] calldata resolvers) external; - - // Recovery Management Functions /////////////////////////////////////////////////////////////////////////////////// - function triggerRecoveryAddressChange(address newRecoveryAddress) external; - function triggerRecoveryAddressChangeFor(uint ein, address newRecoveryAddress) external; - function triggerRecovery(uint ein, address newAssociatedAddress, uint8 v, bytes32 r, bytes32 s, uint timestamp) - external; - function triggerDestruction( - uint ein, address[] calldata firstChunk, address[] calldata lastChunk, bool resetResolvers - ) external; - - // Events ////////////////////////////////////////////////////////////////////////////////////////////////////////// - event IdentityCreated( - address indexed initiator, uint indexed ein, - address recoveryAddress, address associatedAddress, address[] providers, address[] resolvers, bool delegated - ); - event AssociatedAddressAdded( - address indexed initiator, uint indexed ein, address approvingAddress, address addedAddress - ); - event AssociatedAddressRemoved(address indexed initiator, uint indexed ein, address removedAddress); - event ProviderAdded(address indexed initiator, uint indexed ein, address provider, bool delegated); - event ProviderRemoved(address indexed initiator, uint indexed ein, address provider, bool delegated); - event ResolverAdded(address indexed initiator, uint indexed ein, address resolvers); - event ResolverRemoved(address indexed initiator, uint indexed ein, address resolvers); - event RecoveryAddressChangeTriggered( - address indexed initiator, uint indexed ein, address oldRecoveryAddress, address newRecoveryAddress - ); - event RecoveryTriggered( - address indexed initiator, uint indexed ein, address[] oldAssociatedAddresses, address newAssociatedAddress - ); - event IdentityDestroyed(address indexed initiator, uint indexed ein, address recoveryAddress, bool resolversReset); -} -``` - -## Backwards Compatibility -`Identities` established under this standard consist of existing Ethereum addresses; accordingly, there are no backwards compatibility issues. Deployed, non-upgradeable smart contracts that wish to become `Resolvers` for `Identities` will need to write wrapper contracts that resolve addresses to `EIN`-denominated `Identities`. - -## Additional References -- [ERC-1484 Reference Implementation](https://github.com/NoahZinsmeister/ERC-1484) -- [ERC-191 Signatures](https://github.com/ethereum/EIPs/issues/191) -- [ERC-725 Identities](https://github.com/ethereum/EIPs/issues/725) -- [ERC-1056 Identities](https://github.com/ethereum/EIPs/issues/1056) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1484.md diff --git a/EIPS/eip-1485.md b/EIPS/eip-1485.md index 9dbdbcb3ef8114..e7c28e1f1c47c3 100644 --- a/EIPS/eip-1485.md +++ b/EIPS/eip-1485.md @@ -1,200 +1,200 @@ ---- -eip: 1485 -title: TEthashV1 -author: trustfarm (KT Ahn - 안씨아저씨) , trustfarm -discussions-to: https://ethereum-magicians.org/t/anti-eth-asic-mining-eip-1488-pr/1807 -status: Draft -type: Standards Track -category: Core -created: 2018-11-01 ---- - -## Simple Summary -This EIP modifies ethash in order to break ASIC miners specialized for the current ethash mining algorithm. - -## Abstract -This EIP pursue "obsolete current ASIC miners" by modifying PoW algorithm in a very low risk manner and update to latest hash algorithm from deprecated FNV Hash algorithms. - -Following TEthashV1 algorithm suggests safe transition of PoW algorithms and secure the FNV Algorithm in MIX Parts. - -## Motivation -Provide original Ethash proof of work verification with minimal set of changes by updating FNV0 algorithm - -## Specification - -#### 1. Reference materials on ETHASH FNV0 - -#### Where FNV Applied on ETHASH - -- In [ETHASH](https://github.com/ethereum/wiki/wiki/Ethash) , FNV Hash is used on - * 1) On data aggregation function, MIX parts. - - * Ethash Algorithm - - ``` - Header + Nonce - | - Keccak - | - **[MIX 0]** --> **[DAG Page]** - | | - Mixing <--| - ... - | - **[Mix 63]** - | - |-----> Mix64 [Process] ---> Mix Digest [32B] - ``` - - * FNV used in DAG Generation - and Mixing for random access or DAG Page. - -#### 2. Current applied Ethash FNV hash implementation is deprecated now. - -[FNV-0_hash (deprecated)](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-0_hash_(deprecated)) - - It is a simple way of hashing algorithm - - ``` - hash = 0 - for each byte_of_data to be hashed - hash = hash × FNV_prime - hash = hash XOR octet_of_data - return hash - ``` - - When analysed FNV-0 , there's very weak [avalanche effect](https://simple.wikipedia.org/wiki/Avalanche_effect), when hash input changes on 1~2bits. refer [FNV-Analysis reference section](https://github.com/tao-foundation/FNV-Analysis#how-to-test-and-analysis-reference-test-code) - - We need to research and apply newer FNV hash or short message hash algorithm. - -#### 3. FNV1A hash algorithm description - -Previous proposed algorithm based on FNV1 [EIP-1355](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1355.md) - -There's a implementation that looks like "Missing Offset Bias" at **FNV1A**. - -Quotation of [original algorithm FNV1A](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash) -``` -use hash offset -FNV-1a hash -The FNV-1a hash differs from the FNV-1 hash by only the order in which the multiply and XOR is performed:[8][10] - - hash = FNV_offset_basis - for each byte_of_data to be hashed - hash = hash XOR byte_of_data - hash = hash × FNV_prime - return hash -``` - -FNV_offset_basis and computation order change of xor and multiplication Makes one more xor and multiply computation, but more secure hash effects than FNV0. -and make dispersion boundary condition (0, even number, ..) by using of Prime Number. - -#### 4. Real Implementation for FNV1A - -Consider real computation resources, in TEthashV1 uses hash byte_of_data to 4bytes aligned data. - -In TETHashV1, Adapts fully follow the FNV1A implementation. - - - TETHASHV1 FNV1A implementation - -Following are reference implementation of FNV1A adapted in TETHashV1. - -```cpp -// Reference Pseudo c/cpp implementation - -#define FNV_PRIME 0x01000193U -#define FNV_OFFSET_BASIS 0x811c9dc5U - -#define fnv1a(x, y) ((((FNV_OFFSET_BASIS^(x))*FNV_PRIME) ^ (y)) * FNV_PRIME) -#define fnv1a_reduce(a,b,c,d) (fnv1a(fnv1a(fnv1a(a, b), c), d)) -``` - -Another Byte aligned implementation of FNV1A , call to FNV1c - -```cpp -#define FNV_PRIME 0x01000193U -#define FNV_OFFSET_BASIS 0x811c9dc5U - -#define fnv1i(x) ( (( (( (( \ - ( ((FNV_OFFSET_BASIS)^( ((x)>>24)&0x000000ff )) * FNV_PRIME) \ - ^ (((x)>>16 )&0x000000ff)) * FNV_PRIME) \ - ^ (((x)>>8 )&0x000000ff)) * FNV_PRIME) \ - ^ (((x) )&0x000000ff)) * FNV_PRIME) \ - ) -#define fnv1c(x, y) ((fnv1i(x) ^ (y)) * FNV_PRIME) -``` - -#### 5. [FNV-Analysis](https://github.com/tao-foundation/FNV-Analysis) -FNV Mix Algorithm Analysis for TEthashV1 - -#### How to test and analysis reference test code. - -You can compile it with simple in terminal. -No additional library needs, - -``` -gcc -o fnvtest fnvcltest.c -``` - -And You can execute it -``` -fnvtest - -F(00,00)::VEC(0, 0, ffffffff, 0):: FNV :00000000, DF=00000000(00) DS(00000000), FNV1 :00000000, DF=00000000(00) DS(00000000), FNV1a:117697cd, DF=117697cd(17) DS(117697cd), FNV1c:1210d00f, DF=127f8dbf(20) DS(11a1725f), F___RC=efe1b9c4, DF:efe1b9c4(19) , F1__RC=deb68dfe, DF:deb68dfe(22) , F1A_RC=99bad28b, DF:99bad28b(17) , F1C_RC=e29fa497, DF:e29fa497(18) -F(00,01)::VEC(0, 1, ffffffff, 0):: FNV :00000001, DF=00000001(01) DS(00000001), FNV1 :01000193, DF=01000193(06) DS(01000193), FNV1a:1076963a, DF=010001f7(09) DS(01000193), FNV1c:1110ce7c, DF=03001e73(11) DS(01000193), F___RC=fefffe6d, DF:111e47a9(14) , F1__RC=d9fd8597, DF:074b0869(12) , F1A_RC=72c287e0, DF:eb78556b(19) , F1C_RC=6b6991ef, DF:89f63578(17) -F(00,02)::VEC(0, 2, ffffffff, 0):: FNV :00000002, DF=00000003(02) DS(00000001), FNV1 :02000326, DF=030002b5(08) DS(01000193), FNV1a:0f7694a7, DF=1f00029d(11) DS(01000193), FNV1c:1410d335, DF=05001d49(09) DS(030004b9), F___RC=d8fd8404, DF:26027a69(13) , F1__RC=9b16d24c, DF:42eb57db(19) , F1A_RC=c17f0ecb, DF:b3bd892b(18) , F1C_RC=a5be8e78, DF:ced71f97(21) -F(00,03)::VEC(0, 3, ffffffff, 0):: FNV :00000003, DF=00000001(01) DS(00000001), FNV1 :030004b9, DF=0100079f(10) DS(01000193), FNV1a:0e769314, DF=010007b3(09) DS(01000193), FNV1c:1310d1a2, DF=07000297(09) DS(01000193), F___RC=b2fb099b, DF:6a068d9f(16) , F1__RC=5c301f01, DF:c726cd4d(17) , F1A_RC=94cf402e, DF:55b04ee5(16) , F1C_RC=aea1a025, DF:0b1f2e5d(17) -F(00,04)::VEC(0, 4, ffffffff, 0):: FNV :00000004, DF=00000007(03) DS(00000001), FNV1 :0400064c, DF=070002f5(10) DS(01000193), FNV1a:0d769181, DF=03000295(07) DS(01000193), FNV1c:0e10c9c3, DF=1d001861(09) DS(050007df), F___RC=8cf88f32, DF:3e0386a9(14) , F1__RC=1d496bb6, DF:417974b7(17) , F1A_RC=89401d59, DF:1d8f5d77(20) , F1C_RC=e4e96c7c, DF:4a48cc59(13) -F(00,05)::VEC(0, 5, ffffffff, 0):: FNV :00000005, DF=00000001(01) DS(00000001), FNV1 :050007df, DF=01000193(06) DS(01000193), FNV1a:0c768fee, DF=01001e6f(11) DS(01000193), FNV1c:0d10c830, DF=030001f3(09) DS(01000193), F___RC=66f614c9, DF:ea0e9bfb(20) , F1__RC=de62b86b, DF:c32bd3dd(19) , F1A_RC=346e222c, DF:bd2e3f75(21) , F1C_RC=502e5f82, DF:b4c733fe(20) -F(00,06)::VEC(0, 6, ffffffff, 0):: FNV :00000006, DF=00000003(02) DS(00000001), FNV1 :06000972, DF=03000ead(10) DS(01000193), FNV1a:0b768e5b, DF=070001b5(09) DS(01000193), FNV1c:1010cce9, DF=1d0004d9(10) DS(030004b9), F___RC=40f39a60, DF:26058ea9(13) , F1__RC=9f7c0520, DF:411ebd4b(16) , F1A_RC=b376a527, DF:8718870b(13) , F1C_RC=1241a9a4, DF:426ff626(17) -F(00,07)::VEC(0, 7, ffffffff, 0):: FNV :00000007, DF=00000001(01) DS(00000001), FNV1 :07000b05, DF=01000277(08) DS(01000193), FNV1a:0a768cc8, DF=01000293(06) DS(01000193), FNV1c:0f10cb56, DF=1f0007bf(15) DS(01000193), F___RC=1af11ff7, DF:5a028597(13) , F1__RC=609551d5, DF:ffe954f5(22) , F1A_RC=14293bea, DF:a75f9ecd(21) , F1C_RC=49d34bba, DF:5b92e21e(16) -F(00,08)::VEC(0, 8, ffffffff, 0):: FNV :00000008, DF=0000000f(04) DS(00000001), FNV1 :08000c98, DF=0f00079d(12) DS(01000193), FNV1a:09768b35, DF=030007fd(12) DS(01000193), FNV1c:1a10dca7, DF=150017f1(12) DS(0b001151), F___RC=f4eea58e, DF:ee1fba79(21) , F1__RC=21ae9e8a, DF:413bcf5f(19) , F1A_RC=eeebb7a5, DF:fac28c4f(17) , F1C_RC=7da04f47, DF:347304fd(16) -F(00,09)::VEC(0, 9, ffffffff, 0):: FNV :00000009, DF=00000001(01) DS(00000001), FNV1 :09000e2b, DF=010002b3(07) DS(01000193), FNV1a:087689a2, DF=01000297(07) DS(01000193), FNV1c:1910db14, DF=030007b3(10) DS(01000193), F___RC=ceec2b25, DF:3a028eab(14) , F1__RC=e2c7eb3f, DF:c36975b5(18) , F1A_RC=54e1aef8, DF:ba0a195d(15) , F1C_RC=d425e1af, DF:a985aee8(16) -F(00,0a)::VEC(0, a, ffffffff, 0):: FNV :0000000a, DF=00000003(02) DS(00000001), FNV1 :0a000fbe, DF=03000195(07) DS(01000193), FNV1a:0776880f, DF=0f0001ad(10) DS(01000193), FNV1c:1c10dfcd, DF=050004d9(08) DS(030004b9), F___RC=a8e9b0bc, DF:66059b99(15) , F1__RC=a3e137f4, DF:4126dccb(15) , F1A_RC=213fcd63, DF:75de639b(20) , F1C_RC=7e1d2751, DF:aa38c6fe(18) -F(00,0b)::VEC(0, b, ffffffff, 0):: FNV :0000000b, DF=00000001(01) DS(00000001), FNV1 :0b001151, DF=01001eef(12) DS(01000193), FNV1a:0676867c, DF=01000e73(09) DS(01000193), FNV1c:1b10de3a, DF=070001f7(11) DS(01000193), F___RC=82e73653, DF:2a0e86ef(16) , F1__RC=64fa84a9, DF:c71bb35d(19) , F1A_RC=5598ce46, DF:74a70325(14) , F1C_RC=6400c630, DF:1a1de161(14) -F(00,0c)::VEC(0, c, ffffffff, 0):: FNV :0000000c, DF=00000007(03) DS(00000001), FNV1 :0c0012e4, DF=070003b5(10) DS(01000193), FNV1a:057684e9, DF=03000295(07) DS(01000193), FNV1c:1610d65b, DF=0d000861(07) DS(050007df), F___RC=5ce4bbea, DF:de038db9(17) , F1__RC=2613d15e, DF:42e955f7(18) , F1A_RC=6a220ff1, DF:3fbac1b7(20) , F1C_RC=6e781da4, DF:0a78db94(15) -F(00,0d)::VEC(0, d, ffffffff, 0):: FNV :0000000d, DF=00000001(01) DS(00000001), FNV1 :0d001477, DF=01000693(07) DS(01000193), FNV1a:04768356, DF=010007bf(11) DS(01000193), FNV1c:1510d4c8, DF=03000293(07) DS(01000193), F___RC=36e24181, DF:6a06fa6b(17) , F1__RC=e72d1e13, DF:c13ecf4d(18) , F1A_RC=168d4944, DF:7caf46b5(19) , F1C_RC=65bbcfa1, DF:0bc3d205(13) -F(00,0e)::VEC(0, e, ffffffff, 0):: FNV :0000000e, DF=00000003(02) DS(00000001), FNV1 :0e00160a, DF=0300027d(09) DS(01000193), FNV1a:037681c3, DF=07000295(08) DS(01000193), FNV1c:1810d981, DF=0d000d49(09) DS(030004b9), F___RC=10dfc718, DF:263d8699(15) , F1__RC=a8466ac8, DF:4f6b74db(20) , F1A_RC=93e667bf, DF:856b2efb(19) , F1C_RC=76f80ee3, DF:1343c142(11) -F(00,0f)::VEC(0, f, ffffffff, 0):: FNV :0000000f, DF=00000001(01) DS(00000001), FNV1 :0f00179d, DF=01000197(07) DS(01000193), FNV1a:02768030, DF=010001f3(08) DS(01000193), FNV1c:1710d7ee, DF=0f000e6f(13) DS(01000193), F___RC=eadd4caf, DF:fa028bb7(17) , F1__RC=695fb77d, DF:c119ddb5(17) , F1A_RC=0f485682, DF:9cae313d(17) , F1C_RC=3667e8dc, DF:409fe63f(18) -F(00,10)::VEC(0, 10, ffffffff, 0):: FNV :00000010, DF=0000001f(05) DS(00000001), FNV1 :10001930, DF=1f000ead(13) DS(01000193), FNV1a:01767e9d, DF=0300fead(14) DS(01000193), FNV1c:0210b6df, DF=15006131(09) DS(1500210f), F___RC=c4dad246, DF:2e079ee9(17) , F1__RC=2a790432, DF:4326b34f(16) , F1A_RC=d10adebd, DF:de42883f(16) , F1C_RC=1ce48e12, DF:2a8366ce(15) -``` - -`F(00,01)` : is input x,y - -`VEC(0, 1, ffffffff, 0)` : is `fnv_reduce` input vector (a,b,c,d) - -`FNV :00000001, DF=00000001(01) DS(00000001)` : - * `FNV(00,01)` result is 00000001 , - * `DF` : is changed bitcounts, compared with previous outputs, in this case prev[00,00] current[00,01] input is 1bit changed, and output result 1bit changed. - * `DS` : is distances of previous result and current result , ABS(prev_fnvresult,current_fnvresult). - -** Basically, `DF` is higher is best on hash algorithm. - -`F___RC=fefffe6d, DF:111e47a9(14)` : `fnv_reduce = fnv(fnv(fnv(a,b),c),d) ` result is fefffe6d , and Different Bits counts are `14` bits. - - -## Rationale - -In case of ethash algorithm, it can't prevent ASIC forever. - -And, current ethash algorithm's FNV function is deprecated. - -So, It needs to be upgraded and it will make current ethash based ASICs obsolete. - -And current TETHASHV1 FNV1A implementation is based on most of ethash , which is verified for a long time. - -Another propose of big differencing the Ethash algorithm need to crypto analysis for a long times and need to GPU code optimization times. - -**Verification and Optimization timeline Examples** - -original ethminer (2015) -> claymore optimized miner (2016) [1year] - -genoil ethminer (2015) -> ethereum-mining/ethminer (2017) [2year] - -## Test Results:: - -Tethash miner has 2~3% of hashrate degrade on GPU, due to more core computation time. - -## Copyright - -This work is licensed under a [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-nc-sa/4.0/). +--- +eip: 1485 +title: TEthashV1 +author: trustfarm , trustfarm +discussions-to: https://ethereum-magicians.org/t/anti-eth-asic-mining-eip-1488-pr/1807 +status: Stagnant +type: Standards Track +category: Core +created: 2018-11-01 +--- + +## Simple Summary +This EIP modifies ethash in order to break ASIC miners specialized for the current ethash mining algorithm. + +## Abstract +This EIP pursue "obsolete current ASIC miners" by modifying PoW algorithm in a very low risk manner and update to latest hash algorithm from deprecated FNV Hash algorithms. + +Following TEthashV1 algorithm suggests safe transition of PoW algorithms and secure the FNV Algorithm in MIX Parts. + +## Motivation +Provide original Ethash proof of work verification with minimal set of changes by updating FNV0 algorithm + +## Specification + +#### 1. Reference materials on ETHASH FNV0 + +#### Where FNV Applied on ETHASH + +- In [ETHASH](https://web.archive.org/web/20200505215203/https://github.com/ethereum/wiki/wiki/Ethash), FNV Hash is used on + * 1) On data aggregation function, MIX parts. + + * Ethash Algorithm + + ``` + Header + Nonce + | + Keccak + | + **[MIX 0]** --> **[DAG Page]** + | | + Mixing <--| + ... + | + **[Mix 63]** + | + |-----> Mix64 [Process] ---> Mix Digest [32B] + ``` + + * FNV used in DAG Generation + and Mixing for random access or DAG Page. + +#### 2. Current applied Ethash FNV hash implementation is deprecated now. + +[FNV-0_hash (deprecated)](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-0_hash_(deprecated)) + + It is a simple way of hashing algorithm + + ``` + hash = 0 + for each byte_of_data to be hashed + hash = hash × FNV_prime + hash = hash XOR octet_of_data + return hash + ``` + + When analysed FNV-0 , there's very weak [avalanche effect](https://simple.wikipedia.org/wiki/Avalanche_effect), when hash input changes on 1~2bits. refer [FNV-Analysis reference section](https://github.com/tao-foundation/FNV-Analysis#how-to-test-and-analysis-reference-test-code) + + We need to research and apply newer FNV hash or short message hash algorithm. + +#### 3. FNV1A hash algorithm description + +Previous proposed algorithm based on FNV1 [EIP-1355](./eip-1355.md) + +There's an implementation that looks like "Missing Offset Bias" at **FNV1A**. + +Quotation of [original algorithm FNV1A](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash) +``` +use hash offset +FNV-1a hash +The FNV-1a hash differs from the FNV-1 hash by only the order in which the multiply and XOR is performed:[8][10] + + hash = FNV_offset_basis + for each byte_of_data to be hashed + hash = hash XOR byte_of_data + hash = hash × FNV_prime + return hash +``` + +FNV_offset_basis and computation order change of xor and multiplication Makes one more xor and multiply computation, but more secure hash effects than FNV0. +and make dispersion boundary condition (0, even number, ..) by using of Prime Number. + +#### 4. Real Implementation for FNV1A + +Consider real computation resources, in TEthashV1 uses hash byte_of_data to 4bytes aligned data. + +In TETHashV1, Adapts fully follow the FNV1A implementation. + + - TETHASHV1 FNV1A implementation + +Following are reference implementation of FNV1A adapted in TETHashV1. + +```cpp +// Reference Pseudo c/cpp implementation + +#define FNV_PRIME 0x01000193U +#define FNV_OFFSET_BASIS 0x811c9dc5U + +#define fnv1a(x, y) ((((FNV_OFFSET_BASIS^(x))*FNV_PRIME) ^ (y)) * FNV_PRIME) +#define fnv1a_reduce(a,b,c,d) (fnv1a(fnv1a(fnv1a(a, b), c), d)) +``` + +Another Byte aligned implementation of FNV1A , call to FNV1c + +```cpp +#define FNV_PRIME 0x01000193U +#define FNV_OFFSET_BASIS 0x811c9dc5U + +#define fnv1i(x) ( (( (( (( \ + ( ((FNV_OFFSET_BASIS)^( ((x)>>24)&0x000000ff )) * FNV_PRIME) \ + ^ (((x)>>16 )&0x000000ff)) * FNV_PRIME) \ + ^ (((x)>>8 )&0x000000ff)) * FNV_PRIME) \ + ^ (((x) )&0x000000ff)) * FNV_PRIME) \ + ) +#define fnv1c(x, y) ((fnv1i(x) ^ (y)) * FNV_PRIME) +``` + +#### 5. [FNV-Analysis](https://github.com/tao-foundation/FNV-Analysis) +FNV Mix Algorithm Analysis for TEthashV1 + +#### How to test and analysis reference test code. + +You can compile it with simple in terminal. +No additional library needs, + +```sh +gcc -o fnvtest fnvcltest.c +``` + +And You can execute it +``` +fnvtest + +F(00,00)::VEC(0, 0, ffffffff, 0):: FNV :00000000, DF=00000000(00) DS(00000000), FNV1 :00000000, DF=00000000(00) DS(00000000), FNV1a:117697cd, DF=117697cd(17) DS(117697cd), FNV1c:1210d00f, DF=127f8dbf(20) DS(11a1725f), F___RC=efe1b9c4, DF:efe1b9c4(19) , F1__RC=deb68dfe, DF:deb68dfe(22) , F1A_RC=99bad28b, DF:99bad28b(17) , F1C_RC=e29fa497, DF:e29fa497(18) +F(00,01)::VEC(0, 1, ffffffff, 0):: FNV :00000001, DF=00000001(01) DS(00000001), FNV1 :01000193, DF=01000193(06) DS(01000193), FNV1a:1076963a, DF=010001f7(09) DS(01000193), FNV1c:1110ce7c, DF=03001e73(11) DS(01000193), F___RC=fefffe6d, DF:111e47a9(14) , F1__RC=d9fd8597, DF:074b0869(12) , F1A_RC=72c287e0, DF:eb78556b(19) , F1C_RC=6b6991ef, DF:89f63578(17) +F(00,02)::VEC(0, 2, ffffffff, 0):: FNV :00000002, DF=00000003(02) DS(00000001), FNV1 :02000326, DF=030002b5(08) DS(01000193), FNV1a:0f7694a7, DF=1f00029d(11) DS(01000193), FNV1c:1410d335, DF=05001d49(09) DS(030004b9), F___RC=d8fd8404, DF:26027a69(13) , F1__RC=9b16d24c, DF:42eb57db(19) , F1A_RC=c17f0ecb, DF:b3bd892b(18) , F1C_RC=a5be8e78, DF:ced71f97(21) +F(00,03)::VEC(0, 3, ffffffff, 0):: FNV :00000003, DF=00000001(01) DS(00000001), FNV1 :030004b9, DF=0100079f(10) DS(01000193), FNV1a:0e769314, DF=010007b3(09) DS(01000193), FNV1c:1310d1a2, DF=07000297(09) DS(01000193), F___RC=b2fb099b, DF:6a068d9f(16) , F1__RC=5c301f01, DF:c726cd4d(17) , F1A_RC=94cf402e, DF:55b04ee5(16) , F1C_RC=aea1a025, DF:0b1f2e5d(17) +F(00,04)::VEC(0, 4, ffffffff, 0):: FNV :00000004, DF=00000007(03) DS(00000001), FNV1 :0400064c, DF=070002f5(10) DS(01000193), FNV1a:0d769181, DF=03000295(07) DS(01000193), FNV1c:0e10c9c3, DF=1d001861(09) DS(050007df), F___RC=8cf88f32, DF:3e0386a9(14) , F1__RC=1d496bb6, DF:417974b7(17) , F1A_RC=89401d59, DF:1d8f5d77(20) , F1C_RC=e4e96c7c, DF:4a48cc59(13) +F(00,05)::VEC(0, 5, ffffffff, 0):: FNV :00000005, DF=00000001(01) DS(00000001), FNV1 :050007df, DF=01000193(06) DS(01000193), FNV1a:0c768fee, DF=01001e6f(11) DS(01000193), FNV1c:0d10c830, DF=030001f3(09) DS(01000193), F___RC=66f614c9, DF:ea0e9bfb(20) , F1__RC=de62b86b, DF:c32bd3dd(19) , F1A_RC=346e222c, DF:bd2e3f75(21) , F1C_RC=502e5f82, DF:b4c733fe(20) +F(00,06)::VEC(0, 6, ffffffff, 0):: FNV :00000006, DF=00000003(02) DS(00000001), FNV1 :06000972, DF=03000ead(10) DS(01000193), FNV1a:0b768e5b, DF=070001b5(09) DS(01000193), FNV1c:1010cce9, DF=1d0004d9(10) DS(030004b9), F___RC=40f39a60, DF:26058ea9(13) , F1__RC=9f7c0520, DF:411ebd4b(16) , F1A_RC=b376a527, DF:8718870b(13) , F1C_RC=1241a9a4, DF:426ff626(17) +F(00,07)::VEC(0, 7, ffffffff, 0):: FNV :00000007, DF=00000001(01) DS(00000001), FNV1 :07000b05, DF=01000277(08) DS(01000193), FNV1a:0a768cc8, DF=01000293(06) DS(01000193), FNV1c:0f10cb56, DF=1f0007bf(15) DS(01000193), F___RC=1af11ff7, DF:5a028597(13) , F1__RC=609551d5, DF:ffe954f5(22) , F1A_RC=14293bea, DF:a75f9ecd(21) , F1C_RC=49d34bba, DF:5b92e21e(16) +F(00,08)::VEC(0, 8, ffffffff, 0):: FNV :00000008, DF=0000000f(04) DS(00000001), FNV1 :08000c98, DF=0f00079d(12) DS(01000193), FNV1a:09768b35, DF=030007fd(12) DS(01000193), FNV1c:1a10dca7, DF=150017f1(12) DS(0b001151), F___RC=f4eea58e, DF:ee1fba79(21) , F1__RC=21ae9e8a, DF:413bcf5f(19) , F1A_RC=eeebb7a5, DF:fac28c4f(17) , F1C_RC=7da04f47, DF:347304fd(16) +F(00,09)::VEC(0, 9, ffffffff, 0):: FNV :00000009, DF=00000001(01) DS(00000001), FNV1 :09000e2b, DF=010002b3(07) DS(01000193), FNV1a:087689a2, DF=01000297(07) DS(01000193), FNV1c:1910db14, DF=030007b3(10) DS(01000193), F___RC=ceec2b25, DF:3a028eab(14) , F1__RC=e2c7eb3f, DF:c36975b5(18) , F1A_RC=54e1aef8, DF:ba0a195d(15) , F1C_RC=d425e1af, DF:a985aee8(16) +F(00,0a)::VEC(0, a, ffffffff, 0):: FNV :0000000a, DF=00000003(02) DS(00000001), FNV1 :0a000fbe, DF=03000195(07) DS(01000193), FNV1a:0776880f, DF=0f0001ad(10) DS(01000193), FNV1c:1c10dfcd, DF=050004d9(08) DS(030004b9), F___RC=a8e9b0bc, DF:66059b99(15) , F1__RC=a3e137f4, DF:4126dccb(15) , F1A_RC=213fcd63, DF:75de639b(20) , F1C_RC=7e1d2751, DF:aa38c6fe(18) +F(00,0b)::VEC(0, b, ffffffff, 0):: FNV :0000000b, DF=00000001(01) DS(00000001), FNV1 :0b001151, DF=01001eef(12) DS(01000193), FNV1a:0676867c, DF=01000e73(09) DS(01000193), FNV1c:1b10de3a, DF=070001f7(11) DS(01000193), F___RC=82e73653, DF:2a0e86ef(16) , F1__RC=64fa84a9, DF:c71bb35d(19) , F1A_RC=5598ce46, DF:74a70325(14) , F1C_RC=6400c630, DF:1a1de161(14) +F(00,0c)::VEC(0, c, ffffffff, 0):: FNV :0000000c, DF=00000007(03) DS(00000001), FNV1 :0c0012e4, DF=070003b5(10) DS(01000193), FNV1a:057684e9, DF=03000295(07) DS(01000193), FNV1c:1610d65b, DF=0d000861(07) DS(050007df), F___RC=5ce4bbea, DF:de038db9(17) , F1__RC=2613d15e, DF:42e955f7(18) , F1A_RC=6a220ff1, DF:3fbac1b7(20) , F1C_RC=6e781da4, DF:0a78db94(15) +F(00,0d)::VEC(0, d, ffffffff, 0):: FNV :0000000d, DF=00000001(01) DS(00000001), FNV1 :0d001477, DF=01000693(07) DS(01000193), FNV1a:04768356, DF=010007bf(11) DS(01000193), FNV1c:1510d4c8, DF=03000293(07) DS(01000193), F___RC=36e24181, DF:6a06fa6b(17) , F1__RC=e72d1e13, DF:c13ecf4d(18) , F1A_RC=168d4944, DF:7caf46b5(19) , F1C_RC=65bbcfa1, DF:0bc3d205(13) +F(00,0e)::VEC(0, e, ffffffff, 0):: FNV :0000000e, DF=00000003(02) DS(00000001), FNV1 :0e00160a, DF=0300027d(09) DS(01000193), FNV1a:037681c3, DF=07000295(08) DS(01000193), FNV1c:1810d981, DF=0d000d49(09) DS(030004b9), F___RC=10dfc718, DF:263d8699(15) , F1__RC=a8466ac8, DF:4f6b74db(20) , F1A_RC=93e667bf, DF:856b2efb(19) , F1C_RC=76f80ee3, DF:1343c142(11) +F(00,0f)::VEC(0, f, ffffffff, 0):: FNV :0000000f, DF=00000001(01) DS(00000001), FNV1 :0f00179d, DF=01000197(07) DS(01000193), FNV1a:02768030, DF=010001f3(08) DS(01000193), FNV1c:1710d7ee, DF=0f000e6f(13) DS(01000193), F___RC=eadd4caf, DF:fa028bb7(17) , F1__RC=695fb77d, DF:c119ddb5(17) , F1A_RC=0f485682, DF:9cae313d(17) , F1C_RC=3667e8dc, DF:409fe63f(18) +F(00,10)::VEC(0, 10, ffffffff, 0):: FNV :00000010, DF=0000001f(05) DS(00000001), FNV1 :10001930, DF=1f000ead(13) DS(01000193), FNV1a:01767e9d, DF=0300fead(14) DS(01000193), FNV1c:0210b6df, DF=15006131(09) DS(1500210f), F___RC=c4dad246, DF:2e079ee9(17) , F1__RC=2a790432, DF:4326b34f(16) , F1A_RC=d10adebd, DF:de42883f(16) , F1C_RC=1ce48e12, DF:2a8366ce(15) +``` + +`F(00,01)` : is input x,y + +`VEC(0, 1, ffffffff, 0)` : is `fnv_reduce` input vector (a,b,c,d) + +`FNV :00000001, DF=00000001(01) DS(00000001)` : + * `FNV(00,01)` result is 00000001 , + * `DF` : is changed bitcounts, compared with previous outputs, in this case prev[00,00] current[00,01] input is 1bit changed, and output result 1bit changed. + * `DS` : is distances of previous result and current result , ABS(prev_fnvresult,current_fnvresult). + +** Basically, `DF` is higher is best on hash algorithm. + +`F___RC=fefffe6d, DF:111e47a9(14)` : `fnv_reduce = fnv(fnv(fnv(a,b),c),d) ` result is fefffe6d , and Different Bits counts are `14` bits. + + +## Rationale + +In case of ethash algorithm, it can't prevent ASIC forever. + +And, current ethash algorithm's FNV function is deprecated. + +So, It needs to be upgraded and it will make current ethash based ASICs obsolete. + +And current TETHASHV1 FNV1A implementation is based on most of ethash , which is verified for a long time. + +Another propose of big differencing the Ethash algorithm need to crypto analysis for a long times and need to GPU code optimization times. + +**Verification and Optimization timeline Examples** + +original ethminer (2015) -> claymore optimized miner (2016) [1year] + +genoil ethminer (2015) -> ethereum-mining/ethminer (2017) [2year] + +## Test Results:: + +Tethash miner has 2~3% of hashrate degrade on GPU, due to more core computation time. + +## Copyright + +This work is licensed under a [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-nc-sa/4.0/). diff --git a/EIPS/eip-1491.md b/EIPS/eip-1491.md index 66502ef07748b6..e5cdf4854be6e5 100644 --- a/EIPS/eip-1491.md +++ b/EIPS/eip-1491.md @@ -1,544 +1,7 @@ ---- -eip: 1491 -title: Human Cost Accounting Standard (Like Gas but for humans) -author: Iamnot Chris (@cohabo) -discussions-to: https://github.com/freeworkculture/kazini/issues/11 -status: Draft -type: Standards Track -category: ERC -created: 2018-10-12 ---- - - - - -## Simple Summary - -A standard interface for Human Capital Accounting tokens. - -## Abstract - -The following standard allows for the implementation of a standard API for HUCAP tokens within smart contracts. This standard provides basic functionality to discover, track and transfer the motivational hierarchy of human resources. While blockchain architecture has succeeded in the financialisation of integrity by way of transparency; correspondingly real world outcomes will be proportional to the degree of individualisation of capital by way of knowledge. - -## Motivation - -The Ethereum protocol architecture has a deterministic world-view bounded to the random reality of the human domain that supplies the intentions and logic. The yellow paper formally defines the EVM as a state machine with only deterministic parameters and state transition operators. Oracle requests to another on-chain contract, and/or off-chain HTTP lookups still make for multiple deterministic transactions. - -A standard interface that allows the appraisal of individual capabilities concurrently with output and the overall knowledge-base will reduce market search costs and increase the autonomous insertion of mindful innovation into the blockchain ecosystem. We provide for simple smart contracts to define and track an arbitrarily large number of HUCAP assets. Additional applications are discussed below. - -The Belief-Desire-Intention model is a plan-theoretic framework for establishing means-end coherence in agent based modelling system. -The blockchain's cryptographic security architecture reliably scales to a blockchain based PKI web-of-trust hierarchies. -ERC-20 token standard allows any tokens on Ethereum to be re-used by other applications: from wallets to decentralized exchanges. -ERC-721 token standard allows wallet/broker/auction applications to work with any NFT on Ethereum. -ERC-1155 Crypto Item standard allows a smart contract interface where one can represent any number of ERC-20 and ERC-721 assets in a single contract. - -This standard is inspired by the belief–desire–intention (BDI) model of human practical reasoning developed by Michael Bratman as a way of explaining future-directed intention. A BDI agent is a particular type of bounded rational software agent, imbued with particular mental attitudes, viz: Beliefs, Desires and Intentions (BDI). The model identifies commitment as the distinguishing factor between desire and intention, and a noteworthy property that leads to (1) temporal persistence in plans and in the sense of explicit reference to time, (2) further plans being made on the basis of those to which it is already committed, (3) hierarchical nature of plans, since the overarching plan remains in effect while subsidiary plans are being executed. - -The BDI software model is an attempt to solve a problem of plans and planning choice and the execution thereof. The complement of which tenders a sufficient metric for indicating means-end coherence and ascribing cost baselines to such outcomes. - -## Specification - - - -#### Main Interface -``` -pragma solidity ^0.4.25; -pragma experimental ABIEncoderV2; - -/** - @title ERC-**** Human Capital Accounting Standard - @dev See https://github.com/freeworkculture/kazini/issues/11 - Note: the ERC-165 identifier for this interface is 0xf23a6e61. - */ - -interface IERC_HUCAP { - - /** - @notice Compute the index value of an Agents BDI in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function updateIndex() internal returns (bool); - - /** - @notice Get the active/inactive and states of an Agent in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function iam() view public returns (bool iam_, IERC_HUCAP_TYPES.IS state_); - - /** - @notice Fetch the bdi index value of an Agent in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function index() view public returns (uint8 index_); - - /** - @notice Count of Public Keys in key ring of an Agent in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function ringLength() view public returns (uint ringlength_); - - /** - @notice Get the PGP Public Key Id of an Agent in the ecosystem. - @param "" Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function keyId() view public returns (bytes32 KEYID_); - - /** - @notice Get the merit data of an Agent in the ecosystem. - @param "" Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function merits() view public returns ( - uint experience_, - bytes32 reputation_, - bytes32 talent_, - uint8 index_, - bytes32 hash_); - - /** - @notice Get the accreditation of an Agent in the ecosystem. - @param "" Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function kbase() view public returns (IERC_HUCAP_TYPES.KBase kbase_); - - /** - @notice Get the desire of an Agent in the ecosystem. - @param _desire Pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function desire(bytes1 _desire) view external returns (bytes32); - - /** - @notice Get the intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function intention(bool _intention) view external returns (bytes32); - - /** - @notice Cycle the intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function flipIntention() external returns (bool); - - - /** - @notice Get the user data of an Agent in the ecosystem. - @param "" Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function getDoer() view external returns ( - bytes32 fPrint, - bool iam_, - bytes32 email, - bytes32 fName, - bytes32 lName, - uint age, - bytes32 data_); - - /** - @notice Get the belief data of an Agent in the ecosystem. - @param _kbase Source address - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function getBelief(IERC_HUCAP_TYPES.KBase _kbase) view external returns ( - bytes32 country_, - bytes32 cAuthority_, - bytes32 score_); - - /** - @notice Get the desire data of an Agent in the ecosystem. - @param _desire Pro-attitides - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function getDesire(bytes1 _desire) view external returns (bytes32,bool); - - /** - @notice Get the intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function getIntention(bool _intention) view external returns (IERC_HUCAP_TYPES.IS,bytes32,uint256); - - /** - @notice Sign the Public Key of an Agent in the ecosystem. - @param _address Address of key to sign, must belong to an Agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function sign(address _address) public onlyOwner returns (uint, bool signed); - - /** - @notice Sign the Public Key of an Agent in the ecosystem. - @param "" internal helper function to add key in keyring - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function sign() external onlyDoer returns (uint, bool signed); - - /** - @notice Revoke the Public Key of an Agent in the ecosystem. - @param _address Address of key to revoke, must belong to an Agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function revoke(address _address) external onlyDoer returns (uint, bool revoked); - - /** - @notice Revoke the Public Key of an Agent in the ecosystem. - @param "" internal helper function to remove key from keyring - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function revoke() external onlyDoer returns (uint, bool revoked); - - /** - @notice Set the trust level for a Public Key of an Agent in the ecosystem. - @param _level Degree of trust - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function trust(Trust _level) returns (bool); - - /** - @notice Increment the number of keys in the keyring of an Agent in the ecosystem. - @param _keyd Target key - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function incSigns(bytes32 _keyd) external ProxyKey returns (uint); - - /** - @notice Decrement the number of keys in the keyring of an Agent in the ecosystem. - @param _keyd Target key - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function decSigns(bytes32 _keyd) external ProxyKey returns (uint); - - /** - @notice Set the knowledge credentials of an Agent in the ecosystem. - @param _kbase Level of accreditation - @param _country Source country - @param _cAuthority Accreditation authority - @param _score Accreditation - @param _year Year of Accreditation - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi( - KBase _kbase, - bytes32 _country, - bytes32 _cAuthority, - bytes32 _score, - uint _year - ) external ProxyBDI returns (bool qualification_); - - /** - @notice Set the SNA metrics of an Agent in the ecosystem - @param _refMSD Minimum shortest distance - @param _refRank Rank of target key - @param _refSigned No of keys signed I have signed - @param _refSigs No. of keys that have signed my key - @param _refTrust Degree of tructThrows on any error rather than return a false flag to minimize user errors - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi( - uint _refMSD, - uint _refRank, - uint _refSigned, - uint _refSigs, - bytes32 _refTrust - ) external ProxyBDI returns (bool reputation_); - - /** - @notice Set the talents of an Agent in the ecosystem - @param _talent Agent's talent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi(bytes32 _talent) external ProxyBDI returns (bool talent_); - - /** - @notice Set the desires of an Agent in the ecosystem - @param _desire Pro-attitude - @param _goal A goal is an instatiated pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi(bytes1 _desire, Desire _goal) public onlyDoer returns (bool); - - /** - @notice Set the intention of an Agent in the ecosystem - @param _service Conducting-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi(Intention _service) public onlyDoer returns (bool); - - /** - @notice Set the targeted intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @param _state Agent stance - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function intention(bool _intention, IERC_HUCAP_TYPES.IS _state) external returns (IERC_HUCAP_TYPES.IS); - -/* End of interface IERC_HUCAP */ -} - - -``` -#### User Defined Types Extension Interface - - - -``` - -interface IERC_HUCAP_TYPES { - -/* Enums*/ - - // Weights 1, 2, 4, 8, 16, 32, 64, 128 256 - enum KBase {PRIMARY,SECONDARY,TERTIARY,CERTIFICATION,DIPLOMA,LICENSE,BACHELOR,MASTER,DOCTORATE} - - - enum IS { CLOSED, CREATOR, CURATOR, ACTIVE, INACTIVE, RESERVED, PROVER } - -/* Structus */ - - struct Clearance { - bytes32 Zero; - bytes32 Unknown; - bytes32 Generic; - bytes32 Poor; - bytes32 Casual; - bytes32 Partial; - bytes32 Complete; - bytes32 Ultimate; - } -/* End of interface IERC_HUCAP_TYPES */ -} - -``` -#### Web-of-trust Extension Interface - - - -``` -pragma solidity ^0.4.25; -pragma experimental ABIEncoderV2; - -interface IERC_HUCAP_KEYSIGNING_EXTENSION { - - bytes32 constant public _InterfaceId_ERC165_ = "CREATOR 0.0118 XOR OF ALL FUNCTIONS IN THE INTERFACE"; // Complies to ERC165 - -// KEY MASKING TABLE -// bytes32 constant public MASK = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; -// bytes32 constant public KEYID = 0xffffffffffffffffffffffffffffffffff90EBAC34FC40EAC30FC9CB464A2E56; // EXAMPLE PGP PUBLIC KEY ID -// bytes32 constant public KEY_CERTIFICATION = 0x01ffffffffffffff << 192; // “C” Key Certification -// bytes32 constant public SIGN_DATA = 0x02ffffffffffffff << 192; // “S” Sign Data -// bytes32 constant public ENCRYPT_COMMUNICATIONS = 0x04ffffffffffffff << 192; // “E” Encrypt Communications -// Clearance constant public Trust = 0x03ff << 192; // Trust: Unknown - // BYTES32 Value with - // Public Key Id, masking - // Key Certification masking - // Split Key masking - // Generic masking - // Ordinary masking - // Trust.Unknown masking - // bytes32 constant public DOER = 0x11ff10ff100f03ffff00ffffffffffffffff90EBAC34FC40EAC30FC9CB464A2E56; - - bytes32 constant public KEY_CERTIFICATION = 0x01ffffffffffffff << 192; // “C” Key Certification - bytes32 constant public SIGN_DATA = 0x02ffffffffffffff << 192; // “S” Sign Data - bytes32 constant public ENCRYPT_COMMUNICATIONS = 0x04ffffffffffffff << 192; // “E” Encrypt Communications - bytes32 constant public ENCRYPT_STORAGE = 0x08ffffffffffffff << 192; // “E” Encrypt Storage - bytes32 constant public SPLIT_KEY = 0x10ffffffffffffff << 192; // Split key - bytes32 constant public AUTHENTICATION = 0x20ffffffffffffff << 192; // “A” Authentication - bytes32 constant public MULTI_SIGNATURE = 0x80ffffffffffffff << 192; // Held by more than one person - bytes32 constant public TRUST_AMOUNT = 0xffffffffffff00ff << 192; - bytes32 constant public BINARY_DOCUMENT = 0xffff00ffffffffff << 192; // 0x00: Signature of a binary document. - bytes32 constant public CANONICAL_DOCUMENT = 0xffff01ffffffffff << 192; // 0x01: Signature of a canonical text document. - bytes32 constant public STANDALONE_SIGNATURE = 0xffff02ffffffffff << 192; // 0x02: Standalone signature. - bytes32 constant public GENERIC = 0xffff10ffffffffff << 192; // 0x10: Generic certification of a User ID and Public-Key packet. - bytes32 constant public PERSONA = 0xffff11ffffffffff << 192; // 0x11: Persona certification of a User ID and Public-Key packet. - bytes32 constant public CASUAL = 0xffff12ffffffffff << 192; // 0x12: Casual certification of a User ID and Public-Key packet. - bytes32 constant public POSITIVE = 0xffff13ffffffffff << 192; // 0x13: Positive certification of a User ID and Public-Key packet. - bytes32 constant public SUBKEY_BINDING = 0xffff18ffffffffff << 192; // 0x18: Subkey Binding Signature - bytes32 constant public PRIMARY_KEY_BINDING = 0xffff19ffffffffff << 192; // 0x19: Primary Key Binding Signature - bytes32 constant public DIRECTLY_ON_KEY = 0xffff1Fffffffffff << 192; // 0x1F: Signature directly on a key - bytes32 constant public KEY_REVOCATION = 0xffff20ffffffffff << 192; // 0x20: Key revocation signature - bytes32 constant public SUBKEY_REVOCATION = 0xffff28ffffffffff << 192; // 0x28: Subkey revocation signature - bytes32 constant public CERTIFICATION_REVOCATION = 0xffff30ffffffffff << 192; // 0x30: Certification revocation signature - bytes32 constant public TIMESTAMP = 0xffff40ffffffffff << 192; // 0x40: Timestamp signature. - bytes32 constant public THIRD_PARTY_CONFIRMATION = 0xffff50ffffffffff << 192; // 0x50: Third-Party Confirmation signature. - bytes32 constant public ORDINARY = 0xffffffff100fffff << 192; - bytes32 constant public INTRODUCER = 0xffffffff010fffff << 192; - bytes32 constant public ISSUER = 0xffffffff001fffff << 192; - -// EDGES MASKING TABLE - Clearance internal TRUST = Clearance({ - Zero: 0x01ff << 192, - Unknown: 0x03ff << 192, - Generic: 0x07ff << 192, - Poor: 0xF0ff << 192, - Casual: 0xF1ff << 192, - Partial: 0xF3ff << 192, - Complete: 0xF7ff << 192, - Ultimate: 0xFFff << 192 - }); - - /** - /// @notice Cycle through state transition of an Agent in the ecosystem. - /// @param _address toggle on/off a doer agent - // @dev `anybody` can retrieve the talent data in the contract - */ - function flipTo(address _address) external onlyOwner returns (IS); - - /** - /// @notice Turn Agent in the ecosystem to on/off. - /// @param _address toggle on/off a doer agent - // @dev `anybody` can retrieve the talent data in the contract - */ - function toggle(address _address) external onlyOwner returns (bool); - - /** - /// @notice Set the trust level of an Agent in the ecosystem. - /// @param _level toggle on/off a doer agent - // @dev `anybody` can retrieve the talent data in the contract - */ - function trust(Trust _level) returns (bytes32 Trust); - - event LogCall(address indexed from, address indexed to, address indexed origin, bytes _data); - -/* End of interface IERC_HUCAP_KEYSIGNING_EXTENSION */ -} - -``` -#### Human Capital Accounting Extension Interface - -``` -pragma solidity ^0.4.25; -pragma experimental ABIEncoderV2; - -interface IERC_HUCAP_TRACKUSERS_EXTENSION { - - /// @notice Instantiate an Agent in the ecosystem with default data. - /// @param _address initialise a doer agent - // @dev `anybody` can retrieve the talent data in the contract - function initAgent(Doers _address) external onlyControlled returns (bool); - - /// @notice Get the data by uuid of an Agent in the ecosystem. - /// @param _uuid Get the address of a unique uid - // @dev `anybody` can retrieve the talent data in the contract - function getAgent(bytes32 _uuid) view external returns (address); - - /// @notice Get the data of all Talents in the ecosystem. - /// @param _address Query if address belongs to an agent - // @dev `anybody` can retrieve the talent data in the contract - function iam(address _address) view public returns (bool); - - /// @notice Get the data of all Talents in the ecosystem. - /// @param _address Query if address belongs to a doer - // @dev `anybody` can retrieve the talent data in the contract - function isDoer(address _address) view public returns (IS); - - /// @notice Get the number of doers that can be spawned by a Creators. - /// The query condition of the contract - // @dev `anybody` can retrieve the count data in the contract - function getAgent(address _address) - view public returns (bytes32 keyid_, IS state_, bool active_, uint myDoers_); - - /// @notice Get the data of all Talents in the ecosystem. - /// @param _talent The talent whose frequency is being queried - // @dev `anybody` can retrieve the talent data in the contract - function getTalents(bytes32 _talent) - view external returns (uint talentK_, uint talentI_, uint talentR_, uint talentF_); - - /// @notice Increment a kind of talent in the ecosystem. - /// @param The talent whose frequency is being queried - // @dev `anybody` can retrieve the talent data in the contract - function incTalent() payable public onlyDoer returns (bool); - - /// @notice Decrement a kind of talent in the ecosystem.. - /// @param The talent whose frequency is being queried - // @dev `anybody` can retrieve the talent data in the contract - function decTalent() payable public onlyDoer returns (bool); - - /// @notice Set the Public-Key Id of an Agent in the ecosystem. - /// @param _address Set the Public-key Id of an agent - // @dev `anybody` can retrieve the talent data in the contract - function setAgent(address _address, bytes32 _keyId) external onlyControlled returns (bytes32); - - /// @notice Transition the states of an Agent in the ecosystem. - /// @param _address Set the stance of an agent - // @dev `anybody` can retrieve the talent data in the contract - function setAgent(address _address, IS _state) external onlyControlled returns (IS); - - /// @notice Set the active status of an Agent in the ecosystem. - /// @param _address Toggle the true/false status of an agent - // @dev `anybody` can retrieve the talent data in the contract - function setAgent(address _address, bool _active) external onlyControlled returns (bool); - - /// @notice Set the data of all Intentions of Agents in the ecosystem. - /// @param _serviceId Track number of offers available - // @dev `anybody` can retrieve the talent data in the contract - function setAllPromises(bytes32 _serviceId) external onlyControlled; - -/* End of interface IERC_HUCAP_TRACKUSERS_EXTENSION */ -} - - -``` -## Rationale - -[WIP] - -## Backwards Compatibility - -[WIP] - -## Test Cases - -[WIP] - -## Implementation - -[WIP] - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +--- +eip: 1491 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1491.md diff --git a/EIPS/eip-150.md b/EIPS/eip-150.md index c9bef1ed152106..34acf72522b989 100644 --- a/EIPS/eip-150.md +++ b/EIPS/eip-150.md @@ -10,7 +10,7 @@ created: 2016-09-24 ### Meta reference -[Tangerine Whistle](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-608.md). +[Tangerine Whistle](./eip-608.md). ### Parameters diff --git a/EIPS/eip-1504.md b/EIPS/eip-1504.md new file mode 100644 index 00000000000000..3badb18dfe7716 --- /dev/null +++ b/EIPS/eip-1504.md @@ -0,0 +1,7 @@ +--- +eip: 1504 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1504.md diff --git a/EIPS/eip-152.md b/EIPS/eip-152.md new file mode 100644 index 00000000000000..2762bfcff3e549 --- /dev/null +++ b/EIPS/eip-152.md @@ -0,0 +1,267 @@ +--- +eip: 152 +title: Add BLAKE2 compression function `F` precompile +author: Tjaden Hess , Matt Luongo (@mhluongo), Piotr Dyraga (@pdyraga), James Hancock (@MadeOfTin) +discussions-to: https://github.com/ethereum/EIPs/issues/152 +status: Final +type: Standards Track +category: Core +created: 2016-10-04 +--- + +## Simple Summary + +This EIP will enable the BLAKE2b hash function and other higher-round 64-bit BLAKE2 variants to run cheaply on the EVM, allowing easier interoperability between Ethereum and Zcash as well as other Equihash-based PoW coins. + +## Abstract + +This EIP introduces a new precompiled contract which implements the compression function `F` used in the BLAKE2 cryptographic hashing algorithm, for the purpose of allowing interoperability between the EVM and Zcash, as well as introducing more flexible cryptographic hash primitives to the EVM. + +## Motivation + +Besides being a useful cryptographic hash function and SHA3 finalist, BLAKE2 allows for efficient verification of the Equihash PoW used in Zcash, making a BTC Relay - style SPV client possible on Ethereum. A single verification of an Equihash PoW verification requires 512 iterations of the hash function, making verification of Zcash block headers prohibitively expensive if a Solidity implementation of BLAKE2 is used. + +BLAKE2b, the common 64-bit BLAKE2 variant, is highly optimized and faster than MD5 on modern processors. + +Interoperability with Zcash could enable contracts like trustless atomic swaps between the chains, which could provide a much needed aspect of privacy to the very public Ethereum blockchain. + +## Specification + +We propose adding a precompiled contract at address `0x09` wrapping the [BLAKE2 `F` compression function](https://tools.ietf.org/html/rfc7693#section-3.2). + +The precompile requires 6 inputs tightly encoded, taking exactly 213 bytes, as explained below. The encoded inputs are corresponding to the ones specified in the [BLAKE2 RFC Section 3.2](https://tools.ietf.org/html/rfc7693#section-3.2): + +- `rounds` - the number of rounds - 32-bit unsigned big-endian word +- `h` - the state vector - 8 unsigned 64-bit little-endian words +- `m` - the message block vector - 16 unsigned 64-bit little-endian words +- `t_0, t_1` - offset counters - 2 unsigned 64-bit little-endian words +- `f` - the final block indicator flag - 8-bit word + +``` +[4 bytes for rounds][64 bytes for h][128 bytes for m][8 bytes for t_0][8 bytes for t_1][1 byte for f] +``` + +The boolean `f` parameter is considered as `true` if set to `1`. +The boolean `f` parameter is considered as `false` if set to `0`. +All other values yield an invalid encoding of `f` error. + +The precompile should compute the `F` function as [specified in the RFC](https://tools.ietf.org/html/rfc7693#section-3.2) and return the updated state vector `h` with unchanged encoding (little-endian). + +### Example Usage in Solidity + +The precompile can be wrapped easily in Solidity to provide a more development-friendly interface to `F`. + +```solidity +function F(uint32 rounds, bytes32[2] memory h, bytes32[4] memory m, bytes8[2] memory t, bool f) public view returns (bytes32[2] memory) { + bytes32[2] memory output; + + bytes memory args = abi.encodePacked(rounds, h[0], h[1], m[0], m[1], m[2], m[3], t[0], t[1], f); + + assembly { + if iszero(staticcall(not(0), 0x09, add(args, 32), 0xd5, output, 0x40)) { + revert(0, 0) + } + } + + return output; +} + +function callF() public view returns (bytes32[2] memory) { + uint32 rounds = 12; + + bytes32[2] memory h; + h[0] = hex"48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5"; + h[1] = hex"d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b"; + + bytes32[4] memory m; + m[0] = hex"6162630000000000000000000000000000000000000000000000000000000000"; + m[1] = hex"0000000000000000000000000000000000000000000000000000000000000000"; + m[2] = hex"0000000000000000000000000000000000000000000000000000000000000000"; + m[3] = hex"0000000000000000000000000000000000000000000000000000000000000000"; + + bytes8[2] memory t; + t[0] = hex"0300000000000000"; + t[1] = hex"0000000000000000"; + + bool f = true; + + // Expected output: + // ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1 + // 7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923 + return F(rounds, h, m, t, f); +} +``` + +### Gas costs and benchmarks + +Each operation will cost `GFROUND * rounds` gas, where `GFROUND = 1`. Detailed benchmarks are presented in the benchmarks appendix section. + +## Rationale + +BLAKE2 is an excellent candidate for precompilation. BLAKE2 is heavily optimized for modern 64-bit CPUs, specifically utilizing 24 and 63-bit rotations to allow parallelism through SIMD instructions and little-endian arithmetic. These characteristics provide exceptional speed on native CPUs: 3.08 cycles per byte, or 1 gibibyte per second on an Intel i5. + +In contrast, the big-endian 32 byte semantics of the EVM are not conducive to efficient implementation of BLAKE2, and thus the gas cost associated with computing the hash on the EVM is disproportionate to the true cost of computing the function natively. + +An obvious implementation would be a direct BLAKE2b hash function precompile. At first glance, a BLAKE2b precompile satisfies most hashing and interoperability requirements on the EVM. Once we started digging in, however, it became clear that any BLAKE2b implementation would need specific features and internal modifications based on different projects' requirements and libraries. + +A [thread with the Zcash team](https://github.com/ethereum/EIPs/issues/152#issuecomment-499240310) makes the issue clear. + +> The minimal thing that is necessary for a working ZEC-ETH relay is an implementation of BLAKE2b Compression F in a precompile. + +> A BLAKE2b Compression Function F precompile would also suffice for the Filecoin and Handshake interop goals. + +> A full BLAKE2b precompile would suffice for a ZEC-ETH relay, provided that the implementation provided the parts of the BLAKE2 API that we need (personalization, maybe something else—I'm not sure). + +> I'm not 100% certain if a full BLAKE2b precompile would also suffice for the Filecoin and Handshake goals. It almost certainly could, provided that it supports all the API that they need. + +> BLAKE2s — whether the Compression Function F or the full hash — is only a nice-to-have for the purposes of a ZEC-ETH relay. + +From this and other conversations with teams in the space, we believe we should focus first on the `F` precompile as a strictly necessary piece for interoperability projects. A BLAKE2b precompile is a nice-to-have, and we support any efforts to add one-- but it's unclear whether complete requirements and a flexible API can be found in time for Istanbul. + +Implementation of only the core F compression function also allows substantial flexibility and extensibility while keeping changes at the protocol level to a minimum. This will allow functions like tree hashing, incremental hashing, and keyed, salted, and personalized hashing as well as variable length digests, none of which are currently available on the EVM. + +## Backwards Compatibility + +There is very little risk of breaking backwards-compatibility with this EIP, the sole issue being if someone were to build a contract relying on the address at `0x09` being empty. The likelihood of this is low, and should specific instances arise, the address could be chosen to be any arbitrary value with negligible risk of collision. + +## Test Cases + +#### Test vector 0 +* input: (empty) +* output: error "input length for BLAKE2 F precompile should be exactly 213 bytes" + +#### Test vector 1 +* input: +`00000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001` +* output: error "input length for BLAKE2 F precompile should be exactly 213 bytes" + +#### Test vector 2 +* input: +`000000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001` +* output: error "input length for BLAKE2 F precompile should be exactly 213 bytes" + +#### Test vector 3 +* input: +`0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000002` +* output: error "incorrect final block indicator flag" + +#### Test vector 4 +* input: +`0000000048c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001` +* output: +`08c9bcf367e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d282e6ad7f520e511f6c3e2b8c68059b9442be0454267ce079217e1319cde05b` + +#### Test vector 5 +* input: +`0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001` +* output: `ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923` + +#### Test vector 6 +* input: +`0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000` +* output: +`75ab69d3190a562c51aef8d88f1c2775876944407270c42c9844252c26d2875298743e7f6d5ea2f2d3e8d226039cd31b4e426ac4f2d3d666a610c2116fde4735` + +#### Test vector 7 +* input: +`0000000148c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001` +* output: +`b63a380cb2897d521994a85234ee2c181b5f844d2c624c002677e9703449d2fba551b3a8333bcdf5f2f7e08993d53923de3d64fcc68c034e717b9293fed7a421` + +#### Test vector 8 +* input: +`ffffffff48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001` +* output: +`fc59093aafa9ab43daae0e914c57635c5402d8e3d2130eb9b3cc181de7f0ecf9b22bf99a7815ce16419e200e01846e6b5df8cc7703041bbceb571de6631d2615` + +## Implementation + +An initial implementation of the `F` function in Go, adapted from the standard library, can be found in our [Golang BLAKE2 library fork](https://github.com/keep-network/blake2-f). There's also an implementation of the precompile in our fork of [go-ethereum](https://github.com/keep-network/go-ethereum/pull/4). + +## References + +For reference, further discussion on this EIP also occurred in the following PRs and issues + + * [Original Issue](https://github.com/ethereum/EIPs/issues/152) + * [Ethereum Magicians](https://ethereum-magicians.org/t/blake2b-f-precompile/3157) + * [PR 2129](https://github.com/ethereum/EIPs/pull/2129) + +## Appendix - benchmarks + +Assuming ecRecover precompile is perfectly priced, we executed a set of benchmarks comparing Blake2b F compression function precompile with ecRecover precompile. For benchmarks, we used 3.1 GHz Intel Core i7 64-bit machine. + +```sh +$ sysctl -n machdep.cpu.brand_string +Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz +``` + +### 12 rounds + +An average gas price of F precompile call with 12 rounds compared to ecRecover should have been `6.74153` and it gives `0.5618` gas per round. + +``` +Name Gascost Time (ns) MGas/S Gasprice for 10MGas/S Gasprice for ECDSA eq +----------------------------------------- --------- ---------------- --------- ----------------------- ----------------------- +PrecompiledEcrecover/ 3000 152636 19.6546 1526.36 3000 +PrecompiledBlake2F/testVectors2bX_0 12 338 35.503 3.38 6.64326 +PrecompiledBlake2F/testVectors2bX_3 12 336 35.7143 3.36 6.60395 +PrecompiledBlake2F/testVectors2bX_70 12 362 33.1492 3.62 7.11497 +PrecompiledBlake2F/testVectors2bX_140 12 339 35.3982 3.39 6.66291 +PrecompiledBlake2F/testVectors2bX_230 12 339 35.3982 3.39 6.66291 +PrecompiledBlake2F/testVectors2bX_300 12 343 34.9854 3.43 6.74153 +PrecompiledBlake2F/testVectors2bX_370 12 336 35.7143 3.36 6.60395 +PrecompiledBlake2F/testVectors2bX_440 12 337 35.6083 3.37 6.6236 +PrecompiledBlake2F/testVectors2bX_510 12 345 34.7826 3.45 6.78084 +PrecompiledBlake2F/testVectors2bX_580 12 355 33.8028 3.55 6.97738 +``` + +Columns + +* `MGas/S` - Shows what MGas per second was measured on that machine at that time +* `Gasprice for 10MGas/S` shows what the gasprice should have been, in order to reach 10 MGas/second +* `Gasprice for ECDSA eq` shows what the gasprice should have been, in order to have the same cost/cycle as ecRecover + +### 1200 rounds + +An average gas price of F precompile call with 1200 rounds compared to ecRecover should have been `436.1288` and it gives `0.3634` gas per round. + +``` +Name Gascost Time (ns) MGas/S Gasprice for 10MGas/S Gasprice for ECDSA eq +----------------------------------------- --------- ---------------- --------- ----------------------- ----------------------- +PrecompiledEcrecover/ 3000 156152 19.212 1561.52 3000 +PrecompiledBlake2F/testVectors2bX_0 1200 22642 52.9989 226.42 434.999 +PrecompiledBlake2F/testVectors2bX_3 1200 22885 52.4361 228.85 439.668 +PrecompiledBlake2F/testVectors2bX_70 1200 22737 52.7774 227.37 436.824 +PrecompiledBlake2F/testVectors2bX_140 1200 22602 53.0926 226.02 434.231 +PrecompiledBlake2F/testVectors2bX_230 1200 22501 53.331 225.01 432.29 +PrecompiledBlake2F/testVectors2bX_300 1200 22435 53.4879 224.35 431.022 +PrecompiledBlake2F/testVectors2bX_370 1200 22901 52.3995 229.01 439.975 +PrecompiledBlake2F/testVectors2bX_440 1200 23134 51.8717 231.34 444.452 +PrecompiledBlake2F/testVectors2bX_510 1200 22608 53.0786 226.08 434.346 +PrecompiledBlake2F/testVectors2bX_580 1200 22563 53.1844 225.63 433.481 +``` + +### 1 round + +An average gas price of F precompile call with 1 round compared to ecRecover should have been `2.431701`. However, in this scenario the call cost would totally overshadow the dynamic cost anyway. + +``` +Name Gascost Time (ns) MGas/S Gasprice for 10MGas/S Gasprice for ECDSA eq +----------------------------------------- --------- ---------------- ---------- ----------------------- ----------------------- +PrecompiledEcrecover/ 3000 157544 19.0423 1575.44 3000 +PrecompiledBlake2F/testVectors2bX_0 1 126 7.93651 1.26 2.39933 +PrecompiledBlake2F/testVectors2bX_3 1 127 7.87402 1.27 2.41837 +PrecompiledBlake2F/testVectors2bX_70 1 128 7.8125 1.28 2.43741 +PrecompiledBlake2F/testVectors2bX_140 1 125 8 1.25 2.38029 +PrecompiledBlake2F/testVectors2bX_230 1 128 7.8125 1.28 2.43741 +PrecompiledBlake2F/testVectors2bX_300 1 127 7.87402 1.27 2.41837 +PrecompiledBlake2F/testVectors2bX_370 1 131 7.63359 1.31 2.49454 +PrecompiledBlake2F/testVectors2bX_440 1 129 7.75194 1.29 2.45646 +PrecompiledBlake2F/testVectors2bX_510 1 125 8 1.25 2.38029 +PrecompiledBlake2F/testVectors2bX_580 1 131 7.63359 1.31 2.49454 +``` + + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1523.md b/EIPS/eip-1523.md index 31c2fef02c11b5..a74d332e5eb318 100644 --- a/EIPS/eip-1523.md +++ b/EIPS/eip-1523.md @@ -1,129 +1,7 @@ --- eip: 1523 -title: Standard for Insurance Policies as ERC-721 Non Fungible Tokens -author: Christoph Mussenbrock (@christoph2806) -discussions-to: https://github.com/ethereum/EIPs/issues/1523 -status: Draft -type: Standards Track category: ERC -created: 2018-10-10 -requires: 721 +status: Moved --- -## Simple Summary - -A standard interface for insurance policies, based on ERC 721. - -## Abstract - -The following standard allows for the implementation of a standard API for insurance policies within smart contracts. -Insurance policies are financial assets which are unique in some aspects, as they are connected to a customer, a specific risk, or have other unique properties like premium, period, carrier, underwriter etc. -Nevertheless, there are many potential applications where insurance policies can be traded, transferred or otherwise treated as an asset. -The ERC 721 standard already provides the standard and technical means to handle policies as a specific class of non fungible tokens. -insurance In this proposal, we define a minimum metadata structure with properties which are common to the greatest possible class of policies. - -## Motivation - -For a decentralized insurance protocol, a standard for insurance policies is crucial for interoperability of the involved services and application. -It allows policies to be bundled, securitized, traded in a uniform and flexible way by many independent actors like syndicates, brokers, and insurance companies. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -An ERC-1523 compliant insurance policy is a non-fungible token which **MUST adhere to the ERC-721 token standard** and **MUST implement theERC721Metadata and the ERC721Enumerable interface**: - -```solidity -/// @title ERC-1523 Insurance Policy Standard -/// Note: the ERC-165 identifier for this interface is 0x5a04be32 -interface ERC1523 /* is ERC721, ERC721Metadata, ERC721Enumerable */ { - -} -``` - -The implementor MAY choose values for the ```name``` and ```symbol```. - -The **policy metadata extension** is **RECOMMENDED** for ERC-1523 smart contracts. -This allows your smart contract to be interrogated for policy metadata. - -```solidity -/// @title ERC-1523 Insurance Policy Standard, optional policy metadata extension -/// @dev See ... -/// Note: the ERC-165 identifier for this interface is 0x5a04be32 -interface ERC1523PolicyMetadata /* is ERC1523 */ { - - /// @notice Metadata string for a given property. - /// Properties are identified via hash of their property path. - /// e.g. the property "name" in the ERC721 Metadata JSON Schema has the path /properties/name - /// and the property path hash is the keccak256() of this property path. - /// this allows for efficient addressing of arbitrary properties, as the set of properties is potentially unlimited. - /// @dev Throws if `_propertyPathHash` is not a valid property path hash. - function policyMetadata(uint256 _tokenId, bytes32 _propertyPathHash) external view returns (string _property); - -} -``` - -In analogy to the “ERC721 Metadata JSON Schema”, the tokenURI **MUST** point to a JSON file with the following properties: -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this NFT represents", - }, - "description": { - "type": "string", - "description": "Describes the asset to which this NFT represents", - }, - "carrier": { - "type": "string", - "description": "Describes the carrier which takes the primary risk", - }, - "risk": { - "type": "string", - "description": "Describes the risk", - }, - "parameters": { - "type": "string", - "description": "Describes further parameters characterizing the risk", - }, - "status": { - "type": "string", - "description": "Defines the status of the policy, e.g. Applied, Underwritten, Claimed, Paid out, etc." - } - } -} -``` - -## Rationale - -Insurance policies form an important class of financial assets, and it is natural to express those assets as a class of non-fungible tokens which adhere to the established ERC-721 standard. -We propose a standard for the accompanying metadata structures which are needed to uniquely define an insurance policy. -While policies can have a multitude of possible properties, it is common that policies are issued by some entity, which is basically the entity responsible for paying out claims. -Second, an insurance policy is typically related to a specific risk. Some risks are unique, but there are cases where many policies share the same risk -(e.g. all flight delay policies for the same flight). -In general, the relation of policies to risks is a many-to-one relation with the special case of a one-to-one relation. -Third, most policies need more parameters to characterize the risk and other features, like premium, period etc. -Forth, a policy has a lifecycle of different statuses. -We believe that those four properties are necessary to describe a policy. For many applications, those properties may be even sufficient. -However, any implementation **MAY** chose to implement more properties. - -### On-chain vs. off-chain metadata -For some applications it will be sufficient to store the metadata in an off-chain repository or database which can be addressed by the tokenURI resource locator. -For more advanced applications, it can be desirable to have metadata available on-chain. -Therefore, we require that the ```tokenURI``` **MUST** point to a JSON with the above structure, while the implementation of the ```policyMetadata``` function is **OPTIONAL**. - - -## Backwards Compatibility - - -## Test Cases - - -## Implementation - - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1523.md diff --git a/EIPS/eip-1538.md b/EIPS/eip-1538.md index d3d895a5613f83..f984a6b46164e9 100644 --- a/EIPS/eip-1538.md +++ b/EIPS/eip-1538.md @@ -1,474 +1,7 @@ --- eip: 1538 -title: Transparent Contract Standard -author: Nick Mudge -discussions-to: https://github.com/ethereum/EIPs/issues/1538 -status: Draft -type: Standards Track category: ERC -created: 2018-10-31 +status: Moved --- - -## Simple Summary - -This standard provides a contract architecture that makes upgradeable contracts flexible, unlimited in size, and transparent. - -A transparent contract publicly documents the full history of all changes made to it. - -All changes to a transparent contract are reported in a standard format. - -## Abstract - -A transparent contract is a proxy contract design pattern that provides the following: - -1. A way to add, replace and remove multiple functions of a contract atomically (at the same time). -1. Standard events to show what functions are added, replaced and removed from a contract, and why the changes are made. -2. A standard way to query a contract to discover and retrieve information about all functions exposed by it. -3. Solves the 24KB maximum contract size limitation, making the maximum contract size of a transparent contract practically unlimited. This standard makes the worry about contract size a thing of the past. -4. Enables an upgradeable contract to become immutable in the future if desired. - -## Motivation - -A fundamental benefit of Ethereum contracts is that their code is immutable, thereby acquiring trust by trustlessness. People do not have to trust others if it is not possible for a contract to be changed. - -However, a fundamental problem with trustless contracts that cannot be changed is that they cannot be changed. - -#### Bugs - -Bugs and security vulnerabilities are unwittingly written into immutable contracts that ruin them. - -#### Improvements - -Immutable, trustless contracts cannot be improved, resulting in increasingly inferior contracts over time. - -Contract standards evolve, new ones come out. People, groups and organizations learn over time what people want and what is better and what should be built next. Contracts that cannot be improved not only hold back the authors that create them, but everybody who uses them. - -#### Upgradeable Contracts vs. Centralized Private Database -Why have an upgradeable contract instead of a centralized, private, mutable database? -Here are some reasons: -1. Because of the openness of storage data and verified code, it is possible to show a provable history of trustworthiness. -2. Because of the openness, bad behavior can be spotted and reported when it happens. -3. Independent security and domain experts can review the change history of contracts and vouch for their history of trustworthiness. -4. It is possible for an upgradeable contract to become immutable and trustless. -5. An upgradeable contract can have parts of it that are not upgradeable and so are partially immutable and trustless. - -#### Immutability - -In some cases immutable, trustless contracts are the right fit. This is the case when a contract is only needed for a short time or it is known ahead of time that there will never be any reason to change or improve it. - -### Middle Ground - -Transparent contracts provide a middle ground between immutable trustless contracts that can't be improved and upgradeable contracts that can't be trusted. - -### Purposes - -1. Create upgradeable contracts that earn trust by showing a provable history of trustworthiness. -2. Document the development of contracts so their development and change is provably public and can be understood. -3. Create upgradeable contracts that can become immutable in the future if desired. -4. Create contracts that are not limited by a max size. - -### Benefits & Use Cases -This standard is for use cases that benefit from the following: -1. The ability to add, replace or remove multiple functions of a contract atomically (at the same time). -2. Each time a function is added, replaced or removed, it is documented with events. -3. Build trust over time by showing all changes made to a contract. -4. Unlimited contract size. -5. The ability to query information about functions currently supported by the contract. -6. One contract address that provides all needed functionality and never needs to be replaced by another contract address. -7. The ability for a contract to be upgradeable for a time, and then become immutable. -8. Add trustless guarantees to a contract with "unchangeable functions". - -### New Software Possibilities - -This standard enables a form of contract version control software to be written. - -Software and user interfaces can be written to filter the `FunctionUpdate` and `CommitMessage` events of a contract address. Such software can show the full history of changes of any contract that implements this standard. - -User interfaces and software can also use this standard to assist or automate changes of contracts. - -## Specification - - -> **Note:** -The solidity `delegatecall` opcode enables a contract to execute a function from another contract, but it is executed as if the function was from the calling contract. Essentially `delegatecall` enables a contract to "borrow" another contract's function. Functions executed with `delegatecall` affect the storage variables of the calling contract, not the contract where the functions are defined. - -### General Summary - -A transparent contract delegates or forwards function calls to it to other contracts using `delegatecode`. - -A transparent contract has an `updateContract` function that enables multiple functions to be added, replaced or removed. - -An event is emitted for every function that is added, replaced or removed so that all changes to a contract can be tracked in a standard way. - -A transparent contract is a contract that implements and complies with the design points below. - -### Terms - -1. In this standard a **delegate contract** is a contract that a transparent contract fallback function forwards function calls to using `delegatecall`. -2. In this standard an **unchangeable function** is a function that is defined directly in a transparent contract and so cannot be replaced or removed. - -### Design Points - -A contract is a transparent contract if it implements the following design points: - -1. A transparent contract is a contract that contains a fallback function, a constructor, and zero or more unchangeable functions that are defined directly within it. -2. The constructor of a transparent contract associates the `updateContract` function with a contract that implements the ERC1538 interface. The `updateContract` function can be an "unchangeable function" that is defined directly in the transparent contract or it can be defined in a delegate contract. Other functions can also be associated with contracts in the constructor. -3. After a transparent contract is deployed functions are added, replaced and removed by calling the `updateContract` function. -4. The `updateContract` function associates functions with contracts that implement those functions, and emits the `CommitMessage` and `FunctionUpdate` events that document function changes. -5. The `FunctionUpdate` event is emitted for each function that is added, replaced or removed. The `CommitMessage` event is emitted one time for each time the `updateContract` function is called and is emitted after any `FunctionUpdate` events are emitted. -6. The `updateContract` function can take a list of multiple function signatures in its `_functionSignatures` parameter and so add/replace/remove multiple functions at the same time. -7. When a function is called on a transparent contract it executes immediately if it is an "unchangeable function". Otherwise the fallback function is executed. The fallback function finds the delegate contract associated with the function and executes the function using `delegatecall`. If there is no delegate contract for the function then execution reverts. -8. The source code of a transparent contract and all delegate contracts used by it are publicly viewable and verified. - -The transparent contract address is the address that users interact with. The transparent contract address never changes. Only delegate addresses can change by using the `updateContracts` function. - -Typically some kind of authentication is needed for adding/replacing/removing functions from a transparent contract, **however the scheme for authentication or ownership is not part of this standard**. - -### Example - -Here is an example of an implementation of a transparent contract. Please note that the example below is an **example only. It is not the standard**. A contract is a transparent contract when it implements and complies with the design points listed above. - -```solidity -pragma solidity ^0.5.7; - -contract ExampleTransparentContract { - // owner of the contract - address internal contractOwner; - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - // maps functions to the delegate contracts that execute the functions - // funcId => delegate contract - mapping(bytes4 => address) internal delegates; - - // maps each function signature to its position in the funcSignatures array. - // signature => index+1 - mapping(bytes => uint256) internal funcSignatureToIndex; - - event CommitMessage(string message); - event FunctionUpdate(bytes4 indexed functionId, address indexed oldDelegate, address indexed newDelegate, string functionSignature); - - // this is an example of an "unchangeable function". - // return the delegate contract address for the supplied function signature - function delegateAddress(string calldata _functionSignature) external view returns(address) { - require(funcSignatureToIndex[bytes(_functionSignature)] != 0, "Function signature not found."); - return delegates[bytes4(keccak256(bytes(_functionSignature)))]; - } - - // add a function using the updateContract function - // this is an internal helper function - function addFunction(address _erc1538Delegate, address contractAddress, string memory _functionSignatures, string memory _commitMessage) internal { - // 0x03A9BCCF == bytes4(keccak256("updateContract(address,string,string)")) - bytes memory funcdata = abi.encodeWithSelector(0x03A9BCCF, contractAddress, _functionSignatures, _commitMessage); - bool success; - assembly { - success := delegatecall(gas, _erc1538Delegate, add(funcdata, 0x20), mload(funcdata), funcdata, 0) - } - require(success, "Adding a function failed"); - } - - constructor(address _erc1538Delegate) public { - contractOwner = msg.sender; - emit OwnershipTransferred(address(0), msg.sender); - - // adding ERC1538 updateContract function - bytes memory signature = "updateContract(address,string,string)"; - bytes4 funcId = bytes4(keccak256(signature)); - delegates[funcId] = _erc1538Delegate; - emit FunctionUpdate(funcId, address(0), _erc1538Delegate, string(signature)); - emit CommitMessage("Added ERC1538 updateContract function at contract creation"); - - // associate "unchangeable functions" with this transparent contract address - // prevents function selector clashes with delegate contract functions - // uses the updateContract function - string memory functions = "delegateAddress(string)"; - addFunction(_erc1538Delegate, address(this), functions, "Associating unchangeable functions"); - - // adding ERC1538Query interface functions - functions = "functionByIndex(uint256)functionExists(string)delegateAddresses()delegateFunctionSignatures(address)functionById(bytes4)functionBySignature(string)functionSignatures()totalFunctions()"; - // "0x01234567891011121314" is an example address of an ERC1538Query delegate contract - addFunction(_erc1538Delegate, 0x01234567891011121314, functions, "Adding ERC1538Query functions"); - - // additional functions could be added at this point - } - - // Making the fallback function payable makes it work for delegate contract functions - // that are payable and not payable. - function() external payable { - // Delegate every function call to a delegate contract - address delegate = delegates[msg.sig]; - require(delegate != address(0), "Function does not exist."); - assembly { - let ptr := mload(0x40) - calldatacopy(ptr, 0, calldatasize) - let result := delegatecall(gas, delegate, ptr, calldatasize, 0, 0) - let size := returndatasize - returndatacopy(ptr, 0, size) - switch result - case 0 {revert(ptr, size)} - default {return (ptr, size)} - } - } -} -``` -As can be seen in the above example, every function call is delegated to a delegate contract, unless the function is defined directly in the transparent contract (making it an unchangeable function). - -The constructor function adds the `updateContract` function to the transparent contract, which is then used to add other functions to the transparent contract. - -Each time a function is added to a transparent contract the events `CommitMessage` and `FunctionUpdate` are emitted to document exactly what functions where added or replaced and why. - -The delegate contract that implements the `updateContract` function implements the following interface: -### ERC1538 Interface - -```solidity -pragma solidity ^0.5.7; - -/// @title ERC1538 Transparent Contract Standard -/// @dev Required interface -/// Note: the ERC-165 identifier for this interface is 0x61455567 -interface ERC1538 { - /// @dev This emits when one or a set of functions are updated in a transparent contract. - /// The message string should give a short description of the change and why - /// the change was made. - event CommitMessage(string message); - - /// @dev This emits for each function that is updated in a transparent contract. - /// functionId is the bytes4 of the keccak256 of the function signature. - /// oldDelegate is the delegate contract address of the old delegate contract if - /// the function is being replaced or removed. - /// oldDelegate is the zero value address(0) if a function is being added for the - /// first time. - /// newDelegate is the delegate contract address of the new delegate contract if - /// the function is being added for the first time or if the function is being - /// replaced. - /// newDelegate is the zero value address(0) if the function is being removed. - event FunctionUpdate( - bytes4 indexed functionId, - address indexed oldDelegate, - address indexed newDelegate, - string functionSignature - ); - - /// @notice Updates functions in a transparent contract. - /// @dev If the value of _delegate is zero then the functions specified - /// in _functionSignatures are removed. - /// If the value of _delegate is a delegate contract address then the functions - /// specified in _functionSignatures will be delegated to that address. - /// @param _delegate The address of a delegate contract to delegate to or zero - /// to remove functions. - /// @param _functionSignatures A list of function signatures listed one after the other - /// @param _commitMessage A short description of the change and why it is made - /// This message is passed to the CommitMessage event. - function updateContract(address _delegate, string calldata _functionSignatures, string calldata _commitMessage) external; -} -``` -### Function Signatures String Format - -The text format for the `_functionSignatures` parameter is simply a string of function signatures. For example: `"myFirstFunction()mySecondFunction(string)"` This format is easy to parse and is concise. - -Here is an example of calling the `updateContract` function that adds the ERC721 standard functions to a transparent contract: -```javascript -functionSignatures = "approve(address,uint256)balanceOf(address)getApproved(uint256)isApprovedForAll(address,address)ownerOf(uint256)safeTransferFrom(address,address,uint256)safeTransferFrom(address,address,uint256,bytes)setApprovalForAll(address,bool)transferFrom(address,address,uint256)" -tx = await transparentContract.updateContract(erc721Delegate.address, functionSignatures, "Adding ERC721 functions"); -``` - -### Removing Functions - -Functions are removed by passing `address(0)` as the first argument to the `updateContract` function. The list of functions that are passed in are removed. - -### Source Code Verification - -The transparent contract source code and the source code for the delegate contracts should be verified in a provable way by a third party source such as etherscan.io. - - -### Function Selector Clash -A function selector clash occurs when a function is added to a contract that hashes to the same four-byte hash as an existing function. This is unlikely to occur but should be prevented in the implementation of the `updateContract` function. See the [reference implementation of ERC1538](https://github.com/mudgen/transparent-contracts-erc1538) to see an example of how function clashes can be prevented. - -### ERC1538Query - -Optionally, the function signatures of a transparent contract can be stored in an array in the transparent contract and queried to get what functions the transparent contract supports and what their delegate contract addresses are. - -The following is an optional interface for querying function information from a transparent contract: - -```solidity -pragma solidity ^0.5.7; - -interface ERC1538Query { - - /// @notice Gets the total number of functions the transparent contract has. - /// @return The number of functions the transparent contract has, - /// not including the fallback function. - function totalFunctions() external view returns(uint256); - - /// @notice Gets information about a specific function - /// @dev Throws if `_index` >= `totalFunctions()` - /// @param _index The index position of a function signature that is stored in an array - /// @return The function signature, the function selector and the delegate contract address - function functionByIndex(uint256 _index) - external - view - returns( - string memory functionSignature, - bytes4 functionId, - address delegate - ); - - /// @notice Checks to see if a function exists - /// @param The function signature to check - /// @return True if the function exists, false otherwise - function functionExists(string calldata _functionSignature) external view returns(bool); - - /// @notice Gets all the function signatures of functions supported by the transparent contract - /// @return A string containing a list of function signatures - function functionSignatures() external view returns(string memory); - - /// @notice Gets all the function signatures supported by a specific delegate contract - /// @param _delegate The delegate contract address - /// @return A string containing a list of function signatures - function delegateFunctionSignatures(address _delegate) external view returns(string memory); - - /// @notice Gets the delegate contract address that supports the given function signature - /// @param The function signature - /// @return The delegate contract address - function delegateAddress(string calldata _functionSignature) external view returns(address); - - /// @notice Gets information about a function - /// @dev Throws if no function is found - /// @param _functionId The id of the function to get information about - /// @return The function signature and the contract address - function functionById(bytes4 _functionId) - external - view - returns( - string memory signature, - address delegate - ); - - /// @notice Get all the delegate contract addresses used by the transparent contract - /// @return An array of all delegate contract addresses - function delegateAddresses() external view returns(address[] memory); -} -``` - -See the [reference implementation of ERC1538](https://github.com/mudgen/transparent-contracts-erc1538) to see how this is implemented. - -The text format for the list of function signatures returned from the `delegateFunctionSignatures` and `functionSignatures` functions is simply a string of function signatures. Here is an example of such a string: `"approve(address,uint256)balanceOf(address)getApproved(uint256)isApprovedForAll(address,address)ownerOf(uint256)safeTransferFrom(address,address,uint256)safeTransferFrom(address,address,uint256,bytes)setApprovalForAll(address,bool)transferFrom(address,address,uint256)"` - -### How To Deploy A Transparent Contract -1. Create and deploy to a blockchain a contract that implements the ERC1538 interface. You can skip this step if there is already such a contract deployed to the blockchain. -2. Create your transparent contract with a fallback function as given above. Your transparent contract also needs a constructor that adds the `updateContract` function. -3. Deploy your transparent contract to a blockchain. Pass in the address of the ERC1538 delegate contract to your constructor if it requires it. - -See the [reference implementation](https://github.com/mudgen/transparent-contracts-erc1538) for examples of these contracts. - -### Wrapper Contract for Delegate Contracts that Depend on Other Delegate Contracts -In some cases some delegate contracts may need to call external/public functions that reside in other delegate contracts. A convenient way to solve this problem is to create a contract that contains empty implementations of functions that are needed and import and extend this contract in delegate contracts that call functions from other delegate contracts. This enables delegate contracts to compile without having to provide implementations of the functions that are already given in other delegate contracts. This is a way to save gas, prevent reaching the max contract size limit, and prevent duplication of code. This strategy was given by @amiromayer. [See his comment for more information.](https://github.com/ethereum/EIPs/issues/1538#issuecomment-451985155) Another way to solve this problem is to use assembly to call functions provided by other delegate contracts. - -### Decentralized Authority -It is possible to extend this standard to add consensus functionality such as an approval function that multiple different people call to approve changes before they are submitted with the `updateContract` function. Changes only go into effect when the changes are fully approved. The `CommitMessage` and ` FunctionUpdate` events should only be emitted when changes go into effect. - -## Security -> This standard refers to **owner(s)** as one or more individuals that have the power to add/replace/remove functions of an upgradeable contract. - -### General - -The owners(s) of an upgradeable contract have the ability to alter, add or remove data from the contract's data storage. Owner(s) of a contract can also execute any arbitrary code in the contract on behalf of any address. Owners(s) can do these things by adding a function to the contract that they call to execute arbitrary code. This is an issue for upgradeable contracts in general and is not specific to transparent contracts. - ->**Note:** The design and implementation of contract ownership is **not** part of this standard. The examples given in this standard and in the reference implementation are just **examples** of how it could be done. - -### Unchangeable Functions - -"Unchangeable functions" are functions defined in a transparent contract itself and not in a delegate contract. The owner(s) of a transparent contract are not able to replace these functions. The use of unchangeable functions is limited because in some cases they can still be manipulated if they read or write data to the storage of the transparent contract. Data read from the transparent contract's storage could have been altered by the owner(s) of the contract. Data written to the transparent contract's storage can be undone or altered by the owner(s) of the contract. - -In some cases unchangeble functions add trustless guarantees to a transparent contract. - -### Transparency - -Contracts that implement this standard emit an event every time a function is added, replaced or removed. This enables people and software to monitor the changes to a contract. If any bad acting function is added to a contract then it can be seen. To comply with this standard all source code of a transparent contract and delegate contracts must be publicly available and verified. - -Security and domain experts can review the history of change of any transparent contract to detect any history of foul play. - -## Rationale - - -### String of Function Signatures Instead of bytes4[] Array of Function Selectors - -The `updateContract` function takes a `string` list of functions signatures as an argument instead of a `bytes4[]` array of function selectors for three reasons: - -1. Passing in function signatures enables the implementation of `updateContract` to prevent selector clashes. -2. A major part of this standard is to make upgradeable contracts more transparent by making it easier to see what has changed over time and why. When a function is added, replaced or removed its function signature is included in the FunctionUpdate event that is emitted. This makes it relatively easy to write software that filters the events of a contract to display to people what functions have been added/removed and changed over time without needing access to the source code or ABI of the contract. If only four-byte function selectors were provided this would not be possible. -3. By looking at the source code of a transparent contract it is not possible to see all the functions that it supports. This is why the ERC1538Query interface exists, so that people and software have a way to look up and examine or show all functions currently supported by a transparent contract. Function signatures are used so that ERC1538Query functions can show them. - -### Gas Considerations - -Delegating function calls does have some gas overhead. This is mitigated in two ways: -1. Delegate contracts can be small, reducing gas costs. Because it costs more gas to call a function in a contract with many functions than a contract with few functions. -2. Because transparent contracts do not have a max size limitation it is possible to add gas optimizing functions for use cases. For example someone could use a transparent contract to implement the ERC721 standard and implement batch transfer functions from the [ERC1412 standard](https://github.com/ethereum/EIPs/issues/1412) to help reduce gas (and make batch transfers more convenient). - -### Storage - -The standard does not specify how data is stored or organized by a transparent contract. But here are some suggestions: - -**Inherited Storage** - -1. The storage variables of a transparent contract consist of the storage variables defined in the transparent contract source code and the source code of delegate contracts that have been added. - -2. A delegate contract can use any storage variable that exists in a transparent contract as long as it defines within it all the storage variables that exist, in the order that they exist, up to and including the ones being used. - -3. A delegate contract can create new storage variables as long as it has defined, in the same order, all storage variables that exist in the transparent contract. - -Here is a simple way inherited storage could be implemented: - -1. Create a storage contract that contains the storage variables that your transparent contract and delegate contracts will use. -2. Make your delegate contracts inherit the storage contract. -3. If you want to add a new delegate contract that adds new storage variables then create a new storage contract that adds the new storage variables and inherits from the old storage contract. Use your new storage contract with your new delegate contract. -4. Repeat steps 2 or 3 for every new delegate contract. - - -**Unstructured Storage** - -Assembly is used to store and read data at specific storage locations. An advantage to this approach is that previously used storage locations don't have to be defined or mentioned in a delegate contract if they aren't used by it. - -**Eternal Storage** - -Data can be stored using a generic API based on the type of data. [See ERC930 for more information.](https://github.com/ethereum/EIPs/issues/930) - -### Becoming Immutable -It is possible to make a transparent contract become immutable. This is done by calling the `updateContract` function to remove the `updateContract` function. With this gone it is no longer possible to add, replace and remove functions. - -### Versions of Functions - -Software or a user can verify what version of a function is called by getting the delegate contract address of the function. This can be done by calling the `delegateAddress` function from the ERC1538Query interface if it is implemented. This function takes a function signature as an argument and returns the delegate contract address where it is implemented. - -### Best Practices, Tools and More Information - -> More information, tools, tutorials and best practices concerning transparent contracts need to be developed and published. - -Below is a growing list of articles concerning transparent contracts and their use. If you have an article about transparent contracts you would like to share then please submit a comment to this issue about it to get it added. - -[ERC1538: Future Proofing Smart Contracts and Tokens](https://coinjournal.net/erc1538-future-proofing-smart-contacts-and-tokens/) - -[The ERC1538 improving towards the “transparent contract” standard](https://www.crypto-economy.net/en/ethereum-eth-erc1538-transparent-contract-standard/) - -### Inspiration - -This standard was inspired by ZeppelinOS's implementation of [Upgradeability with vtables](https://github.com/zeppelinos/labs/tree/master/upgradeability_with_vtable). - -This standard was also inspired by the design and implementation of the [Mokens contract](https://etherscan.io/address/0xc1eab49cf9d2e23e43bcf23b36b2be14fc2f8838#code) from the [Mokens project](https://github.com/Mokens/MIPs/blob/master/MIPS/mip-2-Goals-and-Objectives.md). The Mokens contract has been [upgraded to implement this standard](https://etherscan.io/address/0x0ac5637fe62ec14fd9e237a81a9679d4adef701f#code). - - -## Backwards Compatibility - -This standard makes a contract compatible with future standards and functionality because new functions can be added and existing functions can be replaced or removed. - -This standard future proofs a contract. - -## Implementation - -A reference implementation of this standard is given in the [transparent-contracts-erc1538](https://github.com/mudgen/transparent-contracts-erc1538) repository. - - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1538.md diff --git a/EIPS/eip-155.md b/EIPS/eip-155.md index 11efe541c5dc3a..17024fa653e75d 100644 --- a/EIPS/eip-155.md +++ b/EIPS/eip-155.md @@ -9,7 +9,7 @@ created: 2016-10-14 --- ### Hard fork -[Spurious Dragon](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-607.md) +[Spurious Dragon](./eip-607.md) ### Parameters - `FORK_BLKNUM`: 2,675,000 @@ -17,7 +17,9 @@ created: 2016-10-14 ### Specification -If `block.number >= FORK_BLKNUM` and `v = CHAIN_ID * 2 + 35` or `v = CHAIN_ID * 2 + 36`, then when computing the hash of a transaction for purposes of signing or recovering, instead of hashing only the first six elements (i.e. nonce, gasprice, startgas, to, value, data), hash nine elements, with `v` replaced by `CHAIN_ID`, `r = 0` and `s = 0`. The currently existing signature scheme using `v = 27` and `v = 28` remains valid and continues to operate under the same rules as it does now. +If `block.number >= FORK_BLKNUM` and `CHAIN_ID` is available, then when computing the hash of a transaction for the purposes of signing, instead of hashing only six rlp encoded elements `(nonce, gasprice, startgas, to, value, data)`, you **SHOULD** hash nine rlp encoded elements `(nonce, gasprice, startgas, to, value, data, chainid, 0, 0)`. If you do, then the `v` of the signature **MUST** be set to `{0,1} + CHAIN_ID * 2 + 35` where `{0,1}` is the parity of the `y` value of the curve point for which `r` is the x-value in the secp256k1 signing process. If you choose to only hash 6 values, then `v` continues to be set to `{0,1} + 27` as previously. + +If `block.number >= FORK_BLKNUM` and `v = CHAIN_ID * 2 + 35` or `v = CHAIN_ID * 2 + 36`, then when computing the hash of a transaction for purposes of recovering, instead of hashing six rlp encoded elements `(nonce, gasprice, startgas, to, value, data)`, hash nine rlp encoded elements `(nonce, gasprice, startgas, to, value, data, chainid, 0, 0)`. The currently existing signature scheme using `v = 27` and `v = 28` remains valid and continues to operate under the same rules as it did previously. ### Example @@ -65,4 +67,4 @@ This would provide a way to send transactions that work on Ethereum without work | 1337 | Geth private chains (default) | -Find more chain ID's on [chainid.network](https://chainid.network) and contribute to [ethereum-lists/chains](https://github.com/ethereum-lists/chains). \ No newline at end of file +Find more chain ID's on [chainid.network](https://chainid.network) and contribute to [ethereum-lists/chains](https://github.com/ethereum-lists/chains). diff --git a/EIPS/eip-1559.md b/EIPS/eip-1559.md index 4dec83e889355e..26a5b739e1661f 100644 --- a/EIPS/eip-1559.md +++ b/EIPS/eip-1559.md @@ -1,74 +1,329 @@ --- eip: 1559 title: Fee market change for ETH 1.0 chain -author: Vitalik Buterin (@vbuterin), Eric Conner (@econoar) +author: Vitalik Buterin (@vbuterin), Eric Conner (@econoar), Rick Dudley (@AFDudley), Matthew Slipper (@mslipper), Ian Norden (@i-norden), Abdelhamid Bakhta (@abdelhamidbakhta) discussions-to: https://ethereum-magicians.org/t/eip-1559-fee-market-change-for-eth-1-0-chain/2783 -status: Draft +status: Final type: Standards Track category: Core created: 2019-04-13 +requires: 2718, 2930 --- - - ## Simple Summary - -The current "first price auction" fee model in Ethereum is inefficient and needlessly costly to users. This EIP proposes a way to replace this with a mechanism that adjusts a base network fee based on network demand, creating better fee price efficiency and reducing the complexity of client software needed to avoid paying unnecessarily high fees. +A transaction pricing mechanism that includes fixed-per-block network fee that is burned and dynamically expands/contracts block sizes to deal with transient congestion. ## Abstract - -There is a BASEFEE value in protocol, which can move up or down by a maximum of 1/8 in each block; initially, miners adjust this value to target an average gas usage of 8 million, increasing BASEFEE if usage is higher and decreasing it if usage is lower. Transaction senders specify their fees by providing two values: - -* A "premium" gasprice which gets added onto the BASEFEE gasprice, which can either be set to a fairly low value (eg. 1 gwei) to compensate miners for uncle rate risk or to a high value to compete during sudden bursts of activity. The BASEFEE gets burned, the premium is given to the miner. +We introduce a new [EIP-2718](./eip-2718.md) transaction type, with the format `0x02 || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list, signature_y_parity, signature_r, signature_s])`. -* A "cap" which represents the maximum total that the transaction sender would be willing to pay to get included. +There is a base fee per gas in protocol, which can move up or down each block according to a formula which is a function of gas used in parent block and gas target (block gas limit divided by elasticity multiplier) of parent block. +The algorithm results in the base fee per gas increasing when blocks are above the gas target, and decreasing when blocks are below the gas target. +The base fee per gas is burned. +Transactions specify the maximum fee per gas they are willing to give to miners to incentivize them to include their transaction (aka: priority fee). +Transactions also specify the maximum fee per gas they are willing to pay total (aka: max fee), which covers both the priority fee and the block's network fee per gas (aka: base fee). +Senders will always pay the base fee per gas of the block their transaction was included in, and they will pay the priority fee per gas set in the transaction, as long as the combined amount of the two fees doesn't exceed the transaction's maximum fee per gas. ## Motivation - -Ethereum currently prices transaction fees using a simple auction mechanism, where users send transactions with bids ("gasprices") and miners choose transactions with the highest bids, and transactions that get included pay the bid that they specify. This leads to several large sources of inefficiency: +Ethereum historically priced transaction fees using a simple auction mechanism, where users send transactions with bids ("gasprices") and miners choose transactions with the highest bids, and transactions that get included pay the bid that they specify. This leads to several large sources of inefficiency: -* **Mismatch between volatility of transaction fee levels and social cost of transactions**: transaction fees on mature public blockchains, that have enough usage so that blocks are full, tend to be extremely volatile. On Ethereum, minimum fees are typically around 2 gwei (10^9 gwei = 1 ETH), but sometimes go up to 20-50 gwei and have even on one occasion gone up to over 200 gwei: https://etherscan.io/chart/gasprice. This clearly creates many inefficiencies, because it's absurd to suggest that the cost incurred by the network from accepting one more transaction into a block actually is 100x more when gas prices are 200 gwei than when they are 2 gwei; in both cases, it's a difference between 8 million gas and 8.02 million gas. +* **Mismatch between volatility of transaction fee levels and social cost of transactions**: bids to include transactions on mature public blockchains, that have enough usage so that blocks are full, tend to be extremely volatile. It's absurd to suggest that the cost incurred by the network from accepting one more transaction into a block actually is 10x more when the cost per gas is 10 nanoeth compared to when the cost per gas is 1 nanoeth; in both cases, it's a difference between 8 million gas and 8.02 million gas. * **Needless delays for users**: because of the hard per-block gas limit coupled with natural volatility in transaction volume, transactions often wait for several blocks before getting included, but this is socially unproductive; no one significantly gains from the fact that there is no "slack" mechanism that allows one block to be bigger and the next block to be smaller to meet block-by-block differences in demand. -* **Inefficiencies of first price auctions**: see https://ethresear.ch/t/first-and-second-price-auctions-and-improved-transaction-fee-markets/2410 for a detailed writeup. In short, the current approach, where transaction senders publish a transaction with a fee, miners choose the highest-paying transactions, and everyone pays what they bid, is well-known in mechanism design literature to be highly inefficient, and so complex fee estimation algorithms are required, and even these algorithms often end up not working very well, leading to frequent fee overpayment. See also https://blog.bitgo.com/the-challenges-of-bitcoin-transaction-fee-estimation-e47a64a61c72 for a Bitcoin core developer's description of the challenges involved in fee estimation in the status quo. -* **Instability of blockchains with no block reward**: in the long run, blockchains where there is no issuance (including Bitcoin and Zcash) at present intend to switch to rewarding miners entirely through transaction fees. However, there are [known results](http://randomwalker.info/publications/mining_CCS.pdf) showing that this likely leads to a lot of instability, incentivizing mining "sister blocks" that steal transaction fees, opening up much stronger selfish mining attack vectors, and more. There is at present no good mitigation for this. - -The proposal in this EIP is to start with a BASEFEE amount which is adjusted up and down by the protocol based on how congested the network is. To accommodate this system, the network capacity would be increased to 16 million gas, so that 50% utilization matches up with our current 8 million gas limit. Then, when the network is at >50% capacity, the BASEFEE increments up slightly and when capacity is at <50%, it decrements down slightly. Because these increments are constrained, the maximum difference in BASEFEE from block to block is predictable. This then allows wallets to auto-set the gas fees for users in a highly reliable fashion. It is expected that most users will not have to manually adjust gas fees, even in periods of high network activity. For most users, the BASEFEE will be automatically set by their wallet, along with the addition of a small fixed amount, called a ‘tip’, to compensate miners (e.g. 0.5 gwei). +* **Inefficiencies of first price auctions**: The current approach, where transaction senders publish a transaction with a bid a maximum fee, miners choose the highest-paying transactions, and everyone pays what they bid. This is well-known in mechanism design literature to be highly inefficient, and so complex fee estimation algorithms are required. But even these algorithms often end up not working very well, leading to frequent fee overpayment. +* **Instability of blockchains with no block reward**: In the long run, blockchains where there is no issuance (including Bitcoin and Zcash) at present intend to switch to rewarding miners entirely through transaction fees. However, there are known issues with this that likely leads to a lot of instability, incentivizing mining "sister blocks" that steal transaction fees, opening up much stronger selfish mining attack vectors, and more. There is at present no good mitigation for this. -An important aspect of this upgraded fee system is that miners only get to keep the tips. The BASEFEE is always burned (i.e. it is destroyed by the protocol). Burning this is important because it prevents miners from manipulating the fee in order to extract more fees from users. It also ensures that only ETH can ever be used to pay for transactions on Ethereum, cementing the economic value of ETH within the Ethereum platform. +The proposal in this EIP is to start with a base fee amount which is adjusted up and down by the protocol based on how congested the network is. When the network exceeds the target per-block gas usage, the base fee increases slightly and when capacity is below the target, it decreases slightly. Because these base fee changes are constrained, the maximum difference in base fee from block to block is predictable. This then allows wallets to auto-set the gas fees for users in a highly reliable fashion. It is expected that most users will not have to manually adjust gas fees, even in periods of high network activity. For most users the base fee will be estimated by their wallet and a small priority fee, which compensates miners taking on orphan risk (e.g. 1 nanoeth), will be automatically set. Users can also manually set the transaction max fee to bound their total costs. +An important aspect of this fee system is that miners only get to keep the priority fee. The base fee is always burned (i.e. it is destroyed by the protocol). This ensures that only ETH can ever be used to pay for transactions on Ethereum, cementing the economic value of ETH within the Ethereum platform and reducing risks associated with miner extractable value (MEV). Additionally, this burn counterbalances Ethereum inflation while still giving the block reward and priority fee to miners. Finally, ensuring the miner of a block does not receive the base fee is important because it removes miner incentive to manipulate the fee in order to extract more fees from users. ## Specification - -**Parameters** -* `FORK_BLKNUM`: TBD -* `BASEFEE_MAX_CHANGE_DENOMINATOR`: 8 -* `SLACK_COEFFICIENT`: 3 -* `TARGET_GASUSED`: 8,000,000 - - -**Proposal** -For all blocks where `block.number >= FORK_BLKNUM`: - -* Impose a hard in-protocol gas limit of `SLACK_COEFFICIENT * TARGET_GASUSED`, used instead of the gas limit calculated using the previously existing formulas -* Replace the `GASLIMIT` field in the block header with a BASEFEE field (the same field can be used) -* Let `PARENT_BASEFEE` be the parent block's `BASEFEE` (or 1 billion wei if `block.number == FORK_BLKNUM`). A valid `BASEFEE` is one such that `abs(BASEFEE - PARENT_BASEFEE) <= max(1, PARENT_BASEFEE // BASEFEE_MAX_CHANGE_DENOMINATOR)` -* Redefine the way the `tx.gasprice` field is used: define `tx.fee_premium = tx.gasprice // 2**128` and `tx.fee_cap = tx.gasprice % 2**128` -* During transaction execution, we calculate the cost to the `tx.origin` and the gain to the `block.coinbase` as follows: - * Let `gasprice = min(BASEFEE + tx.fee_premium, tx.fee_cap)`. The `tx.origin` initially pays `gasprice * tx.gas`, and gets refunded `gasprice * (tx.gas - gasused)`. - * The `block.coinbase` gains `(gasprice - BASEFEE) * gasused`. If `gasprice < BASEFEE` (due to the `fee_cap`), this means that the `block.coinbase` _loses_ funds from this operation; in this case, check that the post-balance is non-negative and throw an exception if it is negative. -As a default strategy, miners set `BASEFEE` as follows. Let `delta = block.gas_used - TARGET_GASUSED` (possibly negative). Set `BASEFEE = PARENT_BASEFEE + PARENT_BASEFEE * delta // TARGET_GASUSED // BASEFEE_MAX_CHANGE_DENOMINATOR`, clamping this result inside of the allowable bounds if needed (with the parameter setting above clamping will not be required). +Block validity is defined in the reference implementation below. +The `GASPRICE` (`0x3a`) opcode **MUST** return the `effective_gas_price` as defined in the reference implementation below. + +As of `FORK_BLOCK_NUMBER`, a new [EIP-2718](./eip-2718.md) transaction is introduced with `TransactionType` 2. + +The intrinsic cost of the new transaction is inherited from [EIP-2930](./eip-2930.md), specifically `21000 + 16 * non-zero calldata bytes + 4 * zero calldata bytes + 1900 * access list storage key count + 2400 * access list address count`. + +The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is `rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list, signature_y_parity, signature_r, signature_s])`. + +The `signature_y_parity, signature_r, signature_s` elements of this transaction represent a secp256k1 signature over `keccak256(0x02 || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list]))`. + +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. + +*Note: `//` is integer division, round down.* +```python +from typing import Union, Dict, Sequence, List, Tuple, Literal +from dataclasses import dataclass, field +from abc import ABC, abstractmethod + +@dataclass +class TransactionLegacy: + signer_nonce: int = 0 + gas_price: int = 0 + gas_limit: int = 0 + destination: int = 0 + amount: int = 0 + payload: bytes = bytes() + v: int = 0 + r: int = 0 + s: int = 0 + +@dataclass +class Transaction2930Payload: + chain_id: int = 0 + signer_nonce: int = 0 + gas_price: int = 0 + gas_limit: int = 0 + destination: int = 0 + amount: int = 0 + payload: bytes = bytes() + access_list: List[Tuple[int, List[int]]] = field(default_factory=list) + signature_y_parity: bool = False + signature_r: int = 0 + signature_s: int = 0 + +@dataclass +class Transaction2930Envelope: + type: Literal[1] = 1 + payload: Transaction2930Payload = Transaction2930Payload() + +@dataclass +class Transaction1559Payload: + chain_id: int = 0 + signer_nonce: int = 0 + max_priority_fee_per_gas: int = 0 + max_fee_per_gas: int = 0 + gas_limit: int = 0 + destination: int = 0 + amount: int = 0 + payload: bytes = bytes() + access_list: List[Tuple[int, List[int]]] = field(default_factory=list) + signature_y_parity: bool = False + signature_r: int = 0 + signature_s: int = 0 + +@dataclass +class Transaction1559Envelope: + type: Literal[2] = 2 + payload: Transaction1559Payload = Transaction1559Payload() + +Transaction2718 = Union[Transaction1559Envelope, Transaction2930Envelope] + +Transaction = Union[TransactionLegacy, Transaction2718] + +@dataclass +class NormalizedTransaction: + signer_address: int = 0 + signer_nonce: int = 0 + max_priority_fee_per_gas: int = 0 + max_fee_per_gas: int = 0 + gas_limit: int = 0 + destination: int = 0 + amount: int = 0 + payload: bytes = bytes() + access_list: List[Tuple[int, List[int]]] = field(default_factory=list) + +@dataclass +class Block: + parent_hash: int = 0 + uncle_hashes: Sequence[int] = field(default_factory=list) + author: int = 0 + state_root: int = 0 + transaction_root: int = 0 + transaction_receipt_root: int = 0 + logs_bloom: int = 0 + difficulty: int = 0 + number: int = 0 + gas_limit: int = 0 # note the gas_limit is the gas_target * ELASTICITY_MULTIPLIER + gas_used: int = 0 + timestamp: int = 0 + extra_data: bytes = bytes() + proof_of_work: int = 0 + nonce: int = 0 + base_fee_per_gas: int = 0 + +@dataclass +class Account: + address: int = 0 + nonce: int = 0 + balance: int = 0 + storage_root: int = 0 + code_hash: int = 0 + +INITIAL_BASE_FEE = 1000000000 +INITIAL_FORK_BLOCK_NUMBER = 10 # TBD +BASE_FEE_MAX_CHANGE_DENOMINATOR = 8 +ELASTICITY_MULTIPLIER = 2 + +class World(ABC): + def validate_block(self, block: Block) -> None: + parent_gas_target = self.parent(block).gas_limit // ELASTICITY_MULTIPLIER + parent_gas_limit = self.parent(block).gas_limit + + # on the fork block, don't account for the ELASTICITY_MULTIPLIER to avoid + # unduly halving the gas target. + if INITIAL_FORK_BLOCK_NUMBER == block.number: + parent_gas_target = self.parent(block).gas_limit + parent_gas_limit = self.parent(block).gas_limit * ELASTICITY_MULTIPLIER + + parent_base_fee_per_gas = self.parent(block).base_fee_per_gas + parent_gas_used = self.parent(block).gas_used + transactions = self.transactions(block) + + # check if the block used too much gas + assert block.gas_used <= block.gas_limit, 'invalid block: too much gas used' + + # check if the block changed the gas limit too much + assert block.gas_limit < parent_gas_limit + parent_gas_limit // 1024, 'invalid block: gas limit increased too much' + assert block.gas_limit > parent_gas_limit - parent_gas_limit // 1024, 'invalid block: gas limit decreased too much' + + # check if the gas limit is at least the minimum gas limit + assert block.gas_limit >= 5000 + + # check if the base fee is correct + if INITIAL_FORK_BLOCK_NUMBER == block.number: + expected_base_fee_per_gas = INITIAL_BASE_FEE + elif parent_gas_used == parent_gas_target: + expected_base_fee_per_gas = parent_base_fee_per_gas + elif parent_gas_used > parent_gas_target: + gas_used_delta = parent_gas_used - parent_gas_target + base_fee_per_gas_delta = max(parent_base_fee_per_gas * gas_used_delta // parent_gas_target // BASE_FEE_MAX_CHANGE_DENOMINATOR, 1) + expected_base_fee_per_gas = parent_base_fee_per_gas + base_fee_per_gas_delta + else: + gas_used_delta = parent_gas_target - parent_gas_used + base_fee_per_gas_delta = parent_base_fee_per_gas * gas_used_delta // parent_gas_target // BASE_FEE_MAX_CHANGE_DENOMINATOR + expected_base_fee_per_gas = parent_base_fee_per_gas - base_fee_per_gas_delta + assert expected_base_fee_per_gas == block.base_fee_per_gas, 'invalid block: base fee not correct' + + # execute transactions and do gas accounting + cumulative_transaction_gas_used = 0 + for unnormalized_transaction in transactions: + # Note: this validates transaction signature and chain ID which must happen before we normalize below since normalized transactions don't include signature or chain ID + signer_address = self.validate_and_recover_signer_address(unnormalized_transaction) + transaction = self.normalize_transaction(unnormalized_transaction, signer_address) + + signer = self.account(signer_address) + + signer.balance -= transaction.amount + assert signer.balance >= 0, 'invalid transaction: signer does not have enough ETH to cover attached value' + # the signer must be able to afford the transaction + assert signer.balance >= transaction.gas_limit * transaction.max_fee_per_gas + + # ensure that the user was willing to at least pay the base fee + assert transaction.max_fee_per_gas >= block.base_fee_per_gas + + # Prevent impossibly large numbers + assert transaction.max_fee_per_gas < 2**256 + # Prevent impossibly large numbers + assert transaction.max_priority_fee_per_gas < 2**256 + # The total must be the larger of the two + assert transaction.max_fee_per_gas >= transaction.max_priority_fee_per_gas + + # priority fee is capped because the base fee is filled first + priority_fee_per_gas = min(transaction.max_priority_fee_per_gas, transaction.max_fee_per_gas - block.base_fee_per_gas) + # signer pays both the priority fee and the base fee + effective_gas_price = priority_fee_per_gas + block.base_fee_per_gas + signer.balance -= transaction.gas_limit * effective_gas_price + assert signer.balance >= 0, 'invalid transaction: signer does not have enough ETH to cover gas' + gas_used = self.execute_transaction(transaction, effective_gas_price) + gas_refund = transaction.gas_limit - gas_used + cumulative_transaction_gas_used += gas_used + # signer gets refunded for unused gas + signer.balance += gas_refund * effective_gas_price + # miner only receives the priority fee; note that the base fee is not given to anyone (it is burned) + self.account(block.author).balance += gas_used * priority_fee_per_gas + + # check if the block spent too much gas transactions + assert cumulative_transaction_gas_used == block.gas_used, 'invalid block: gas_used does not equal total gas used in all transactions' + + # TODO: verify account balances match block's account balances (via state root comparison) + # TODO: validate the rest of the block + + def normalize_transaction(self, transaction: Transaction, signer_address: int) -> NormalizedTransaction: + # legacy transactions + if isinstance(transaction, TransactionLegacy): + return NormalizedTransaction( + signer_address = signer_address, + signer_nonce = transaction.signer_nonce, + gas_limit = transaction.gas_limit, + max_priority_fee_per_gas = transaction.gas_price, + max_fee_per_gas = transaction.gas_price, + destination = transaction.destination, + amount = transaction.amount, + payload = transaction.payload, + access_list = [], + ) + # 2930 transactions + elif isinstance(transaction, Transaction2930Envelope): + return NormalizedTransaction( + signer_address = signer_address, + signer_nonce = transaction.payload.signer_nonce, + gas_limit = transaction.payload.gas_limit, + max_priority_fee_per_gas = transaction.payload.gas_price, + max_fee_per_gas = transaction.payload.gas_price, + destination = transaction.payload.destination, + amount = transaction.payload.amount, + payload = transaction.payload.payload, + access_list = transaction.payload.access_list, + ) + # 1559 transactions + elif isinstance(transaction, Transaction1559Envelope): + return NormalizedTransaction( + signer_address = signer_address, + signer_nonce = transaction.payload.signer_nonce, + gas_limit = transaction.payload.gas_limit, + max_priority_fee_per_gas = transaction.payload.max_priority_fee_per_gas, + max_fee_per_gas = transaction.payload.max_fee_per_gas, + destination = transaction.payload.destination, + amount = transaction.payload.amount, + payload = transaction.payload.payload, + access_list = transaction.payload.access_list, + ) + else: + raise Exception('invalid transaction: unexpected number of items') + + @abstractmethod + def parent(self, block: Block) -> Block: pass + + @abstractmethod + def block_hash(self, block: Block) -> int: pass + + @abstractmethod + def transactions(self, block: Block) -> Sequence[Transaction]: pass + + # effective_gas_price is the value returned by the GASPRICE (0x3a) opcode + @abstractmethod + def execute_transaction(self, transaction: NormalizedTransaction, effective_gas_price: int) -> int: pass + + @abstractmethod + def validate_and_recover_signer_address(self, transaction: Transaction) -> int: pass + + @abstractmethod + def account(self, address: int) -> Account: pass +``` ## Backwards Compatibility -Transactions published before this EIP or by wallets that do not support this EIP will be interpreted by the above formulas as having a `fee_premium` of zero and a `fee_cap` of the fee that they submit. Provided that at least some miners are temporarily willing to be altruistic and accept zero-fee-premium transactions for a short period of time after the fork, this should not greatly affect usability. There is an invariant that a `gasprice` constructed "the old way" still constitutes an upper bound on the amount that a user will pay. +Legacy Ethereum transactions will still work and be included in blocks, but they will not benefit directly from the new pricing system. This is due to the fact that upgrading from legacy transactions to new transactions results in the legacy transaction's `gas_price ` entirely being consumed either by the `base_fee_per_gas` and the `priority_fee_per_gas`. + +### Block Hash Changing +The datastructure that is passed into keccak256 to calculate the block hash is changing, and all applications that are validating blocks are valid or using the block hash to verify block contents will need to be adapted to support the new datastructure (one additional item). If you only take the block header bytes and hash them you should still correctly get a hash, but if you construct a block header from its constituent elements you will need to add in the new one at the end. + +### GASPRICE +Previous to this change, `GASPRICE` represented both the ETH paid by the signer per gas for a transaction as well as the ETH received by the miner per gas. As of this change, `GASPRICE` now only represents the amount of ETH paid by the signer per gas, and the amount a miner was paid for the transaction is no longer accessible directly in the EVM. +## Security Considerations +### Increased Max Block Size/Complexity +This EIP will increase the maximum block size, which could cause problems if miners are unable to process a block fast enough as it will force them to mine an empty block. Over time, the average block size should remain about the same as without this EIP, so this is only an issue for short term size bursts. It is possible that one or more clients may handle short term size bursts poorly and error (such as out of memory or similar) and client implementations should make sure their clients can appropriately handle individual blocks up to max size. -## Test Cases - +### Transaction Ordering +With most people not competing on priority fees and instead using a baseline fee to get included, transaction ordering now depends on individual client internal implementation details such as how they store the transactions in memory. It is recommended that transactions with the same priority fee be sorted by time the transaction was received to protect the network from spamming attacks where the attacker throws a bunch of transactions into the pending pool in order to ensure that at least one lands in a favorable position. Miners should still prefer higher gas premium transactions over those with a lower gas premium, purely from a selfish mining perspective. +### Miners Mining Empty Blocks +It is possible that miners will mine empty blocks until such time as the base fee is very low and then proceed to mine half full blocks and revert to sorting transactions by the priority fee. While this attack is possible, it is not a particularly stable equilibrium as long as mining is decentralized. Any defector from this strategy will be more profitable than a miner participating in the attack for as long as the attack continues (even after the base fee reached 0). Since any miner can anonymously defect from a cartel, and there is no way to prove that a particular miner defected, the only feasible way to execute this attack would be to control 50% or more of hashing power. If an attacker had exactly 50% of hashing power, they would make no Ether from priority fee while defectors would make double the Ether from priority fees. For an attacker to turn a profit, they need to have some amount over 50% hashing power, which means they can instead execute double spend attacks or simply ignore any other miners which is a far more profitable strategy. -## Implementation - +Should a miner attempt to execute this attack, we can simply increase the elasticity multiplier (currently 2x) which requires they have even more hashing power available before the attack can even be theoretically profitable against defectors. +### ETH Burn Precludes Fixed Supply +By burning the base fee, we can no longer guarantee a fixed Ether supply. This could result in economic instability as the long term supply of ETH will no longer be constant over time. While a valid concern, it is difficult to quantify how much of an impact this will have. If more is burned on base fee than is generated in mining rewards then ETH will be deflationary and if more is generated in mining rewards than is burned then ETH will be inflationary. Since we cannot control user demand for block space, we cannot assert at the moment whether ETH will end up inflationary or deflationary, so this change causes the core developers to lose some control over Ether's long term quantity. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1571.md b/EIPS/eip-1571.md index 942d0e359bbcc4..3d0f998860eeef 100644 --- a/EIPS/eip-1571.md +++ b/EIPS/eip-1571.md @@ -1,24 +1,26 @@ --- eip: 1571 title: EthereumStratum/2.0.0 -author: Andrea Lanfranchi (@AndreaLanfranchi) , Pawel Bylica (@chfast) , Marius Van Der Wijden (@MariusVanDerWijden) +author: Andrea Lanfranchi (@AndreaLanfranchi), Pawel Bylica (@chfast), Marius Van Der Wijden (@MariusVanDerWijden) discussions-to: https://github.com/AndreaLanfranchi/EthereumStratum-2.0.0/issues -status: Draft +status: Stagnant type: Standards Track -category: Networking +category: Interface created: 2018-11-09 --- -# EthereumStratum/2.0.0 - Implementation proposal guide lines ## Abstract + This draft contains the guidelines to define a new standard for the Stratum protocol used by Ethereum miners to communicate with mining pool servers. ### Conventions + The key words `MUST`, `MUST NOT`, `REQUIRED`, `SHALL`, `SHALL NOT`, `SHOULD`, `SHOULD NOT`, `RECOMMENDED`, `MAY`, and `OPTIONAL` in this document are to be interpreted as described in [RFC 2119](https://tools.ietf.org/html/rfc2119). The definition `mining pool server`, and it's plural form, is to be interpreted as `work provider` and later in this document can be shortened as `pool` or `server`. The definition `miner(s)`, and it's plural form, is to be interpreted as `work receiver/processor` and later in this document can be shortened as `miner` or `client`. ### Rationale + Ethereum does not have an official Stratum implementation yet. It officially supports only getWork which requires miners to constantly pool the work provider. Only recently go-ethereum have implemented a [push mechanism](https://github.com/ethereum/go-ethereum/pull/17347) to notify clients for mining work, but whereas the vast majority of miners do not run a node, it's main purpose is to facilitate mining pools rather than miners. The Stratum protocol on the other hand relies on a standard stateful TCP connection which allows two-way exchange of line-based messages. Each line contains the string representation of a JSON object following the rules of either [JSON-RPC 1.0](https://www.jsonrpc.org/specification_v1) or [JSON-RPC 2.0](https://www.jsonrpc.org/specification). Unfortunately, in absence of a well defined standard, various flavours of Stratum have bloomed for Ethereum mining as a derivative work for different mining pools implementations. The only attempt to define a standard was made by NiceHash with their [EthereumStratum/1.0.0](https://github.com/nicehash/Specifications/blob/master/EthereumStratum_NiceHash_v1.0.0.txt) implementation which is the main source this work inspires from. @@ -26,36 +28,43 @@ Mining activity, thus the interaction among pools and miners, is at it's basics Due to the simplicity of the subject, the proponent, means to stick with JSON formatted objects rather than investigating more verbose solutions, like for example [Google's Protocol Buffers](https://developers.google.com/protocol-buffers/docs/overview) which carry the load of strict object definition. ### Stratum design flaws + The main Stratum design flaw is the absence of a well defined standard. This implies that miners (and mining software developers) have to struggle with different flavours which make their life hard when switching from one pool to another or even when trying to "guess" which is the flavour implemented by a single pool. Moreover all implementations still suffer from an excessive verbosity for a chain with a very small block time like Ethereum. A few numbers may help understand. A normal `mining.notify` message weigh roughly 240 bytes: assuming the dispatch of 1 work per block to an audience of 50k connected TCP sockets means the transmission of roughly 1.88TB of data a month. And this can be an issue for large pools. But if we see the same figures the other way round, from a miner's perspective, we totally understand how mining decentralization is heavily affected by the quality of internet connections. ### Sources of inspiration + - [NiceHash EthereumStratum/1.0.0](https://github.com/nicehash/Specifications/blob/master/EthereumStratum_NiceHash_v1.0.0.txt) - [Zcash variant of the Stratum protocol](https://github.com/zcash/zips/blob/23d74b0373c824dd51c7854c0e3ea22489ba1b76/drafts/str4d-stratum/draft1.rst#json-rpc-1-0) ## Specification + The Stratum protocol is an instance of [JSON-RPC-2.0](https://www.jsonrpc.org/specification). The miner is a JSON-RPC client, and the server is a JSON-RPC server. All communications exist within the scope of a `session`. A session starts at the moment a client opens a TCP connection to the server till the moment either party do voluntary close the very same connection or it gets broken. Servers **MAY** support session resuming if this is initially negotiated (on first session handshaking) between the client and the server. During a session all messages exchanged among server and client are line-based which means all messages are JSON strings terminated by ASCII LF character (which may also be denoted as `\n` in this document). The LF character **MUST NOT** appear elsewhere in a message. Client and server implementations **MUST** assume that once they read a LF character, the current message has been completely received and can be processed. -Line messages are of three types : +Line messages are of three types: + - `Requests` : messages for which the issuer expects a response. The receiver **MUST** reply back to any request individually - `Responses` : solicited messages by a previous request. The responder **MUST** label the response with the same identifier of the originating request. -- `Notifications` : unsolicited messages for which the issuer is not interested nor is expecting a response. Nevertheless a response (eg. an aknowledgement) **MAY** be sent by the receiver. +- `Notifications` : unsolicited messages for which the issuer is not interested nor is expecting a response. Nevertheless a response (eg. an acknowledgement) **MAY** be sent by the receiver. During a `session` both parties **CAN** exchange messages of the above depicted three types. ### JSON-RPC-2.0 Compliances -As per [JSON-RPC-2.0](https://www.jsonrpc.org/specification) specification requests and responses differ from notifications by the identifier (`id`) member in the JSON object: +As per [JSON-RPC-2.0](https://www.jsonrpc.org/specification) specification requests and responses differ from notifications by the identifier (`id`) member in the JSON object: + - Requests **MUST** have an `id` member - Responses **MUST** have an `id` member valued exactly as the `id` member of the request this response is for - Notifications **MUST NOT** have an `id` member ### JSON-RPC-2.0 Defiances -In order to get the most concise messages among parties of a session/conversation this implementation enforces the following defiances : +In order to get the most concise messages among parties of a session/conversation this implementation enforces the following defiances: + - JSON member `jsonrpc` (always valued to "2.0") **MUST ALWAYS BE OMITTED** - JSON member `id` **MUST NOT** be `null`. When member is present, mandatorily in requests and responses, it **MUST** be valued to an integer Number ranging from 0 to 65535. Please note that a message with `"id": 0` **MUST NOT** be interpreted as a notification: it's a request with identifier 0 - JSON member `id` **MUST** be only of type primitive number. The removal of other identifier types (namely strings) is due to the need to reduce the number of bytes transferred. ## Conventions + - The representation of a JSON object is, at it's base, a string - The conversation among the client and the server is made of strings. Each string ending with a LF (ASCII char 10) denotes a `line`. Each line **MUST** contain only one JSON root object. Eventually the root object **MAY** contain additional JSON objects in it's members. - Aside the `LF` delimiter each `line` **MUST** be made of printable ASCII chars in the range 32..126 @@ -71,35 +80,45 @@ In order to get the most concise messages among parties of a session/conversatio - Numbers : any non-fractional number **MUST** be transferred by it's hexadecimal representation ### Requests + The JSON representation of `request` object is made of these parts: + - mandatory `id` member of type Integer : the identifier established by the issuer - mandatory `method` member of type String : the name of the method to be invoked on the receiver side - optional `params` member : in case the method invocation on the receiver side requires the application of additional parameters to be executed. The type **CAN** be Object (with named members of different types) or Array of single type. In case of an array the parameters will be applied by their ordinal position. If the method requested for invocation on the receiver side does not require the application of additional parameters this member **MUST NOT** be present. The notation `"params" : null` **IS NOT PERMITTED** ### Responses + The JSON representation of `response` object is made of these parts: + - mandatory `id` member of type Integer : the identifier of the request this response corresponds to - optional `error` member : whether an error occurred during the parsing of the method or during it's execution this member **MUST** be present and valued. If no errors occurred this member **MUST NOT** be present. For a detailed structure of the `error` member see below. - optional `result` member : This has to be set, if the corresponding request requires a result from the user. If no errors occurred by invoking the corresponding function, this member **MUST** be present even if one or more information are null. The type can be of Object or single type Array or Primitive string/number. If no data is meant back for the issuer (the method is void on the receiver) or an error occurred this member **MUST NOT** be present. -You'll notice here some differences with standard JSON-RPC-2.0. Namely the result member is not always required. Basically a response like this : +You'll notice here some differences with standard JSON-RPC-2.0. Namely the result member is not always required. Basically a response like this: + ```json {"id": 2} ``` + means "request received and processed correctly with no data to send back". To better clarify the concept and clear the field of free interpretations let's take another example of **wrong response** + ```json {"id": 2, "result": false} ``` -This response syntax leaves room to many interpretations : is it an error ? is `false` the legit response value to the issued request ? + +This response syntax leaves room to many interpretations: is it an error? is `false` the legit response value to the issued request? For this reason responses, we reiterate, **MUST BE** of two types: + - success responses : no error occurred during the processing, the request was legit, syntactically correct, and the receiver had no issues processing it. This kind of responses **MUST NOT** have the `error` member and **MAY** have the `result` member if a value is expected back to the issuer. - failure responses : something wrong with the request, it's syntax, it's validity scope, or server processing problems. This kind of responses **MUST HAVE** the `error` member and **MAY** have the `result` member. The latter deserves a better explanation: failure responses can be distinguished by a severity degree. -Example 1 : a client submits a solution and server rejects it cause it's not below target. Server **MUST** respond like this +Example 1 : a client submits a solution and server rejects it cause it's not below target. Server **MUST** respond like this; + ```json { "id": 31, @@ -109,7 +128,9 @@ Example 1 : a client submits a solution and server rejects it cause it's not bel } } ``` -Example 2 : a client submits a solution and server **accepts** it **but** it accounts the share as stale. Server **MUST** respond like this + +Example 2 : a client submits a solution and server **accepts** it **but** it accounts the share as stale. Server **MUST** respond like this; + ```json { "id": 31, @@ -119,7 +140,9 @@ Example 2 : a client submits a solution and server **accepts** it **but** it acc } } ``` -Example 3 : a client submits an authorization request specifying an invalid workername. Server authorizes the account but rejects worker name. Server **MUST** respond like this + +Example 3 : a client submits an authorization request specifying an invalid workername. Server authorizes the account but rejects worker name. Server **MUST** respond like this; + ```json { "id": 1, @@ -141,15 +164,19 @@ Using proper error codes pools may properly inform miners of the condition of th - Error codes 5xx : server could not process the request due to internal errors ### Notifications + A notification message has the very same representation of a `request` with the only difference the `id` member **MUST NOT** be present. This means the issuer is not interested nor expects any response to this message. It's up to the receiver to take actions accordingly. For instance the receiver **MAY** decide to execute the method, or, in case of errors or methods not allowed, drop the connection thus closing the session. #### Error member + As seen above a `response` **MAY** contain an `error` member. When present this member **MUST** be an Object with: + - mandatory member `code` : a Number which identifies the error occurred - mandatory member `message` : a short human readable sentence describing the error occurred - optional member `data` : a Structured or Primitive value that contains additional information about the error. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.). ## Protocol Flow + - Client starts session by opening a TCP socket to the server - Client advertises and request protocol compatibility - Server confirms compatibility and declares ready @@ -167,6 +194,7 @@ As seen above a `response` **MAY** contain an `error` member. When present this - Eventually either party closes session and TCP connection ### Session Handling - Hello + ~~One of the worst annoyances until now is that server, at the very moment of socket connection, does not provide any useful information about the stratum flavour implemented. This means the client has to start a conversation by iteratively trying to connect via different protocol flavours. This proposal amends the situation making mandatory for the server to advertise itself to the client. When a new client connects to the server, the server **MUST** send a `mining.hello` notification :~~ @@ -186,7 +214,9 @@ For this reason the duty of first advertisement is kept on client which will iss } } ``` + The `params` member object has these mandatory members: + - `agent` (string) the mining software version - `host` (string) the host name of the server this client is willing to connect to - `port` (hex) the port number of the server this client is willing to connect to @@ -195,6 +225,7 @@ The `params` member object has these mandatory members: The rationale behind sending host and port is it enables virtual hosting, where virtual pools or private URLs might be used for DDoS protection, but that are aggregated on Stratum server backends. As with HTTP, the server CANNOT trust the host string. The port is included separately to parallel the client.reconnect method (see below). If the server is prepared to start/resume a session with such requirements it **MUST** reply back with a response like this: + ```json { "id" : 0, @@ -209,7 +240,9 @@ If the server is prepared to start/resume a session with such requirements it ** } } ``` + Where the `result` is an object made of 5 mandatory members + - `proto` (string) which **MUST** match the exact version requested by the client - `encoding` (string) which value states whether or not all **next messages** should be gzip compressed or not. Possible values are "gzip" or "plain" - `resume` (hex) which value states whether or not the host can resume a previously created session; @@ -223,6 +256,7 @@ Should the server, after this reply, receive other messages as plain text, it ** Eventually the client will continue with `mining.subscribe` (further on descripted) Otherwise, in case of errors or rejection to start the conversation, the server **MAY** reply back with an error giving the other party useful information or, at server's maintainers discretion, abruptly close the connection. + ```json { "id" : 0, @@ -233,7 +267,9 @@ Otherwise, in case of errors or rejection to start the conversation, the server } } ``` + or + ```json { "id" : 0, @@ -244,22 +280,28 @@ or } } ``` + _The above two JSON error values are only samples_ Eventually the server will close the connection. -Why a pool should advertise the node's version ? It's a matter of transparency : miners should know whether or not pool have upgraded to latest patches/releases for node's software. +Why a pool should advertise the node's version? It's a matter of transparency : miners should know whether or not pool have upgraded to latest patches/releases for node's software. ### Session Handling - Bye + Disconnection are not gracefully handled in Stratum. Client disconnections from pool may be due to several errors and this leads to waste of TCP sockets on server's side which wait for keepalive timeouts to trigger. A useful notification is `mining.bye` which, once processed, allows both parties of the session to stop receiving and gracefully close TCP connections + ```json { "method": "mining.bye" } ``` + The party receiving this message aknowledges the other party wants to stop the conversation and closes the socket. The issuer will close too. The explicit issuance of this notification implies the session gets abandoned so no session resuming will be possible even on server which support session-resuming. Client reconnecting to the same server which implements session resuming **SHOULD** expect a new session id and **MUST** re-authorize all their workers. ### Session Handling - Session Subscription + After receiving the response to `mining.hello` from server, the client, in case the server does support session resuming **MAY** request to resume a previously interrupted session with `mining.subscribe` request: + ```json { "id": 1, @@ -267,9 +309,11 @@ After receiving the response to `mining.hello` from server, the client, in case "params": "s-12345" } ``` + where `params` is the id of the session the client wants to resume. Otherwise, if client wants to start a new session **OR** server does not support session resuming, the request of subscription **MUST** omit the `params` member: + ```json { "id": 1, @@ -278,19 +322,24 @@ Otherwise, if client wants to start a new session **OR** server does not support ``` ### Session Handling - Response to Subscription + A server receiving a client session subscription **MUST** reply back with + ```json { "id": 1, "result": "s-12345" } ``` + A server receiving a subscription request with `params` being a string holding the session id. This cases may apply + - If session resuming is not supported `result` will hold a new session Id which **MUST** be a different value from the `session` member issued by client in previous `mining.subscribe` method - If session resuming is supported it will retrieve working values from cache and `result` will have the same id requested by the client. This means a session is "resumed": as a consequence the server **CAN** start pushing jobs omitting to precede them with `mining.set` (see below) and the client **MUST** continue to use values lastly received within the same session scope. In addition the client **CAN** omit to re-authorize all it's workers. - If session resuming is supported but the requested session has expired or it's cache values have been purged `result` will hold a new session Id which **MUST** be a different value from the `session` member issued by client in previous `mining.subscribe` method. As a consequence the server **MUST** wait for client to request authorization for it's workers and **MUST** send `mining.set` values before pushing jobs. The client **MUST** prepare for a new session discarding all previously cached values (if any). -A server implementing session-resuming **MUST** cache : +A server implementing session-resuming **MUST** cache: + - The session Ids - Any active job per session - The extraNonce @@ -301,16 +350,21 @@ Servers **MAY** drop entries from the cache on their own schedule. It's up to se A client which successfully subscribes and resumes session (the `session` value in server response is identical to `session` value requested by client on `mining.subscribe`) **CAN** omit to issue the authorization request for it's workers. ### Session Handling - Noop + There are cases when a miner struggles to find a solution in a reasonable time so it may trigger the timeout imposed by the server in case of no communications (the server, in fact, may think the client got disconnected). To mitigate the problem a new method `mining.noop`(with no additional parameters) may be requested by the client. + ```json { "id": 50, "method": "mining.noop" } ``` + ### Session Handling - Reconnect + Under certain circumstances the server may need to free some resources and or to relocate miners to another machine. Until now the only option for servers was to abruptly close the connection. On the miner's side this action is interpreted as a server malfunction and they, more often than not, switch to a failover pool. The implementation of the notification `mining.reconnect` helps client to better merge with logic of handling of large mining pools. + ```json { "method": "mining.reconnect", @@ -321,15 +375,18 @@ The implementation of the notification `mining.reconnect` helps client to better } } ``` + This notification is meant only from servers to clients. Should a server receive such a notification it will simply ignore it. After the notification has been properly sent, the server is ALLOWED to close the connection, while the client will take the proper actions to reconnect to the suggested end-point. -The `host` member in `params` object **SHOULD** report an host DNS name and not an IP address: TLS encrypted connections require to validate the CN name in the certificate which, 99% of the cases, is an host name. +The `host` member in `params` object **SHOULD** report a host DNS name and not an IP address: TLS encrypted connections require to validate the CN name in the certificate which, 99% of the cases, is a host name. The third member `resume` of the `params` object sets whether or not the receiving server is prepared for session resuming. After this notification has been issued by the server, the client should expect no further messages and **MUST** disconnect. ### Workers Authorization + The miner **MUST** authorize at least one worker in order to begin receiving jobs and submit solutions or hashrates. The miner **MAY** authorize multiple workers in the same session. The server **MUST** allow authorization for multiple workers within a session and **MUST** validate at least one authorization from the client before starting to send jobs. A `worker` is a tuple of the address where rewards must be credited coupled with identifier of the machine actually doing the work. For Ethereum the most common form is `.`. The same account can be bound to multiple machines. For pool's allowing anonymous mining the account is the address where rewards must be credited, while, for pools requiring registration, the account is the login name. Each time a solution is submitted by the client it must be labelled with the Worker identifier. It's up to server to keep the correct accounting for different addresses. The syntax for the authorization request is the following: + ```json { "id": 2, @@ -337,22 +394,27 @@ The syntax for the authorization request is the following: "params": ["[.]", "password"] } ``` + `params` member must be an Array of 2 string elements. For anonymous mining the "password" can be any string value or empty but not null. Pools allowing anonymous mining will simply ignore the value. The server **MUST** reply back either with an error or, in case of success, with + ```json { "id": 2, "result": "w-123" } ``` + Where the `result` member is a string which holds an unique - within the scope of the `session` - token which identifies the authorized worker. For every further request issued by the client, and related to a Worker action, the client **MUST** use the token given by the server in response to an `mining.authorize` request. This reduces the number of bytes transferred for solution and /or hashrate submission. If client is resuming a previous session it **CAN** omit the authorization request for it's workers and, in this case, **MUST** use the tokens assigned in the originating session. It's up to the server to keep the correct map between tokens and workers. The server receiving an authorization request where the credentials match previously authorized ones within the same session **MUST** reply back with the previously generated unique token. ### Prepare for mining + A lot of data is sent over the wire multiple times with useless redundancy. For instance the seed hash is meant to change only every 30000 blocks (roughly 5 days) while fixed-diff pools rarely change the work target. Moreover pools must optimize the search segments among miners trying to assign to every session a different "startNonce" (AKA extraNonce). For this purpose the `notification` method `mining.set` allows to set (on miner's side) only those params which change less frequently. The server will keep track of seed, target and extraNonce at session level and will push a notification `mining.set` whenever any (or all) of those values change to the connected miner. + ```json { "method": "mining.set", @@ -364,8 +426,10 @@ For this purpose the `notification` method `mining.set` allows to set (on miner' } } ``` + At the beginning of each `session` the server **MUST** send this notification before any `mining.notify`. All values passed by this notification will be valid for all **NEXT** jobs until a new `mining.set` notification overwrites them. Description of members is as follows: -- optional `epoch` (hex) : unlike all actual Stratum implementations the server should inform the client of the epoch number instead of passing the seed hash. This is enforced by two reasons : the main one is that client has only one way to compute the epoch number and this is by a linear search from epoch 0 iteratively trying increasing epochs till the hash matches the seed hash. Second reason is that epoch number is more concise than seed hash. In the end the seed hash is only transmitted to inform the client about the epoch and is not involved in the mining algorithm. + +- optional `epoch` (hex) : unlike all actual Stratum implementations the server should inform the client of the epoch number instead of passing the seed hash. This is enforced by two reasons: the main one is that client has only one way to compute the epoch number and this is by a linear search from epoch 0 iteratively trying increasing epochs till the hash matches the seed hash. Second reason is that epoch number is more concise than seed hash. In the end the seed hash is only transmitted to inform the client about the epoch and is not involved in the mining algorithm. - optional `target` (hex) : this is the boundary hash already adjusted for pool difficulty. Unlike in EthereumStratum/1.0.0, which provides a `mining.set_difficulty` notification of an _index of difficulty_, the proponent opt to pass directly the boundary hash. If omitted the client **MUST** assume a boundary of `"0x00000000ffff0000000000000000000000000000000000000000000000000000"` - optional `algo` (string) : the algorithm the miner is expected to mine on. If omitted the client **MUST** assume `"algo": "ethash"` - optional `extranonce` (hex) : a starting search segment nonce assigned by server to clients so they possibly do not overlap their search segments. If server wants to "cancel" a previously set extranonce it must pass this member valued as an empty string. @@ -384,7 +448,8 @@ If `extranonce` is valued to an empty string, or it's never been set within the Miners connected to a pool might likely process the very same nonces thus wasting a lot of duplicate jobs. A `nonce` is any valid number which, applied to algorithm and job specifications, produces a result which is below a certain target. For every job pushed by server to client(s) there are 2^64 possible nonces to test. -To be noted that : +To be noted that: + - Any nonce in the 2^64 has the very same possibility to be the right one. - A certain hashing job can be solved by more than one nonce @@ -397,25 +462,30 @@ Every "test" over a number is called a hash. Assuming a miner should receive a j This computation capacity is well beyond any miner on the market (including ASICs). For this reason single miners can process only small chunks (segments) of this humongous range. The way miners pick the segments to search on is beyond the scope of this work. Fact is as miners are not coordinated there is no knowledge - for a single miner - of segments picked by other miners. Extranonce concept is here to mitigate this possibility of duplicate jobs charging the server (the work provider) to give miners, at the maximum possible extent, different segments to search on. -Giving the above assumptions we can depict a nonce as any number in the hex range : +Giving the above assumptions we can depict a nonce as any number in the hex range: ``` Min 0x0000000000000000 Max 0xffffffffffffffff ``` + _the prefix 0x is voluntarily inserted here only to give a better visual representation_. -The `extranonce` is, at it's basics, the message of the server saying the client "_I give you the first number to start search from_". More in detail the `extranoce` is the leftmost part of that number. -Assume a pool notifies the client the usage of extranonce `ab5d` this means the client will see it's search segment narrowed as +The `extranonce` is, at it's basics, the message of the server saying the client "_I give you the first number to start search from_". More in detail the `extranonce` is the leftmost part of that number. +Assume a pool notifies the client the usage of extranonce `ab5d` this means the client will see it's search segment narrowed as + ``` Min 0xab5d000000000000 Max 0xab5dffffffffffff ``` + Pushing an extranonce of 4 bytes (like in the example) will give pool the possibility to separate segment 65535 different miners ( or if you prefer 0xffff miners ) while leaving the miner still a segment of 2^48 possible nonces to search on. Recalculating, as above, the computation capacity needed to search this segment we get + ``` ( 2^48 / 15 ) / 1T ~ 18.76 TeraHashes per second ``` + Which is still a wide segment where miners can randomly (or using other ergodic techniques) pick their internal search segments. Extranonce **MUST** be passed with all relevant bytes (no omission of left zeroes) for a specific reason. Assume an extranonce of "01ac" : it has the same decimal value of "1ac" but the number of bytes changes thus changing available search segment @@ -426,12 +496,15 @@ Extranonce **MUST** be passed with all relevant bytes (no omission of left zeroe Min 0x01ac000000000000 Min 0x1ac0000000000000 Max 0x01acffffffffffff Max 0x1acfffffffffffff ``` + As you can see resulting segments are quite different This all said pools (server), when making use of extranonce, **MUST** observe a maximum length of 6 bytes (hex). ### Jobs notification + When available server will dispatch jobs to connected miners issuing a `mining.notify` notification. + ```json { "method": "mining.notify", @@ -443,14 +516,18 @@ When available server will dispatch jobs to connected miners issuing a `mining.n ] } ``` + `params` member is made of 4 mandatory elements: + - 1st element is jobId as specified by pool. To reduce the amount of data sent over the wire pools **SHOULD** keep their job IDs as concise as possible. Pushing a Job id which is identical to headerhash is a bad practice and is highly discouraged. - 2nd element is the hex number of the block id - 3rd element is the headerhash. - 4th element is an hex boolean indicating whether or not eventually found shares from previous jobs will be accounted for sure as stale. ### Solution submission + When a miner finds a solution for a job he is mining on it sends a `mining.submit` request to server. + ```json { "id": 31, @@ -462,19 +539,23 @@ When a miner finds a solution for a job he is mining on it sends a `mining.submi ] } ``` + First element of `params` array is the jobId this solution refers to (as sent in the `mining.notify` message from the server). Second element is the `miner nonce` as hex. Third element is the token given to the worker previous `mining.authorize` request. Any `mining.submit` request bound to a worker which was not successfully authorized - i.e. the token does not exist in the session - **MUST** be rejected. -You'll notice in the sample above the `miner nonce` is only 12 bytes wide (should be 16). Why ? +You'll notice in the sample above the `miner nonce` is only 12 bytes wide (should be 16). Why? That's because in the previous `mining.set` the server has set an `extranonce` of `af4c`. This means the full nonce is `af4c68765fccd712` In presence of extranonce the miner **MUST** submit only the chars to append to the extranonce to build the final hex value. If no extranonce is set for the session or for the work the miner **MUST** send all 16 bytes. It's server duty to keep track of the tuples `job ids <-> extranonces` per session. When the server receives this request it either responds success using the short form + ```json {"id": 31} ``` + or, in case of any error or condition with a detailed error object + ```json { "id": 31, @@ -488,10 +569,13 @@ or, in case of any error or condition with a detailed error object Client **should** treat errors as "soft" errors (stales) or "hard" (bad nonce computation, job not found etc.). Errors in 5xx range are server errors and suggest the miner to abandon the connection and switch to a failover. ### Hashrate + Most pools offer statistic information, in form of graphs or by API calls, about the calculated hashrate expressed by the miner while miners like to compare this data with the hashrate they read on their devices. Communication about parties of these information have never been coded in Stratum and most pools adopt the method from getWork named `eth_submitHashrate`. In this document we propose an official implementation of the `mining.hashrate` request. This method behaves differently when issued from client or from server. + #### Client communicates it's hashrate to server. + ```json { "id" : 16, @@ -502,12 +586,16 @@ This method behaves differently when issued from client or from server. ] } ``` + where `params` is an array made of two elements: the first is a hexadecimal string representation (32 bytes) of the hashrate the miner reads on it's devices and the latter is the authorization token issued to worker this hashrate is refers to (see above for `mining.authorization`). Server **MUST** respond back with either an aknowledgment message + ```json {"id": 16 } ``` + Optionally the server can reply back reporting it's findings about calculated hashrate **for the same worker**. + ```json { "id": 16, @@ -517,7 +605,9 @@ Optionally the server can reply back reporting it's findings about calculated ha ] } ``` + In case of errors - for example when the client submits too frequently - with + ```json { "id": 16, @@ -527,8 +617,11 @@ In case of errors - for example when the client submits too frequently - with } } ``` + #### Server communicates hashrate to client + Optionally the server can **notify** client about it's overall performance (according to schedule set on server) with a `mining.hashrate` notification composed like this + ```json { "method": "mining.hashrate", @@ -540,7 +633,9 @@ Optionally the server can **notify** client about it's overall performance (acco } } ``` + Where `params` is an object which holds these members for values of the **whole session**: + - `interval` (number) the width, in minutes, of the observation window. "_in the last x minutes we calculated ..._" - `hr` (hex) representation of the hashrate the pool has calculated for the miner - `accepted` is an array of two number elements : the first is the overall count of accepted shares and the second is the number of stale shares. The array must be interpreted as "total accepted of which x are stale" @@ -549,4 +644,5 @@ Where `params` is an object which holds these members for values of the **whole The client will eventually take internal actions to reset/restart it's workers. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1577.md b/EIPS/eip-1577.md index bcd1467bae5567..97c2eae9470fb3 100644 --- a/EIPS/eip-1577.md +++ b/EIPS/eip-1577.md @@ -1,108 +1,7 @@ --- eip: 1577 -title: contenthash field for ENS -author: Dean Eigenmann , Nick Johnson -type: Standards Track category: ERC -status: Draft -created: 2018-11-13 +status: Moved --- -## Abstract - -This EIP introduces the new `contenthash` field for ENS resolvers, allowing for a better defined system of mapping names to network and content addresses. Additionally the `content` and `multihash` fields are deprecated. - -## Motivation - -Multiple applications including [Metamask](https://metamask.io/) and mobile clients such as [Status](https://status.im) have begun resolving ENS names to content hosted on distributed systems such as [IPFS](https://ipfs.io/) and [Swarm](https://swarm-guide.readthedocs.io). Due to the various ways content can be stored and addressed, a standard is required so these applications know how to resolve names and that domain owners know how their content will be resolved. - -The `contenthash` field allows for easy specification of network and content addresses in ENS. - -## Specification - -The field `contenthash` is introduced, which permits a wide range of protocols to be supported by ENS names. Resolvers supporting this field MUST return `true` when the `supportsInterface` function is called with argument `0xbc1c58d1`. - -The fields `content` and `multihash` are deprecated. - -The value returned by `contenthash` MUST be represented as a machine-readable [multicodec](https://github.com/multiformats/multicodec). The format is specified as follows: - -``` - -``` - -protoCodes and their meanings are specified in the [multiformats/multicodec](https://github.com/multiformats/multicodec) repository. - -The encoding of the value depends on the content type specified by the protoCode. Values with protocodes of 0xe3 and 0xe4 represent IPFS and Swarm content; these values are encoded as v1 [CIDs](https://github.com/multiformats/cid) without a base prefix, meaning their value is formatted as follows: - -``` - -``` - -When resolving a `contenthash`, applications MUST use the protocol code to determine what type of address is encoded, and resolve the address appropriately for that protocol, if supported. - -### Example - -#### IPFS - -Input data: - -``` -storage system: IPFS (0xe3) -CID version: 1 (0x01) -content type: dag-pb (0x70) -hash function: sha2-256 (0x12) -hash length: 32 bytes (0x20) -hash: 29f2d17be6139079dc48696d1f582a8530eb9805b561eda517e22a892c7e3f1f -``` - -Binary format: - -``` -0xe3010170122029f2d17be6139079dc48696d1f582a8530eb9805b561eda517e22a892c7e3f1f -``` - -Text format: - -``` -ipfs://QmRAQB6YaCyidP37UdDnjFY5vQuiBrcqdyoW1CuDgwxkD4 -``` - -### Swarm - -Input data: - -``` -storage system: Swarm (0xe4) -CID version: 1 (0x01) -content type: swarm-manifest (0xfa) -hash function: keccak256 (0x1b) -hash length: 32 bytes (0x20) -hash: d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -Binary format: -``` -0xe40101fa011b20d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -Text format: -``` -bzz://d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -Example usage with swarm hash: -``` -$ swarm hash ens contenthash d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -> e40101fa011b20d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -### Fallback - -In order to support names that have an IPFS or Swarm hash in their `content` field, a grace period MUST be implemented offering those name holders time to update their names. If a resolver does not support the `multihash` interface, it MUST be checked whether they support the `content` interface. If they do, the value of that field SHOULD be treated in a context dependent fashion and resolved. This condition MUST be enforced until at least March 31st, 2019. - -### Implementation - -To support `contenthash`, a new resolver has been developed and can be found [here](https://github.com/ensdomains/resolvers/blob/master/contracts/PublicResolver.sol), which has been deployed at [0xd3ddccdd3b25a8a7423b5bee360a42146eb4baf3](https://etherscan.io/address/0xd3ddccdd3b25a8a7423b5bee360a42146eb4baf3) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1577.md diff --git a/EIPS/eip-158.md b/EIPS/eip-158.md index 70dcb4c3564046..8267ce6361eded 100644 --- a/EIPS/eip-158.md +++ b/EIPS/eip-158.md @@ -1,19 +1,18 @@ --- eip: 158 title: State clearing -author: Vitalik Buterin +author: Vitalik Buterin (@vbuterin) type: Standards Track category: Core -status: Replaced +status: Final created: 2016-10-16 -superseded-by: 161 --- # Specification For all blocks where `block.number >= FORK_BLKNUM` (TBA): 1. In all cases where a state change is made to an account, and this state change results in the account state being saved with nonce = 0, balance = 0, code empty, storage empty (hereinafter "empty account"), the account is instead deleted. -2. If a address is "touched" and that address contains an empty account, then it is deleted. A "touch" is defined as any situation where if the account at the given address were nonexistent it would be created. +2. If an address is "touched" and that address contains an empty account, then it is deleted. A "touch" is defined as any situation where if the account at the given address were nonexistent it would be created. 3. Whenever the EVM checks if an account exists, emptiness is treated as equivalent to nonexistence. Particularly, note that this implies that, once this change is enabled, there is no longer a meaningful difference between emptiness and nonexistence from the point of view of EVM execution. 4. Zero-value calls and zero-value suicides no longer consume the 25000 account creation gas cost in any circumstance diff --git a/EIPS/eip-1581.md b/EIPS/eip-1581.md index e49d8e76f382dd..3dc95e93e5a2da 100644 --- a/EIPS/eip-1581.md +++ b/EIPS/eip-1581.md @@ -1,52 +1,7 @@ --- eip: 1581 -title: Non-wallet usage of keys derived from BIP-32 trees -author: Michele Balistreri (@bitgamma) -discussions-to: https://ethereum-magicians.org/t/non-wallet-usage-of-keys-derived-from-bip-32-trees/1817 -status: Draft -type: Standards Track category: ERC -created: 2018-11-13 +status: Moved --- -## Simple Summary -This EIP describes a derivation path structure for [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) wallets to be used for non-wallet keypairs. - -## Abstract -BIP32 defines a way to generate hierarchical trees of keys which can be derived from a common master key. BIP32 and [BIP44](https://https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) defines the usage of these keys as wallets. In this EIP we describe the usage of such keys outside the scope of the blockchain defining a logical tree for key usage which can coexist (and thus share the same master) with existing BIP44 compatible wallets. - -## Motivation -Applications interacting with the blockchain often make use of additional, non-blockchain technologies to perform the task they are designed for. For privacy and security sensitive mechanisms, sets of keys are needed. Reusing keys used for wallets can prove to be insecure, while keeping completely independent keys make backup and migration of the full set of credentials more complex. Defining a separate (from BIP44 compliant wallets) derivation branch allows combining the security of independent keys with the convenience of having a single piece of information which needs to be backup or migrated. - -## Specification - -### Path levels -We define the following levels in BIP32 path: - -```m / purpose' / coin_type' / subpurpose' / key_type' / key_index``` - -Apostrophe in the path indicates that BIP32 hardened derivation is used. - -This structure follows the [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) recommendations and its [amendments for non-Bitcoin usage](https://github.com/bitcoin/bips/pull/523/files). Each level has a special meaning, described in the chapters below. - -### Purpose/Coin Type/Subpurpose -This part is constant and set to ```m / 43' / 60' / 1581'```, meaning BIP 43 -> Ethereum -> This EIP. - -All subtrees under this prefix are the scope of this EIP. - -### Key type -Describes the purpose for which the key is being used. Key types should be generic. "Instant messaging" is a good example whereas "Whisper" is not. The reason is that you want to be able to use the same identity across different services. Key types are defined at: TBD - -Hardened derivation is used at this level. - -### Key index -The key index is a field of variable length identifying a specific key. In its simplest case, it is a number from 0 to 2^31-1. If a larger identifier is desired (for example representing a hash or a GUID), the value must be split -across several BIP32 nesting levels, most significant bit first and left aligned, bit-padded with 0s if needed. All levels, except the last one must used hardened key derivation. The last level must use public derivation. This means that every level can carry 31-bit of the identifier to represent. - -As an example, let's assume we have a key with key type 4' and a key_index representing a 62-bit ID represented as hexadecimal 0x2BCDEFFEDCBAABCD the complete keypath would be ```m / 43' / 60' / 1581' / 4' / ‭1469833213‬' / ‭1555737549‬ ```. If you are using random identifiers, it might be convenient to generate a conventional GUID, for example 128-bit just fix the value of the most significant bit of each 32-bit word to 1 for all of them, except the last one which will be 0. - -## Rationale -The structure proposed above follows the BIP43 generic structure and is similar to the widely adopted BIP44 specification. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1581.md diff --git a/EIPS/eip-1588.md b/EIPS/eip-1588.md index 4e6d279aa00c89..f7e4202c16d3a7 100644 --- a/EIPS/eip-1588.md +++ b/EIPS/eip-1588.md @@ -2,7 +2,7 @@ eip: 1588 title: "Hardfork Meta: Ethereum ProgPoW" author: Ikmyeong Na (@naikmyeong) -status: Draft +status: Stagnant type: Meta created: 2018-11-16 requires: 1057 @@ -19,8 +19,8 @@ This meta-EIP specifies the changes included in the alternative Ethereum hardfor - Activation: - `Block >= 7280000` on the Ethereum mainnet - Included EIPs: - - [EIP 1057](./eip-1057.md): ProgPoW, a Programmatic Proof-of-Work + - [EIP-1057](./eip-1057.md): ProgPoW, a Programmatic Proof-of-Work ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1592.md b/EIPS/eip-1592.md index 3c10b2b397bfaa..5e8d2293249514 100644 --- a/EIPS/eip-1592.md +++ b/EIPS/eip-1592.md @@ -1,171 +1,7 @@ --- eip: 1592 -title: Address and ERC20-compliant transfer rules -author: Cyril Lapinte , Laurent Aapro -discussions-to: https://github.com/ethereum/EIPs/issues/1597 -type: Standards Track category: ERC -status: Draft -created: 2018-11-09 +status: Moved --- -## Simple Summary - -We propose a standard and an interface to define transfer rules, in the context of ERC20 tokens and possibly beyond. - - -A rule can act based on sender, destination and amount, and is triggered (and rejects the transfer) according to any required business logic. - - -To ease rule reusability and composition, we also propose an interface and base implementation for a rule engine. - -## Abstract - -This standard proposal should answer the following challenges: -- Enable integration of rules with interacting platforms such as exchanges, decentralized wallets and DApps. -- Externale code and storage, improve altogether reusability, gas costs and contracts' memory footprint. -- Highlight contract behavior and its evolution, in order to ease user interaction with such contract. - - -If these challenges are answered, this proposal will provide a unified basis for transfer rules and hopefully address the transfer restriction needs of other EIPs as well, e.g. -[EIP-902](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-902.md), -[EIP-1066](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1066.md) -and [EIP-1175](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1175.md). - -This document proposes specifications for a standard of **transfer rules** and interfaces to both the rules and the rule engine, which was made to be inherited by a token, but may have a much broader scope in the authors' opinion. - -The last section of this document illustrates the proposal with a rule template and links to rule implementations. - -## Motivation - -ERC20 was designed as a standard interface allowing any token on Ethereum to be handled by other applications: from wallets to decentralized exchanges. This has been extremely powerful, but future developments in the industry of tokenization are bringing new challenges. For example it is already hard to know exactly why an ERC20 transfer failed, and it will become even harder when many tokens add their own transfer rules to the mix; we propose that it should be trivial to determine before a tx is sent, whether the transfer should turn out valid or invalid, and why (unless conditions change in the meantime obviously). On the other hand, if the rules were changed, it should also be easily detected, so that the interacting party knows it must adjust its expectations or model. - -## Specification - -We define below an interface for a rule. Rules are meant to be as simple as possible, to limit gas expenditure, since that logic will be executed on every transfer. Another reason for keeping rules simple and short, and strive for atomicity, is to facilitate both composition and interpretation of rejected transfers. By knowing which rule was triggered, we obtain a clear picture of the reason for rejection. - -The engine we propose executes all the rules defined by its owner, on every transfer and it is easy to add and remove rules individually, although we have chosen to use quite a raw rule update method, to save on deployment costs, which are often tight when it comes to token smart contracts. - -Rules are deployed on the blockchain as individual smart contracts, and called upon by the rule engine they were attached to. But any third party, for example an exchange preparing a cashout for a customer, can very cheaply query the rule engine of the token, or a single rule directly, to verify the validity of a transfer before execution, so as to never get a rejected transaction. - -## Rule interface - -`IRule` interface should provide a way to validate if an address or a transfer is valid. - -If one of these two methods is not applicable, it can simply be made to return true systematically. -If any parameter of `isTransferValid` is not needed, its name should be commented out with `/* */`. - -```js -pragma solidity ^0.4.25; - -interface IRule { - function isAddressValid(address _address) external view returns (bool); - function isTransferValid(address _from, address _to, uint256 _amount) - external view returns (bool); -} -``` - -## WithRules interface - -`WithRules` interface describes the integration of rules to a rule engine. -Developers may choose to not implement this interface if their code will only deal with one rule, or if it is not desirable to update the rules. - -The rules ordering must be thought through carefully. -Rules which are cheaper to validate or have a higher chance to break should be put first to reduce global gas expenditure, then business logic should guide the ordering of rules. That is why rules for a given context should be defined as a whole and not individually. - -```js -pragma solidity ^0.4.25; - -import "./IRule.sol"; - -interface IWithRules { - function ruleLength() public view returns (uint256); - function rule(uint256 _ruleId) public view returns (IRule); - function validateAddress(address _address) public view returns (bool); - function validateTransfer(address _from, address _to, uint256 _amount) - public view returns (bool); - - function defineRules(IRule[] _rules) public; - - event RulesDefined(uint256 count); -} -``` - -## WithRules implementation - -We also propose a simple implementation of the rule engine, available [here](https://github.com/MtPelerin/MtPelerin-protocol/blob/master/contracts/rule/WithRules.sol). It has been kept minimal both to save on gas costs on each transfer, and to reduce the deployment cost overhead for the derived smart contract. - - -On top of implementing the interface above, this engine also defines two modifiers (`whenAddressRulesAreValid`and `whenTransferRulesAreValid`), which can be used throughout the token contract to restrict `transfer()`, `transferFrom` and any other function that needs to respect either a simple whitelist or complex transfer rules. - - -## Integration - -To use rules within a token is as easy as having the token inherit from WithRules, then writing rules according to the IRule interface and deploying each rule individually. The token owner can then use `defineRules()` to attach all rules in the chosen order, within a single transaction. - -Below is a template for a rule. - -``` -import "../interface/IRule.sol"; - -contract TemplateRule is IRule { - - // state vars for business logic - - constructor(/* arguments for init */) public { - - // initializations - - } - - function isAddressValid(address _from) public view returns (bool) { - boolean isValid; - - // business logic - - return isValid; - } - - function isTransferValid( - address _from, - address _to, - uint256 _amount) - public view returns (bool) - { - boolean isValid; - - // business logic - - return isValid; - } -} -``` - -*** Notes *** -The MPS (Mt Pelerin's Share) token is the current live implementation of this standard. -Other implementations may be written with different trade-offs: from gas savings to improved security. - -#### Example of rules implementations - -- [YesNo rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/YesNoRule.sol): Trivial rule used to demonstrate both a rule and the rule engine. - -- [Freeze rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/FreezeRule.sol): This rule allows to prevent any transfer of tokens to or from chosen addresses. A smart blacklist. - -- [Lock rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/LockRule.sol): Define a global transfer policy preventing either sending or receiving tokens within a period of time. Exceptions may be granted to some addresses by the token admin. A smart whitelist. - -- [User Kyc Rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/UserKycRule.sol): Rule example relying on an existing whitelist to assert transfer and addresses validity. It is a good example of a rule that completely externalizes it's tasks. - -#### Example implementations are available at -- [Mt Pelerin Bridge protocol rules implementation](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule) -- [Mt Pelerin Token with rules](https://github.com/MtPelerin/MtPelerin-protocol/blob/master/contracts/token/component/TokenWithRules.sol) - -## History - -Historical links related to this standard: - -- The first regulated tokenized share issued by Mt Pelerin (MPS token) is using an early version of this proposal: https://www.mtpelerin.com/blog/world-first-tokenized-shares -The rule engine was updated several times, after the token issuance and during the tokensale, to match changing business and legal requirements, showcasing the solidity and flexibility of the rule engine. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). -External references outside this repository will have their own specific copyrights. +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1592.md diff --git a/EIPS/eip-160.md b/EIPS/eip-160.md index 21a12dfef18bb7..0caf02b6b66778 100644 --- a/EIPS/eip-160.md +++ b/EIPS/eip-160.md @@ -9,7 +9,7 @@ created: 2016-10-20 --- ### Hard fork -[Spurious Dragon](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-607.md) +[Spurious Dragon](./eip-607.md) ### Parameters - `FORK_BLKNUM`: 2,675,000 diff --git a/EIPS/eip-161.md b/EIPS/eip-161.md index fa61e602ca84d1..b746c239881f24 100644 --- a/EIPS/eip-161.md +++ b/EIPS/eip-161.md @@ -1,7 +1,7 @@ --- eip: 161 title: State trie clearing (invariant-preserving alternative) -author: Gavin Wood +author: Gavin Wood (@gavofyork) type: Standards Track category: Core status: Final @@ -9,11 +9,11 @@ created: 2016-10-24 --- ### Hard fork -[Spurious Dragon](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-607.md) +[Spurious Dragon](./eip-607.md) ### Parameters - `FORK_BLKNUM`: 2,675,000 -- `CHAIN_ID`: 1 (main net) +- `CHAIN_ID`: 1 (Mainnet) ### Specification @@ -66,4 +66,4 @@ On 2016-11-24, a consensus bug occurred due to two implementations having differ 1. EIP-158 issue and discussion: https://github.com/ethereum/EIPs/issues/158 2. EIP-161 issue and discussion: https://github.com/ethereum/EIPs/issues/161 3. https://blog.ethereum.org/2016/11/25/security-alert-11242016-consensus-bug-geth-v1-4-19-v1-5-2/ -> Details: Geth was failing to revert empty account deletions when the transaction causing the deletions of empty accounts ended with an an out-of-gas exception. An additional issue was found in Parity, where the Parity client incorrectly failed to revert empty account deletions in a more limited set of contexts involving out-of-gas calls to precompiled contracts; the new Geth behavior matches Parity’s, and empty accounts will cease to be a source of concern in general in about one week once the state clearing process finishes. +> Details: Geth was failing to revert empty account deletions when the transaction causing the deletions of empty accounts ended with an out-of-gas exception. An additional issue was found in Parity, where the Parity client incorrectly failed to revert empty account deletions in a more limited set of contexts involving out-of-gas calls to precompiled contracts; the new Geth behavior matches Parity’s, and empty accounts will cease to be a source of concern in general in about one week once the state clearing process finishes. diff --git a/EIPS/eip-1613.md b/EIPS/eip-1613.md index 973e040f1ef96d..bcfccf6d9a323b 100644 --- a/EIPS/eip-1613.md +++ b/EIPS/eip-1613.md @@ -1,298 +1,7 @@ --- -eip: 1613 -title: Gas stations network -author: Yoav Weiss , Dror Tirosh , Alex Forshtat -discussions-to: https://github.com/yoav-tabookey/EIPs/issues/1 -status: Draft -type: Standards Track +eip: 1613 category: ERC -created: 2018-11-18 -requires: 1077 +status: Moved --- -## Simple Summary -Make smart contracts (e.g. dapps) accessible to non-ether users by allowing contracts to accept "[collect-calls](https://en.wikipedia.org/wiki/Collect_call)", paying for incoming calls. -Let contracts "listen" on publicly accessible channels (e.g. web URL or a whisper address). -Incentivize nodes to run "gas stations" to facilitate this. -Require no network changes, and minimal contract changes. - -## Abstract -Communicating with dapps currently requires paying ETH for gas, which limits dapp adoption to ether users. -Therefore, contract owners may wish to pay for the gas to increase user acquisition, or let their users pay for gas with fiat money. -Alternatively, a 3rd party may wish to subsidize the gas costs of certain contracts. -Solutions such as described in [EIP-1077](https://eips.ethereum.org/EIPS/eip-1077) could allow transactions from addresses that hold no ETH. - -The gas stations network is an [EIP-1077](https://eips.ethereum.org/EIPS/eip-1077) compliant effort to solve the problem by creating an incentive for nodes to run gas stations, where gasless transactions can be "fueled up". -It abstracts the implementation details from both the dapp maintainer and the user, making it easy to convert existing dapps to accept "collect-calls". - -The network consists of a single public contract trusted by all participating dapp contracts, and a decentralized network of relay nodes (gas stations) incentivized to listen on non-ether interfaces such as web or whisper, -pay for transactions and get compensated by that contract. The trusted contract can be verified by anyone, and the system is otherwise trustless. -Gas stations cannot censor transactions as long as there's at least one honest gas station. Attempts to undermine the system can be proven on-chain and offenders can be penalized. - -## Motivation - -* Increase user adoption of smart contracts by: - * Removing the user hassle of acquiring ETH. Transactions are still paid by ETH but costs can be borne by the dapp or paid by the user through other means. - * Removing the need to interact directly with the blockchain, while maintaining decentralization and censorship-resistance. - Contracts can "listen" on multiple public channels, and users can interact with the contracts through common protocols that are generally permitted even in restrictive environments. -* Ethereum nodes get a revenue source without requiring mining equipment. The entire network benefits from having more nodes. -* No protocol changes required. The gas station network is self-organized via a smart contract, and dapps interact with the network by implementing an interface. - -## Specification - -The system consists of a `RelayHub` singleton contract, participating contracts inheriting the `RelayRecipient` contract, a decentralized network of `Relay` nodes, a.k.a. Gas Stations, -and user applications (e.g. mobile or web) interacting with contracts via relays. - -Roles of the `RelayHub`: - -* Maintain a list of active relays. Senders select a `Relay` from this list for each transaction. The selection process is discussed below. -* Mediate all communication between relays and contracts. -* Provide contracts with trusted versions of the real msg.sender and msg.data. -* Hold ETH stakes placed by relays. A minimum stake size is enforced. Stake can be withdrawn after a relay unregisters and waits for a cooldown period. -* Hold ETH prepayments made by contracts and use them to compensate relays. -* Penalize provably-offensive relays by giving their stakes to an address providing the proof, thus keeping relays honest. -* Provide a free way for relays to know whether they'll be compensated for a future transaction. - -Roles of a `Relay` node: - -* Maintain a hot wallet with a small amount of ETH, to pay for gas. -* Provide a public interface for user apps to send gasless transactions via channels such as https or whisper. -* Publish it's public interfaces and its price (as a multiplier of the actual transaction gas cost) in `RelayHub`. -* Optionally monitor reverted transactions of other relays through RelayHub, catching offending relays and claiming their stakes. This can be done by anyone, not just a relay. - -Implementing a `RelayRecipient` contract: - -* Know the address of `RelayHub` and trust it to provide information about the transaction. -* Maintain a small balance of ETH gas prepayment deposit in `RelayHub`. Can be paid directly by the `RelayRecipient` contract, or by the dapp's owner on behalf of the `RelayRecipient` address. - The dapp owner is responsible for ensuring sufficient balance for the next transactions, and can stop depositing if something goes wrong, thus limiting the potential for abuse of system bugs. In DAO usecases it will be up to the DAO logic to maintain a sufficient deposit. -* Use `get_sender()` and `get_data()` instead of `msg.sender` and `msg.data`, everywhere. `RelayRecipient` provides these functions and gets the information from `RelayHub`. -* Implement a `accept_relayed_call(address relay, address from, bytes encoded_function, uint gas_price, uint transaction_fee )` view function that returns **zero** if and only if it is willing to accept a transaction and pay for it. - `accept_relayed_call` is called by `RelayHub` as a view function when a `Relay` inquires it, and also during the actual transaction. Transactions are reverted if **non-zero**, and `Relay` only gets compensated for transactions (whether successful or reverted) if `accept_relayed_call` returns **zero**. Some examples of `accept_relayed_call()` implementations: - * Whitelist of trusted dapp members. - * Balance sheet of registered users, maintained by the dapp owner. Users pay the dapp with a credit card or other non-ETH means, and are credited in the `RelayRecipient` balance sheet. - Users can never cost the dapp more than they were credited for. - * Whitelist of known transactions used for onboarding new users. This allows certain anonymous calls and is subject to Sybil attacks. - Therefore it should be combined with a restricted gasPrice, and a whitelist of trusted relays, to reduce the incentive for relays to create bogus transactions and rob the dapp's prepaid gas deposit. - Dapps allowing anonymous onboarding transactions might benefit from registering their own `Relay` and accepting anonymous transactions only from that `Relay`, whereas other transactions can be accepted from any relay. - Alternatively, dapps may use the balance sheet method for onboarding as well, by applying the methods suggested in the attacks/mitigations section below. -* Implement `post_relayed_call(address relay, address from, bytes encoded_function, bool success, uint used_gas, uint transaction_fee )` - - This method is called after a transaction is relayed. By default, it does nothing. - It can be used as a method to charge the user in dapp-specific manner. - -Glossary of terms used in the processes below: - -* `RelayHub` - the RelayHub singleton contract, used by everyone. -* `Recipient` - a contract implementing `RelayRecipient`, accepting relayed transactions from the RelayHub contract and paying for the incoming transactions. -* `Sender` - an external address with a valid keypair but no ETH to pay for gas. -* `Relay` - a node holding ETH in an external address, listed in RelayHub and relaying transactions from Senders to RelayHub for a fee. - -![Sequence Diagram](https://bit.ly/2EWWVN8) - -The process of registering/refreshing a `Relay`: - -* Relay starts listening as a web app (or on some other communication channel). -* If starting for the first time (no key yet), generate a key pair for Relay's address. -* If Relay's address doesn't hold sufficient funds for gas (e.g. because it was just generated), Relay stays inactive until its owner funds it. -* Relay's owner funds it. -* Relay's owner sends the required stake to `RelayHub` by calling `RelayHub.stake(address relay, uint unstake_delay)`. -* `RelayHub` puts the `owner` and `unstake delay` in the relays map, indexed by `relay` address. -* Relay calls `RelayHub.register_relay(uint transaction_fee, string memory url)` with the relay's `transaction fee` (as a multiplier on transaction gas cost), and a URL for incoming transactions. -* `RelayHub` ensures that Relay has a sufficient stake. -* `RelayHub` puts the `transaction fee` in the relays map. -* `RelayHub` emits an event, `RelayAdded(Relay, owner, transaction_fee, relay_stake, unstake_delay, url)`. -* Relay starts a timer to perform a `keepalive` transaction every 6000 blocks. -* `Relay` goes to sleep and waits for signing requests. - -The process of sending a relayed transaction: - -* `Sender` selects a live `Relay` from RelayHub's list by looking at `RelayAdded` events from `RelayHub`, and sorting based on its own criteria. Selection may be based on a mix of: - * Relay published transaction fees. - * Relay stake size and lock-up time. - * Recent relay transactions (visible through `TransactionRelayed` events from `RelayHub`). - * Optionally, reputation/blacklist/whitelist held by the sender app itself, or its backend, on per-app basis (not part of the gas stations network). -* Sender prepares the transaction with Sender's address, the recipient address, the actual transaction data, Relay's transaction fee, gas price, gas limit, its current nonce from `RelayHub.nonces`, RelayHub's address, and Relay's address, and then signs it. -* Sender verifies that `RelayHub.balances[recipient]` holds enough ETH to pay Relay's fee. -* Sender verifies that `Relay.balance` has enough eth to send the transaction -* Sender reads the Relay's current `nonce` value and decides on the `max_nonce` parameter. -* Sender sends the signed transaction amd metadata to Relay's web interface. -* `Relay` wraps the transaction with a transaction to `RelayHub`, with zero ETH value. -* `Relay` signs the wrapper transaction with its key in order to pay for gas. -* `Relay` verifies that: - * The transaction's recipient contract will accept this transaction when submitted, by calling `RelayHub.can_relay()`, a view function, - which checks the recipient's `accept_relayed_call`, also a view function, stating whether it's willing to accept the charges). - * The transaction nonce matches `RelayHub.nonces[sender]`. - * The relay address in the transaction matches Relay's address. - * The transaction's recipient has enough ETH deposited in `RelayHub` to pay the transaction fee. - * Relay has enough ETH to pay for the gas required by the transaction. - * Value of `max_nonce` is higher than current Relay's `nonce` -* If any of Relay's checks fail, it returns an error to sender, and doesn't proceed. -* Relay submits the signed wrapped transaction to the blockchain. -* Relay immediately returns the signed wrapped transaction to the sender. This step is discussed below, in attacks/mitigations. -* `Sender` receives the wrapped transaction and verifies that: - * It's a valid relay call to `RelayHub`. from Relay's address. - * The transaction's ethereum nonce matches Relay's current nonce. - * The transaction's ethereum nonce is lower than or equal to `max_nonce`. - * `Relay` is sufficiently funded to pay for it. - * The wrapped transaction is valid and signed by `sender`. - * Recipient contract has sufficient funds in `RelayHub.balances` to pay for Relay's fee as stated in the transaction. -* If any of sender's checks fails, it goes back to selecting a new Relay. Sender may also file a report on the unresponsive relay to its backend or save it locally, to down-sort this relay in future transactions. -* `Sender` may also submit the raw wrapped transaction to the blockchain without paying for gas, through any Ethereum node. - This submission is likely ignored because an identical transaction is already in the network's pending transactions, but no harm in putting it twice, to ensure that it happens. - This step is not strictly necessary, for reasons discussed below in attacks/mitigations, but may speed things up. -* `Sender` monitors the blockchain, waiting for the transaction to be mined. - The transaction was verified, with Relay's current nonce, so mining must be successful unless Relay submitted another (different) transaction with the same nonce. - If mining fails due to such attack, sender may call `RelayHub.penalize_repeated_nonce` through another relay, to collect the offending relay's stake, and then go back to selecting a new Relay for the transaction. - See discussion in the attacks/mitigations section below. -* `RelayHub` receives the transaction: - * Records `gasLeft()` as initial_gas for later payment. - * Verifies the transaction is sent from a registered relay. - * Verifies that the signature of the internal transaction matches its stated origin (sender's key). - * Verifies that the relay address written in the transaction matches msg.sender. - * Verifies that the transaction's `nonce` matches the stated origin's nonce in `RelayHub.nonces`. - * Calls recipient's `accept_relayed_call` function, asking whether it's going to accept the transaction. If not, `RelayHub` reverts. - In this case, Relay doesn't get paid, as it was its responsibility to check `RelayHub.can_relay` before releasing the transaction. - * Sends the transaction to the recipient. The call is made using `call()`, so reverts won't kill the transaction, just return false. - When passing gas to `call()`, enough gas is preserved by `RelayHub`, for post-call handling. Recipient may run out of gas, but `RelayHub` never does. - `RelayHub` also sends sender's address at the end of `msg.data`, so `RelayRecipient.get_sender()` will be able to extract the real sender, and trust it because the transaction came from the known `RelayHub` address. -* Recipient contract handles the transaction. -* `RelayHub` calls recipient's `post_relayed_call` -* `RelayHub` checks call's return value of call, and emits `TransactionRelayed(transaction_hash, bool result)`. -* `RelayHub` increases `RelayHub.nonces[sender]`. -* `RelayHub` transfers ETH balance from recipient to `Relay.owner`, to pay the transaction fee, based on the measured transaction cost. - Note on relay payment: The relay gets paid for actual gas used, regardless of whether the recipient reverted. - The only case where the relay sustains a loss, is if can_relay returns non-zero, since the relay was responsible to verify this view function prior to submitting. - Any other revert is caught and paid for. See attacks/mitigations below. -* `Relay` keeps track of transactions it sent, and waits for `TransactionRelayed` events to see the charge. - If a transaction reverts and goes unpaid, which means the recipient's `accept_relayed_call()` function was inconsistent, `Relay` refuses service to that recipient for a while (or blacklists it indefinitely, if it happens often). - See attacks/mitigations below. - -The process of winding a `Relay` down: - -* Relay's owner (the address that initially funded it) calls `RelayHub.remove_relay_by_owner(Relay)`. -* `RelayHub` ensures that the sender is indeed Relay's owner, then removes `Relay`, and emits `RelayRemoved(Relay)`. -* `RelayHub` starts the countdown towards releasing the owner's stake. -* `Relay` receives its `RelayRemoved` event. -* `Relay` sends all its remaining ETH to its owner. -* `Relay` shuts down. -* Once the owner's unstake delay is over, owner calls `RelayHub.unstake()`, and withdraws the stake. - -## Rationale -The rationale for the gas stations network design is a combination of two sets of requirements: Easy adoption, and robustness. - -For easy adoption, the design goals are: - -* No network changes. -* Minimal changes to contracts, apps and frameworks. - -The robustness requirement translates to decentralization and attack resistance. The gas stations network is decentralized, and we have to assume that any entity may attack other entities in the system. - -Specifically we've considered the following types of attacks: - -* Denial-of-service attacks against individual senders, i.e. transactions censorship. -* Denial-of-service and financial attacks against individual relays. -* Denial-of-service and financial attacks against individual contracts. -* Denial-of-service attacks against the entire network, either by attacking existing entities, or by introducing any number of malicious entities. - -#### Attacks and mitigations - -##### Attack: Relay attempts to censor a transaction by not signing it, or otherwise ignoring a user request. -Relay is expected to return the signed transaction to the sender, immediately. -Sender doesn't need to wait for the transaction to be mined, and knows immediately whether it's request has been served. -If a relay doesn't return a signed transaction within a couple of seconds, sender cancels the operation, drops the connection, and switches to another relay. -It also marks Relay as unresponsive in its private storage to avoid using it in the near future. - -Therefore, the maximal damage a relay can cause with such attack, is a one-time delay of a couple of seconds. After a while, senders will avoid it altogether. - -##### Attack: Relay attempts to censor a transaction by signing it, returning it to the sender, but never putting it on the blockchain. -This attack will backfire and not censor the transaction. -The sender can submit the transaction signed by Relay to the blockchain as a raw transaction through any node, so the transaction does happen, -but Relay may be unaware and therefore be stuck with a bad nonce which will break its next transaction. - -##### Attack: Relay attempts to censor a transaction by signing it, but publishing a different transaction with the same nonce. -Reusing the nonce is the only DoS performed by a Relay, that cannot be detected within a couple of seconds during the http request. -It will only be detected when the malicious transaction with the same nonce gets mined and triggers the `RelayHub.TransactionRelayed` event. -However, the attack will backfire and cost Relay its entire stake. - -Sender has a signed transaction from Relay with nonce N, and also gets a mined transaction from the blockchain with nonce N, also signed by Relay. -This proves that Relay performed a DoS attack against the sender. -The sender calls `RelayHub.penalize_repeated_nonce(bytes transaction1, bytes transaction2)`, which verifies the attack, confiscates Relay's stake, -and splits it between the sender and the other relay who delivered the penalize_repeated_nonce call. -The sender then proceeds to select a new relay and send the original transaction. - -The result of such attack is a delay of a few blocks in sending the transaction (until the attack is detected) but the relay gets removed and loses its entire stake. -Scaling such attack would be prohibitively expensive, and actually quite profitable for senders and honest relays. - -##### Attack: Relay attempts to censor a transaction by signing it, but using a nonce higher than it's current nonce. -In this attack, the Relay did create and return a perfectly valid transaction, but it will not be mined until this Relay fills the gap in the nonce with 'missing' transactions. -This may delay the relaying of some transactions indefinitely. In order to mitigate that, the sender includes a `max_nonce` parameter with it's signing request. -It is suggested to be higher by 2-3 from current nonce, to allow the relay process several transactions. - -When the sender receives a transaction signed by a Relay he validates that the nonce used is valid, and if it is not, the client will ignore the given relay and use other relays to relay given transaction. Therefore, there will be no actual delay introduced by such attack. - -##### Attack: Dapp attempts to burn relays funds by implementing an inconsistent accept_relayed_call() and using multiple sender addresses to generate expensive transactions, thus performing a DoS attack on relays and reducing their profitability. -In this attack, a contract sets an inconsistent accept_relayed_call (e.g. return zero for even blocks, nonzero for odd blocks), and uses it to exhaust relay resources through unpaid transactions. -Relays can easily detect it after the fact. -If a transaction goes unpaid, the relay knows that the recipient contract's accept_relayed_call has acted inconsistently, because the relay has verified its view function before sending the transaction. -It might be the result of a rare race condition where the contract's state has changed between the view call and the transaction, but if it happens too frequently, relays will blacklist this contract and refuse to serve transactions to it. -Each offending contract can only cause a small damage (e.g. the cost of 2-3 transactions) to a relay, before getting blacklisted. - -Relays may also look at recipients' history on the blockchain, looking for past unpaid transactions (reverted by RelayHub without pay), and denying service to contracts with a high failure rate. -If a contract caused this minor loss to a few relays, all relays will stop serving it, so it can't cause further damage. - -This attack doesn't scale because the cost of creating a malicious contract is in the same order of magnitude as the damage it can cause to the network. -Causing enough damage to exhaust the resources of all relays, would be prohibitively expensive. - -The attack can be made even more impractical by setting RelayHub to require a stake from dapps before they can be served, and enforcing an unstaking delay, -so that attackers will have to raise a vast amount of ETH in order to simultaneously create enough malicious contracts and attack relays. -This protection is probably an overkill, since the attack doesn't scale regardless. - -##### Attack: User attempts to rob dapps by registering its own relay and sending expensive transactions to dapps. -If a malicious sender repeatedly abuses a recipient by sending meaningless/reverted transactions and causing the recipient to pay a relay for nothing, -it is the recipient's responsibility to blacklist that sender and have its accept_relayed_call function return nonzero for that sender. -Collect calls are generally not meant for anonymous senders unknown to the recipient. -Dapps that utilize the gas station networks should have a way to blacklist malicious users in their system and prevent Sybil attacks. - -A simple method that mitigates such Sybil attack, is that the dapp lets users buy credit with a credit card, and credit their account in the dapp contract, -so accept_relayed_call() only returns zero for users that have enough credit, and deduct the amount paid to the relay from the user's balance, whenever a transaction is relayed for the user. -With this method, the attacker can only burn its own resources, not the dapp's. - -A variation of this method, for free dapps (that don't charge the user, and prefer to pay for their users transactions) is to require a captcha during user creation in their web interface, -or to login with a Google/Facebook account, which limits the rate of the attack to the attacker's ability to open many Google/Facebook accounts. -Only a user that passed that process is given credit in RelayRecipient. The rate of such Sybil attack would be too low to cause any real damage. - -##### Attack: Attacker attempts to reduce network availability by registering many unreliable relays. -Registering a relay requires placing a stake in RelayHub, and the stake can only be withdrawn after the relay is unregistered and a long cooldown period has passed, e.g. a month. - -Each unreliable relay can only cause a couple of seconds delay to senders, once, and then it gets blacklisted by them, as described in the first attack above. -After it caused this minor delay and got blacklisted, the attacker must wait a month before reusing the funds to launch another unreliable relay. -Simultaneously bringing up a number of unreliable relays, large enough to cause a noticeable network delay, would be prohibitively expensive due to the required stake, -and even then, all those relays will get blacklisted within a short time. - -##### Attack: Attacker attempts to replay a relayed transaction. -Transactions include a nonce. RelayHub maintains a nonce (counter) for each sender. Transactions with bad nonces get reverted by RelayHub. Each transaction can only be relayed once. - -##### Attack: User does not execute the raw transaction received from the Relayer, therefore blocking the execution of all further transactions signed by this relayer -The user doesn't really have to execute the raw transaction. It's enough that the user can. The relationship between relay and sender is mutual distrust. The process described above incentivizes the relay to execute the transaction, so the user doesn't need to wait for actual mining to know that the transaction has been executed. - -Once relay returns the signed transaction, which should happen immediately, the relay is incentivized to also execute it on chain, so that it can advance its nonce and serve the next transaction. The user can (but doesn't have to) also execute the transaction. To understand why the attack isn't viable, consider the four possible scenarios after the signed transaction was returned to the sender: - -1. Relay executes the transaction, and the user doesn't. In this scenario the transaction is executed, so no problem. This is the case described in this attack. -2. Relay doesn't execute the transaction, but the user does. Similarly to 1, the transaction is executed, so no problem. -3. Both of them execute the transaction. The transactions are identical in the pending transactions pool, so the transaction gets executed once. No problem. -4. None of them execute the transaction. In this case the transaction doesn't get executed, but the relay is stuck. It can't serve the next transaction with the next nonce, because its nonce hasn't been advanced on-chain. It also can't serve the next transaction with the current nonce, as this can be proven by the user, having two different transactions signed by the same relay, with the same nonce. The user could use this to take the relay's nonce. So the relay is stuck unless it executes the transaction. - -As this matrix shows, the relay is __always__ incentivized to execute the transaction, once it returned it to the user, in order to end up in #1 or #3, and avoid the risk of #4. It's just a way to commit the relay to do its work, without requiring the user to wait for on-chain confirmation. - -## Backwards Compatibility - -The gas stations network is implemented as smart contracts and external entities, and does not require any network changes. - -Dapps adding gas station network support remain backwards compatible with their existing apps/users. The added methods apply on top of the existing ones, so no changes are required for existing apps. - -## Implementation - -A working implementation of the [**gas stations network**](https://github.com/tabookey-dev/tabookey-gasless) is being developed by **TabooKey**. It consists of `RelayHub`, `RelayRecipient`, `web3 hooks`, an implementation of a gas station inside `geth`, and sample dapps using the gas stations network. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1613.md diff --git a/EIPS/eip-1616.md b/EIPS/eip-1616.md index c22cdec233d9ab..77e12726f4766d 100644 --- a/EIPS/eip-1616.md +++ b/EIPS/eip-1616.md @@ -1,395 +1,7 @@ --- eip: 1616 -title: ERC-1616 Attribute Registry Standard -author: 0age (@0age), Santiago Palladino (@spalladino), Leo Arias (@elopio), Alejo Salles (@fiiiu), Stephane Gosselin (@thegostep) -discussions-to: https://github.com/ethereum/EIPs/issues/1616 -status: Draft -type: Standards Track category: ERC -created: 2018-11-23 -requires: 165 +status: Moved --- - -## Simple Summary - -EIP-1616 provides a basic interface for querying a registry for attribute metadata assigned to Ethereum accounts. - -## Abstract - -This EIP contains the following core ideas: -1. Instead of relying directly on the reputation of a claims issuer to assess the veracity of a given claim, trust can be brought up to the level of a registry curator. This registry which we call an "**Attribute Registry**" allows for reduced complexity in implementation since a party needing to verify an attribute can now work with a trusted claims aggregator instead of relying on individual claim providers. -2. Claims are abstracted as standard "attributes" which represent metadata assigned to an account, with claims decoupled from the issuing party. Attributes are registered as a flat `uint256 -> uint256` key-value pair on each account, with the important property that **each attribute type has one canonical value per address**. This property allows for composability of attribute registries and advanced attribute formation. -3. There is a generic method for determining the set of attribute keys or IDs made available by the registry. The standard does not specify requirements or recommendations for how attributes and their values are managed, or what additional metadata may be associated with attributes. It is likely that a standard set of attribute names and metadata schema could be proposed in a separate EIP. - -Potential advanced uses of attribute registries include: -* Encoding complex boolean expressions which combine multiple attributes into a single uint256 key, which is then parsed and evaluated by the registry logic. -* Using values associated with an attribute to query additional on-chain or off-chain metadata. -* Resolving attribute values by calling into separate attribute registries or other contracts, delegating authority without changing the interface of the registry. - -## Motivation - -This EIP is motivated by the need for contracts and external accounts to be able to verify information about a given address from a single trusted source **without concerning themselves with the particular details of how the information was obtained**, and to do so in as simple a manner as possible. It is also motivated by the desire to promote broad **cross-compatibility and composability** between attribute registries, a property which is amplified by both the simplicity of the interface as well as by the guarantees on uniqueness provided by the proposed standard. - -Existing EIPs for assigning metadata to an account include EIP-735 and EIP-780, which both allow for multiple claims to be issued on the same address for any given claim topic. This forces verifiers of said metadata to assess the veracity of each claim, taking into account the relative reputation of each claim issuer. It also prescribes a methodology for adding and removing claims, which may not be appropriate for all use cases. - -This EIP proposes a light-weight abstraction layer for a standard account metadata registry interface. This abstraction layer can sit on top of claims registries like EIP-735 and EIP-780 or others as the attribute registry curator selects trusted data sources. - -## Specification - -The Attribute Registry interface contains four functions, outlined as follows: -``` -/** - * @title EIP-1616 Attribute Registry Standard interface. EIP-165 ID: 0x5f46473f - */ -interface AttributeRegistryInterface { - function hasAttribute(address account, uint256 attributeTypeID) external view returns (bool); - function getAttributeValue(address account, uint256 attributeTypeID) external view returns (uint256); - function countAttributeTypes() external view returns (uint256); - function getAttributeTypeID(uint256 index) external view returns (uint256); -} -``` - -Contracts that comply with the Attribute Registry EIP MUST implement the above interface. - -As an additional requirement, the ERC-165 interface MUST be included: -``` -/** - * @title EIP-165 interface. EIP-165 ID: 0x01ffc9a7 - */ -interface EIP-165 { - /** - * @notice EIP-165 support. Attribute Registry interface ID is 0x5f46473f. - * @param _interfaceID The interface identifier, as specified in EIP-165 - * @return True for 0x01ffc9a7 & 0x5f46473f, false for unsupported interfaces. - */ - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} -``` - -The implementation MUST follow the specifications described below. - -### View Functions -The view functions detailed below MUST be implemented. - -#### `hasAttribute` function -``` -function hasAttribute(address account, uint256 attributeTypeID) external view returns (bool) -``` - -Check if an attribute has been assigned to a given account on the registry and is currently valid. - -_**NOTE**_: This function MUST return either true or false - i.e. calling this function MUST NOT cause the caller to revert. Implementations that wish to call into another contract during execution of this function MUST catch any `revert` and instead return `false`. - -_**NOTE**_: This function MUST return two equal values when performing two directly consecutive function calls with identical `account` and `attributeTypeID` parameters, regardless of differences in the caller's address, the transaction origin, or other out-of-band information. - - - -#### `getAttributeValue` function -``` -function getAttributeValue(address account, uint256 attributeTypeID) external view returns (uint256) -``` - -Retrieve the `uint256` value of an attribute on a given account on the registry, assuming the attribute is currently valid. - -_**NOTE**_: This function MUST revert if a directly preceding or subsequent function call to `hasAttribute` with identical `account` and `attributeTypeID` parameters would return false. - -_**NOTE**_: This function MUST return two equal values when performing two directly consecutive function calls with identical `account` and `attributeTypeID` parameters, regardless of differences in the caller's address, the transaction origin, or other out-of-band information. - -#### `countAttributeTypes` function -``` -function countAttributeTypes() external view returns (uint256) -``` - -Retrieve the total number of valid attribute types defined on the registry. Used alongside `getAttributeTypeID` to determine all of the attribute types that are available on the registry. - -_**NOTE**_: This function MUST return a positive integer value - i.e. calling this function MUST NOT cause the caller to revert. - -_**NOTE**_: This function MUST return a value that encompasses all indexes of attribute type IDs whereby a call to `hasAttribute` on some address with an attribute type ID at the given index would return `true`. - -#### `getAttributeTypeID` function -``` -function getAttributeTypeID(uint256 index) external view returns (uint256) -``` - -Retrieve an ID of an attribute type defined on the registry by index. Used alongside `countAttributeTypes` to determine all of the attribute types that are available on the registry. - -_**NOTE**_: This function MUST revert if the provided `index` value falls outside of the range of the value returned from a directly preceding or subsequent function call to `countAttributeTypes`. It MUST NOT revert if the provided `index` value falls inside said range. - -_**NOTE**_: This function MUST return an `attributeTypeID` value on *some* index if the same `attributeTypeID` value would cause a given call to `hasAttribute` to return `true` when passed as a parameter. - -## Rationale - -This standard extends the applicability of metadata assignment to those use cases that are not adequately represented by EIP-735, EIP-780, or similar proposals. Namely, it enforces the constraint of one attribute value per attribute ID per address, as opposed to one value per ID per address *per issuer*. - -Aside from the prescribed attribute value, attribute properties are deliberately omitted from the standard. While many attribute registries will require additional metadata on attributes at both the instance and the class level, reliable and flexible interoperability between highly variable registry extensions is facilitated more effectively by enforcing a widely-applicable base layer for attributes. - -## Backwards Compatibility - -There are no backwards compatibility concerns. - -## Test Cases - -Targeted test cases with 100% code coverage can be found at [this repository](https://github.com/0age/AttributeRegistry). See [here](https://github.com/TPL-protocol/tpl-contracts) for tests on a more complex contract that implements the application registry interface. - -## Implementation - -The basic implementation that follows can be found at [this repository](https://github.com/0age/AttributeRegistry) (see [here](https://github.com/TPL-protocol/tpl-contracts/blob/master/contracts/BasicJurisdiction.sol#L399) for an example of a more complex implementing contract): - -``` -pragma solidity ^0.4.25; - -/** - * @title Attribute Registry interface. EIP-165 ID: 0x5f46473f - */ -interface AttributeRegistryInterface { - /** - * @notice Check if an attribute of the type with ID `attributeTypeID` has - * been assigned to the account at `account` and is currently valid. - * @param account address The account to check for a valid attribute. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return True if the attribute is assigned and valid, false otherwise. - * @dev This function MUST return either true or false - i.e. calling this - * function MUST NOT cause the caller to revert. - */ - function hasAttribute( - address account, - uint256 attributeTypeID - ) external view returns (bool); - - /** - * @notice Retrieve the value of the attribute of the type with ID - * `attributeTypeID` on the account at `account`, assuming it is valid. - * @param account address The account to check for the given attribute value. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return The attribute value if the attribute is valid, reverts otherwise. - * @dev This function MUST revert if a directly preceding or subsequent - * function call to `hasAttribute` with identical `account` and - * `attributeTypeID` parameters would return false. - */ - function getAttributeValue( - address account, - uint256 attributeTypeID - ) external view returns (uint256); - - /** - * @notice Count the number of attribute types defined by the registry. - * @return The number of available attribute types. - * @dev This function MUST return a positive integer value - i.e. calling - * this function MUST NOT cause the caller to revert. - */ - function countAttributeTypes() external view returns (uint256); - - /** - * @notice Get the ID of the attribute type at index `index`. - * @param index uint256 The index of the attribute type in question. - * @return The ID of the attribute type. - * @dev This function MUST revert if the provided `index` value falls outside - * of the range of the value returned from a directly preceding or subsequent - * function call to `countAttributeTypes`. It MUST NOT revert if the provided - * `index` value falls inside said range. - */ - function getAttributeTypeID(uint256 index) external view returns (uint256); -} - - -/** - * @title A simple example of an Attribute Registry implementation. - */ -contract AttributeRegistry is AttributeRegistryInterface { - // This particular implementation just defines two attribute types. - enum Affiliation { Whitehat, Blackhat } - - // Top-level information about attribute types held in a static array. - uint256[2] private _attributeTypeIDs; - - // The number of attributes currently issued tracked in a static array. - uint256[2] private _issuedAttributeCounters; - - // Issued attributes held in a nested mapping by account & attribute type. - mapping(address => mapping(uint256 => bool)) private _issuedAttributes; - - // Issued attribute values held in a nested mapping by account & type. - mapping(address => mapping(uint256 => uint256)) private _issuedAttributeValues; - - /** - * @notice The constructor function, defines the two attribute types available - * on this particular registry. - */ - constructor() public { - // Set the attribute type IDs for whitehats (8008) and blackhats (1337). - _attributeTypeIDs = [8008, 1337]; - } - - /** - * @notice Assign a "whitehat" attribute type to `msg.sender`. - * @dev The function may not be called by accounts with a "blackhat" attribute - * type already assigned. This function is arbitrary and not part of the - * Attribute Registry specification. - */ - function joinWhitehats() external { - // Get the index of the blackhat attribute type on the attribute registry. - uint256 blackhatIndex = uint256(Affiliation.Blackhat); - - // Get the attribute type ID of the blackhat attribute type. - uint256 blackhatAttributeTypeID = _attributeTypeIDs[blackhatIndex]; - - // Do not allow the whitehat attribute to be set if blackhat is already set. - require( - !_issuedAttributes[msg.sender][blackhatAttributeTypeID], - "no blackhats allowed!" - ); - - // Get the index of the whitehat attribute type on the attribute registry. - uint256 whitehatIndex = uint256(Affiliation.Whitehat); - - // Get the attribute type ID of the whitehat attribute type. - uint256 whitehatAttributeTypeID = _attributeTypeIDs[whitehatIndex]; - - // Mark the attribute as issued on the given address. - _issuedAttributes[msg.sender][whitehatAttributeTypeID] = true; - - // Calculate the new number of total whitehat attributes. - uint256 incrementCounter = _issuedAttributeCounters[whitehatIndex] + 1; - - // Set the attribute value to the new total assigned whitehat attributes. - _issuedAttributeValues[msg.sender][whitehatAttributeTypeID] = incrementCounter; - - // Update the value of the counter for total whitehat attributes. - _issuedAttributeCounters[whitehatIndex] = incrementCounter; - } - - /** - * @notice Assign a "blackhat" attribute type to `msg.sender`. - * @dev The function may be called by any account, but assigned "whitehat" - * attributes will be removed. This function is arbitrary and not part of the - * Attribute Registry specification. - */ - function joinBlackhats() external { - // Get the index of the blackhat attribute type on the attribute registry. - uint256 blackhatIndex = uint256(Affiliation.Blackhat); - - // Get the attribute type ID of the blackhat attribute type. - uint256 blackhatAttributeTypeID = _attributeTypeIDs[blackhatIndex]; - - // Mark the attribute as issued on the given address. - _issuedAttributes[msg.sender][blackhatAttributeTypeID] = true; - - // Calculate the new number of total blackhat attributes. - uint256 incrementCounter = _issuedAttributeCounters[blackhatIndex] + 1; - - // Set the attribute value to the new total assigned blackhat attributes. - _issuedAttributeValues[msg.sender][blackhatAttributeTypeID] = incrementCounter; - - // Update the value of the counter for total blackhat attributes. - _issuedAttributeCounters[blackhatIndex] = incrementCounter; - - // Get the index of the whitehat attribute type on the attribute registry. - uint256 whitehatIndex = uint256(Affiliation.Whitehat); - - // Get the attribute type ID of the whitehat attribute type. - uint256 whitehatAttributeTypeID = _attributeTypeIDs[whitehatIndex]; - - // Determine if a whitehat attribute type has been assigned. - if (_issuedAttributes[msg.sender][whitehatAttributeTypeID]) { - // If so, delete the attribute. - delete _issuedAttributes[msg.sender][whitehatAttributeTypeID]; - - // Delete the attribute value as well. - delete _issuedAttributeValues[msg.sender][whitehatAttributeTypeID]; - - // Set the attribute value to the new total assigned whitehat attributes. - uint256 decrementCounter = _issuedAttributeCounters[whitehatIndex] - 1; - - // Update the value of the counter for total whitehat attributes. - _issuedAttributeCounters[whitehatIndex] = decrementCounter; - } - } - - /** - * @notice Get the total number of assigned whitehat and blackhat attributes. - * @return Array with counts of assigned whitehat and blackhat attributes. - * @dev This function is arbitrary and not part of the Attribute Registry - * specification. - */ - function totalHats() external view returns (uint256[2]) { - // Return the array containing counter values. - return _issuedAttributeCounters; - } - - /** - * @notice Check if an attribute of the type with ID `attributeTypeID` has - * been assigned to the account at `account` and is currently valid. - * @param account address The account to check for a valid attribute. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return True if the attribute is assigned and valid, false otherwise. - * @dev This function MUST return either true or false - i.e. calling this - * function MUST NOT cause the caller to revert. - */ - function hasAttribute( - address account, - uint256 attributeTypeID - ) external view returns (bool) { - // Return assignment status of attribute by account and attribute type ID - return _issuedAttributes[account][attributeTypeID]; - } - - /** - * @notice Retrieve the value of the attribute of the type with ID - * `attributeTypeID` on the account at `account`, assuming it is valid. - * @param account address The account to check for the given attribute value. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return The attribute value if the attribute is valid, reverts otherwise. - * @dev This function MUST revert if a directly preceding or subsequent - * function call to `hasAttribute` with identical `account` and - * `attributeTypeID` parameters would return false. - */ - function getAttributeValue( - address account, - uint256 attributeTypeID - ) external view returns (uint256 value) { - // Revert if attribute with given account & attribute type ID is unassigned - require( - _issuedAttributes[account][attributeTypeID], - "could not find a value with the provided account and attribute type ID" - ); - - // Return the attribute value. - return _issuedAttributeValues[account][attributeTypeID]; - } - - /** - * @notice Count the number of attribute types defined by the registry. - * @return The number of available attribute types. - * @dev This function MUST return a positive integer value - i.e. calling - * this function MUST NOT cause the caller to revert. - */ - function countAttributeTypes() external view returns (uint256) { - // Return the length of the attribute type IDs array. - return _attributeTypeIDs.length; - } - - /** - * @notice Get the ID of the attribute type at index `index`. - * @param index uint256 The index of the attribute type in question. - * @return The ID of the attribute type. - * @dev This function MUST revert if the provided `index` value falls outside - * of the range of the value returned from a directly preceding or subsequent - * function call to `countAttributeTypes`. It MUST NOT revert if the provided - * `index` value falls inside said range. - */ - function getAttributeTypeID(uint256 index) external view returns (uint256) { - // Revert if the provided index is out of range. - require( - index < _attributeTypeIDs.length, - "provided index is outside of the range of defined attribute type IDs" - ); - - // Return the attribute type ID at the given index in the array. - return _attributeTypeIDs[index]; - } -} -``` - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1616.md diff --git a/EIPS/eip-162.md b/EIPS/eip-162.md index eaefc623561a14..3c028fa1f8a4f1 100644 --- a/EIPS/eip-162.md +++ b/EIPS/eip-162.md @@ -1,248 +1,7 @@ --- eip: 162 -title: Initial ENS Hash Registrar -author: Maurelian, Nick Johnson , Alex Van de Sande -status: Final -type: Standards Track category: ERC -created: 2016-10-25 +status: Moved --- -## Contents -- Abstract -- Motivations -- Specification - - Initial restrictions - - Name format for hash registration - - Auctioning names - - Deeds - - Deployment and Upgrade process - - Registrar Interface -- Rationale - - Not committing to a permanent registrar at the outset - - Valid names >= 7 characters - - Restricting TLD to `.eth` - - Holding ether as collateral -- Prior work - - - -## Abstract - -This ERC describes the implementation, as deployed to the main ethereum network on 2017-05-04, of a registrar contract to govern the allocation of names in the Ethereum Name Service (ENS). The corresponding source code is [here](https://github.com/ethereum/ens/blob/mainnet/contracts/HashRegistrarSimplified.sol). - -For more background, refer to [EIP 137](https://github.com/ethereum/EIPs/issues/137). - -> Registrars are responsible for allocating domain names to users of the system, and are the only entities capable of updating the ENS; the owner of a node in the ENS registry is its registrar. Registrars may be contracts or externally owned accounts, though it is expected that the root and top-level registrars, at a minimum, will be implemented as contracts. -> -> \- EIP 137 - -A well designed and governed registrar is essential to the success of the ENS described in EIP 137, but is described separately in this document as it is external to the core ENS protocol. - -In order to maximize utility and adoption of a new namespace, the registrar should mitigate speculation and "name squatting", however the best approach for mitigation is unclear. Thus an "initial" registrar is proposed, which implements a simple approach to name allocation. During the initial period, the available namespace will be significantly restricted to the `.eth` top level domain, and subdomain shorter than 7 characters in length disallowed. This specification largely describes @alexvandesande and @arachnid's [hash registrar implementation](https://github.com/ethereum/ens/blob/mainnet/contracts/HashRegistrarSimplified.sol) in order to facilitate discussion. - -The intent is to replace the Initial Registrar contract with a permanent registrar contract. The Permanent Registrar will increase the available namespace, and incorporate lessons learned from the performance of the Initial Registrar. This upgrade is expected to take place within approximately 2 years of initial deployment. - -## Motivations - -The following factors should be considered in order to optimize for adoption of the ENS, and good governance of the Initial Registrar's namespace. - -**Upgradability:** The Initial Registrar should be safely upgradeable, so that knowledge gained during its deployment can be used to replace it with an improved and permanent registrar. - -**Effective allocation:** Newly released namespaces often create a land grab situation, resulting in many potentially valuable names being purchased but unused, with the hope of re-selling at a profit. This reduces the availability of the most useful names, in turn decreasing the utility of the name service to end users. - -Achieving an effective allocation may or may not require human intervention for dispute resolution and other forms of curation. The Initial Registrar should not aim to create to most effective possible allocation, but instead limit the cost of misallocation in the long term. - -**Security:** The registrar will hold a balance of ether without an explicit limit. It must be designed securely. - -**Simplicity:** The ENS specification itself emphasizes a separation of concerns, allowing the most essential element, the registry to be as simple as possible. The interim registrar in turn should be as simple as possible while still meeting its other design goals. - -**Adoption:** Successful standards become more successful due to network effects. The registrar should consider what strategies will encourage the adoption of the ENS in general, and the namespace it controls in particular. - -## Specification - -### Initial restrictions - -The Initial Registrar is expected to be in service for approximately two years, prior to upgrading. This should be sufficient time to learn, observe, and design an updated system. - -During the initial two year period, the available name space will be restricted to the `.eth` TLD. - -This restriction is enforced by the owner of the ENS root node who should not assign any nodes other than `.eth` to the Initial Registrar. The ENS's root node should be controlled by multiple parties using a multisig contract. - -The Initial Registrar will also prohibit registration of names 6 characters or less in length. - -### Name format for hash registration - -Names submitted to the initial registrar must be hashed using Ethereum's sha3 function. Note that the hashes submitted to the registrar are the hash of the subdomain label being registered, not the namehash as defined in EIP 137. - -For example, in order to register `abcdefg.eth`, one should submit `sha3('abcdefg')`, not `sha3(sha3(0, 'eth'), 'abcdefg')`. - -### Auctioning names - -The registrar will allocate the available names through a Vickrey auction: - -> A Vickrey auction is a type of sealed-bid auction. Bidders submit written bids without knowing the bid of the other people in the auction. The highest bidder wins but the price paid is the second-highest bid. This type of auction... gives bidders an incentive to bid their true value. -> -> \- [Vickrey Auction, Wikipedia](https://en.wikipedia.org/wiki/Vickrey_auction) - -The auction lifecycle of a name has 5 possible states, or Modes. - -1. **Not-yet-available:** The majority of names will be initially unavailable for auction, and will become available some time during the 8 weeks after launch. -2. **Open:** The earliest availability for a name is determined by the most significant byte of its sha3 hash. `0x00` would become available immediately, `0xFF` would become available after 8 weeks, and the availability of other names is distributed accordingly. Once a name is available, it is possible to start an auction on it. -3. **Auction:** Once the auction for a name has begun, there is a 72 hour bidding period. Bidders must submit a payment of ether, along with sealed bids as a hash of `sha3(bytes32 hash, address owner, uint value, bytes32 salt)`. The bidder may obfuscate the true bid value by sending a greater amount of ether. -4. **Reveal:** After the bidding period, a 48 hour reveal period commences. During this time, bidders must reveal the true parameters of their sealed bid. As bids are revealed, ether payments are returned according to the schedule of "refund ratios" outlined in the table below. If no bids are revealed, the name will return to the Open state. -5. **Owned:** After the reveal period has finished, the winning bidder must submit a transaction to finalize the auction, which then calls the ENS's `setSubnodeOwner` function, recording the winning bidder's address as the owner of the hash of the name. - -The following table outlines important parameters which define the Registrar's auction mechanism. - -#### Registrar Parameters - -| Name | Description | Value | -|--------------------|----------------------------------------------------------------------------------------------------|------------| -| totalAuctionLength | The full time period from start of auction to end of the reveal period. | 5 days | -| revealPeriod | The length of the time period during which bidding is no longer allowed, and bids must be revealed. | 48 hours | -| launchLength | The time period during which all names will become available for auction. | 8 weeks | -| minPrice | The minimum amount of ether which must be locked up in exchange for ownership of a name. | 0.01 ether | - -### Deeds - -The Initial Registrar contract does not hold a balance itself. All ether sent to the Registrar will be held in a separate `Deed` contracts. A deed contract is first created and funded when a sealed bid is submitted. After an auction is completed and a hash is registered, the deed for the winning bid is held in exchange for ownership of the hash. Non-winning bids are refunded. - -A deed for an owned name may be transferred to another account by its owner, thus transferring ownership and control of the name. - -After 1 year of registration, the owner of a hash may choose to relinquish ownership and have the value of the deed returned to them. - -Deeds for non-winning bids can be closed by various methods, at which time any ether held will either be returned to the bidder, burnt, or sent to someone else as a reward for actions which help the registrar. - -The following table outlines what portion of the balance held in a deed contract will be returned upon closure, and to whom. The remaining balance will be burnt. - -#### Refund schedule - -| Reason for Deed closure | Refund Recipient | Refund Percentage | -| --- | --- | --- | -| A valid non-winning bid is revealed. | Bidder | 99.5% | -| A bid submitted after the auction period is revealed. | Bidder | 99.5% | -| An otherwise valid bid is revealed on an owned name. 1 | Bidder | 0.5% | -| An expired sealed bid is cancelled. 2 | Canceler | 0.5% | -| A registered hash is reported as invalid. 3 | Reporter | 50% | -| A registered hash is reported as invalid. 3 | Owner | 50% | - -##### Notes: - -1. This incentivizes all bids to be revealed in time. If bids could be revealed late, an extortion attack on the current highest bidder could be made by threatening to reveal a new second highest bid. -2. A bid which remains sealed after more than 2 weeks and 5 days may be cancelled by anyone to collect a small reward. -2. Since names are hashed before auctioning and registration, the Initial Registrar is unable to enforce character length restrictions independently. A reward is therefore provided for reporting invalid names. - -### Deployment and Upgrade process - -The Initial Registrar requires the ENS's address as a constructor, and should be deployed after the ENS. The multisig account owning the root node in the ENS should then set the Initial Registrar's address as owner of the `eth` node. - -The Initial Registrar is expected to be replaced by a Permanent Registrar approximately 2 years after deployment. The following process should be used for the upgrade: -1. The Permanent Registrar contract will be deployed. -2. The multisig account owning the root node in the ENS will assign ownership of the `.eth` node to the Permanent Registrar. -3. Owners of hashes in the Initial Registrar will be responsible for registering their deeds to the Permanent Registrar. A couple options are considered here: - 1. Require owners to transfer their ownership prior to a cutoff date in order to maintain ownership and/or continue name resolution services. - 2. Have the Permanent Registrar query the Initial Registrar for ownership if it is lacking an entry. - -### Planned deactivation - -In order to limit dependence on the Initial Registrar, new auctions will stop after 4 years, and all ether held in deeds after 8 years will become unreachable. - -### Registrar Interface - -`function state(bytes32 _hash) constant returns (Mode)` -- Implements a state machine returning the current state of a name - -`function entries(bytes32 _hash) constant returns (Mode, address, uint, uint, uint)` -- Returns the following information regarding a registered name: - * state - * deed address - * registration date - * balance of the deed - * highest value bid at auction - -`function getAllowedTime(bytes32 _hash) constant returns (uint timestamp)` -- Returns the time at which the hash will no longer be in the initial `not-yet-available` state. - -`function isAllowed(bytes32 _hash, uint _timestamp) constant returns (bool allowed)` -- Takes a hash and a time, returns true if and only if it has passed the initial `not-yet-available` state. - -`function startAuction(bytes32 _hash);` -- Moves the state of a hash from Open to Auction. Throws if state is not Open. - -`function startAuctions(bytes32[] _hashes);` -- Starts multiple auctions on an array of hashes. This enables someone to open up an auction for a number of dummy hashes when they are only really interested in bidding for one. This will increase the cost for an attacker to simply bid blindly on all new auctions. Dummy auctions that are open but not bid on are closed after a week. - -`function shaBid(bytes32 hash, address owner, uint value, bytes32 salt) constant returns (bytes32 sealedBid);` -- Takes the parameters of a bid, and returns the sealedBid hash value required to participate in the bidding for an auction. This obfuscates the parameters in order to mimic the mechanics of placing a bid in an envelope. - -`function newBid(bytes32 sealedBid);` -- Bids are sent by sending a message to the main contract with a sealedBid hash and an amount of ether. The hash contains information about the bid, including the bidded name hash, the bid value, and a random salt. Bids are not tied to any one auction until they are revealed. The value of the bid itself can be masqueraded by sending more than the value of your actual bid. This is followed by a 48h reveal period. Bids revealed after this period will be burned and the ether unrecoverable. Since this is an auction, it is expected that most public hashes, like known domains and common dictionary words, will have multiple bidders pushing the price up. - -`function startAuctionsAndBid(bytes32[] hashes, bytes32 sealedBid)` -- A utility function allowing a call to `startAuctions` followed by `newBid` in a single transaction. - - -`function unsealBid(bytes32 _hash, address _owner, uint _value, bytes32 _salt);` -- Once the bidding period is completed, there is a reveal period during with the properties of a bid are submitted to reveal them. The registrar hashes these properties using the `shaBid()` function above to verify that they match a pre-existing sealed bid. If the unsealedBid is the new best bid, the old best bid is returned to its bidder. - -`function cancelBid(bytes32 seal);` -- Cancels an unrevealed bid according to the rules described in the notes on the refund schedule above. - -`function finalizeAuction(bytes32 _hash);` - -After the registration date has passed, this function can be called to finalize the auction, which then calls the ENS function `setSubnodeOwner()` updating the ENS record to set the winning bidder as owner of the node. - -`function transfer(bytes32 _hash, address newOwner);` -- Update the owner of the ENS node corresponding to the submitted hash to a new owner. This function must be callable only by the current owner. - -`function releaseDeed(bytes32 _hash);` -- After some time, the owner can release the property and get their ether back. - -`function invalidateName(string unhashedName);` -- Since registration is done on the hash of a name, the registrar itself cannot validate names. This function can be used to report a name which is 6 characters long or less. If it has been registered, the submitter will earn 10% of the deed value. We are purposefully handicapping the simplified registrar as a way to force it into being restructured in a few years. - -`function eraseNode(bytes32[] labels)` -- Allows anyone to delete the owner and resolver records for a subdomain of a name that is not currently owned in the registrar. For instance, to zero `foo.bar.eth` on a registrar that owns `.eth`, pass an array containing `[sha3('foo'), sha3('bar')]`. - -`function transferRegistrars(bytes32 _hash) onlyOwner(_hash);` -- Used during the upgrade process to a permanent registrar. If this registrar is no longer the owner of the its root node in the ENS, this function will transfers the deed to the current owner, which should be a new registrar. This function throws if this registrar still owns its root node. - -## Rationale - -### Starting with a temporary registrar - -Anticipating and designing for all the potential issues of name allocation names is unlikely to succeed. This approach chooses not to be concerned with getting it perfect, but allows us to observe and learn with training wheels on, and implement improvements before expanding the available namespace to shorter names or another TLD. - -### Valid names >= 7 characters - -Preserving the shortest, and often most valuable, domain names for the upgraded registrar provides the opportunity to implement processes for dispute resolution (assuming they are found to be necessary). - -### Delayed release of names - -A slower release allows for extra time to identify, and address any issues which may arise after launch. - -### Restricting TLD to `.eth` - -Choosing a single TLD helps to maximize network effects by focusing on one namespace. - -A three letter TLD is a pattern made familiar by it's common usage in internet domain names. This familiarity significantly increases the potential of the ENS to be integrated into pre-existing DNS systems, and reserved as a [special-use domain name](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml#special-use-domain). A recent precedent for this is the [reservation of the `.onion` domain](https://tools.ietf.org/html/rfc7686). - -### Holding ether as collateral - -This approach is simpler than the familiar model of requiring owners to make recurring payments to retain ownership of a domain name. It also makes the initial registrar a revenue neutral service. - -## Prior work - -This document borrows heavily from several sources: -- [EIP 137](https://github.com/ethereum/EIPs/issues/137) outlines the initial implementation of the Registry Contract (ENS.sol) and associated Resolver contracts. -- [ERC 26](https://github.com/ethereum/EIPs/issues/26) was the first ERC to propose a name service at the contract layer -- @alexvandesande's current implementation of the [HashRegistrar](https://github.com/ethereum/ens/blob/mainnet/contracts/HashRegistrarSimplified.sol) - -### Edits: -- 2016-10-26 Added link Alex's design in abstract -- 2016-11-01 change 'Planned deactivation' to h3' -- 2017-03-13 Update timelines for bidding and reveal periods - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-162.md diff --git a/EIPS/eip-1620.md b/EIPS/eip-1620.md index fc127e91266fca..0b348ff48c4163 100644 --- a/EIPS/eip-1620.md +++ b/EIPS/eip-1620.md @@ -1,308 +1,7 @@ --- eip: 1620 -title: ERC-1620 Money Streaming -author: Paul Berg (@PaulRBerg) -discussions-to: https://github.com/ethereum/EIPs/issues/1620 -status: Draft -type: Standards Track category: ERC -created: 2018-11-24 +status: Moved --- - - -## Simple Summary - -Money streaming represents the idea of continuous payments over a finite period of time. Block numbers are used as a proxy of time to continuously update balances. - -## Abstract - -The following describes a standard whereby time is measured using block numbers and streams are mappings in a master contract. - -1. A provider sets up a money streaming contract. -2. A prospective payer can interact with the contract and start the stream right away by depositing the funds required for the chosen period. -3. The payee is able to withdraw money from the contract based on its ongoing solvency. That is: `payment rate * (current block height - starting block height)` -4. The stream terms (payment rate, length, metadata) can be updated at any time if both parties pledge their signatures. -5. The stream can be stopped at any point in time by any party without on-chain consensus. -6. If the stream period ended and it was not previously stopped by any party, the payee is entitled to withdraw all the deposited funds. - -## Motivation - -This standardised interface aims to change the way we think about long-term financial commitments. Thanks to blockchains, payments need not be sent in chunks (e.g. monthly salaries), as there is much less overhead in paying-as-you-go. Money as a function of time would better align incentives in a host of scenarios. - -### Use Cases - -This is just a preliminary list of use cases. There are other spooky ideas interesting to explore, such as time-dependent disincetivisation, but, for brevity, we have not included them here. - -- Salaries -- Subscriptions -- Consultancies -- CDPs -- Rent -- Parking - -### Crowdsales -[RICOs](https://github.com/lukso-network/rico), or Reversible ICOs, were introduced at Devcon4 by @frozeman. The idea is to endow investors with more power and safety guarantees by allowing them to "reverse" the investment based on the evolution of the project. We previously discussed a similar concept called SICOs, or Streamable ICOs, in this research [thread](https://ethresear.ch/t/chronos-a-quirky-application-proposal-for-plasma/2928/14?u=paulrberg). - -Instead of investing a lump sum and giving the money away to the project developers, funds are held in a smart contract which allocates money based on the passage of time. Project developers can withdraw funds as the stream stays active, while investors have the power to get back a significant percentage of their initial commitment if the project halts. - -## Specification - - -
Expand - -### Structs - -The structure of a `stream` should be as follows: - -- `stream` - - `sender`: the `address` of the entity funding the stream - - `recipient`: the `address` where the money is being delivered to - - `tokenAddress`: the `address` of the ERC20 token used as payment asset - - `balance`: the total funds left in the stream - - `timeframe`: as defined below - - `rate`: as defined below - -```solidity - struct Stream { - address sender; - address recipient; - address tokenAddress; - uint256 balance; - Timeframe timeframe; - Rate rate; - } -``` - -- `timeframe` - - `start`: the starting block number of the stream - - `stop`: the stopping block number of the stream - -```solidity -struct Timeframe { - uint256 start; - uint256 stop; -} -``` - -- `rate` - - `payment`: how much money moves from `sender` to `recipient` - - `interval`: how often `payment` moves from `sender` to `recipient` - -```solidity -struct Rate { - uint256 payment; - uint256 interval; -} -``` - ---- - -### Methods - -#### balanceOf - -Returns available funds for the given stream id and address. - -```solidity -function balanceOf(uint256 _streamId, address _addr) -``` - -#### getStream - -Returns the full stream data, if the id points to a valid stream. - -```solidity -function getStream(uint256 _streamId) returns (address sender, address recipient, address tokenAddress, uint256 balance, uint256 startBlock, uint256 stopBlock, uint256 payment, uint256 interval) -``` - -#### create - -Creates a new stream between `msg.sender` and `_recipient`. - -MUST allow senders to create multiple streams in parallel. SHOULD not accept Ether and only use ERC20-compatible tokens. - -**Triggers Event**: [LogCreate](#log-create) - -```solidity -function create(address _recipient, address _tokenAddress, uint256 _startBlock, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - -#### withdraw - -Withdraws all or a fraction of the available funds. - -MUST allow only the recipient to perform this action. - -**Triggers Event**: [LogWithdraw](#log-withdraw) - -```solidity -function withdraw(uint256 _streamId, uint256 _funds) -``` - -#### redeem - -Redeems the stream by distributing the funds to the sender and the recipient. - -SHOULD allow any party to redeem the stream. - -**Triggers Event**: [LogRedeem](#log-redeem) - -```solidity -function redeem(uint256 _streamId) -``` - -#### confirmUpdate - -Signals one party's willingness to update the stream - -SHOULD allow any party to do this but MUST NOT be executed without consent from all involved parties. - -**Triggers Event**: [LogConfirmUpdate](#log-confirm-update) - -**Triggers Event**: [LogExecuteUpdate](#log-execute-update) when the last involved party calls this function - -```solidity -function update(uint256 _streamId, address _tokenAddress, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - -#### revokeUpdate - -Revokes an update proposed by one of the involved parties. - -MUST allow any party to do this. - -**Triggers Event**: [LogRevokeUpdate](#log-revoke-update) - -```solidity -function confirmUpdate(uint256 _streamId, address _tokenAddress, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - ---- - -### Events - -#### LogCreate - -MUST be triggered when `create` is successfully called. - -```solidity -event LogCreate(uint256 indexed _streamId, address indexed _sender, address indexed _recipient, address _tokenAddress, uint256 _startBlock, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - -#### LogWithdraw - -MUST be triggered when `withdraw` is successfully called. - -```solidity -event LogWithdraw(uint256 indexed _streamId, address indexed _recipient, uint256 _funds) -``` - -#### LogRedeem - -MUST be triggered when `redeem` is successfully called. - -```solidity -event LogRedeem(uint256 indexed _streamId, address indexed _sender, address indexed _recipient, uint256 _senderBalance, uint256 _recipientBalance) -``` - -#### LogConfirmUpdate - -MUST be triggered when `confirmUpdate` is successfully called. - -```solidity -event LogConfirmUpdate(uint256 indexed _streamId, address indexed _confirmer, address _newTokenAddress, uint256 _newStopBlock, uint256 _newPayment, uint256 _newInterval); -``` - -#### LogRevokeUpdate - -MUST be triggered when `revokeUpdate` is successfully called. - -```solidity -event LogRevokeUpdate(uint256 indexed _streamId, address indexed revoker, address _newTokenAddress, uint256 _newStopBlock, uint256 _newPayment, uint256 _newInterval) -``` - -#### LogExecuteUpdate - -MUST be triggered when an update is approved by all involved parties. - -```solidity -event LogExecuteUpdate(uint256 indexed _newStreamId, address indexed _sender, address indexed _recipient, address _newTokenAddress, uint256 _newStopBlock, uint256 _newPayment, uint256 _newInterval) -``` - -
- -## Rationale - - -This specification was designed to serve as an entry point to the quirky concept of money as a function of time and it is definitely not set in stone. Several other designs, including payment channels and Plasma chains were also considered, but they were eventually deemed dense in assumptions unnecessary for an initial version. - - - -Block times are a reasonable, trustless proxy for time on the blockchain. Between 2016 and 2018, the Ethereum block time average value [hovered](https://etherscan.io/chart/blocktime) around 14 seconds, excluding the last two quarters of 2017. Mathematically speaking, it would be ideal to have a standard deviation as close to 0 as possible, but that is not how things work in the real world. This has huge implications on the feasibility of this ERC which we shall investigate below. - -### GCD -When setting up a stream, a payer and a payee may want to make the total streaming duration a multiple of the "greatest common denominator" (GCD) of the chain they operate on; that is, the average block time. This is not imperative in the smart contracts per se, but there needs to be an off-chain process to map streams to real world time units in order to create a sound and fair payment mechanism. - -### Block Times -Because there is uncertainty regarding block times, streams may not be settled on the blockchain as initially planned. Let `$d` be the total streaming duration measured in seconds, `$t` the average block time before the stream started and `$t'` the actual average block time over `$d` after the stream started. We distinguish two undesirable scenarios: - -1. `$t` < `$t'`: the payee will get their funds *later* than expected - -2. `$t` > `$t'`: the payee will get their funds *sooner* than expected - -If the combined error delta is smaller than the payment rate (fifth parameter of the `create` method, measured in wei), there is no problem at all. Conversely, we stumble upon trust issues because real-world time frames do not correspond to the stream terms. For instance, if an employee is normally entitled to withdraw all the funds from the stream at the end of the month, but block times cause case 1 from above to occur, the employee is in a financial disadvantage because their continuous effort is not compensated as promised. - -Limiting the problem scope only to Ethereum, we propose two remedies: - -1. Consensus on calling the `update` function to correct the stream terms. This might sound preposterous, but in most cases the stakes are low and stream participants are involved in long-term financial commitments. There is a high disincentive to refuse to cooperate. - -2. Autonomously fix significant error deltas. In theory, we could achieve this using previous blocks' timestamps, "checkpointing" the stream once in a predefined number of blocks. This is still an area of active research because of potentially high overheads in gas costs. - -Nonetheless, it is important to note that this is still a major improvement on the traditional model where absolute trust is required. - -### Sidechains - -It could be more efficient to implement this standard on independent sidechains like [POA Network](https://poa.network) or [xDai](https://medium.com/poa-network/poa-network-partners-with-makerdao-on-xdai-chain-the-first-ever-usd-stable-blockchain-65a078c41e6a) - thanks to their rather predictable nature. Admittedly, security is traded for scalability, but proper cryptoeconomic stakes could alleviate potential problems. - -Furthermore, it is intriguing to explore the prospect of stream-specific sidechains. - -### Oracles - -The proposed specification uses block numbers to proxy time, but this need not be the only method. Albeit it would imply different trust assumptions, oracles could be used to provide a feed of timestamps. Coupled with the aforementioned idea of stream-specific sidechains, oracles could efficiently solve the problems outlined in [Block Times](#block-times). - -### Multi-Hop Streams - -Future or upgraded versions of this standard may describe "multi-hop" streams. If: - -1. There is a stream between A and B -2. There is another stream between B and C - -There could be a way to avoid running two different streams in parallel. That is, a fraction or all of the funds being streamed from A to B could be automatically wired to C. An interesting use case for this is taxes. Instead of manually moving money around, proactively calculating how much you owe and then transfer it, a stream could atomically perform those operations for you. - -## Implementation - - -- [ChronosProtocol WIP implementation](https://github.com/ChronosProtocol/monorepo) - -## Additional References -- [Chronos Protocol Ethresear.ch Plasma Proposal](https://ethresear.ch/t/chronos-a-quirky-application-proposal-for-plasma/2928?u=paulrberg) -- [Chronos Protocol White Paper](http://chronosprotocol.org/chronos-white-paper.pdf) -- [Flipper: Streaming Salaries @ CryptoLife Hackathon](https://devpost.com/software/flipper-3gvl4b) -- [SICOs or Streamed ICOs](https://ethresear.ch/t/chronos-a-quirky-application-proposal-for-plasma/2928/14?u=paulrberg) -- [RICOs or Reversible ICOs](https://twitter.com/feindura/status/1058057076306518017) -- [Andreas Antonopoulos' Keynote on Bitcoin, Lightning and Money Streaming](https://www.youtube.com/watch?v=gF_ZQ_eijPs) - -## Final Notes - -Many thanks to @mmilton41 for countless brainstorming sessions. We have been doing research on the topic of money streaming for quite a while within the context of @ChronosProtocol. In August this year, we published the first version of our white paper describing a Plasma approach. However, in the meantime, we realised that it would be much more [fun](https://twitter.com/PaulRBerg/status/1056595919116910592) and easier to start small on Ethereum itself and sidechains like [xDai](https://blockscout.com/poa/dai). - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1620.md diff --git a/EIPS/eip-1633.md b/EIPS/eip-1633.md new file mode 100644 index 00000000000000..d6d4959661f223 --- /dev/null +++ b/EIPS/eip-1633.md @@ -0,0 +1,7 @@ +--- +eip: 1633 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1633.md diff --git a/EIPS/eip-165.md b/EIPS/eip-165.md index b930acbcc045d5..8cdfd7787845ec 100644 --- a/EIPS/eip-165.md +++ b/EIPS/eip-165.md @@ -1,235 +1,7 @@ --- eip: 165 -title: ERC-165 Standard Interface Detection -author: Christian Reitwießner , Nick Johnson , Fabian Vogelsteller , Jordi Baylina , Konrad Feldmeier , William Entriken -type: Standards Track category: ERC -status: Final -created: 2018-01-23 -requires: 214 +status: Moved --- -## Simple Summary - -Creates a standard method to publish and detect what interfaces a smart contract implements. - -## Abstract - -Herein, we standardize the following: - -1. How interfaces are identified -2. How a contract will publish the interfaces it implements -3. How to detect if a contract implements ERC-165 -4. How to detect if a contract implements any given interface - -## Motivation - -For some "standard interfaces" like [the ERC-20 token interface](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md), it is sometimes useful to query whether a contract supports the interface and if yes, which version of the interface, in order to adapt the way in which the contract is to be interacted with. Specifically for ERC-20, a version identifier has already been proposed. This proposal standardizes the concept of interfaces and standardizes the identification (naming) of interfaces. - -## Specification - -### How Interfaces are Identified - -For this standard, an *interface* is a set of [function selectors as defined by the Ethereum ABI](https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector). This a subset of [Solidity's concept of interfaces](https://solidity.readthedocs.io/en/develop/abi-spec.html) and the `interface` keyword definition which also defines return types, mutability and events. - -We define the interface identifier as the XOR of all function selectors in the interface. This code example shows how to calculate an interface identifier: - -```solidity -pragma solidity ^0.4.20; - -interface Solidity101 { - function hello() external pure; - function world(int) external pure; -} - -contract Selector { - function calculateSelector() public pure returns (bytes4) { - Solidity101 i; - return i.hello.selector ^ i.world.selector; - } -} -``` - -Note: interfaces do not permit optional functions, therefore, the interface identity will not include them. - -### How a Contract will Publish the Interfaces it Implements - -A contract that is compliant with ERC-165 shall implement the following interface (referred as `ERC165.sol`): - -```solidity -pragma solidity ^0.4.20; - -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -The interface identifier for this interface is `0x01ffc9a7`. You can calculate this by running ` bytes4(keccak256('supportsInterface(bytes4)'));` or using the `Selector` contract above. - -Therefore the implementing contract will have a `supportsInterface` function that returns: - -- `true` when `interfaceID` is `0x01ffc9a7` (EIP165 interface) -- `false` when `interfaceID` is `0xffffffff` -- `true` for any other `interfaceID` this contract implements -- `false` for any other `interfaceID` - -This function must return a bool and use at most 30,000 gas. - -Implementation note, there are several logical ways to implement this function. Please see the example implementations and the discussion on gas usage. - -### How to Detect if a Contract Implements ERC-165 - -1. The source contract makes a `STATICCALL` to the destination address with input data: `0x01ffc9a701ffc9a700000000000000000000000000000000000000000000000000000000` and gas 30,000. This corresponds to `contract.supportsInterface(0x01ffc9a7)`. -2. If the call fails or return false, the destination contract does not implement ERC-165. -3. If the call returns true, a second call is made with input data `0x01ffc9a7ffffffff00000000000000000000000000000000000000000000000000000000`. -4. If the second call fails or returns true, the destination contract does not implement ERC-165. -5. Otherwise it implements ERC-165. - -### How to Detect if a Contract Implements any Given Interface - -1. If you are not sure if the contract implements ERC-165, use the above procedure to confirm. -2. If it does not implement ERC-165, then you will have to see what methods it uses the old-fashioned way. -3. If it implements ERC-165 then just call `supportsInterface(interfaceID)` to determine if it implements an interface you can use. - -## Rationale - -We tried to keep this specification as simple as possible. This implementation is also compatible with the current Solidity version. - -## Backwards Compatibility - -The mechanism described above (with `0xffffffff`) should work with most of the contracts previous to this standard to determine that they do not implement ERC-165. - -Also [the ENS](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md) already implements this EIP. - -## Test Cases - -Following is a contract that detects which interfaces other contracts implement. From @fulldecent and @jbaylina. - -```solidity -pragma solidity ^0.4.20; - -contract ERC165Query { - bytes4 constant InvalidID = 0xffffffff; - bytes4 constant ERC165ID = 0x01ffc9a7; - - function doesContractImplementInterface(address _contract, bytes4 _interfaceId) external view returns (bool) { - uint256 success; - uint256 result; - - (success, result) = noThrowCall(_contract, ERC165ID); - if ((success==0)||(result==0)) { - return false; - } - - (success, result) = noThrowCall(_contract, InvalidID); - if ((success==0)||(result!=0)) { - return false; - } - - (success, result) = noThrowCall(_contract, _interfaceId); - if ((success==1)&&(result==1)) { - return true; - } - return false; - } - - function noThrowCall(address _contract, bytes4 _interfaceId) constant internal returns (uint256 success, uint256 result) { - bytes4 erc165ID = ERC165ID; - - assembly { - let x := mload(0x40) // Find empty storage location using "free memory pointer" - mstore(x, erc165ID) // Place signature at beginning of empty storage - mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature - - success := staticcall( - 30000, // 30k gas - _contract, // To addr - x, // Inputs are stored at location x - 0x24, // Inputs are 36 bytes long - x, // Store output over input (saves space) - 0x20) // Outputs are 32 bytes long - - result := mload(x) // Load the result - } - } -} -``` - -## Implementation - -This approach uses a `view` function implementation of `supportsInterface`. The execution cost is 586 gas for any input. But contract initialization requires storing each interface (`SSTORE` is 20,000 gas). The `ERC165MappingImplementation` contract is generic and reusable. - -```solidity -pragma solidity ^0.4.20; - -import "./ERC165.sol"; - -contract ERC165MappingImplementation is ERC165 { - /// @dev You must not set element 0xffffffff to true - mapping(bytes4 => bool) internal supportedInterfaces; - - function ERC165MappingImplementation() internal { - supportedInterfaces[this.supportsInterface.selector] = true; - } - - function supportsInterface(bytes4 interfaceID) external view returns (bool) { - return supportedInterfaces[interfaceID]; - } -} - -interface Simpson { - function is2D() external returns (bool); - function skinColor() external returns (string); -} - -contract Lisa is ERC165MappingImplementation, Simpson { - function Lisa() public { - supportedInterfaces[this.is2D.selector ^ this.skinColor.selector] = true; - } - - function is2D() external returns (bool){} - function skinColor() external returns (string){} -} -``` - -Following is a `pure` function implementation of `supportsInterface`. The worst-case execution cost is 236 gas, but increases linearly with a higher number of supported interfaces. - -```solidity -pragma solidity ^0.4.20; - -import "./ERC165.sol"; - -interface Simpson { - function is2D() external returns (bool); - function skinColor() external returns (string); -} - -contract Homer is ERC165, Simpson { - function supportsInterface(bytes4 interfaceID) external view returns (bool) { - return - interfaceID == this.supportsInterface.selector || // ERC165 - interfaceID == this.is2D.selector - ^ this.skinColor.selector; // Simpson - } - - function is2D() external returns (bool){} - function skinColor() external returns (string){} -} -``` - -With three or more supported interfaces (including ERC165 itself as a required supported interface), the mapping approach (in every case) costs less gas than the pure approach (at worst case). - -## Version history -* PR 1640, finalized 2019-01-23 -- This corrects the noThrowCall test case to use 36 bytes rather than the previous 32 bytes. The previous code was an error that still silently worked in Solidity 0.4.x but which was broken by new behavior introduced in Solidity 0.5.0. This change was discussed at [#1640](https://github.com/ethereum/EIPs/pull/1640). - -* EIP 165, finalized 2018-04-20 -- Original published version. - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-165.md diff --git a/EIPS/eip-1679.md b/EIPS/eip-1679.md index c7e99985869ec5..b3f791b88d7b19 100644 --- a/EIPS/eip-1679.md +++ b/EIPS/eip-1679.md @@ -4,9 +4,9 @@ title: "Hardfork Meta: Istanbul" author: Alex Beregszaszi (@axic), Afri Schoedon (@5chdn) discussions-to: https://ethereum-magicians.org/t/hardfork-meta-istanbul-discussion/3207 type: Meta -status: Draft +status: Final created: 2019-01-04 -requires: 1716 +requires: 152, 1108, 1344, 1716, 1884, 2028, 2200 --- ## Abstract @@ -16,66 +16,27 @@ This meta-EIP specifies the changes included in the Ethereum hardfork named Ista ## Specification - Codename: Istanbul -- Activation: TBD -### Included EIPs - -- TBD - -### Accepted EIPs - -- TBD +### Activation + - `Block >= 9,069,000` on the Ethereum Mainnet + - `Block >= 6,485,846` on the Ropsten testnet + - `Block >= 14,111,141` on the Kovan testnet + - `Block >= 5,435,345` on the Rinkeby testnet + - `Block >= 1,561,651` on the Görli testnet -### Proposed EIPs - -- [EIP-615](https://eips.ethereum.org/EIPS/eip-615): Subroutines and Static Jumps for the EVM -- [EIP-663](https://eips.ethereum.org/EIPS/eip-663): Unlimited SWAP and DUP instructions -- [EIP-1057](https://eips.ethereum.org/EIPS/eip-1057): ProgPoW, a Programmatic - Proof-of-Work - - There is a - [pending audit](https://medium.com/ethereum-cat-herders/progpow-audit-goals-expectations-75bb902a1f01), - above and beyond standard security considerations, that should be evaluated - prior to inclusion. -- [EIP-1108](https://eips.ethereum.org/EIPS/eip-1108): Reduce alt_bn128 precompile gas costs -- [EIP-1109](https://eips.ethereum.org/EIPS/eip-1109): PRECOMPILEDCALL opcode (Remove CALL costs for precompiled contracts) - - requirement of EIP-1962 -- [EIP-1283](https://eips.ethereum.org/EIPS/eip-1283): Net gas metering for SSTORE without dirty maps -- [EIP-1344](https://eips.ethereum.org/EIPS/eip-1344): Add ChainID opcode -- [EIP-1352](https://eips.ethereum.org/EIPS/eip-1352): Specify restricted address range for precompiles/system contracts -- [EIP-1380](https://eips.ethereum.org/EIPS/eip-1380): Reduced gas cost for call to self -- [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559): Fee market change for ETH 1.0 chain -- [EIP-1965](https://eips.ethereum.org/EIPS/eip-1965): Method to check if a chainID is valid at a specific block Number -- [EIP-1702](https://eips.ethereum.org/EIPS/eip-1702): Generalized account versioning scheme -- [EIP-1706](https://eips.ethereum.org/EIPS/eip-1706): Disable SSTORE with gasleft lower than call stipend -- [EIP-1803](https://eips.ethereum.org/EIPS/eip-1803): Rename opcodes for clarity -- [EIP-1829](https://eips.ethereum.org/EIPS/eip-1829): Precompile for Elliptic Curve Linear Combinations -- [EIP-1884](https://eips.ethereum.org/EIPS/eip-1884): Repricing for trie-size-dependent opcodes -- [EIP-1930](https://eips.ethereum.org/EIPS/eip-1930): CALLs with strict gas semantic. Revert if not enough gas available. -- [EIP-1985](https://eips.ethereum.org/EIPS/eip-1985): Sane limits for certain EVM parameters -- [EIP-1959](https://eips.ethereum.org/EIPS/eip-1959): New Opcode to check if a chainID is part of the history of chainIDs -- [EIP-1962](https://eips.ethereum.org/EIPS/eip-1962): EC arithmetic and pairings with runtime definitions - - replaces EIP-1829 -- [EIP-2014](https://eips.ethereum.org/EIPS/eip-2014): Extended State Oracle -- [EIP-2026](https://eips.ethereum.org/EIPS/eip-2026): State Rent H - Fixed Prepayment for accounts -- [EIP-2027](https://eips.ethereum.org/EIPS/eip-2027): State Rent C - Net contract size accounting -- [EIP-2028](https://eips.ethereum.org/EIPS/eip-2028): Calldata gas cost reduction -- [EIP-2029](https://eips.ethereum.org/EIPS/eip-2029): State Rent A - State counters contract - - requirement of EIP-2031 -- [EIP-2031](https://eips.ethereum.org/EIPS/eip-2031): State Rent B - Net transaction counter -- [EIP-2035](https://eips.ethereum.org/EIPS/eip-2035): Stateless Clients - Repricing SLOAD and SSTORE to pay for block proofs -- [EIP-2046](https://eips.ethereum.org/EIPS/eip-2046): Reduced gas cost for static calls made to precompiles - -## Timeline - -* 2019-05-17 (Fri) hard deadline to accept proposals for "Istanbul" -* 2019-07-19 (Fri) soft deadline for major client implementations -* 2019-08-14 (Wed) projected date for testnet network upgrade (Ropsten, Görli, or ad-hoc testnet) -* 2019-10-16 (Wed) projected date for mainnet upgrade ("Istanbul") +### Included EIPs + - [EIP-152](./eip-152.md): Add Blake2 compression function `F` precompile + - [EIP-1108](./eip-1108.md): Reduce alt_bn128 precompile gas costs + - [EIP-1344](./eip-1344.md): Add ChainID opcode + - [EIP-1884](./eip-1884.md): Repricing for trie-size-dependent opcodes + - [EIP-2028](./eip-2028.md): Calldata gas cost reduction + - [EIP-2200](./eip-2200.md): Rebalance net-metered SSTORE gas cost with consideration of SLOAD gas cost change ## References -- [Core Dev call notes](https://github.com/ethereum/pm/issues/66#issuecomment-450840440) where timeline was proposed and accepted +1. Included EIPs were finalized in [All Core Devs Call #68](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2068.md) +2. https://medium.com/ethereum-cat-herders/istanbul-testnets-are-coming-53973bcea7df ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1681.md b/EIPS/eip-1681.md index 28c6b2fca4a720..a17f2c9dc8d497 100644 --- a/EIPS/eip-1681.md +++ b/EIPS/eip-1681.md @@ -3,7 +3,7 @@ eip: 1681 title: Temporal Replay Protection author: Martin Holst Swende (@holiman) discussions-to: https://ethereum-magicians.org/t/temporal-replay-protection/2355 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-01-08 @@ -87,5 +87,5 @@ user actively wants to start using it. Secondary security impacts are that the addition of a timestamp would make the transactions a little bit larger. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1682.md b/EIPS/eip-1682.md new file mode 100644 index 00000000000000..3a0f0a5ee13217 --- /dev/null +++ b/EIPS/eip-1682.md @@ -0,0 +1,220 @@ +--- +eip: 1682 +title: Storage Rent +author: Felix J Lange (@fjl), Martin Holst Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/storage-rent-eip/2357 +status: Withdrawn +type: Standards Track +category: Core +created: 2018-11-10 +--- + +## Abstract + +This EIP describes a scheme to charge for data in state, and 'archive' data which is no longer being paid for. It also describes how resurrection of 'archived' data happens. + +## Motivation + +The Ethereum blockchain in its current form is not sustainable because it grows +indefinitely. This is true of any blockchain, but Ethereum grows faster than most chains. +Many implementation strategies to slow down growth exist. A common strategy is 'state +pruning' which discards historical state, keeping only the active copy of contract data +and a few recent versions to deal with short-range chain reorganizations. Several +implementations also employ compression techniques to keep the active copy of the state as +small as possible. + +A full node participating in consensus today requires storing large amounts of data even +with advanced storage optimizations applied. Future storage requirements are unbounded +because any data stored in a contract must be retained forever as dictated by the +protocol. This EIP attempts to correct this by adding new consensus rules that put an +upper bound on the size of the Ethereum state. + +Adding these new rules changes fundamental guarantees of the system and requires a hard +fork. Users of Ethereum already pay for the creation and modification of accounts and +their storage entries. Under the rules introduced in this EIP, users must also pay to keep +accounts accessible. A similar rent scheme was proposed in [EIP-103] but rejected +even back then because the proposal would've upset peoples expectations. As implementers +of Ethereum, we still feel that state rent is the right path to long-term sustainability +of the Ethereum blockchain and that its undesirable implications can be overcome with +off-protocol tooling and careful design. + +[EIP-103]: https://github.com/ethereum/EIPs/issues/35 + +## Specification + +The cost of storing an account over time is called `rent`. The amount of `rent` due depends +on the size of the account. The `ether` that is paid for `rent` is destroyed. The `rent` is deducted whenever an account is touched. + +`rent` can be paid from the account's regular `balance` or from its 'rent balance'. Accounts +can be endowed with `rent balance` through a new EVM opcode. When `rent` is charged, it is +first taken from the `rent balance`. When `rent balance` is zero, it is instead charged from the account's regular `balance` instead. + +The reason to separate `balance` and `rent balance` is that certain contracts do not accept `ether` sends, or always send the entire balance off to some other destination. For these cases, a separate`rent balance` is required. + +When an account's `balance` is insufficient to pay rent, the account becomes `inactive`. Its +storage and contract code are removed. Inactive accounts cannot be interacted with, i.e. +it behaves as if it has no contract code. + +Inactive accounts can be restored by re-uploading their storage. To restore an inactive +account `A`, a new account `B` is created with arbitrary code and its storage modified +with `SSTORE` operations until it matches the storage root of `A`. Account `B` can restore +`A` through the `RESTORETO` opcode. This means the cost of restoring an account is +equivalent to recreating it via successive `SSTORE` operations. + +### Changes To State + +At the top level, a new key `size` is added to the accounts trie. This key tracks the +total number of trie nodes across all accounts, including storage trie nodes. To track +rent, the structure of account entries is changed as well. + +Before processing the block in which this EIP becomes active, clients iterate the whole +state once to count the number of trie nodes and to change the representation of all +accounts to the new format. + +#### Account Representation + +```text +account = [nonce, balance, storageroot, codehash, rentbalance, rentblock, storagesize] +``` + +Each account gets three additional properties: `rentbalance`, `rentblock` and +`storagesize`. + +The `rentbalace` field tracks the amount of `rent balance` available to the account. Upon +self-destruction any remaining `rent balance` is transferred to the beneficiary. Any +modification of the account recomputes its current `rent balance`. + +The `rentblock` field tracks the block number in which the `rent balance` was last +recomputed. Upon creation, this field is initialized with the current block number. +`rentblock` is also updated with the current block number whenever the account is +modified. + +The `storagesize` field tracks the amount of storage related to the account. It is a +number containing the number of storage slots currently set. The `storagesize` of an +inactive account is zero. + +### Charging Rent + +There is a new protocol constant `MAX_STORAGE_SIZE` that specifies the upper bound on the +number of state tree nodes: + +```python +MAX_STORAGE_SIZE = 2**32 # ~160GB of state +``` + +A 'storage fee factor' for each block is derived from this constant such that fees +increase as the limit is approached. + +```python +def storagefee_factor(block): + ramp = MAX_STORAGE_SIZE / (MAX_STORAGE_SIZE - total_storage_size(block)) + return 2**22 * ramp +``` + +When a block is processed, `rent` is deducted from all accounts modified by transactions in +the block after the transactions have been processed. The amount due for each account is +based on the account's storage size. + +```python +def rent(prestate, poststate, addr, currentblock): + fee = 0 + for b in range(prestate[addr].rentblock+1, currentblock-1): + fee += storagefee_factor(b) * prestate[addr].storagesize + return fee + storagefee_factor(currentblock) * poststate[addr].storagesize + +def charge_rent(prestate, poststate, addr, currentblock): + fee = rent(prestate, poststate, addr, currentblock) + if fee <= poststate[addr].rentbalance: + poststate[addr].rentbalance -= fee + else: + fee -= poststate[addr].rentbalance + poststate[addr].rentbalance = 0 + poststate[addr].balance -= min(poststate[addr].balance, fee) + poststate[addr].rentblock = currentblock +``` + +### New EVM Opcodes + +#### `PAYRENT ` + +At any time, the `rent balance` of an account may be topped up by the `PAYRENT` opcode. +`PAYRENT` deducts the given amount of `ether` from the account executing the opcode and adds +it to the `rent balance` of the address specified as beneficiary. + +Any participant can pay the rent for any other participant. + +Gas cost: TBD + +#### `RENTBALANCE ` + +The `rent balance` of an account may be queried through the `RENTBALANCE` opcode. It pushes the +`rentbalance` field of the given address to the stack. + +Gas cost: like `EXTCODEHASH`. + +#### `SSIZE ` + +This opcode pushes the `storagesize` field of the given account to the stack. + +Gas cost: like `EXTCODEHASH`. + +#### `RESTORETO ` + +This opcode restores the inactive account at the given address. This is a bit like +`SELFDESTRUCT` but has more specific semantics. + +The account at `addr` must be `inactive` (i.e. have `storagesize` zero) and its +`storageroot` must match the `storageroot` of the contract executing `RESTORETO`. The +`codeaddr` specifies the address of a contract from which code is taken. The code of the +`codeaddr` account must match the `codehash` of `addr`. + +If all these preconditions are met, `RESTORETO` transfers the storage of the account +executing the opcode to `addr` and resets its `storagesize` to the full size of the +storage. The code of `addr` is restored as well. `RESTORETO` also transfers any remaining +balance and rent balance to `addr`. The contract executing `RESTORETO` is deleted. + +Gas cost: TBD + +## Rationale + +### Why do we need a separate rent balance? + +Accounts need a separate rent balance because some contracts are non-payable, i.e. they +reject regular value transfers. Such contracts might not be able to keep themselves alive, +but users of those contracts can keep them alive by paying rent for them. + +Having the additional balance also makes things easier for contracts that hold balance on +behalf of a user. Consider the canonical crowdfunding example, a contract which changes +behavior once a certain balance is reached and which tracks individual user's balances. +Deducting rent from the main balance of the contract would mess up the contract's +accounting, leaving it unable to pay back users accurately if the threshold balance isn't +reached. + +### Why restoration? + +One of the fundamental guarantees provided by Ethereum is that changes to contract storage +can only be made by the contract itself and storage will persist forever. If you hold a +token balance in a contract, you'll have those tokens forever. By adding restoration, we +can maintain this guarantee to a certain extent. + +### Implementation Impact + +The proposed changes tries to fit within the existing state transition model. Note that +there is no mechanism for deactivating accounts the moment they can't pay rent. Users must +touch accounts to ensure their storage is removed because we'd need to track all accounts +and their rent requirements in an auxlilary data structure otherwise. + +## Backwards Compatibility + +TBA + +## Test Cases + +TBA + +## Implementation + +TBA + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-170.md b/EIPS/eip-170.md index 4f965519841223..632f216a62e340 100644 --- a/EIPS/eip-170.md +++ b/EIPS/eip-170.md @@ -9,15 +9,16 @@ created: 2016-11-04 --- ### Hard fork -[Spurious Dragon](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-607.md) +[Spurious Dragon](./eip-607.md) ### Parameters +- `MAX_CODE_SIZE`: `0x6000` (`2**14 + 2**13`) - `FORK_BLKNUM`: 2,675,000 -- `CHAIN_ID`: 1 (main net) +- `CHAIN_ID`: 1 (Mainnet) ### Specification -If `block.number >= FORK_BLKNUM`, then if contract creation initialization returns data with length of **more than** `0x6000` (`2**14 + 2**13`) bytes, contract creation fails with an out of gas error. +If `block.number >= FORK_BLKNUM`, then if contract creation initialization returns data with length of **more than** `MAX_CODE_SIZE` bytes, contract creation fails with an out of gas error. ### Rationale diff --git a/EIPS/eip-1702.md b/EIPS/eip-1702.md index e6096ee500971a..f200ae2bcdf065 100644 --- a/EIPS/eip-1702.md +++ b/EIPS/eip-1702.md @@ -3,7 +3,7 @@ eip: 1702 title: Generalized Account Versioning Scheme author: Wei Tang (@sorpaas) discussions-to: https://github.com/sorpaas/EIPs/issues/2 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2017-12-30 @@ -43,11 +43,31 @@ might still be a good idea. Re-define account state stored in the world state trie to have 5 items: `nonce`, `balance`, `storageRoot`, `codeHash`, and -`version`. The newly added field `version` is a 256-bit integer. When -`version` is zero, the account is RLP-encoded with the first 4 +`version`. The newly added field `version` is a 256-bit **scalar**. We +use the definition of "scalar" from Yellow Paper. Note that this is +the same type as `nonce` and `balance`, and it is equivalent to a RLP +variable-sized byte array with no leading zero, of maximum length 32. + +When `version` is zero, the account is RLP-encoded with the first 4 items. When `version` is not zero, the account is RLP-encoded with 5 items. +Account versions can also optionally define additional account state +RLP fields, whose meaning are specified through its `version` +field. In those cases, the parsing strategy is defined in "Additional +Fields in Account State RLP" section. + +### Contract Execution + +When fetching an account code from state, we always fetch the +associated version field together. We refer to this as the *code's +version* below. The code of the account is always executed in the +*code's version*. + +In particular, this means that for `DELEGATECALL` and `CALLCODE`, the +version of the execution call frame is the same as +delegating/receiving contract's version. + ### Contract Deployment In Ethereum, a contract has a deployment method, either by a contract @@ -58,32 +78,12 @@ transaction. We let a family of contracts to always have the same `version`. That is, `CREATE` and `CREATE2` will always deploy contract that has the -same `version` as the calling `address`. +same `version` as the *code's version*. -#### Alternative Design - -This provides an alternative design that allows `CREATE`, `CREATE2` -and contract creation transaction to deploy contract whose version are -different. - -The client maintains a mapping `V` of currently supported version -prefix (for example, `\0asm`) to `version` number. All version -prefixes have the invariant that given any prefix in mapping `a` and -`b`, `a` is not `b`'s prefix. Version numbers in `V` cannot be zero. - -Apply the following cause on contract deployment for all `CREATE`, -`CREATE2` and contract deployment transaction. - -* If the `version` of caller (determined by `I_a`) is zero, then - `CREATE` and `CREATE2` will always deploy contract with version zero. -* If the `version` of caller (determined by `I_a`) is not zero, do the - following checks and operations, and return out-of-gas if any of it - fails: - * Check that the code starts with an prefix in `V`, with `version` - number. - * Use `version`'s validation procedure to validate the *whole* code - (with prefix). - * Deploy the contract with `version`. +In other words, `CREATE` and `CREATE2` will execute the init code +using the current *code's version*, and deploy the contract of the +current *code's version*. This holds even if the to-be-deployed code +is empty. ### Validation @@ -96,31 +96,14 @@ that has to be passed. If the validation phrase fails, deployment does not proceed and return out-of-gas. -### Contract Execution - -VM version used in contract execution is determined via calling -`address` (`I_a` in yellow paper). - ### Contract Creation Transaction Define `LATEST_VERSION` in a hard fork to be the latest supported VM version. A contract creation transaction is always executed in -`LATEST_VERSION`. Before a contract creation transaction is executed, -run *validation* on the contract creation code. If it does not pass, -return out-of-gas. - -#### Alternative Design - -This provides an alternative design that allows contract to be created -in multiple versions. - -Add an additional field `version` (256-bit integer) in contract -creation transaction. So it becomes `nonce`, `gasprice`, `startgas`, -`to`, `value`, `data`, `v`, `r`, `s`, `version`. When signing or -recovering, sign ten items, with `v`, `r`, `s` as defined by EIP-155. - -The transaction would be executed in `version` supplied. If `version` -is not supported or *validation* does not pass, return out-of-gas. +`LATEST_VERSION` (which means the *code's version* is +`LATEST_VERSION`), and deploys contracts of `LATEST_VERSION`. Before a +contract creation transaction is executed, run *validation* on the +contract creation code. If it does not pass, return out-of-gas. ### Precompiled Contract and Externally-owned Address @@ -130,31 +113,92 @@ Precompiled contracts and externally-owned addresses do not have or a non-existing precompiled contract address, it is always created with `version` field being `0`. +### Additional Fields in Account State RLP + +In the future we may need to associate more information into an +account, and we already have some EIPs that define new additional +fields in the account state RLP. In this section, we define the +parsing strategy when additional fields are added. + +* Check the RLP list length, if it is 4, then set account version to + `0`, and do not parse any additional fields. +* If the RLP list length more than 4, set the account version to the + scalar at position `4` (counting from `0`). + * Check version specification for the number of additional fields + defined `N`, if the RLP list length is not equal to `5 + N`, + return parse error. + * Parse RLP position `5` to `4 + N` as the meaning specified in + additional fields. + +## Extensions + +In relation to the above "Specification" section, we have defined the +base account versioning layer. The base account versioning layer is +already useful by itself and can handle most EVM improvements. Below +we define two specifications that can be deployed separately, which +improves functionality of base layer account versioning. + +Note that this section is provided only for documentation +purpose. When "enabling EIP-1702", those extensions should not be +enabled unless the extension specification is also included. + +* [44-VERTXN: Account Versioning Extension for Contract Creation + Transaction](https://corepaper.org/ethereum/compatibility/versioning/#extensions-for-state-based-account-versioning) +* [45-VEROP: Account Versioning Extension for CREATE and + CREATE2](https://corepaper.org/ethereum/compatibility/versioning/#create-and-create2-extension) + +## Usage Template + +This section defines how other EIPs might use this account +versioning specification. Note that currently we only define the usage +template for base layer. + +Account versioning is usually applied directly to a hard fork +meta. EIPs in the hard fork are grouped by the virtual machine +type, for example, EVM and eWASM. For each of them, we define: + +* **Version**: a non-zero scalar less than `2^256` that uniquely + identifies this version. Note that it does not need to be + sequential. +* **Parent version**: the base that all new features derived + from. With parent version of `0` we define the base to be legacy + VM. Note that once a version other than `0` is defined, the legacy + VM's feature set must be frozen. When defining an entirely new VM + (such as eWASM), parent version does not apply. +* **Features**: all additional features that are enabled upon this + version. + +If a meta EIP includes EIPs that provide additional account state RLP +fields, we also define: + +* **Account fields**: all account fields up to the end of this meta + EIP, excluding the basic 5 fields (`nonce`, `balance`, + `storageRoot`, `codeHash` and `version`). If EIPs included that are + specific to modifying account fields do not modify VM execution + logic, it is recommended that we specify an additional version whose + execution logic is the same as previous version, but only the + account fields are changed. + ## Rationale This introduces account versioning via a new RLP item in account -state. The first design above gets account versioning by making the -contract *family* always have the same version. In this way, versions -are only needed to be provided by contract creation transaction, and -there is no restrictions on formats of code for any version. If we -want to support multiple newest VMs (for example, EVM and WebAssembly -running together), then this requires alternative design in contract -creation transaction section - -The second design above requires new versions of VMs follow a -formatting -- that it always has a prefix. In this way, the version -can be derived from the prefix, thus allowing a contract *family* to -have multiple versions. It also makes it so that we can pin contract -creation transaction using only one VM version, and it can deploy -other VM versions. +state. The design above gets account versioning by making the contract +*family* always have the same version. In this way, versions are only +needed to be provided by contract creation transaction, and there is +no restrictions on formats of code for any version. If we want to +support multiple newest VMs (for example, EVM and WebAssembly running +together), then this will requires extensions such as 44-VERTXN and +45-VEROP. Alternatively, account versioning can also be done through: -* **EIP-1707** and **EIP-1712**: This makes an account's versioning - soly dependent on its code header prefix. If with only EIP-1707, it - is not possible to certify any code is valid, because current VM - allows treating code as data. This can be fixed by EIP-1712, but the - drawback is that it's potentially backward incompatible. +* **[26-VER](https://corepaper.org/ethereum/compatibility/versioning/#prefix-based-account-versioning)** and + **[40-UNUSED](https://corepaper.org/ethereum/compatibility/forward/)**: This makes an + account's versioning solely dependent on its code header prefix. If + with only 26-VER, it is not possible to certify any code is valid, + because current VM allows treating code as data. This can be fixed + by 40-UNUSED, but the drawback is that it's potentially backward + incompatible. * **EIP-1891**: Instead of writing version field into account RLP state, we write it in a separate contract. This can accomplish the same thing as this EIP and potentially reduces code complexity, but @@ -186,3 +230,12 @@ defined as above. ## Test Cases and Implementations To be added. + +## References + +The source of this specification can be found at +[43-VER](https://corepaper.org/ethereum/compatibility/versioning/#state-based-account-versioning). + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1706.md b/EIPS/eip-1706.md index 7d8ec43c9ae328..6c559b96589921 100644 --- a/EIPS/eip-1706.md +++ b/EIPS/eip-1706.md @@ -3,41 +3,35 @@ eip: 1706 title: Disable SSTORE with gasleft lower than call stipend author: Alex Forshtat , Yoav Weiss discussions-to: https://github.com/alex-forshtat-tbk/EIPs/issues/1 -status: Draft +status: Withdrawn +withdrawal-reason: The authors prefer [EIP-2200](./eip-2200.md) type: Standards Track category: Core created: 2019-01-15 requires: 1283 --- - - ## Simple Summary - The proposal that had been accepted changes security properties of a large portion of an existing contract code base that may be infeasible to update and validate. This proposal will make the old assumptions hold even after a network upgrade. ## Abstract - -[EIP-1283](https://eips.ethereum.org/EIPS/eip-1283) significantly lowers the gas costs of writing to contract's storage. This created a danger of a new kind of reentrancy attacks on existing contracts as Solidity by default grants a 'stipend' of 2300 gas to simple transfer calls. +[EIP-1283](./eip-1283.md) significantly lowers the gas costs of writing to contract's storage. This created a danger of a new kind of reentrancy attacks on existing contracts as Solidity by default grants a 'stipend' of 2300 gas to simple transfer calls. This danger is easily mitigated if SSTORE is not allowed in low gasleft state, without breaking the backward compatibility and the original intention of this EIP. ## Motivation - An attack that is described in [this article](https://medium.com/chainsecurity/constantinople-enables-new-reentrancy-attack-ace4088297d9). Explicitly specifying the call stipend as an invariant will have a positive effect on Ethereum protocol security: https://www.reddit.com/r/ethereum/comments/agdqsm/security_alert_ethereum_constantinople/ee5uvjt ## Specification - -Add the following condition to to the SSTORE opcode gas cost calculation: +Add the following condition to the SSTORE opcode gas cost calculation: * If *gasleft* is less than or equal to 2300, fail the current call frame with 'out of gas' exception. ## Rationale - In order to keep in place the implicit reentrancy protection of existing contracts, transactions should not be allowed to modify state if the remaining gas is lower then the 2300 stipend given to 'transfer'/'send' in Solidity. These are other proposed remediations and objections to implementing them: @@ -57,15 +51,12 @@ These are other proposed remediations and objections to implementing them: ## Backwards Compatibility - Performing SSTORE has never been possible with less than 5000 gas, so it does not introduce incompatibility to the Ethereum mainnet. Gas estimation should account for this requirement. ## Test Cases - Test cases for an implementation are mandatory for EIPs that are affecting consensus changes. Other EIPs can choose to include links to test cases if applicable. TODO ## Implementation - TODO ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1710.md b/EIPS/eip-1710.md index 876910ae7be2d1..a9b72bb081ae5c 100644 --- a/EIPS/eip-1710.md +++ b/EIPS/eip-1710.md @@ -1,66 +1,7 @@ --- eip: 1710 -title: URL Format for Web3 Browsers -author: Bruno Barbieri (@brunobar79) -discussions-to: https://ethereum-magicians.org/t/standarize-url-format-for-web3-browsers/2422 -status: Draft -type: Standards Track category: ERC -created: 2019-01-13 -requires: 155 +status: Moved --- - - -## Simple Summary - -A standard way of representing web3 browser URLs for decentralized applications. - -## Abstract - - -Since most normal web browsers (specifically on mobile devices) can not run decentralized applications correctly because of the lack of web3 support, it is necessary to differentiate them from normal urls, so they can be opened in web3 browsers if available. - -## Motivation - - -Lots of dApps that are trying to improve their mobile experience are currently (deep)linking to specific mobile web3 browsers which are currently using their own url scheme. - -In order to make the experience more seamless, dApps should still be able to recommend a specific mobile web3 browser via [deferred deeplinking](https://en.wikipedia.org/wiki/Deferred_deep_linking) but by having a standard url format, if the user already has a web3 browser installed that implements this standard, it will be automatically linked to it. - -There is also a compatibility problem with the current `ethereum:` url scheme described in [EIP-831](https://eips.ethereum.org/EIPS/eip-831) where any ethereum related app (wallets, identity management, etc) already registered it and because of iOS unpredictable behavior for multiple apps handling a single url scheme, users can end up opening an `ethereum:` link in an app that doesn not include a web3 browser and will not be able to handle the deeplink correctly. - -## Specification - - - -### Syntax - -Web3 browser URLs contain "dapp" in their schema (protocol) part and are constructed as follows: - - request = "dapp" ":" [chain_id "@"] dapp_url - chain_id = 1*DIGIT - dapp_url = URI - -### Semantics - -`chain_id` is optional and it is a parameter for the browser to automatically select the corresponding chain ID as specified in [EIP-155](https://eips.ethereum.org/EIPS/eip-155) before opening the dApp. - -`dapp_url` is a valid [RFC3986](https://www.ietf.org/rfc/rfc3986.txt) URI - -This a complete example url: - -`dapp:1@peepeth.com/brunobar79?utm_source=github` - -which will open the web3 browser, select `mainnet` (chain_id = 1) and then navigate to: - -`https://peepeth.com/brunobar79?utm_source=github` - -## Rationale - - -The proposed format attempts to solve the problem of vendor specific protocols for web3 browsers, avoiding conflicts with the existing 'ethereum:' URL scheme while also adding an extra feature: `chain_id` which will help dApps to be accessed with the right network preselected, optionally extracting away that complexity from end users. - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1710.md diff --git a/EIPS/eip-1716.md b/EIPS/eip-1716.md index adda1b4e4f7571..031f20d3bc3dce 100644 --- a/EIPS/eip-1716.md +++ b/EIPS/eip-1716.md @@ -17,13 +17,13 @@ This meta-EIP specifies the changes included in the Ethereum hardfork that remov - Codename: Petersburg - Aliases: St. Petersfork, Peter's Fork, Constantinople Fix - Activation: - - `Block >= 7_280_000` on the Ethereum mainnet + - `Block >= 7_280_000` on the Ethereum Mainnet - `Block >= 4_939_394` on the Ropsten testnet - `Block >= 10_255_201` on the Kovan testnet - - `Block >= 9_999_999` on the Rinkeby testnet + - `Block >= 4_321_234` on the Rinkeby testnet - `Block >= 0` on the Görli testnet - Removed EIPs: - - [EIP 1283](./eip-1283.md): Net gas metering for SSTORE without dirty maps + - [EIP-1283](./eip-1283.md): Net gas metering for SSTORE without dirty maps If `Petersburg` and `Constantinople` are applied at the same block, `Petersburg` takes precedence: with the net effect of EIP-1283 being _disabled_. @@ -36,4 +36,4 @@ If `Petersburg` is defined with an earlier block number than `Constantinople`, t ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-173.md b/EIPS/eip-173.md index 8c88f1bcb357e3..0e0fb9515c2485 100644 --- a/EIPS/eip-173.md +++ b/EIPS/eip-173.md @@ -1,111 +1,7 @@ --- eip: 173 -title: ERC-173 Contract Ownership Standard -author: Nick Mudge , Dan Finlay -discussions-to: https://github.com/ethereum/EIPs/issues/173 -type: Standards Track category: ERC -status: Draft -created: 2018-06-07 +status: Moved --- -## Simple Summary - -A standard interface for ownership of contracts. - -## Abstract - -The following standard allows for the implementation of a standard API for getting the owner address of a contract and transferring contract ownership to a different address. - -Key factors influencing the standard: -- Keeping the number of functions in the interface to a minimum to prevent contract bloat. -- Backwards compatibility with existing contracts. -- Simplicity -- Gas efficient - -## Motivation - -Many smart contracts require that they be owned or controlled in some way. For example to withdraw funds or perform administrative actions. It is so common that the contract interface used to handle contract ownership should be standardized to allow compatibility with contracts that manage contracts. - -Here are some examples of kinds of contracts and applications that can benefit from this standard: -1. Exchanges that buy/sell/auction ethereum contracts. This is only widely possible if there is a standard for getting the owner of a contract and transferring ownership. -2. Contract wallets that hold the ownership of contracts and that can transfer the ownership of contracts. -3. Contract registries. It makes sense for some registries to only allow the owners of contracts to add/remove their contracts. A standard must exist for these contract registries to verify that a contract is being submitted by the owner of it before accepting it. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -Every ERC-173 compliant contract must implement the `ERC173` interface. Contracts that inherit from OpenZeppelin's `Ownable` contract are compliant with ERC-173. However future contracts should also implement `ERC165` for the ERC-173 interface. - -```solidity -pragma solidity ^0.4.24; - -/// @title ERC-173 Contract Ownership Standard -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-173.md -/// Note: the ERC-165 identifier for this interface is 0x7f5828d0 -interface ERC173 /* is ERC165 */ { - /// @dev This emits when ownership of a contract changes. - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - /// @notice Get the address of the owner - /// @return The address of the owner. - function owner() view external; - - /// @notice Set the address of the new owner of the contract - /// @param _newOwner The address of the new owner of the contract - function transferOwnership(address _newOwner) external; -} - -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -The `owner()` function may be implemented as `pure` or `view`. - -The `transferOwnership(address _newOwner)` function may be implemented as `public` or `external`. - -The OwnershipTransferred event does not have to be emitted when a contract is created. - -## Rationale - -Several ownership schemes were considered. The scheme chosen in this standard was chosen because of its simplicity, low gas cost and backwards compatibility with OpenZeppelin's implementation of the Ownable contract which is in active use. - -Here are other schemes that were considered: -1. **Associating an Ethereum Name Service (ENS) domain name with a contract.** A contract's `owner()` function could look up the owner address of a particular ENS name and use that as the owning address of the contract. Using this scheme a contract could be transferred by transferring the ownership of the ENS domain name to a different address. Short comings to this approach are that it is not backwards compatible with existing contracts and requires gas to make external calls to ENS related contracts to get the owner address. -2. **Associating an ERC721-based non-fungible token (NFT) with a contract.** Ownership of a contract could be tied to the ownership of an NFT. The benefit of this approach is that the existing ERC721-based infrastructure could be used to sell/buy/auction contracts. Short comings to this approach are additional complexity and infrastructure required. A contract could be associated with a particular NFT but the NFT would not track that it had ownership of a contract unless it was programmed to track contracts. In addition handling ownership of contracts this way is not backwards compatible. - -This standard does not exclude the above ownership schemes or other schemes from also being implemented in the same contract. For example a contract could implement this standard and also implement the other schemes so that ownership could be managed and transferred in multiple ways. This standard does provide a simple ownership scheme that is backwards compatible, is light-weight and simple to implement, and can be widely adopted and depended on. - -## Backwards Compatibility - -OpenZeppelin's Ownable contract is actively being used in contracts. Contracts that inherit Ownable are in compliance with this standard. - -However future contracts should also implement `ERC165` for the ERC-173 interface. - -## Implementations - -OpenZeppelin's implementation is here: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - - - - - - - - - - - - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-173.md diff --git a/EIPS/eip-1753.md b/EIPS/eip-1753.md new file mode 100644 index 00000000000000..f68dacb368cde3 --- /dev/null +++ b/EIPS/eip-1753.md @@ -0,0 +1,7 @@ +--- +eip: 1753 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1753.md diff --git a/EIPS/eip-1761.md b/EIPS/eip-1761.md index 7b4057e16eae76..8715be483c4f7f 100644 --- a/EIPS/eip-1761.md +++ b/EIPS/eip-1761.md @@ -1,175 +1,7 @@ --- eip: 1761 -title: ERC-1761 Scoped Approval Interface -author: Witek Radomski , Andrew Cooke , James Therien , Eric Binet -type: Standards Track category: ERC -status: Draft -created: 2019-02-18 -discussions-to: https://github.com/ethereum/EIPs/issues/1761 -requires: 165 +status: Moved --- -## Simple Summary - -A standard interface to permit restricted approval in token contracts by defining "scopes" of one or more Token IDs. - -## Abstract - -This interface is designed for use with token contracts that have an "ID" domain, such as ERC-1155 or ERC-721. This enables restricted approval of one or more Token IDs to a specific "scope". When considering a smart contract managing tokens from multiple different domains, it makes sense to limit approvals to those domains. Scoped approval is a generalization of this idea. Implementors can define scopes as needed. - -Sample use cases for scopes: - -* A company may represent its fleet of vehicles on the blockchain and it could create a scope for each regional office. -* Game developers could share an [ERC-1155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md) contract where each developer manages tokens under a specified scope. -* Tokens of different value could be split into separate scopes. High-value tokens could be kept in smaller separate scopes while low-value tokens might be kept in a shared scope. Users would approve the entire low-value token scope to a third-party smart contract, exchange, or other application without concern about losing their high-value tokens in the event of a problem. - -## Motivation - -It may be desired to restrict approval in some applications. Restricted approval can prevent losses in cases where users do not audit the contracts they're approving. No standard API is supplied to manage scopes as this is implementation specific. Some implementations may opt to offer a fixed number of scopes, or assign a specific set of scopes to certain types. Other implementations may open up scope configuration to its users and offer methods to create scopes and assign IDs to them. - -# Specification - -```solidity -pragma solidity ^0.5.2; - -/** - Note: The ERC-165 identifier for this interface is 0x30168307. -*/ -interface ScopedApproval { - /** - @dev MUST emit when approval changes for scope. - */ - event ApprovalForScope(address indexed _owner, address indexed _operator, bytes32 indexed _scope, bool _approved); - - /** - @dev MUST emit when the token IDs are added to the scope. - By default, IDs are in no scope. - The range is inclusive: _idStart, _idEnd, and all IDs in between have been added to the scope. - _idStart must be lower than or equal to _idEnd. - */ - event AddIdsToScope(uint256 indexed _idStart, uint256 indexed _idEnd, bytes32 indexed _scope); - - /** - @dev MUST emit when the token IDs are removed from the scope. - The range is inclusive: _idStart, _idEnd, and all IDs in between have been removed from the scope. - _idStart must be lower than or equal to _idEnd. - */ - event RemoveIdsFromScope(uint256 indexed _idStart, uint256 indexed _idEnd, bytes32 indexed _scope); - - /** @dev MUST emit when a scope URI is set or changes. - URIs are defined in RFC 3986. - The URI MUST point a JSON file that conforms to the "Scope Metadata JSON Schema". - */ - event ScopeURI(string _value, bytes32 indexed _scope); - - /** - @notice Returns the number of scopes that contain _id. - @param _id The token ID - @return The number of scopes containing the ID - */ - function scopeCountForId(uint256 _id) public view returns (uint32); - - /** - @notice Returns a scope that contains _id. - @param _id The token ID - @param _scopeIndex The scope index to query (valid values are 0 to scopeCountForId(_id)-1) - @return The Nth scope containing the ID - */ - function scopeForId(uint256 _id, uint32 _scopeIndex) public view returns (bytes32); - - /** - @notice Returns a URI that can be queried to get scope metadata. This URI should return a JSON document containing, at least the scope name and description. Although supplying a URI for every scope is recommended, returning an empty string "" is accepted for scopes without a URI. - @param _scope The queried scope - @return The URI describing this scope. - */ - function scopeUri(bytes32 _scope) public view returns (string memory); - - /** - @notice Enable or disable approval for a third party ("operator") to manage the caller's tokens in the specified scope. - @dev MUST emit the ApprovalForScope event on success. - @param _operator Address to add to the set of authorized operators - @param _scope Approval scope (can be identified by calling scopeForId) - @param _approved True if the operator is approved, false to revoke approval - */ - function setApprovalForScope(address _operator, bytes32 _scope, bool _approved) external; - - /** - @notice Queries the approval status of an operator for a given owner, within the specified scope. - @param _owner The owner of the Tokens - @param _operator Address of authorized operator - @param _scope Scope to test for approval (can be identified by calling scopeForId) - @return True if the operator is approved, false otherwise - */ - function isApprovedForScope(address _owner, address _operator, bytes32 _scope) public view returns (bool); -} -``` - -## Scope Metadata JSON Schema - -This schema allows for localization. `{id}` and `{locale}` should be replaced with the appropriate values by clients. - -```json -{ - "title": "Scope Metadata", - "type": "object", - "required": ["name"], - "properties": { - "name": { - "type": "string", - "description": "Identifies the scope in a human-readable way.", - }, - "description": { - "type": "string", - "description": "Describes the scope to allow users to make informed approval decisions.", - }, - "localization": { - "type": "object", - "required": ["uri", "default", "locales"], - "properties": { - "uri": { - "type": "string", - "description": "The URI pattern to fetch localized data from. This URI should contain the substring `{locale}` which will be replaced with the appropriate locale value before sending the request." - }, - "default": { - "type": "string", - "description": "The locale of the default data within the base JSON" - }, - "locales": { - "type": "array", - "description": "The list of locales for which data is available. These locales should conform to those defined in the Unicode Common Locale Data Repository (http://cldr.unicode.org/)." - } - } - } - } -} -``` - -### Localization - -Metadata localization should be standardized to increase presentation uniformity across all languages. As such, a simple overlay method is proposed to enable localization. If the metadata JSON file contains a `localization` attribute, its content may be used to provide localized values for fields that need it. The `localization` attribute should be a sub-object with three attributes: `uri`, `default` and `locales`. If the string `{locale}` exists in any URI, it MUST be replaced with the chosen locale by all client software. - -## Rationale - -The initial design was proposed as an extension to ERC-1155: [Discussion Thread - Comment 1](https://github.com/ethereum/EIPs/issues/1155#issuecomment-459505728). After some discussion: [Comment 2](https://github.com/ethereum/EIPs/issues/1155#issuecomment-460603439) and suggestions by the community to implement this approval mechanism in an external contract [Comment 3](https://github.com/ethereum/EIPs/issues/1155#issuecomment-461758755), it was decided that as an interface standard, this design would allow many different token standards such as ERC-721 and ERC-1155 to implement scoped approvals without forcing the system into all implementations of the tokens. - -### Metadata JSON - -The Scope Metadata JSON Schema was added in order to support human-readable scope names and descriptions in more than one language. - -## References - -**Standards** -- [ERC-1155 Multi Token Standard](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md) -- [ERC-165 Standard Interface Detection](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) -- [JSON Schema](http://json-schema.org/) - -**Implementations** -- [Enjin Coin](https://enjincoin.io) ([github](https://github.com/enjin)) - -**Articles & Discussions** -- [Github - Original Discussion Thread](https://github.com/ethereum/EIPs/issues/1761) -- [Github - ERC-1155 Discussion Thread](https://github.com/ethereum/EIPs/issues/1155) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1761.md diff --git a/EIPS/eip-1767.md b/EIPS/eip-1767.md index 02a9246ee3e9ec..616604100df8c3 100644 --- a/EIPS/eip-1767.md +++ b/EIPS/eip-1767.md @@ -3,7 +3,7 @@ eip: 1767 title: GraphQL interface to Ethereum node data author: Nick Johnson (@arachnid), Raúl Kripalani (@raulk), Kris Shinn (@kshinn) discussions-to: https://ethereum-magicians.org/t/graphql-interface-to-ethereum-node-data/2710 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2019-02-14 @@ -220,7 +220,7 @@ type Block { # Logs returns a filtered set of logs from this block. logs(filter: BlockFilterCriteria!): [Log!]! # Account fetches an Ethereum account at the current block's state. - account(address: Address!): Account! + account(address: Address!): Account # Call executes a local call operation at the current block's state. call(data: CallData!): CallResult # EstimateGas estimates the amount of gas that will be required for @@ -303,7 +303,7 @@ type Pending { # Transactions is a list of transactions in the current pending state. transactions: [Transaction!] # Account fetches an Ethereum account for the pending state. - account(address: Address!): Account! + account(address: Address!): Account # Call executes a local call operation for the pending state. call(data: CallData!): CallResult # EstimateGas estimates the amount of gas that will be required for @@ -408,7 +408,11 @@ For specific reasoning behind omitted functionality, see the Rationale section. TBD. ## Implementation -A go-ethereum implementation was completed in [PR 18445](https://github.com/ethereum/go-ethereum/pull/18445) and will be available in a forthcoming geth release. + +- Implemented and released in [Go-ethereum 1.9.0](https://github.com/ethereum/go-ethereum/releases/tag/v1.9.0) +- Implemented and released in [Pantheon 1.1.1](https://github.com/PegaSysEng/pantheon/blob/master/CHANGELOG.md#111) +- Work in progress in [Trinity](https://github.com/ethereum/trinity/issues/302) +- Work in progress in [Parity](https://github.com/paritytech/parity-ethereum/issues/10933) ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1775.md b/EIPS/eip-1775.md index 8aa747219a2302..efc42dbbf536aa 100644 --- a/EIPS/eip-1775.md +++ b/EIPS/eip-1775.md @@ -1,634 +1,7 @@ --- eip: 1775 -title: App Keys, application specific wallet accounts -author: Vincent Eli (@Bunjin), Dan Finlay (@DanFinlay) -discussions-to: https://ethereum-magicians.org/t/eip-erc-app-keys-application-specific-wallet-accounts/2742 -status: Draft -type: Standards Track category: ERC -created: 2019-02-20 -requires: 137 +status: Moved --- - -## Simple Summary - - -Among others cryptographic applications, scalability and privacy solutions for ethereum blockchain require that an user performs a significant amount of signing operations. It may also require her to watch some state and be ready to sign data automatically (e.g. sign a state or contest a withdraw). The way wallets currently implement accounts poses several obstacles to the development of a complete web3.0 experience both in terms of UX, security and privacy. - -This proposal describes a standard and api for a new type of wallet accounts that are derived specifically for a each given application. We propose to call them `app keys`. They allow to isolate the accounts used for each application, thus potentially increasing privacy. They also allow to give more control to the applications developers over account management and signing delegation. For these app keys, wallets can have a more permissive level of security (e.g. not requesting user's confirmation) while keeping main accounts secure. Finally wallets can also implement a different behavior such as allowing to sign transactions without broadcasting them. - -This new accounts type can allow to significantly improve UX and permit new designs for applications of the crypto permissionned web. - -## Abstract - -In a wallet, an user often holds most of her funds in her main accounts. These accounts require a significant level of security and should not be delegated in any way, this significantly impacts the design of cryptographic applications if a user has to manually confirm every action. Also often an user uses the same accounts across apps, which is a privacy and potentially also a security issue. - -We introduce here a new account type, app keys, which permits signing delegation and accounts isolation across applications for privacy and security. - -In this EIP, we provide a proposal on how to uniquely identify and authenticate each application, how to derive the accounts along an Hierarchical Deterministic (HD) path restricted for the domain and we finally define an API for applications to derive and use these app keys. This ERC aims at finding a standard that will fit the needs of wallets and application developers while also allowing app keys to be used across wallets and yield the same accounts for the user for each application. - -## Motivation - -Wallets developers have agreed on an HD derivation path for ethereum accounts using BIP32, BIP44, SLIP44, [(see the discussion here)](https://github.com/ethereum/EIPs/issues/84). Web3 wallets have implemented in a roughly similar way the rpc eth api. [EIP1102](https://eips.ethereum.org/EIPS/eip-1102) introduced privacy through non automatic opt-in of a wallet account into an app increasing privacy. - -However several limitations remain in order to allow for proper design and UX for crypto permissioned apps. - -Most of GUI based current wallets don't allow to: -* being able to automatically and effortlessly use different keys / accounts for each apps, -* being able to sign some app's action without prompting the user with the same level of security as sending funds from their main accounts, -* being able to use throwable keys to improve anonymity, -* effortlessly signing transactions for an app without broadcasting these while still being able to perform other transaction signing as usual from their main accounts, -* All this while being fully restorable using the user's mnemonic or hardware wallet and the HD Path determined uniquely by the app's ens name. - -We try to overcome these limitations by introducing a new account's type, app keys, made to be used along side the existing main accounts. - -These new app keys can permit to give more power and flexibility to the crypto apps developers. This can allow to improve a lot the UX of crypto dapps and to create new designs that were not possible before leveraging the ability to create and handle many accounts, to presign messages and broadcast them later. These features were not compatible with the level of security we were requesting for main accounts that hold most of an user's funds. - - -## Specification - - -### Applications - -An app is a website (or other) that would like to request from a wallet to access app keys. It can be any form of cryptography/identity relying application, ethereum but not only. - -Once connected to a wallet, an application can request to access a set of accounts derived exclusively for that application using the hierarchical deterministic (HD) paths. - -### Applications' HD path - -Using the BIP32 and BIP43 standards, we propose to use the following HD path for each app keys: - -`m / [standardized Path Beginning]' / [persona path]' / [application uniquely assigned path]' / [app's custom subpath]` - -Where: - -`standardized HD Path Beginning` is based on the EIP number that will be assigned to this EIP and we harden it. We use a different path than 44' since it's not bip44 compliant. At this point, I'm not sure if there is a list of BIP43 codes of standards following the `purpose` field specification of [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki). - -`persona path` allows to use applications with different and isolated personas (or in other words accounts) that are tracable by the application. They will still be fully restorable from the same mnemonic. - -`application uniquely assigned path` isolate each application along unique branches of the tree through these unique subPath combination. - -`app's custom subPath` give freedom to application to use this BIP32 compliant subPath to manage accounts and other needed parameters. - -Note that we suggest that each of these indexes, except those belonging to the app's custom subpath, must be hardened to fully isolate the public keys across personas and applications. - -### Standardized HD Path Beginning - -For the path header, several alternative are possible depending on what the cryptocommunities agree upon. - -The least contentious is the following one (as suggested [here in the BIP repository](https://github.com/bitcoin/bips/pull/523)): - -` 43' / 60' / 1775 ' ` - -However, there may be benefits to use only one depth instead of 3. We could use the `EIP Number'` (ie. 1775) or a ` BIP Number'` if we attain some cross crypto agreement that would avoid collision. - - -### Personas - -We allow the user to use different personas in combination to her mnemonic to potentially fully isolate her interaction with a given app across personas. One can use this for instance to create a personal and business profile for a given's domain both backup up from the same mnemonic, using 2 different personnas indexes. The app or domain, will not be aware that it is the same person and mnemonic behind both. - -We use a string following BIP32 format (can be hardened) to define personas. -The indexes should be hex under 0x80000000, 31 bits. - -E.g. `0'` or `0'/1/2'/0` or `1d7b'/a41c'` - -### Applications' Unique Identifiers - -#### Applications Names - -We need a way to uniquely identify each application. We will use a naming and a hashing scheme. - -In our favored spec, each application is uniquely defined and authenticated by its name, a domain string. It can be a Domain Name Service DNS name or and Ethereum Name Service ENS name. - -There are a few restrictions however on the characters used and normalisation, each name should be passed through the [NamePrep Algorithm](https://tools.ietf.org/html/rfc3491) - -In addition there must be a maximum size to the domain string that we need to determine such that the mapping from strings to nodes remains injective, to avoid collision. - -We recommend this standard to be following the [ENS Specs](http://docs.ens.domains/en/latest/implementers.html#namehash), reproduced below for convenience and reference. - -``` -Normalising and validating names -Before a name can be converted to a node hash using Namehash, the name must first be normalised and checked for validity - for instance, converting fOO.eth into foo.eth, and prohibiting names containing forbidden characters such as underscores. It is crucial that all applications follow the same set of rules for normalisation and validation, as otherwise two users entering the same name on different systems may resolve the same human-readable name into two different ENS names. -``` - -#### Hashing and Applications UIDs - -The ENS uses an hashing scheme to associate a domain to a unique hash, `node`, through the `namehash` function. We will use this hashing scheme both for ENS and for DNS names. - -This gives an unique identifier (UID) of 32 bytes. - -``` -e.g. for foo.bar.eth -app's uid 0x6033644d673b47b3bea04e79bbe06d78ce76b8be2fb8704f9c2a80fd139c81d3 -``` - -For reference, here are the specs of ENS: - -``` -domain - the complete, human-readable form of a name; eg, ‘vitalik.wallet.eth’. -label - a single component of a domain; eg, ‘vitalik’, ‘wallet’, or ‘eth’. A label may not contain a period (‘.’). -label hash - the output of the keccak-256 function applied to a label; eg, keccak256(‘eth’) = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0. -node - the output of the namehash function, used to uniquely identify a name in ENS. -Algorithm -First, a domain is divided into labels by splitting on periods (‘.’). So, ‘vitalik.wallet.eth’ becomes the list [‘vitalik’, ‘wallet’, ‘eth’]. - -The namehash function is then defined recursively as follows: - -namehash([]) = 0x0000000000000000000000000000000000000000000000000000000000000000 -namehash([label, …]) = keccak256(namehash(…), keccak256(label)) - -keccak256(‘eth’) = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0 - -``` - -We thus propose to use the node of each app's domain as a unique identifier for each app but one can think of other UIDs, we include some alternative specs in the [Rationale](#Rationale) section below. - -### Applications' authentication - -If the application is using a DNS name then we simply authenticate the application by using the url of the loaded browser webpage. - -For applications using ENS, we can authenticate the application through ENS resolution. -The ENS can also allow to register and resolve metadata for the application such as `url`, and other parameters. - -If we use for instance this resolver profile defined in [EIP634](https://eips.ethereum.org/EIPS/eip-634) which permits the lookup of arbitrary key-value text data, we can for instance use the key `url` to point to a website. - -``` -A new resolver interface is defined, consisting of the following method: - -function text(bytes32 node, string key) constant returns (string text); -The interface ID of this interface is 0x59d1d43c. - -The text data may be any arbitrary UTF-8 string. If the key is not present, the empty string must be returned. -``` - -One can think of other authentication methods and even use some of them alongside the url-resolution method through ENS. We mention other methods in the [Rationale](#Rationale) section. - -We suggest for instance to also add an `authorEthAddress` text metadata field that can be used to authenticate messages from the application, with for instance a sign challenge. - -### Applications UID decomposition to get a BIP32 HD path - -Since each child index in an HD path only has 31 bits we will decompose the domain's hash as several child indexes, first as hex bytes then parsed as integers. - -For the applications's uid we use an `ENS namehash node` of 32 bytes, 256 bits (removing the leading `0x`). - -e.g. `foo.bar.eth` which gives the following namehash node: `0x6033644d673b47b3bea04e79bbe06d78ce76b8be2fb8704f9c2a80fd139c81d3` - -We can decompose it in several ways, here are 2 potential ways: - -* First approach could favor having the least indexes: - -This requires to first convert the hex uid to 256 bits then decompose it as 8 * 31 bits + 8 bits - -``` -x = x0 || x1 || x2 || x3 || x4 || x5 || x6 || x7 || x8 -``` -where `x0` to `x7` are 31 bits and `x8` is 8 bits - -then we convert the `x_i` to uints. - -The derivation sub-path would be: -`x0'/x1'/x2'/x3'/x4'/x5'/x6'/x7'/x8'` - - -``` -E.g. - -foo.bar.eth - - -0x6033644d673b47b3bea04e79bbe06d78ce76b8be2fb8704f9c2a80fd139c81d3 - -converted to binary (256 bits) - -6033644d673b -011000000011001101100100010011010110011100111011 -47b3bea04e79 -010001111011001110111110101000000100111001111001 -bbe06d78ce76 -101110111110000001101101011110001100111001110110 -b8be2fb8704f -101110001011111000101111101110000111000001001111 -9c2a80fd139c -100111000010101010000000111111010001001110011100 -81d3 -1000000111010011 - -256 bits: -0110000000110011011001000100110101100111001110110100011110110011101111101010000001001110011110011011101111100000011011010111100011001110011101101011100010111110001011111011100001110000010011111001110000101010100000001111110100010011100111001000000111010011 - -converted to less than or equal to 31 bits indexes: - -8 * 31 bits + 1 * 8 bits - -0110000000110011011001000100110 -1011001110011101101000111101100 -1110111110101000000100111001111 -0011011101111100000011011010111 -1000110011100111011010111000101 -1111000101111101110000111000001 -0011111001110000101010100000001 -1111101000100111001110010000001 -11010011 - -and converted to uints - -806990374'/1506726380'/2010384847'/465438423'/1181988293'/2025775553'/523785473'/2098437249'/211' - - -``` - - -* Second approach favors an homogeneous decomposition: - -Equal length indexes would be 16 * 16 bits or in other words 16 * 2 bytes, cleanest and favored spec: - -``` -x = x0 || x1 || x2 || x3 || x4 || x5 || x6 || x7 || x8 || x9 || x10 || x11 || x12 || x13 || x14 || x15 - -where || is concatenation -``` - - -``` -E.g. - -foo.bar.eth -0x6033644d673b47b3bea04e79bbe06d78ce76b8be2fb8704f9c2a80fd139c81d3 -6033 644d 673b 47b3 bea0 4e79 bbe0 6d78 ce76 b8be 2fb8 704f 9c2a 80fd 139c 81d3 -6033'/644d'/673b'/47b3'/bea0'/4e79'/bbe0'/6d78'/ce76'/b8be'/2fb8'/704f'/9c2a'/80fd'/139c'/81d3' -24627'/25677'/26427'/18355'/48800'/20089'/48096'/28024'/52854'/47294'/12216'/28751'/39978'/33021'/5020'/33235' -``` - - -Between these 2 decomposition approaches, there is a trade-off between computational efficiency (having less depth) and having an homegenous decomposition. We tend to favor the first approach with least indexes. - - -### Application customisable HD sub path - -Finally, the last part of the hd path is under the application's control. This will allow applications developers to use the HD path structure that best fits their needs. Developers can for instance, among any combination of other parameters they like, choose to include a `version` field if they would like to use different signing accounts when updating to a new version. They can then also manage the user accounts in the way they would like, for instance including or not an index for `sets of accounts` (called `accounts` in BIP44), an index for `change` and an index for `account` (called `address_index` in BIP44). -We consider that a given child on the HD tree should be called an `account` and not an `address` since it is composed of a private key, a public key and an address. - -Similarly to the persona path, this sub path must follow bip32, with hex under 0x80000000, 31 bits. -It can be hardened depending on each application's needs and can be written as hex or unsigned integers. -It can include a large number of indexes. - -Q [Should we set a limit on the persona and application customsable hd path number of indexes?] - -### Example HD paths for app keys: - -``` -Dummy data: -EIP Number: 1775 -personaPath: 0'/712' -application's name: foo.bar.eth -uid: 0x6033644d673b47b3bea04e79bbe06d78ce76b8be2fb8704f9c2a80fd139c81d3 -app custom path params: app_version, set_of_accounts_index, account_index -``` - -`m/43'/60'/1775'/0'/712'/806990374'/1506726380'/2010384847'/465438423'/1181988293'/2025775553'/523785473'/2098437249'/211'/0'/0'/0` - -## API: - -We propose to introduce new RPC methods but they should be restricted and wrapped such that some parameters (e.g. domain name) are imposed by the wallet on the caller depending on the caller's authentication. - -[TBD] Specify scope of RPC methods (some params should be forced to the authenticated domain value) and how to integrate them into web3 api. - -### App keys exposure: - -* `wallet.appkey.enable(options)` -This method allows to enable app keys (getting user permission to use and allow him to select the persona she would like to use). - -[TBD] Could return the account public key from the HD path before `the app's custom subPath`. Hence from this app's root account, one could derive all non hardened children public keys of the app's keys. - -[TBD] where `options` is a javascript object containing the permissions requested for these app keys. -Options could also include a challenge to be signed by the app's root account (would serve as authentication of the users from the app's perspective). The signature should then be also returned. - -Options should also include a parameter for the application to indicate which name should be used to compute the domain's HD path. That's required for applications that are loaded through ENS. They could be authenticated either through ENS or through DNS. These applications may like to use the DNS name even when they are resolved through ENS. (e.g. an application that just upgraded to ENS may like to continue using DNS paths to be retro-compatible for its former users). - -Uses the persona selected by the user (not known nor controllable by application). - -Uses the domain ens namehash (node) that was resolved to load window (not provided by application itself) - -### Ethereum accounts methods: - -* `appKey_eth_getPublicKey(hdSubPath) returns publicKey 64 bytes`: - -`hdSubPath` string with BIP32 format, "index_i / index_(i+1) '", can use hardening - -`publicKey` returns e.g. 0x80b994e25fb98f69518b1a03e59ddf4494a1a86cc66019131a732ff4a85108fbb86491e2bc423b2cdf6f1f0f4468ec73db0535a1528ca192d975116899289a4b - -* `appKey_eth_getAddress(hdSubPath) returns address 20 bytes`: - -`hdSubPath`: string with BIP32 format, "index_i / index_(i+1) '", can use hardening - -`address` e.g. 0x9df77328a2515c6d529bae90edf3d501eaaa268e - -* `appKey_eth_derivePublicKeyFromParent(parentPublicKey, hdSubPath) returns publicKey 64 bytes` - -`hdSubPath`: string with BIP32 format, "index_i / index_(i+1) '", should not use hardening here. - -* `appKey_eth_getAddressForPublicKey(publicKey) returns address 20 bytes` - -`publicKey` 64 bytes - -### Ethereum signing methods: - -* `appKey_eth_signTransaction(fromAddress, tx)` -tx is ethereum-js tx object - -* `appKey_eth_sign(fromAddress, message)` -* `appKey_eth_personalSign(fromAddress, message)` -* `appKey_eth_signTypedMessage(fromAddress, message)` -EIP712 - -### Ethereum broadcasting methods: - -* `appKey_eth_broadcastTransaction(tx, signedTx)` -tx is ethereum-js tx object - - -### Other potential methods: - -#### Other cryptocurrencies: -We defined for now Ethereum accounts and signing methods. However, one could do the same for other cryptocurrencies deriving accounts along their standards. This may open to some very interesting cross-blockchains application designs. - -#### Other cryptographic methods: -Similarly, using entropy provided by the HD Path, one could think of other cryptographic methods such as encryption and also other curve types. - - -#### Storage: -The HD path for each application can also be used as a key to isolate databases for user's persistent data. We could introduce methods that allow to read and write in a database specific to the application. - -Q [Benefit of this compared to using classical browser local storage?] - -### API permissions and confirmations from users: - -#### Initial permission request and full access afterwards: - -Each wallet has freedom in the way they implement their permission system along with this EIP and this API. We tend to favor a design where the applications would request once and for all full access to the applications keys (for their domain) and that the user has to confirm this once. From then on, any account derivation or signing for those applications keys will not prompt a confirmation request on the wallet side. -However applications themselves are free to reproduce some confirmation at their own level if they would like the users to double check the transactions or signatures they are making at the application level. This will be of course dependent on trusting the application code. - -#### Paranoia mode: -However, we would like to give users the option to monitor at any point applications keys and how applications user them. We therefore encourage wallets to introduce a `paranoia mode` that users can activate (for instance in the wallet advanced settings) to force confirmations request for all the applications keys actions. - -## Rationale - -### Isolated paths but customisable -The proposed specifications permit to have isolation between personas and between applications. Each persona / application combination will yield a unique subtree that can be explored by the application using the structure it would like to use. - -Personas are known only by the user and its wallet, application' UID based path is computable by everyone from the application's name. And then the application decides and communicates the final levels of the path. - -Only the wallet and the user will know the full tree and where we are in the tree (depth, parents). Applications will have knowledge only of the subtree, starting after the persona. - - -### API not exposing private keys - -Applications can derive accounts and request signing from them but they will not get access to the private keys of these accounts. So when the user closes her wallet entirely, the application can not continue signing for the user. This is of course in order to keep an user's ultimate control over its accounts. - -If there is a strong demand, we could add a method that exposes the private keys for the application accounts but it would be an optional to request upon app keys initial setup. - -We indeed think that writing applications that don't need to manipulate the user private keys is a better pattern. For instance, if one needs the user to sign data while being offline, one should for instance rather implement a delegation method to an external application's controlled account rather than storing the user private key on a server that stays online. - -### Persona isolation across applications for privacy - -The persona path is set by the user-wallet interaction and known only by them. There is thus a strict isolation between 2 different persona subpaths as if they were generated by different mnemonics. - - -Instead of personas, an alternative proposal would be to make the `application UID based path` a subset of a user's ethereum main accounts) - -Most wallets use the following derivation path for ethereum accounts: -`m/44'/60'/a'/0/n` -where a is a set of account number and n is the account index - -We could use: -`m/44'/60'/a'/0/n / [Application UID based path] / [App controlled HD subPath]` - -This way, we could use accounts as personas. - -However it does not necessarily make sense to anchor an application to a single main account. Some applications may like to interact with several "main accounts" or allow the user to change the main account they are using to deposit while keeping the same signing `app keys` accounts. Some applications may even like to use non ethereum accounts. - -Also this alternative specification HD path would not be BIP44 compliant but would be using this purpose field. - -Also it may add complexity to restore a wallet and the used accounts, one should remember which account is associated with which application and application can not suggest you which account to use because they are not aware of this part of the path. -If we don't harden the level indexes after the main account index, we could however enumerate all app keys of an user given a list a applications. We would first enumerate over the main accounts (assuming the wallet uses an [account gap limit](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#Address_gap_limit)), then over the Applications list and then over the `Application controlled HD subPath` if it allows to do so and has an account gap limit. - -For the persona specification this may not be possible, unless we impose some structure on the personas such as using a basic index. - -### Hardened and non-hardened indexes: privacy and functionality - -Hardening allows to increase privacy. If the extended public key of a parent level in the HD tree is known, public keys of its children can not be computed if they are hardened. On the contrary if the child indexes are not hardened one can enumerate the child public keys and use that for the application design or to easily restore a wallet and it increases functionality. - -For the first parts of the HD tree, we need isolation and privacy. Thus we use hardened indexes for the persona and application paths in case some extended public key leaks at some previous level of the tree, it would protect the sub trees (of course this has no impact if private keys leak). - -For instance if we don't harden the application path, in case a persona public key is known and the application subpath does not use hardening either, one could get all `app keys` public keys for every application for this persona. - -However the app can use non hardened indexes in their custom path part to be able to benefit from guessing child public keys from parent one (for instance for counterfactual state channel interaction across 2 peers that would like to use new keys every time they counterfactually instantiate a new sub app). - -### Alternatives for the HD derivation path - -Our proposed specification follows [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) and [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki): - -`m / purpose' / *` - -It is of course not be BIP44 compliant which uses the following tree level structure: -`m / purpose' / coin_type' / account' / change / address_index` - -One could think of alternative specifications deviating from BIP43 or even BIP32. Or on the contrary, one could try to become BIP44 compliant, although we do not really see the benefit of that for app keys and it would impose serious limitations on how to identify the applications using potentially the `coin_type` field. - - -### HD derivation path purpose field - -If we agree on not using BIP44 but following BIP32 and BIP43, we need to settle on a purpose field. We can either use the 3 depth path proposed here (https://github.com/bitcoin/bips/pull/523) or try to rech agreement on a one depth path. A one depth path should however avoid collision. This can be achieves by either submitting a BIP or by maintening a list of BIP 43 purpose fields. - -We did not find a list of BIP43 purpose code so here is what we could gather: - - -| code | Reference | Title | -|------|--------------------------------------------------------------------------|-------| -| 44 | [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) | Multi-Account Hierarchy for Deterministic Wallets | -| 45 | [BIP45](https://github.com/bitcoin/bips/blob/master/bip-0045.mediawiki) | Structure for Deterministic P2SH Multisignature Wallets| -| 48 | [SLIP48](https://github.com/satoshilabs/slips/issues/49) | Deterministic Key Hierarchy for Graphene-based Networks | -| 49 | [BIP49](https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki) | Derivation scheme for P2WPKH-nested-in-P2SH based accounts | -| 80 | [BIP80](https://github.com/bitcoin/bips/blob/master/bip-0080.mediawiki) | Hierarchy for Non-Colored Voting Pool Deterministic Multisig Wallets | -| 84 | [BIP84](https://github.com/bitcoin/bips/blob/master/bip-0084.mediawiki) | Derivation scheme for P2WPKH based accounts | -| 535348 | [Ledger app ssh](https://github.com/LedgerHQ/ledger-app-ssh-agent/blob/master/getPublicKey.py#L49) | | -| 80475047| [GPG/SSH Ledger](https://github.com/LedgerHQ/ledger-app-openpgp-card/blob/master/doc/developper/gpgcard3.0-addon.rst#deterministic-key-derivation)| | -| 1775 | EIP1775 | App Keys: application specific wallet accounts | - - -### Application's identification - -#### Favoring a deterministic scheme for application uids - -Quoting Vitalik in his post [Meta: we should value privacy more](https://ethereum-magicians.org/t/meta-we-should-value-privacy-more/2475), we indeed favor a deterministic scheme for applications specific accounts generation: - -``` -It would be nice to keep wallet software stateless, so users can easily export and import their keys between wallets; this implies using some deterministic scheme like privkey_for_dapp = hash(master_key + dapp_id). But then what is the dapp_id? How would that work for multi-contract dapps? -``` -And we proposed to use the ENS domain hash, or node, as the dapp_id and to use a BIP32 structure instead to derive the private keys. - -#### Alternative: using a centraly maintened index of application uids - -[EIP1581: Non-wallet usage of keys derived from BIP32 trees](https://eips.ethereum.org/EIPS/eip-1581) -also discussed [here](https://ethereum-magicians.org/t/non-wallet-usage-of-keys-derived-from-bip-32-trees/1817/4) proposes a scheme that relies on a list of indexes where application should register (similar to SLIP44 list for instance). - -We think our approach while also being more englobing benefits from not requiring a centrally maintained registry. In our approach every application has already a potential unique identifier assigned to it. - - -#### Shortening the Hash node - -Our current approach uses identification through an ENS name converted to a hash node and sliced fully but one could potentially keep only the first 16 bytes of the node for instance and slice them similarly. This may increase the chance of app collision but we probably can reduce the length while retaining an injective mapping from strings to hashes. - -#### Alternative application identification specification - -For the application unique identifiers, an alternative specification could favor using an `ethereum author address` and including a signed message challenge for author for authentication. - -It would also need to specify how to decompose this address. -The same reasoning as before would apply, if we use an `eth address` of 20 bytes, 160 bits - -e.g. 0x9df77328a2515c6d529bae90edf3d501eaaa268e - -``` -x = x0 || x1 || x2 || x3 || x4 || x5 -``` -where `x0` to `x4` are 30 bits and `x5` is 10 bits. - - -or alternatively equal length -``` -x = x0 || x1 || x2 || x3 || x4 || x5 || x6 || x7 -``` -where `x0` to `x7` are 20 bits. - - -Another alternative could be to use the plain website url and get rid of ens altogether but it would require another way to authenticate applications. See for instance [SLIP13](https://github.com/satoshilabs/slips/blob/master/slip-0013.md) for such a proposal. - -### Application's authentication - -For authentication we use DNS and ENS resolution, and browsing to a given url resolved. A few comments on this: - -A few comments in case of ENS resolution: -* First connection requires the wallet to connect to ethereum mainnet, but once first resolution is done we could use some metadata parameter such as `author address` for a blockchain less authentication of the application (e.g. application server signs a challenge message with the author address resolved in the ENS metadata). - -* The url the name resolves to through ENS can change without the user knowing and then a different application/website may be granted access to his app keys. But this means the ENS name owner address was copromised. This would be similar to using a signing challenge authentified by a known public key. If this known public key is compromised we have a similar problem. - -* Homoglyph attacks are not a bigger problem for `app keys` than it is for ENS since it will not grant access to `app keys` from the real domain (they would be derived along a different path). However homoglyph applications may lure the user to send funds from her main account to an `app key` of a malicious homoglyphic domain. - -Other metadata resolution through ENS that can be used alongside: -* `author address`: already mentioned above -* `contract address`: For app keys that would be designed to interact with a given ethereum contract (for instance app keys for a given token, if one desires to do so), other metadata fields could be used such as contract addresses. -* [TBD] - -In relation to the SLIP13 proposal mentioned above, one could think of alternative specifications that would use some certificate for authentication similar to https. - -### An Account gap limit standard for application controlled hd sub-path? - -If applications don't enumerate through their hd sub-path structure, we won't be able to restore `app keys` accounts by enumeration. However it has benefits to give total freedom to applications over the way they create accounts and use their sub-path. Also, it may be safe to assume that the part of the restoring procedure will be carried by the application itself and not by the wallets. The application will need a way to remember what accounts were derived for each user. - - -### Privacy and the funding trail - -If all an application needs to do with its keys is to sign messages and it does not require funding, then this EIP allows for privacy through the use of distinct keys for each application with a simple deterministic standard compatible across wallets. - -However if these application keys require funding, there can be trail and the use of app keys would not fully solve the privacy problem there. - -Mixers or anonymous ways of funding an ethereum address (ring signatures) along with this proposal would guarantee privacy. - -Even if privacy is not solved fully without this anonymous funding method, we still need a way to easily create and restore different accounts/addresses for each application - -## Backwards Compatibility - -From a wallet point of view, there does not seem to be incompatibities since these are separate accounts from those that were used previously by wallets and they are supposed to be used along-side in synergy. - -However, for applications that associated in some way their users to their main accounts ethereum addresses may want to reflect on if and how they would like to leverage the power offered by `app keys` to migrate to them and increase their user's privacy, security and potentially also user-flow. - - - -## Test Cases - -[TBD] - -Provide some examples of accounts derived from a given mnemonic, persona, application and application's custom subpath. - -## Implementation - -[WIP] -[See here for an early implementation of the HD methods](https://github.com/Bunjin/appKeys) - -## Example use cases - -* signing transactions without broadcasting them -https://github.com/MetaMask/metamask-extension/issues/3475 - -* token contract -https://github.com/ethereum/EIPs/issues/85 - -* default account for dapps -https://ethereum-magicians.org/t/default-accounts-for-dapps/904 - -* non wallet/crypto accounts -[EIP1581: Non-wallet usage of keys derived from BIP32 trees](https://eips.ethereum.org/EIPS/eip-1581) - -* state channel application - -* privacy solution - -* non custodian cross cryptocurrency exchange... - -## Acknowledgements -MetaMask team, Christian Lundkvist, Counterfactual team, Liam Horne, Erik Bryn, Richard Moore, Jeff Coleman. - - -## References - -### HD and mnemonics -#### BIPs -* [BIP32: Hierarchical Deterministic Wallets:](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) - -* [BIP39: Mnemonic code for generating deterministic keys:](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) - -* [BIP43: Purpose Field for Deterministic Wallets](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) - -* [BIP44: Multi-Account Hierarchy for Deterministic Wallets](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#Address_gap_limit) - -* [SLIP44: Registered coin types for BIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) - -* [Is there a comprehensive list of registered BIP43 purposes?](https://bitcoin.stackexchange.com/questions/60470/is-there-a-comprehensive-list-of-registered-bip43-purposes) - -#### Derivation path for eth -* [Issue 84](https://github.com/ethereum/EIPs/issues/84) - -* [Issue 85](https://github.com/ethereum/EIPs/issues/85) - -* [EIP600 Ethereum purpose allocation for Deterministic Wallets](https://eips.ethereum.org/EIPS/eip-600) - - -* [EIP601 Ethereum hierarchy for deterministic wallets](https://eips.ethereum.org/EIPS/eip-601) - -#### Accounts Privacy - - -### ENS -* [EIP137: Ethereum Domain Name Service - specification](https://eips.ethereum.org/EIPS/eip-137) - -* [EIP165: Standard Interface Detection](https://eips.ethereum.org/EIPS/eip-165) - -* [EIP634: Storage of text record in ENS](https://eips.ethereum.org/EIPS/eip-634) - -* [ENS docs about namehash:](http://docs.ens.domains/en/latest/implementers.html#namehash) - -### Previous proposals and discussions related to app keys -* [Meta: we should value privacy more](https://ethereum-magicians.org/t/meta-we-should-value-privacy-more/2475) - -* [EIP1102: Opt-in account exposure](https://eips.ethereum.org/EIPS/eip-1102) - -* [EIP1581: Non-wallet usage of keys derived from BIP-32 trees](https://eips.ethereum.org/EIPS/eip-1581) - -* [EIP1581: discussion](https://ethereum-magicians.org/t/non-wallet-usage-of-keys-derived-from-bip-32-trees/1817/4) - -* [SLIP13: Authentication using deterministic hierarchy](https://github.com/satoshilabs/slips/blob/master/slip-0013.md) - - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1775.md diff --git a/EIPS/eip-1803.md b/EIPS/eip-1803.md index 303879c30725ef..2d0e50c1b93b03 100644 --- a/EIPS/eip-1803.md +++ b/EIPS/eip-1803.md @@ -2,9 +2,10 @@ eip: 1803 title: Rename opcodes for clarity author: Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-1803-rename-opcodes-for-clarity/3345 type: Standards Track category: Interface -status: Draft +status: Stagnant created: 2017-07-28 requires: 141 --- @@ -33,9 +34,9 @@ Not applicable. ## References -[EIP-6](https://eips.ethereum.org/EIPS/eip-6) previously renamed `SUICIDE` (`0xff`) to `SELFDESTRUCT`. +[EIP-6](./eip-6.md) previously renamed `SUICIDE` (`0xff`) to `SELFDESTRUCT`. Renaming `SHA3` was previously proposed by [EIP-59](https://github.com/ethereum/EIPs/issues/59). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-181.md b/EIPS/eip-181.md index cd8dd713343033..5d88a64419342c 100644 --- a/EIPS/eip-181.md +++ b/EIPS/eip-181.md @@ -1,209 +1,7 @@ --- eip: 181 -title: ENS support for reverse resolution of Ethereum addresses -author: Nick Johnson -status: Final -type: Standards Track category: ERC -created: 2016-12-01 +status: Moved --- -# Abstract -This EIP specifies a TLD, registrar, and resolver interface for reverse resolution of Ethereum addresses using ENS. This permits associating a human-readable name with any Ethereum blockchain address. Resolvers can be certain that the reverse record was published by the owner of the Ethereum address in question. - -# Motivation -While name services are mostly used for forward resolution - going from human-readable identifiers to machine-readable ones - there are many use-cases in which reverse resolution is useful as well: - - - Applications that allow users to monitor accounts benefit from showing the name of an account instead of its address, even if it was originally added by address. - - Attaching metadata such as descriptive information to an address allows retrieving this information regardless of how the address was originally discovered. - - Anyone can configure a name to resolve to an address, regardless of ownership of that address. Reverse records allow the owner of an address to claim a name as authoritative for that address. - -# Specification -Reverse ENS records are stored in the ENS hierarchy in the same fashion as regular records, under a reserved domain, `addr.reverse`. To generate the ENS name for a given account's reverse records, convert the account to hexadecimal representation in lower-case, and append `addr.reverse`. For instance, the ENS registry's address at `0x112234455c3a32fd11230c42e7bccd4a84e02010` has any reverse records stored at `112234455c3a32fd11230c42e7bccd4a84e02010.addr.reverse`. - -Note that this means that contracts wanting to do dynamic reverse resolution of addresses will need to perform hex encoding in the contract. - -## Registrar -The owner of the `addr.reverse` domain will be a registrar that permits the caller to take ownership of -the reverse record for their own address. It provides the following methods: - -### function claim(address owner) returns (bytes32 node) - -When called by account `x`, instructs the ENS registry to transfer ownership of the name `hex(x) + '.addr.reverse'` to the provided address, and return the namehash of the ENS record thus transferred. - -Allowing the caller to specify an owner other than themselves for the relevant node facilitates contracts that need accurate reverse ENS entries delegating this to their creators with a minimum of code inside their constructor: - - reverseRegistrar.claim(msg.sender) - -### function claimWithResolver(address owner, address resolver) returns (bytes32 node) - -When called by account `x`, instructs the ENS registry to set the resolver of the name `hex(x) + '.addr.reverse' to the specified resolver, then transfer ownership of the name to the provided address, and return the namehash of the ENS record thus transferred. This method facilitates setting up a custom resolver and owner in fewer transactions than would be required if calling `claim`. - -### function setName(string name) returns (bytes32 node) - -When called by account `x`, sets the resolver for the name `hex(x) + '.addr.reverse'` to a default resolver, and sets the name record on that name to the specified name. This method facilitates setting up simple reverse records for users in a single transaction. - -## Resolver interface -A new resolver interface is defined, consisting of the following method: - - function name(bytes32 node) constant returns (string); - -Resolvers that implement this interface must return a valid ENS name for the requested node, or the empty string if no name is defined for the requested node. - -The interface ID of this interface is 0x691f3431. - -Future EIPs may specify more record types appropriate to reverse ENS records. - -# Appendix 1: Registrar implementation - -This registrar, written in Solidity, implements the specifications outlined above. - - pragma solidity ^0.4.10; - - import "./AbstractENS.sol"; - - contract Resolver { - function setName(bytes32 node, string name) public; - } - - /** - * @dev Provides a default implementation of a resolver for reverse records, - * which permits only the owner to update it. - */ - contract DefaultReverseResolver is Resolver { - AbstractENS public ens; - mapping(bytes32=>string) public name; - - /** - * @dev Constructor - * @param ensAddr The address of the ENS registry. - */ - function DefaultReverseResolver(AbstractENS ensAddr) { - ens = ensAddr; - } - - /** - * @dev Only permits calls by the reverse registrar. - * @param node The node permission is required for. - */ - modifier owner_only(bytes32 node) { - require(msg.sender == ens.owner(node)); - _; - } - - /** - * @dev Sets the name for a node. - * @param node The node to update. - * @param _name The name to set. - */ - function setName(bytes32 node, string _name) public owner_only(node) { - name[node] = _name; - } - } - - contract ReverseRegistrar { - // namehash('addr.reverse') - bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; - - AbstractENS public ens; - Resolver public defaultResolver; - - /** - * @dev Constructor - * @param ensAddr The address of the ENS registry. - * @param resolverAddr The address of the default reverse resolver. - */ - function ReverseRegistrar(AbstractENS ensAddr, Resolver resolverAddr) { - ens = ensAddr; - defaultResolver = resolverAddr; - } - - /** - * @dev Transfers ownership of the reverse ENS record associated with the - * calling account. - * @param owner The address to set as the owner of the reverse record in ENS. - * @return The ENS node hash of the reverse record. - */ - function claim(address owner) returns (bytes32 node) { - return claimWithResolver(owner, 0); - } - - /** - * @dev Transfers ownership of the reverse ENS record associated with the - * calling account. - * @param owner The address to set as the owner of the reverse record in ENS. - * @param resolver The address of the resolver to set; 0 to leave unchanged. - * @return The ENS node hash of the reverse record. - */ - function claimWithResolver(address owner, address resolver) returns (bytes32 node) { - var label = sha3HexAddress(msg.sender); - node = sha3(ADDR_REVERSE_NODE, label); - var currentOwner = ens.owner(node); - - // Update the resolver if required - if(resolver != 0 && resolver != ens.resolver(node)) { - // Transfer the name to us first if it's not already - if(currentOwner != address(this)) { - ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, this); - currentOwner = address(this); - } - ens.setResolver(node, resolver); - } - - // Update the owner if required - if(currentOwner != owner) { - ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, owner); - } - - return node; - } - - /** - * @dev Sets the `name()` record for the reverse ENS record associated with - * the calling account. First updates the resolver to the default reverse - * resolver if necessary. - * @param name The name to set for this address. - * @return The ENS node hash of the reverse record. - */ - function setName(string name) returns (bytes32 node) { - node = claimWithResolver(this, defaultResolver); - defaultResolver.setName(node, name); - return node; - } - - /** - * @dev Returns the node hash for a given account's reverse records. - * @param addr The address to hash - * @return The ENS node hash. - */ - function node(address addr) constant returns (bytes32 ret) { - return sha3(ADDR_REVERSE_NODE, sha3HexAddress(addr)); - } - - /** - * @dev An optimised function to compute the sha3 of the lower-case - * hexadecimal representation of an Ethereum address. - * @param addr The address to hash - * @return The SHA3 hash of the lower-case hexadecimal encoding of the - * input address. - */ - function sha3HexAddress(address addr) private returns (bytes32 ret) { - addr; ret; // Stop warning us about unused variables - assembly { - let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000 - let i := 40 - loop: - i := sub(i, 1) - mstore8(i, byte(and(addr, 0xf), lookup)) - addr := div(addr, 0x10) - i := sub(i, 1) - mstore8(i, byte(and(addr, 0xf), lookup)) - addr := div(addr, 0x10) - jumpi(loop, i) - ret := sha3(0, 40) - } - } - } - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-181.md diff --git a/EIPS/eip-1812.md b/EIPS/eip-1812.md index 11d4bd4790875f..dd5985dacff9c5 100644 --- a/EIPS/eip-1812.md +++ b/EIPS/eip-1812.md @@ -1,442 +1,7 @@ --- eip: 1812 -title: Ethereum Verifiable Claims -author: Pelle Braendgaard <@pelle> -discussions-to: https://ethereum-magicians.org/t/erc-1812-ethereum-verifiable-claims/2814 -status: Draft -type: Standards Track category: ERC -created: 2019-03-03 -requires: 712 +status: Moved --- -# Ethereum Verifiable Claims - -## Simple Summary - -Reusable Verifiable Claims using [EIP 712 Signed Typed Data](https://github.com/ethereum/EIPs/issues/712). - -## Abstract -A new method for Off-Chain Verifiable Claims built on [EIP 712](https://github.com/ethereum/EIPs/issues/712). These Claims can be issued by any user with a EIP 712 compatible web3 provider. Claims can be stored off chain and verified on-chain by Solidity Smart Contracts, State Channel Implementations or off-chain libraries. - -## Motivation -Reusable Off-Chain Verifiable Claims provide an important piece of integrating smart contracts with real world organizational requirements such as meeting regulatory requirements such as KYC, GDPR, Accredited Investor rules etc. - -[ERC 735](https://github.com/ethereum/EIPs/issues/735) and [ERC 780](https://github.com/ethereum/EIPs/issues/780) provide methods of making claims that live on chain. This is useful for some particular use cases, where some claim about an address must be verified on chain. - -In most cases though it is both dangerous and in some cases illegal (according to EU GDPR rules for example) to record Identity Claims containing Personal Identifying Information (PII) on an immutable public database such as the Ethereum blockchain. - -The W3C [Verifiable Claims Data Model and Representations](https://www.w3.org/TR/verifiable-claims-data-model/) as well as uPorts [Verification Message Spec](https://developer.uport.me/messages/verification) are proposed off-chain solutions. - -While built on industry standards such as [JSON-LD](https://json-ld.org) and [JWT](https://jwt.io) neither of them are easy to integrate with the Ethereum ecosystem. - -[EIP 712](https://eips.ethereum.org/EIPS/eip-712) introduces a new method of signing off chain Identity data. This provides both a data format based on Solidity ABI encoding that can easily be parsed on-chain an a new JSON-RPC call that is easily supported by existing Ethereum wallets and Web3 clients. - -This format allows reusable off-chain Verifiable Claims to be cheaply issued to users, who can present them when needed. - -## Prior Art -Verified Identity Claims such as those proposed by [uPort](https://developer.uport.me/messages/verification) and [W3C Verifiable Claims Working Group](https://www.w3.org/2017/vc/WG/) form an important part of building up reusable identity claims. - -[ERC 735](https://github.com/ethereum/EIPs/issues/735) and [ERC 780](https://github.com/ethereum/EIPs/issues/780) provide on-chain storage and lookups of Verifiable Claims. - -## Specification -### Claims -Claims can be generalized like this: - -> Issuer makes the claim that Subject is something or has some attribute and value. - -Claims should be deterministic, in that the same claim signed multiple times by the same signer. - -### Claims data structure -Each claim should be typed based on its specific use case, which EIP 712 lets us do effortlessly. But there are 3 minimal attributes required of the claims structure. - -* `subject` the subject of the claim as an `address` (who the claim is about) -* `validFrom` the time in seconds encoded as a `uint256` of start of validity of claim. In most cases this would be the time of issuance, but some claims may be valid in the future or past. -* `validTo` the time in seconds encoded as a `uint256` of when the validity of the claim expires. If you intend for the claim not to expire use `0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`. - -The basic minimal claim data structure as a Solidity struct: - -```solidity -struct [CLAIM TYPE] { - address subject; - uint256 validFrom; - uint256 validTo; -} -``` - -The CLAIM TYPE is the actual name of the claim. While not required, in most cases use the taxonomy developed by [schema.org](https://schema.org/docs/full.html) which is also commonly used in other Verifiable Claims formats. - -Example claim that issuer knows a subject: - -```solidity -struct Know { - address subject; - uint256 validFrom; - uint256 validTo; -} -``` - -### Presenting a Verifiable Claim -#### Verifying Contract -When defining Verifiable Claims formats a Verifying Contract should be created with a public `verify()` view function. This makes it very easy for other smart contracts to verify a claim correctly. - -It also provides a convenient interface for web3 and state channel apps to verify claims securely. - -```solidity -function verifyIssuer(Know memory claim, uint8 v, bytes32 r, bytes32 s) public returns (address) { - bytes32 digest = keccak256( - abi.encodePacked( - "\x19\x01", - DOMAIN_SEPARATOR, - hash(claim) - ) - ); - require( - (claim.validFrom >= block.timestamp) && (block.timestamp < claim.validTo) -, "invalid issuance timestamps"); - return ecrecover(digest, v, r, s); -} -``` - -#### Calling a SmartContract function -Verifiable Claims can be presented to a solidity function call as it’s struct together with the `v`, `r` and `s` signature components. - -```solidity -function vouch(Know memory claim, uint8 v, bytes32 r, bytes32 s) public returns (bool) { - address issuer = verifier.verifyIssuer(claim, v, r, s); - require(issuer !== '0x0'); - knows[issuer][claim.subject] = block.number; - return true; -} -``` - -#### Embedding a Verifiable Claim in another Signed Typed Data structure -The Claim struct should be embedded in another struct together with the `v`, `r` and `s` signature parameters. - -```solidity -struct Know { - address subject; - uint256 validFrom; - uint256 validTo; -} - -struct VerifiableReference { - Know delegate; - uint8 v; - bytes32 r; - bytes32 s; -} - -struct Introduction { - address recipient; - VerifiableReference issuer; -} -``` - -Each Verifiable Claim should be individually verified together with the parent Signed Typed Data structure. - -Verifiable Claims issued to different EIP 712 Domains can be embedded within each other. - -#### State Channels -This proposal will not show how to use Eth Verifiable Claims as part of a specific State Channel method. - -Any State Channel based on EIP712 should be able to include the embeddable Verifiable Claims as part of its protocol. This could be useful for exchanging private Identity Claims between the parties for regulatory reasons, while ultimately not posting them to the blockchain on conclusion of a channel. - -### Key Delegation -In most simple cases the issuer of a Claim is the signer of the data. There are cases however where signing should be delegated to an intermediary key. - -KeyDelegation can be used to implement off chain signing for smart contract based addresses, server side key rotation as well as employee permissions in complex business use cases. - -#### ERC1056 Signing Delegation - -[ERC-1056](https://github.com/ethereum/EIPs/issues/1056) provides a method for addresses to assign delegate signers. One of the primary use cases for this is that a smart contract can allow a key pair to sign on its behalf for a certain period. It also allows server based issuance tools to institute key rotation. - -To support this an additional `issuer` attribute can be added to the Claim Type struct. In this case the verification code should lookup the EthereumDIDRegistry to see if the signer of the data is an allowed signing delegate for the `issuer` - -The following is the minimal struct for a Claim containing an issuer: - -```solidity -struct [CLAIM TYPE] { - address subject; - address issuer; - uint256 validFrom; - uint256 validTo; -} -``` - -If the `issuer` is specified in the struct In addition to performing the standard ERC712 verification the verification code MUST also verify that the signing address is a valid `veriKey` delegate for the address specified in the issuer. - -```solidity -registry.validDelegate(issuer, 'veriKey', recoveredAddress) -``` - - -#### Embedded Delegation Proof -There may be applications, in particularly where organizations want to allow delegates to issue claims about specific domains and types. - -For this purpose instead of the `issuer` we allow a special claim to be embedded following this same format: - -```solidity -struct Delegate { - address issuer; - address subject; - uint256 validFrom; - uint256 validTo; -} - -struct VerifiableDelegate { - Delegate delegate; - uint8 v; - bytes32 r; - bytes32 s; -} - - -struct [CLAIM TYPE] { - address subject; - VerifiedDelegate issuer; - uint256 validFrom; - uint256 validTo; -} -``` - -Delegates should be created for specific EIP 712 Domains and not be reused across Domains. - -Implementers of new EIP 712 Domains can add further data to the `Delegate` struct to allow finer grained application specific rules to it. - -### Claim Types -#### Binary Claims -A Binary claim is something that doesn’t have a particular value. It either is issued or not. - -Examples: -* subject is a Person -* subject is my owner (eg. Linking an ethereum account to an owner identity) - -Example: - -```solidity -struct Person { - address issuer; - address subject; - uint256 validFrom; - uint256 validTo; -} -``` - -This is exactly the same as the minimal claim above with the CLAIM TYPE set to [Person](https://schema.org/Person). - -### Value Claims -Value claims can be used to make a claim about the subject containing a specific readable value. - -**WARNING**: Be very careful about using Value Claims as part of Smart Contract transactions. Identity Claims containing values could be a GDPR violation for the business or developer encouraging a user to post it to a public blockchain. - -Examples: -* subject’s name is Alice -* subjects average account balance is 1234555 - -Each value should use the `value` field to indicate the value. - -A Name Claim - -```solidity -struct Name { - address issuer; - address subject; - string name; - uint256 validFrom; - uint256 validTo; -} -``` - -Average Balance - -```solidity -struct AverageBalance { - address issuer; - address subject; - uint256 value; - uint256 validFrom; - uint256 validTo; -} -``` - -### Hashed Claims -Hashed claims can be used to make a claim about the subject containing the hash of a claim value. Hashes should use ethereum standard `keccak256` hashing function. - -**WARNING**: Be very careful about using Hashed Claims as part of Smart Contract transactions. Identity Claims containing hashes of known values could be a GDPR violation for the business or developer encouraging a user to post it to a public blockchain. - -Examples: -- [ ] hash of subject’s name is `keccak256(“Alice Torres”)` -- [ ] hash of subject’s email is `keccak256(“alice@example.com”)` - -Each value should use the `keccak256 ` field to indicate the hashed value. Question. The choice of using this name is that we can easily add support for future algorithms as well as maybe zkSnark proofs. - -A Name Claim - -```solidity -struct Name { - address issuer; - address subject; - bytes32 keccak256; - uint256 validFrom; - uint256 validTo; -} -``` - -Email Claim - -```solidity -struct Email { - address issuer; - address subject; - bytes32 keccak256; - uint256 validFrom; - uint256 validTo; -} -``` - -### EIP 712 Domain -The EIP 712 Domain specifies what kind of message that is to be signed and is used to differentiate between signed data types. The content MUST contain the following: - -```solidity -{ - name: "EIP1???Claim", - version: 1, - chainId: 1, // for mainnet - verifyingContract: 0x // TBD - salt: ... -} -``` - -#### Full Combined format for EIP 712 signing: - -Following the EIP 712 standard we can combine the Claim Type with the EIP 712 Domain and the claim itself (in the `message`) attribute. - -Eg: -```solidity - { - "types": { - "EIP712Domain": [ - { - "name": "name", - "type": "string" - }, - { - "name": "version", - "type": "string" - }, - { - "name": "chainId", - "type": "uint256" - }, - { - "name": "verifyingContract", - "type": "address" - } - ], - "Email": [ - { - "name": "subject", - "type": "address" - }, - { - "name": "keccak256", - "type": "bytes32" - }, - { - "name": "validFrom", - "type": "uint256" - }, - { - "name": "validTo", - "type": "uint256" - } - ] - }, - "primaryType": "Email", - "domain": { - "name": "EIP1??? Claim", - "version": "1", - "chainId": 1, - "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" - }, - "message": { - "subject": "0x5792e817336f41de1d8f54feab4bc200624a1d9d", - "value": "9c8465d9ae0b0bc167dee7f62880034f59313100a638dcc86a901956ea52e280", - "validFrom": "0x0000000000000000000000000000000000000000000000000001644b74c2a0", - "validTo": "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - } - } -``` - - -### Revocation -Both Issuers and Subjects should be allowed to revoke Verifiable Claims. Revocations can be handled through a simple on-chain registry. - -The ultimate rules of who should be able to revoke a claim is determined by the Verifying contract. - -The `digest` used for revocation is the EIP712 Signed Typed Data digest. - -```solidity -contract RevocationRegistry { - mapping (bytes32 => mapping (address => uint)) public revocations; - - function revoke(bytes32 digest) public returns (bool) { - revocations[digest][msg.sender] = block.number; - return true; - } - - function revoked(address party, bytes32 digest) public view returns (bool) { - return revocations[digest][party] > 0; - } -} -``` - -A verifying contract can query the Revocation Registry as such: - -```solidity -bytes32 digest = keccak256( - abi.encodePacked( - "\x19\x01", - DOMAIN_SEPARATOR, - hash(claim) - ) -); -require(valid(claim.validFrom, claim.validTo), "invalid issuance timestamps"); -address issuer = ecrecover(digest, v, r, s); -require(!revocations.revoked(issuer, digest), "claim was revoked by issuer"); -require(!revocations.revoked(claim.subject, digest), "claim was revoked by subject"); -``` - -### Creation of Verifiable Claims Domains - -Creating specific is Verifiable Claims Domains is out of the scope of this EIP. The Example Code has a few examples. - -EIP’s or another process could be used to standardize specific important Domains that are universally useful across the Ethereum world. - -## Rationale -Signed Typed Data provides a strong foundation for Verifiable Claims that can be used in many different kinds of applications built on both Layer 1 and Layer 2 of Ethereum. - -### Rationale for using not using a single EIP 712 Domain -EIP712 supports complex types and domains in itself, that we believe are perfect building blocks for building Verifiable Claims for specific purposes. - -The Type and Domain of a Claim is itself an important part of a claim and ensures that Verifiable Claims are used for the specific purposes required and not misused. - -EIP712 Domains also allow rapid experimentation, allowing taxonomies to be built up by the community. - -## Test Cases -There is a repo with a few example verifiers and consuming smart contracts written in Solidity: - -**Example Verifiers** -* [Verifier for very simple IdVerification Verifiable Claims containing minimal Personal Data](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/IdentityClaimsVerifier.sol) -* [Verifier for OwnershipProofs signed by a users wallet](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/OwnershipProofVerifier.sol) - -**Example Smart Contracts** -* [KYCCoin.sol](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/KYCCoin.sol) - Example Token allows reusable IdVerification claims issued by trusted verifiers and users to whitelist their own addresses using OwnershipProofs -* [ConsortiumAgreement.sol](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/ConsortiumAgreements.sol) - Example Consortium Agreement smart contract. Consortium Members can issue Delegated Claims to employees or servers to interact on their behalf. - -**Shared Registries** -* [RevocationRegistry.sol](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/RevocationRegistry.sol) - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/_). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1812.md diff --git a/EIPS/eip-1820.md b/EIPS/eip-1820.md index c40a5d8a7c133d..a3f2b2cc2b848f 100644 --- a/EIPS/eip-1820.md +++ b/EIPS/eip-1820.md @@ -1,928 +1,7 @@ --- eip: 1820 -title: Pseudo-introspection Registry Contract -author: Jordi Baylina , Jacques Dafflon -discussions-to: https://github.com/ethereum/EIPs/pull/1820 -status: Final -type: Standards Track category: ERC -requires: 165, 214 -created: 2019-03-04 -replaces: 820 +status: Moved --- -> :information_source: **[ERC1820] has superseded [ERC820].** :information_source: -> [ERC1820] fixes the incompatibility in the [ERC165] logic which was introduced by the Solidty 0.5 update. -> Have a look at the [official announcement][erc1820-annoucement], and the comments about the [bug][erc820-bug] and the [fix][erc820-fix]. -> Apart from this fix, [ERC1820] is functionally equivalent to [ERC820]. -> -> :warning: [ERC1820] MUST be used in lieu of [ERC820]. :warning: - -## Simple Summary - -This standard defines a universal registry smart contract where any address (contract or regular account) can register which interface it supports and which smart contract is responsible for its implementation. - -This standard keeps backward compatibility with [ERC165]. - -## Abstract - -This standard defines a registry where smart contracts and regular accounts can publish which functionality they implement---either directly or through a proxy contract. - -Anyone can query this registry to ask if a specific address implements a given interface and which smart contract handles its implementation. - -This registry MAY be deployed on any chain and shares the same address on all chains. - -Interfaces with zeroes (`0`) as the last 28 bytes are considered [ERC165] interfaces, -and this registry SHALL forward the call to the contract to see if it implements the interface. - -This contract also acts as an [ERC165] cache to reduce gas consumption. - -## Motivation - -There have been different approaches to define pseudo-introspection in Ethereum. -The first is [ERC165] which has the limitation that it cannot be used by regular accounts. -The second attempt is [ERC672] which uses reverse [ENS]. Using reverse [ENS] has two issues. -First, it is unnecessarily complicated, and second, [ENS] is still a centralized contract controlled by a multisig. -This multisig theoretically would be able to modify the system. - -This standard is much simpler than [ERC672], and it is *fully* decentralized. - -This standard also provides a *unique* address for all chains. -Thus solving the problem of resolving the correct registry address for different chains. - -## Specification - -### [ERC1820] Registry Smart Contract - -> This is an exact copy of the code of the [ERC1820 registry smart contract]. - -``` solidity -/* ERC1820 Pseudo-introspection Registry Contract - * This standard defines a universal registry smart contract where any address (contract or regular account) can - * register which interface it supports and which smart contract is responsible for its implementation. - * - * Written in 2019 by Jordi Baylina and Jacques Dafflon - * - * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to - * this software to the public domain worldwide. This software is distributed without any warranty. - * - * You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see - * . - * - * ███████╗██████╗ ██████╗ ██╗ █████╗ ██████╗ ██████╗ - * ██╔════╝██╔══██╗██╔════╝███║██╔══██╗╚════██╗██╔═████╗ - * █████╗ ██████╔╝██║ ╚██║╚█████╔╝ █████╔╝██║██╔██║ - * ██╔══╝ ██╔══██╗██║ ██║██╔══██╗██╔═══╝ ████╔╝██║ - * ███████╗██║ ██║╚██████╗ ██║╚█████╔╝███████╗╚██████╔╝ - * ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚════╝ ╚══════╝ ╚═════╝ - * - * ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ - * ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝ - * ██████╔╝█████╗ ██║ ███╗██║███████╗ ██║ ██████╔╝ ╚████╔╝ - * ██╔══██╗██╔══╝ ██║ ██║██║╚════██║ ██║ ██╔══██╗ ╚██╔╝ - * ██║ ██║███████╗╚██████╔╝██║███████║ ██║ ██║ ██║ ██║ - * ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ - * - */ -pragma solidity 0.5.3; -// IV is value needed to have a vanity address starting with '0x1820'. -// IV: 53759 - -/// @dev The interface a contract MUST implement if it is the implementer of -/// some (other) interface for any address other than itself. -interface ERC1820ImplementerInterface { - /// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not. - /// @param interfaceHash keccak256 hash of the name of the interface - /// @param addr Address for which the contract will implement the interface - /// @return ERC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'. - function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32); -} - - -/// @title ERC1820 Pseudo-introspection Registry Contract -/// @author Jordi Baylina and Jacques Dafflon -/// @notice This contract is the official implementation of the ERC1820 Registry. -/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-1820 -contract ERC1820Registry { - /// @notice ERC165 Invalid ID. - bytes4 constant internal INVALID_ID = 0xffffffff; - /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`). - bytes4 constant internal ERC165ID = 0x01ffc9a7; - /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address. - bytes32 constant internal ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); - - /// @notice mapping from addresses and interface hashes to their implementers. - mapping(address => mapping(bytes32 => address)) internal interfaces; - /// @notice mapping from addresses to their manager. - mapping(address => address) internal managers; - /// @notice flag for each address and erc165 interface to indicate if it is cached. - mapping(address => mapping(bytes4 => bool)) internal erc165Cached; - - /// @notice Indicates a contract is the 'implementer' of 'interfaceHash' for 'addr'. - event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer); - /// @notice Indicates 'newManager' is the address of the new manager for 'addr'. - event ManagerChanged(address indexed addr, address indexed newManager); - - /// @notice Query if an address implements an interface and through which contract. - /// @param _addr Address being queried for the implementer of an interface. - /// (If '_addr' is the zero address then 'msg.sender' is assumed.) - /// @param _interfaceHash Keccak256 hash of the name of the interface as a string. - /// E.g., 'web3.utils.keccak256("ERC777TokensRecipient")' for the 'ERC777TokensRecipient' interface. - /// @return The address of the contract which implements the interface '_interfaceHash' for '_addr' - /// or '0' if '_addr' did not register an implementer for this interface. - function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) { - address addr = _addr == address(0) ? msg.sender : _addr; - if (isERC165Interface(_interfaceHash)) { - bytes4 erc165InterfaceHash = bytes4(_interfaceHash); - return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : address(0); - } - return interfaces[addr][_interfaceHash]; - } - - /// @notice Sets the contract which implements a specific interface for an address. - /// Only the manager defined for that address can set it. - /// (Each address is the manager for itself until it sets a new manager.) - /// @param _addr Address for which to set the interface. - /// (If '_addr' is the zero address then 'msg.sender' is assumed.) - /// @param _interfaceHash Keccak256 hash of the name of the interface as a string. - /// E.g., 'web3.utils.keccak256("ERC777TokensRecipient")' for the 'ERC777TokensRecipient' interface. - /// @param _implementer Contract address implementing '_interfaceHash' for '_addr'. - function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external { - address addr = _addr == address(0) ? msg.sender : _addr; - require(getManager(addr) == msg.sender, "Not the manager"); - - require(!isERC165Interface(_interfaceHash), "Must not be an ERC165 hash"); - if (_implementer != address(0) && _implementer != msg.sender) { - require( - ERC1820ImplementerInterface(_implementer) - .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC1820_ACCEPT_MAGIC, - "Does not implement the interface" - ); - } - interfaces[addr][_interfaceHash] = _implementer; - emit InterfaceImplementerSet(addr, _interfaceHash, _implementer); - } - - /// @notice Sets '_newManager' as manager for '_addr'. - /// The new manager will be able to call 'setInterfaceImplementer' for '_addr'. - /// @param _addr Address for which to set the new manager. - /// @param _newManager Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.) - function setManager(address _addr, address _newManager) external { - require(getManager(_addr) == msg.sender, "Not the manager"); - managers[_addr] = _newManager == _addr ? address(0) : _newManager; - emit ManagerChanged(_addr, _newManager); - } - - /// @notice Get the manager of an address. - /// @param _addr Address for which to return the manager. - /// @return Address of the manager for a given address. - function getManager(address _addr) public view returns(address) { - // By default the manager of an address is the same address - if (managers[_addr] == address(0)) { - return _addr; - } else { - return managers[_addr]; - } - } - - /// @notice Compute the keccak256 hash of an interface given its name. - /// @param _interfaceName Name of the interface. - /// @return The keccak256 hash of an interface name. - function interfaceHash(string calldata _interfaceName) external pure returns(bytes32) { - return keccak256(abi.encodePacked(_interfaceName)); - } - - /* --- ERC165 Related Functions --- */ - /* --- Developed in collaboration with William Entriken. --- */ - - /// @notice Updates the cache with whether the contract implements an ERC165 interface or not. - /// @param _contract Address of the contract for which to update the cache. - /// @param _interfaceId ERC165 interface for which to update the cache. - function updateERC165Cache(address _contract, bytes4 _interfaceId) external { - interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache( - _contract, _interfaceId) ? _contract : address(0); - erc165Cached[_contract][_interfaceId] = true; - } - - /// @notice Checks whether a contract implements an ERC165 interface or not. - // If the result is not cached a direct lookup on the contract address is performed. - // If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling - // 'updateERC165Cache' with the contract address. - /// @param _contract Address of the contract to check. - /// @param _interfaceId ERC165 interface to check. - /// @return True if '_contract' implements '_interfaceId', false otherwise. - function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) { - if (!erc165Cached[_contract][_interfaceId]) { - return implementsERC165InterfaceNoCache(_contract, _interfaceId); - } - return interfaces[_contract][_interfaceId] == _contract; - } - - /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. - /// @param _contract Address of the contract to check. - /// @param _interfaceId ERC165 interface to check. - /// @return True if '_contract' implements '_interfaceId', false otherwise. - function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) { - uint256 success; - uint256 result; - - (success, result) = noThrowCall(_contract, ERC165ID); - if (success == 0 || result == 0) { - return false; - } - - (success, result) = noThrowCall(_contract, INVALID_ID); - if (success == 0 || result != 0) { - return false; - } - - (success, result) = noThrowCall(_contract, _interfaceId); - if (success == 1 && result == 1) { - return true; - } - return false; - } - - /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not. - /// @param _interfaceHash The hash to check. - /// @return True if '_interfaceHash' is an ERC165 interface (ending with 28 zeroes), false otherwise. - function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) { - return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0; - } - - /// @dev Make a call on a contract without throwing if the function does not exist. - function noThrowCall(address _contract, bytes4 _interfaceId) - internal view returns (uint256 success, uint256 result) - { - bytes4 erc165ID = ERC165ID; - - assembly { - let x := mload(0x40) // Find empty storage location using "free memory pointer" - mstore(x, erc165ID) // Place signature at beginning of empty storage - mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature - - success := staticcall( - 30000, // 30k gas - _contract, // To addr - x, // Inputs are stored at location x - 0x24, // Inputs are 36 (4 + 32) bytes long - x, // Store output over input (saves space) - 0x20 // Outputs are 32 bytes long - ) - - result := mload(x) // Load the result - } - } -} - -``` - -### Deployment Transaction - -Below is the raw transaction which MUST be used to deploy the smart contract on any chain. - -``` -0xf90a388085174876e800830c35008080b909e5608060405234801561001057600080fd5b506109c5806100206000396000f3fe608060405234801561001057600080fd5b50600436106100a5576000357c010000000000000000000000000000000000000000000000000000000090048063a41e7d5111610078578063a41e7d51146101d4578063aabbb8ca1461020a578063b705676514610236578063f712f3e814610280576100a5565b806329965a1d146100aa5780633d584063146100e25780635df8122f1461012457806365ba36c114610152575b600080fd5b6100e0600480360360608110156100c057600080fd5b50600160a060020a038135811691602081013591604090910135166102b6565b005b610108600480360360208110156100f857600080fd5b5035600160a060020a0316610570565b60408051600160a060020a039092168252519081900360200190f35b6100e06004803603604081101561013a57600080fd5b50600160a060020a03813581169160200135166105bc565b6101c26004803603602081101561016857600080fd5b81019060208101813564010000000081111561018357600080fd5b82018360208201111561019557600080fd5b803590602001918460018302840111640100000000831117156101b757600080fd5b5090925090506106b3565b60408051918252519081900360200190f35b6100e0600480360360408110156101ea57600080fd5b508035600160a060020a03169060200135600160e060020a0319166106ee565b6101086004803603604081101561022057600080fd5b50600160a060020a038135169060200135610778565b61026c6004803603604081101561024c57600080fd5b508035600160a060020a03169060200135600160e060020a0319166107ef565b604080519115158252519081900360200190f35b61026c6004803603604081101561029657600080fd5b508035600160a060020a03169060200135600160e060020a0319166108aa565b6000600160a060020a038416156102cd57836102cf565b335b9050336102db82610570565b600160a060020a031614610339576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6103428361092a565b15610397576040805160e560020a62461bcd02815260206004820152601a60248201527f4d757374206e6f7420626520616e204552433136352068617368000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103b85750600160a060020a0382163314155b156104ff5760405160200180807f455243313832305f4143434550545f4d4147494300000000000000000000000081525060140190506040516020818303038152906040528051906020012082600160a060020a031663249cb3fa85846040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083815260200182600160a060020a0316600160a060020a031681526020019250505060206040518083038186803b15801561047e57600080fd5b505afa158015610492573d6000803e3d6000fd5b505050506040513d60208110156104a857600080fd5b5051146104ff576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03818116600090815260016020526040812054909116151561059a5750806105b7565b50600160a060020a03808216600090815260016020526040902054165b919050565b336105c683610570565b600160a060020a031614610624576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146106435780610646565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b600082826040516020018083838082843780830192505050925050506040516020818303038152906040528051906020012090505b92915050565b6106f882826107ef565b610703576000610705565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b600080600160a060020a038416156107905783610792565b335b905061079d8361092a565b156107c357826107ad82826108aa565b6107b85760006107ba565b815b925050506106e8565b600160a060020a0390811660009081526020818152604080832086845290915290205416905092915050565b6000808061081d857f01ffc9a70000000000000000000000000000000000000000000000000000000061094c565b909250905081158061082d575080155b1561083d576000925050506106e8565b61084f85600160e060020a031961094c565b909250905081158061086057508015155b15610870576000925050506106e8565b61087a858561094c565b909250905060018214801561088f5750806001145b1561089f576001925050506106e8565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108f2576108eb83836107ef565b90506106e8565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160248189617530fa90519096909550935050505056fea165627a7a72305820377f4a2d4301ede9949f163f319021a6e9c687c292a5e2b2c4734c126b524e6c00291ba01820182018201820182018201820182018201820182018201820182018201820a01820182018201820182018201820182018201820182018201820182018201820 -``` - -The strings of `1820`'s at the end of the transaction are the `r` and `s` of the signature. -From this deterministic pattern (generated by a human), anyone can deduce that no one knows the private key for the deployment account. - -### Deployment Method - -This contract is going to be deployed using the keyless deployment method---also known as [Nick]'s method---which relies on a single-use address. -(See [Nick's article] for more details). This method works as follows: - -1. Generate a transaction which deploys the contract from a new random account. - - This transaction MUST NOT use [EIP155] in order to work on any chain. - - This transaction MUST have a relatively high gas price to be deployed on any chain. In this case, it is going to be 100 Gwei. - -2. Set the `v`, `r`, `s` of the transaction signature to the following values: - - ``` - v: 27, - r: 0x1820182018201820182018201820182018201820182018201820182018201820' - s: 0x1820182018201820182018201820182018201820182018201820182018201820' - ``` - - Those `r` and `s` values---made of a repeating pattern of `1820`'s---are predictable "random numbers" generated deterministically by a human. - -3. We recover the sender of this transaction, i.e., the single-use deployment account. - - > Thus we obtain an account that can broadcast that transaction, but we also have the warranty that nobody knows the private key of that account. - -4. Send exactly 0.08 ether to this single-use deployment account. - -5. Broadcast the deployment transaction. - -This operation can be done on any chain, guaranteeing that the contract address is always the same and nobody can use that address with a different contract. - - -### Single-use Registry Deployment Account - -``` -0xa990077c3205cbDf861e17Fa532eeB069cE9fF96 -``` - -This account is generated by reverse engineering it from its signature for the transaction. -This way no one knows the private key, but it is known that it is the valid signer of the deployment transaction. - -> To deploy the registry, 0.08 ether MUST be sent to this account *first*. - -### Registry Contract Address - -``` -0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 -``` - -The contract has the address above for every chain on which it is deployed. - -
-Raw metadata of ./contracts/ERC1820Registry.sol -
-{
-        "compiler": {
-          "version": "0.5.3+commit.10d17f24"
-        },
-        "language": "Solidity",
-        "output": {
-          "abi": [
-            {
-              "constant": false,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceHash",
-                  "type": "bytes32"
-                },
-                {
-                  "name": "_implementer",
-                  "type": "address"
-                }
-              ],
-              "name": "setInterfaceImplementer",
-              "outputs": [],
-              "payable": false,
-              "stateMutability": "nonpayable",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                }
-              ],
-              "name": "getManager",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "address"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "constant": false,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                },
-                {
-                  "name": "_newManager",
-                  "type": "address"
-                }
-              ],
-              "name": "setManager",
-              "outputs": [],
-              "payable": false,
-              "stateMutability": "nonpayable",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_interfaceName",
-                  "type": "string"
-                }
-              ],
-              "name": "interfaceHash",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "bytes32"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "pure",
-              "type": "function"
-            },
-            {
-              "constant": false,
-              "inputs": [
-                {
-                  "name": "_contract",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceId",
-                  "type": "bytes4"
-                }
-              ],
-              "name": "updateERC165Cache",
-              "outputs": [],
-              "payable": false,
-              "stateMutability": "nonpayable",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceHash",
-                  "type": "bytes32"
-                }
-              ],
-              "name": "getInterfaceImplementer",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "address"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_contract",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceId",
-                  "type": "bytes4"
-                }
-              ],
-              "name": "implementsERC165InterfaceNoCache",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "bool"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_contract",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceId",
-                  "type": "bytes4"
-                }
-              ],
-              "name": "implementsERC165Interface",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "bool"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "anonymous": false,
-              "inputs": [
-                {
-                  "indexed": true,
-                  "name": "addr",
-                  "type": "address"
-                },
-                {
-                  "indexed": true,
-                  "name": "interfaceHash",
-                  "type": "bytes32"
-                },
-                {
-                  "indexed": true,
-                  "name": "implementer",
-                  "type": "address"
-                }
-              ],
-              "name": "InterfaceImplementerSet",
-              "type": "event"
-            },
-            {
-              "anonymous": false,
-              "inputs": [
-                {
-                  "indexed": true,
-                  "name": "addr",
-                  "type": "address"
-                },
-                {
-                  "indexed": true,
-                  "name": "newManager",
-                  "type": "address"
-                }
-              ],
-              "name": "ManagerChanged",
-              "type": "event"
-            }
-          ],
-          "devdoc": {
-            "author": "Jordi Baylina and Jacques Dafflon",
-            "methods": {
-              "getInterfaceImplementer(address,bytes32)": {
-                "params": {
-                  "_addr": "Address being queried for the implementer of an interface. (If '_addr' is the zero address then 'msg.sender' is assumed.)",
-                  "_interfaceHash": "Keccak256 hash of the name of the interface as a string. E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface."
-                },
-                "return": "The address of the contract which implements the interface '_interfaceHash' for '_addr' or '0' if '_addr' did not register an implementer for this interface."
-              },
-              "getManager(address)": {
-                "params": {
-                  "_addr": "Address for which to return the manager."
-                },
-                "return": "Address of the manager for a given address."
-              },
-              "implementsERC165Interface(address,bytes4)": {
-                "params": {
-                  "_contract": "Address of the contract to check.",
-                  "_interfaceId": "ERC165 interface to check."
-                },
-                "return": "True if '_contract' implements '_interfaceId', false otherwise."
-              },
-              "implementsERC165InterfaceNoCache(address,bytes4)": {
-                "params": {
-                  "_contract": "Address of the contract to check.",
-                  "_interfaceId": "ERC165 interface to check."
-                },
-                "return": "True if '_contract' implements '_interfaceId', false otherwise."
-              },
-              "interfaceHash(string)": {
-                "params": {
-                  "_interfaceName": "Name of the interface."
-                },
-                "return": "The keccak256 hash of an interface name."
-              },
-              "setInterfaceImplementer(address,bytes32,address)": {
-                "params": {
-                  "_addr": "Address for which to set the interface. (If '_addr' is the zero address then 'msg.sender' is assumed.)",
-                  "_implementer": "Contract address implementing '_interfaceHash' for '_addr'.",
-                  "_interfaceHash": "Keccak256 hash of the name of the interface as a string. E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface."
-                }
-              },
-              "setManager(address,address)": {
-                "params": {
-                  "_addr": "Address for which to set the new manager.",
-                  "_newManager": "Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.)"
-                }
-              },
-              "updateERC165Cache(address,bytes4)": {
-                "params": {
-                  "_contract": "Address of the contract for which to update the cache.",
-                  "_interfaceId": "ERC165 interface for which to update the cache."
-                }
-              }
-            },
-            "title": "ERC1820 Pseudo-introspection Registry Contract"
-          },
-          "userdoc": {
-            "methods": {
-              "getInterfaceImplementer(address,bytes32)": {
-                "notice": "Query if an address implements an interface and through which contract."
-              },
-              "getManager(address)": {
-                "notice": "Get the manager of an address."
-              },
-              "implementsERC165InterfaceNoCache(address,bytes4)": {
-                "notice": "Checks whether a contract implements an ERC165 interface or not without using nor updating the cache."
-              },
-              "interfaceHash(string)": {
-                "notice": "Compute the keccak256 hash of an interface given its name."
-              },
-              "setInterfaceImplementer(address,bytes32,address)": {
-                "notice": "Sets the contract which implements a specific interface for an address. Only the manager defined for that address can set it. (Each address is the manager for itself until it sets a new manager.)"
-              },
-              "setManager(address,address)": {
-                "notice": "Sets '_newManager' as manager for '_addr'. The new manager will be able to call 'setInterfaceImplementer' for '_addr'."
-              },
-              "updateERC165Cache(address,bytes4)": {
-                "notice": "Updates the cache with whether the contract implements an ERC165 interface or not."
-              }
-            },
-            "notice": "This contract is the official implementation of the ERC1820 Registry.For more details, see https://eips.ethereum.org/EIPS/eip-1820"
-          }
-        },
-        "settings": {
-          "compilationTarget": {
-            "./contracts/ERC1820Registry.sol": "ERC1820Registry"
-          },
-          "evmVersion": "byzantium",
-          "libraries": {},
-          "optimizer": {
-            "enabled": true,
-            "runs": 200
-          },
-          "remappings": []
-        },
-        "sources": {
-          "./contracts/ERC1820Registry.sol": {
-            "content": "/* ERC1820 Pseudo-introspection Registry Contract\n * This standard defines a universal registry smart contract where any address (contract or regular account) can\n * register which interface it supports and which smart contract is responsible for its implementation.\n *\n * Written in 2019 by Jordi Baylina and Jacques Dafflon\n *\n * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to\n * this software to the public domain worldwide. This software is distributed without any warranty.\n *\n * You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see\n * .\n *\n *    ███████╗██████╗  ██████╗ ██╗ █████╗ ██████╗  ██████╗\n *    ██╔════╝██╔══██╗██╔════╝███║██╔══██╗╚════██╗██╔═████╗\n *    █████╗  ██████╔╝██║     ╚██║╚█████╔╝ █████╔╝██║██╔██║\n *    ██╔══╝  ██╔══██╗██║      ██║██╔══██╗██╔═══╝ ████╔╝██║\n *    ███████╗██║  ██║╚██████╗ ██║╚█████╔╝███████╗╚██████╔╝\n *    ╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚═╝ ╚════╝ ╚══════╝ ╚═════╝\n *\n *    ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗   ██╗\n *    ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝\n *    ██████╔╝█████╗  ██║  ███╗██║███████╗   ██║   ██████╔╝ ╚████╔╝\n *    ██╔══██╗██╔══╝  ██║   ██║██║╚════██║   ██║   ██╔══██╗  ╚██╔╝\n *    ██║  ██║███████╗╚██████╔╝██║███████║   ██║   ██║  ██║   ██║\n *    ╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝\n *\n */\npragma solidity 0.5.3;\n// IV is value needed to have a vanity address starting with '0x1820'.\n// IV: 53759\n\n/// @dev The interface a contract MUST implement if it is the implementer of\n/// some (other) interface for any address other than itself.\ninterface ERC1820ImplementerInterface {\n    /// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not.\n    /// @param interfaceHash keccak256 hash of the name of the interface\n    /// @param addr Address for which the contract will implement the interface\n    /// @return ERC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'.\n    function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32);\n}\n\n\n/// @title ERC1820 Pseudo-introspection Registry Contract\n/// @author Jordi Baylina and Jacques Dafflon\n/// @notice This contract is the official implementation of the ERC1820 Registry.\n/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-1820\ncontract ERC1820Registry {\n    /// @notice ERC165 Invalid ID.\n    bytes4 constant internal INVALID_ID = 0xffffffff;\n    /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`).\n    bytes4 constant internal ERC165ID = 0x01ffc9a7;\n    /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address.\n    bytes32 constant internal ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked(\"ERC1820_ACCEPT_MAGIC\"));\n\n    /// @notice mapping from addresses and interface hashes to their implementers.\n    mapping(address => mapping(bytes32 => address)) internal interfaces;\n    /// @notice mapping from addresses to their manager.\n    mapping(address => address) internal managers;\n    /// @notice flag for each address and erc165 interface to indicate if it is cached.\n    mapping(address => mapping(bytes4 => bool)) internal erc165Cached;\n\n    /// @notice Indicates a contract is the 'implementer' of 'interfaceHash' for 'addr'.\n    event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer);\n    /// @notice Indicates 'newManager' is the address of the new manager for 'addr'.\n    event ManagerChanged(address indexed addr, address indexed newManager);\n\n    /// @notice Query if an address implements an interface and through which contract.\n    /// @param _addr Address being queried for the implementer of an interface.\n    /// (If '_addr' is the zero address then 'msg.sender' is assumed.)\n    /// @param _interfaceHash Keccak256 hash of the name of the interface as a string.\n    /// E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface.\n    /// @return The address of the contract which implements the interface '_interfaceHash' for '_addr'\n    /// or '0' if '_addr' did not register an implementer for this interface.\n    function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) {\n        address addr = _addr == address(0) ? msg.sender : _addr;\n        if (isERC165Interface(_interfaceHash)) {\n            bytes4 erc165InterfaceHash = bytes4(_interfaceHash);\n            return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : address(0);\n        }\n        return interfaces[addr][_interfaceHash];\n    }\n\n    /// @notice Sets the contract which implements a specific interface for an address.\n    /// Only the manager defined for that address can set it.\n    /// (Each address is the manager for itself until it sets a new manager.)\n    /// @param _addr Address for which to set the interface.\n    /// (If '_addr' is the zero address then 'msg.sender' is assumed.)\n    /// @param _interfaceHash Keccak256 hash of the name of the interface as a string.\n    /// E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface.\n    /// @param _implementer Contract address implementing '_interfaceHash' for '_addr'.\n    function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external {\n        address addr = _addr == address(0) ? msg.sender : _addr;\n        require(getManager(addr) == msg.sender, \"Not the manager\");\n\n        require(!isERC165Interface(_interfaceHash), \"Must not be an ERC165 hash\");\n        if (_implementer != address(0) && _implementer != msg.sender) {\n            require(\n                ERC1820ImplementerInterface(_implementer)\n                    .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC1820_ACCEPT_MAGIC,\n                \"Does not implement the interface\"\n            );\n        }\n        interfaces[addr][_interfaceHash] = _implementer;\n        emit InterfaceImplementerSet(addr, _interfaceHash, _implementer);\n    }\n\n    /// @notice Sets '_newManager' as manager for '_addr'.\n    /// The new manager will be able to call 'setInterfaceImplementer' for '_addr'.\n    /// @param _addr Address for which to set the new manager.\n    /// @param _newManager Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.)\n    function setManager(address _addr, address _newManager) external {\n        require(getManager(_addr) == msg.sender, \"Not the manager\");\n        managers[_addr] = _newManager == _addr ? address(0) : _newManager;\n        emit ManagerChanged(_addr, _newManager);\n    }\n\n    /// @notice Get the manager of an address.\n    /// @param _addr Address for which to return the manager.\n    /// @return Address of the manager for a given address.\n    function getManager(address _addr) public view returns(address) {\n        // By default the manager of an address is the same address\n        if (managers[_addr] == address(0)) {\n            return _addr;\n        } else {\n            return managers[_addr];\n        }\n    }\n\n    /// @notice Compute the keccak256 hash of an interface given its name.\n    /// @param _interfaceName Name of the interface.\n    /// @return The keccak256 hash of an interface name.\n    function interfaceHash(string calldata _interfaceName) external pure returns(bytes32) {\n        return keccak256(abi.encodePacked(_interfaceName));\n    }\n\n    /* --- ERC165 Related Functions --- */\n    /* --- Developed in collaboration with William Entriken. --- */\n\n    /// @notice Updates the cache with whether the contract implements an ERC165 interface or not.\n    /// @param _contract Address of the contract for which to update the cache.\n    /// @param _interfaceId ERC165 interface for which to update the cache.\n    function updateERC165Cache(address _contract, bytes4 _interfaceId) external {\n        interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache(\n            _contract, _interfaceId) ? _contract : address(0);\n        erc165Cached[_contract][_interfaceId] = true;\n    }\n\n    /// @notice Checks whether a contract implements an ERC165 interface or not.\n    //  If the result is not cached a direct lookup on the contract address is performed.\n    //  If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling\n    //  'updateERC165Cache' with the contract address.\n    /// @param _contract Address of the contract to check.\n    /// @param _interfaceId ERC165 interface to check.\n    /// @return True if '_contract' implements '_interfaceId', false otherwise.\n    function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) {\n        if (!erc165Cached[_contract][_interfaceId]) {\n            return implementsERC165InterfaceNoCache(_contract, _interfaceId);\n        }\n        return interfaces[_contract][_interfaceId] == _contract;\n    }\n\n    /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.\n    /// @param _contract Address of the contract to check.\n    /// @param _interfaceId ERC165 interface to check.\n    /// @return True if '_contract' implements '_interfaceId', false otherwise.\n    function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) {\n        uint256 success;\n        uint256 result;\n\n        (success, result) = noThrowCall(_contract, ERC165ID);\n        if (success == 0 || result == 0) {\n            return false;\n        }\n\n        (success, result) = noThrowCall(_contract, INVALID_ID);\n        if (success == 0 || result != 0) {\n            return false;\n        }\n\n        (success, result) = noThrowCall(_contract, _interfaceId);\n        if (success == 1 && result == 1) {\n            return true;\n        }\n        return false;\n    }\n\n    /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not.\n    /// @param _interfaceHash The hash to check.\n    /// @return True if '_interfaceHash' is an ERC165 interface (ending with 28 zeroes), false otherwise.\n    function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) {\n        return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0;\n    }\n\n    /// @dev Make a call on a contract without throwing if the function does not exist.\n    function noThrowCall(address _contract, bytes4 _interfaceId)\n        internal view returns (uint256 success, uint256 result)\n    {\n        bytes4 erc165ID = ERC165ID;\n\n        assembly {\n            let x := mload(0x40)               // Find empty storage location using \"free memory pointer\"\n            mstore(x, erc165ID)                // Place signature at beginning of empty storage\n            mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature\n\n            success := staticcall(\n                30000,                         // 30k gas\n                _contract,                     // To addr\n                x,                             // Inputs are stored at location x\n                0x24,                          // Inputs are 36 (4 + 32) bytes long\n                x,                             // Store output over input (saves space)\n                0x20                           // Outputs are 32 bytes long\n            )\n\n            result := mload(x)                 // Load the result\n        }\n    }\n}\n",
-            "keccak256": "0x64025ecebddb6e126a5075c1fd6c01de2840492668e2909cef7157040a9d1945"
-          }
-        },
-        "version": 1
-      }
-
-
- -### Interface Name - -Any interface name is hashed using `keccak256` and sent to `getInterfaceImplementer()`. - -If the interface is part of a standard, it is best practice to explicitly state the interface name and link to this published [ERC1820] such that other people don't have to come here to look up these rules. - -For convenience, the registry provides a function to compute the hash on-chain: - -``` solidity -function interfaceHash(string _interfaceName) public pure returns(bytes32) -``` - -Compute the keccak256 hash of an interface given its name. - -> **identifier:** `65ba36c1` -> **parameters** -> `_interfaceName`: Name of the interface. -> **returns:** The `keccak256` hash of an interface name. - -#### **Approved ERCs** - -If the interface is part of an approved ERC, it MUST be named `ERC###XXXXX` where `###` is the number of the ERC and XXXXX should be the name of the interface in CamelCase. -The meaning of this interface SHOULD be defined in the specified ERC. - -Examples: - -- `keccak256("ERC20Token")` -- `keccak256("ERC777Token")` -- `keccak256("ERC777TokensSender")` -- `keccak256("ERC777TokensRecipient")` - -#### **[ERC165] Compatible Interfaces** - -> The compatibility with [ERC165], including the [ERC165 Cache], has been designed and developed with [William Entriken]. - -Any interface where the last 28 bytes are zeroes (`0`) SHALL be considered an [ERC165] interface. - -**[ERC165] Lookup** - -Anyone can explicitly check if a contract implements an [ERC165] interface using the registry by calling one of the two functions below: - -``` solidity -function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) -``` - -Checks whether a contract implements an [ERC165] interface or not. - -If the result is not cached a direct lookup on the contract address is performed. - -*NOTE*: If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling `updateERC165Cache` with the contract address. -(See [ERC165 Cache] for more details.) - -> **identifier:** `f712f3e8` -> **parameters** -> `_contract`: Address of the contract to check. -> `_interfaceId`: [ERC165] interface to check. -> **returns:** `true` if `_contract` implements `_interfaceId`, `false` otherwise. - -``` solidity -function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) -``` - -Checks whether a contract implements an [ERC165] interface or not without using nor updating the cache. - -> **identifier:** `b7056765` -> **parameters** -> `_contract`: Address of the contract to check. -> `_interfaceId`: [ERC165] interface to check. -> **returns:** `true` if `_contract` implements `_interfaceId`, false otherwise. - -**[ERC165] Cache** - -Whether a contract implements an [ERC165] interface or not can be cached manually to save gas. - -If a contract dynamically changes its interface and relies on the [ERC165] cache of the [ERC1820] registry, the cache MUST be updated manually---there is no automatic cache invalidation or cache update. -Ideally the contract SHOULD automatically update the cache when changing its interface. -However anyone MAY update the cache on the contract's behalf. - -The cache update MUST be done using the `updateERC165Cache` function: - -``` solidity -function updateERC165Cache(address _contract, bytes4 _interfaceId) external -``` - -> **identifier:** `a41e7d51` -> **parameters** -> `_contract`: Address of the contract for which to update the cache. -> `_interfaceId`: [ERC165] interface for which to update the cache. - -#### **Private User-defined Interfaces** - -This scheme is extensible. -You MAY make up your own interface name and raise awareness to get other people to implement it and then check for those implementations. -Have fun but please, you MUST not conflict with the reserved designations above. - -### Set An Interface For An Address - -For any address to set a contract as the interface implementation, it must call the following function of the [ERC1820] registry: - -``` solidity -function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external -``` - -Sets the contract which implements a specific interface for an address. - -Only the `manager` defined for that address can set it. -(Each address is the manager for itself, see the [manager] section for more details.) - -*NOTE*: If `_addr` and `_implementer` are two different addresses, then: - -- The `_implementer` MUST implement the `ERC1820ImplementerInterface` (detailed below). -- Calling `canImplementInterfaceForAddress` on `_implementer` with the given `_addr` and `_interfaceHash` MUST return the `ERC1820_ACCEPT_MAGIC` value. - -*NOTE*: The `_interfaceHash` MUST NOT be an [ERC165] interface---it MUST NOT end with 28 zeroes (`0`). - -*NOTE*: The `_addr` MAY be `0`, then `msg.sender` is assumed. -This default value simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance. - -> **identifier:** `29965a1d` -> **parameters** -> `_addr`: Address for which to set the interface. (If `_addr` is the zero address then `msg.sender` is assumed.) -> `_interfaceHash`: Keccak256 hash of the name of the interface as a string, for example `web3.utils.keccak256('ERC777TokensRecipient')` for the ERC777TokensRecipient interface. -> `_implementer`: Contract implementing `_interfaceHash` for `_addr`. - -### Get An Implementation Of An Interface For An Address - -Anyone MAY query the [ERC1820] Registry to obtain the address of a contract implementing an interface on behalf of some address using the `getInterfaceImplementer` function. - -``` solidity -function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) -``` - -Query if an address implements an interface and through which contract. - -*NOTE*: If the last 28 bytes of the `_interfaceHash` are zeroes (`0`), then the first 4 bytes are considered an [ERC165] interface and the registry SHALL forward the call to the contract at `_addr` to see if it implements the [ERC165] interface (the first 4 bytes of `_interfaceHash`). -The registry SHALL also cache [ERC165] queries to reduce gas consumption. Anyone MAY call the `erc165UpdateCache` function to update whether a contract implements an interface or not. - -*NOTE*: The `_addr` MAY be `0`, then `msg.sender` is assumed. -This default value is consistent with the behavior of the `setInterfaceImplementer` function and simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance. - -> **identifier:** `aabbb8ca` -> **parameters** -> `_addr`: Address being queried for the implementer of an interface. (If `_addr` is the zero address then `msg.sender` is assumed.) -> `_interfaceHash`: keccak256 hash of the name of the interface as a string. E.g. `web3.utils.keccak256('ERC777Token')` -> **returns:** The address of the contract which implements the interface `_interfaceHash` for `_addr` or `0` if `_addr` did not register an implementer for this interface. - - -### Interface Implementation (`ERC1820ImplementerInterface`) - -``` solidity -interface ERC1820ImplementerInterface { - /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr` or not. - /// @param interfaceHash keccak256 hash of the name of the interface - /// @param addr Address for which the contract will implement the interface - /// @return ERC1820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `addr`. - function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32); -} -``` - -Any contract being registered as the implementation of an interface for a given address MUST implement said interface. -In addition if it implements an interface on behalf of a different address, the contract MUST implement the `ERC1820ImplementerInterface` shown above. - -``` solidity -function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32) -``` - -Indicates whether a contract implements an interface (`interfaceHash`) for a given address (`addr`). - -If a contract implements the interface (`interfaceHash`) for a given address (`addr`), it MUST return `ERC1820_ACCEPT_MAGIC` when called with the `addr` and the `interfaceHash`. -If it does not implement the `interfaceHash` for a given address (`addr`), it MUST NOT return `ERC1820_ACCEPT_MAGIC`. - -> **identifier:** `f0083250` -> **parameters** -> `interfaceHash`: Hash of the interface which is implemented -> `addr`: Address for which the interface is implemented -> **returns:** `ERC1820_ACCEPT_MAGIC` only if the contract implements `ìnterfaceHash` for the address `addr`. - -The special value `ERC1820_ACCEPT_MAGIC` is defined as the `keccka256` hash of the string `"ERC1820_ACCEPT_MAGIC"`. - -``` solidity -bytes32 constant internal ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); -``` - -> The reason to return `ERC1820_ACCEPT_MAGIC` instead of a boolean is to prevent cases where a contract fails to implement the `canImplementInterfaceForAddress` but implements a fallback function which does not throw. In this case, since `canImplementInterfaceForAddress` does not exist, the fallback function is called instead, executed without throwing and returns `1`. Thus making it appear as if `canImplementInterfaceForAddress` returned `true`. - -### Manager - -The manager of an address (regular account or a contract) is the only entity allowed to register implementations of interfaces for the address. -By default, any address is its own manager. - -The manager can transfer its role to another address by calling `setManager` on the registry contract with the address for which to transfer the manager and the address of the new manager. - -**`setManager` Function** - -``` solidity -function setManager(address _addr, address _newManager) external -``` - -Sets `_newManager` as manager for `_addr`. - -The new manager will be able to call `setInterfaceImplementer` for `_addr`. - -If `_newManager` is `0x0`, the manager is reset to `_addr` itself as the manager. - -> **identifier:** `5df8122f` -> **parameters** -> `_addr`: Address for which to set the new manager. -> `_newManager`: The address of the new manager for `_addr`. (Pass `0x0` to reset the manager to `_addr`.) - -**`getManager` Function** - -``` solidity -function getManager(address _addr) public view returns(address) -``` - -Get the manager of an address. - -> **identifier:** `3d584063` -> **parameters** -> `_addr`: Address for which to return the manager. -> **returns:** Address of the manager for a given address. - -## Rationale - -This standards offers a way for any type of address (externally owned and contracts) to implement an interface and potentially delegate the implementation of the interface to a proxy contract. -This delegation to a proxy contract is necessary for externally owned accounts and useful to avoid redeploying existing contracts such as multisigs and DAOs. - -The registry can also act as a [ERC165] cache in order to save gas when looking up if a contract implements a specific [ERC165] interface. -This cache is intentionally kept simple, without automatic cache update or invalidation. -Anyone can easily and safely update the cache for any interface and any contract by calling the `updateERC165Cache` function. - -The registry is deployed using a keyless deployment method relying on a single-use deployment address to ensure no one controls the registry, thereby ensuring trust. - -## Backward Compatibility - -This standard is backward compatible with [ERC165], as both methods MAY be implemented without conflicting with each other. - -## Test Cases - -Please check the [0xjac/ERC1820] repository for the full test suite. - -## Implementation - -The implementation is available in the repo: [0xjac/ERC1820]. - -## Copyright -Copyright and related rights waived via [CC0]. - -[EIP155]: https://eips.ethereum.org/EIPS/eip-155 -[ERC165]: https://eips.ethereum.org/EIPS/eip-165 -[ERC672]: https://github.com/ethereum/EIPs/issues/672 -[ERC820]: https://eips.ethereum.org/EIPS/eip-820 -[ERC1820]: https://eips.ethereum.org/EIPS/eip-1820 -[ERC1820 registry smart contract]: https://github.com/0xjac/ERC1820/blob/master/contracts/ERC1820Registry.sol -[erc1820-annoucement]: https://github.com/ethereum/EIPs/issues/820#issuecomment-464109166 -[erc820-bug]: https://github.com/ethereum/EIPs/issues/820#issuecomment-452465748 -[erc820-fix]: https://github.com/ethereum/EIPs/issues/820#issuecomment-454021564 -[manager]: #manager -[lookup]: #get-an-implementation-of-an-interface-for-an-address -[ERC165 Cache]: #erc165-cache -[Nick's article]: https://medium.com/@weka/how-to-send-ether-to-11-440-people-187e332566b7 -[0xjac/ERC1820]: https://github.com/0xjac/ERC1820 -[CC0]: https://creativecommons.org/publicdomain/zero/1.0/ -[Nick]: https://github.com/Arachnid/ -[William Entriken]: https://github.com/fulldecent -[ENS]: https://ens.domains/ +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1820.md diff --git a/EIPS/eip-1822.md b/EIPS/eip-1822.md index 40daeaf975a4a5..8c50fb12544d8c 100644 --- a/EIPS/eip-1822.md +++ b/EIPS/eip-1822.md @@ -1,349 +1,7 @@ --- eip: 1822 -title: Universal Upgradeable Proxy Standard (UUPS) -author: Gabriel Barros , Patrick Gallagher -discussions-to: https://ethereum-magicians.org/t/eip-1822-universal-upgradeable-proxy-standard-uups -status: Draft -type: Standards Track category: ERC -created: 2019-03-04 +status: Moved --- -## Table of contents - - - -- [Table of contents](#table-of-contents) -- [Simple Summary](#simple-summary) -- [Abstract](#abstract) -- [Motivation](#motivation) -- [Terminology](#terminology) -- [Specification](#specification) - - [Proxy Contract](#proxy-contract) - - [Functions](#functions) - - [`fallback`](#fallback) - - [`constructor`](#constructor) - - [Proxiable Contract](#proxiable-contract) - - [Functions](#functions-1) - - [`proxiable`](#proxiable) - - [`updateCodeAddress`](#updatecodeaddress) -- [Pitfalls when using a proxy](#pitfalls-when-using-a-proxy) - - [Separating Variables from Logic](#separating-variables-from-logic) - - [Restricting dangerous functions](#restricting-dangerous-functions) -- [Examples](#examples) - - [Owned](#owned) - - [ERC-20 Token](#erc-20-token) - - [Proxy Contract](#proxy-contract-1) - - [Token Logic Contract](#token-logic-contract) -- [References](#references) -- [Copyright](#copyright) - - -## Simple Summary - -Standard upgradeable proxy contract. - -## Abstract - -The following describes a standard for proxy contracts which is universally compatible with all contracts, and does not create incompatibility between the proxy and business-logic contracts. This is achieved by utilizing a unique storage position in the proxy contract to store the Logic Contract's address. A compatibility check ensures successful upgrades. Upgrading can be performed unlimited times, or as determined by custom logic. In addition, a method for selecting from multiple constructors is provided, which does not inhibit the ability to verify bytecode. - -## Motivation - -- Improve upon existing proxy implementations to improve developer experience for deploying and maintaining Proxy and Logic Contracts. - -- Standardize and improve the methods for verifying the bytecode used by the Proxy Contract. - -## Terminology - -- `delegatecall()` - Function in contract **A** which allows an external contract **B** (delegating) to modify **A**'s storage (see diagram below, [Solidity docs](https://solidity.readthedocs.io/en/v0.5.3/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries)) -- **Proxy Contract** - The contract **A** which stores data, but uses the logic of external contract **B** by way of `delegatecall()`. -- **Logic Contract** - The contract **B** which contains the logic used by Proxy Contract **A** -- **Proxiable Contract** - Inherited in Logic Contract **B** to provide the upgrade functionality - -

diagram

- -## Specification - -The Proxy Contract proposed here should be deployed _as is_, and used as a drop-in replacement for any existing methods of lifecycle management of contracts. In addition to the Proxy Contract, we propose the Proxiable Contract interface/base which establishes a pattern for the upgrade which does not interfere with existing business rules. The logic for allowing upgrades can be implemented as needed. - -### Proxy Contract - -#### Functions - -##### `fallback` - -The proposed fallback function follows the common pattern seen in other Proxy Contract implementations such as [Zeppelin][1] or [Gnosis][2]. - -However, rather than forcing use of a variable, the address of the Logic Contract is stored at the defined storage position `keccak256("PROXIABLE")`. This eliminates the possibility of collision between variables in the Proxy and Logic Contracts, thus providing "universal" compatibility with any Logic Contract. - -```javascript -function() external payable { - assembly { // solium-disable-line - let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) - calldatacopy(0x0, 0x0, calldatasize) - let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0) - let retSz := returndatasize - returndatacopy(0, 0, retSz) - switch success - case 0 { - revert(0, retSz) - } - default { - return(0, retSz) - } - } -} -``` - -#### `constructor` - -The proposed constructor accepts any number of arguments of any type, and thus is compatible with any Logic Contract constructor function. - -In addition, the arbitrary nature of the Proxy Contract's constructor provides the ability to select from one or more constructor functions available in the Logic Contract source code (e.g., `constructor1`, `constructor2`, ... etc. ). Note that if multiple constructors are included in the Logic Contract, a check should be included to prohibit calling a constructor again post-initialization. - -It's worth noting that the added functionality of supporting multiple constructors does not inhibit verification of the Proxy Contract's bytecode, since the initialization tx call data (input) can be decoded by first using the Proxy Contract ABI, and then using the Logic Contract ABI. - -The contract below shows the proposed implementation of the Proxy Contract. - -```javascript -contract Proxy { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - constructor(bytes memory constructData, address contractLogic) public { - // save the code address - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, contractLogic) - } - (bool success, bytes memory _ ) = contractLogic.delegatecall(constructData); // solium-disable-line - require(success, "Construction failed"); - } - - function() external payable { - assembly { // solium-disable-line - let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) - calldatacopy(0x0, 0x0, calldatasize) - let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0) - let retSz := returndatasize - returndatacopy(0, 0, retSz) - switch success - case 0 { - revert(0, retSz) - } - default { - return(0, retSz) - } - } - } -} -``` - -### Proxiable Contract - -The Proxiable Contract is included in the Logic Contract, and provides the functions needed to perform an upgrade. The compatibility check `proxiable` prevents irreparable updates during an upgrade. - -> :warning: Warning: `updateCodeAddress` and `proxiable` must be present in the Logic Contract. Failure to include these may prevent upgrades, and could allow the Proxy Contract to become entirely unusable. See below [Restricting dangerous functions](#restricting-dangerous-functions) - -#### Functions - -##### `proxiable` - -Compatibility check to ensure the new Logic Contract implements the Universal Upgradeable Proxy Standard. Note that in order to support future implementations, the `bytes32` comparison could be changed e.g., `keccak256("PROXIABLE-ERC1822-v1")`. - -##### `updateCodeAddress` - -Stores the Logic Contract's address at storage `keccak256("PROXIABLE")` in the Proxy Contract. - -The contract below shows the proposed implementation of the Proxiable Contract. - -```javascript -contract Proxiable { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - - function updateCodeAddress(address newAddress) internal { - require( - bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), - "Not compatible" - ); - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) - } - } - function proxiableUUID() public pure returns (bytes32) { - return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; - } -} -``` - -## Pitfalls when using a proxy - -The following common best practices should be employed for all Logic Contracts when using a proxy contract. - -### Separating Variables from Logic - -Careful consideration should be made when designing a new Logic Contract to prevent incompatibility with the existing storage of the Proxy Contract after an upgrade. Specifically, the order in which variables are instantiated in the new contract should not be modified, and any new variables should be added after all existing variables from the previous Logic Contract - -To facilitate this practice, we recommend utilizing a single "base" contract which holds all variables, and which is inherited in subsequent logic contract(s). This practice greatly reduces the chances of accidentally reordering variables or overwriting them in storage. - -### Restricting dangerous functions - -The compatibility check in the Proxiable Contract is a safety mechanism to prevent upgrading to a Logic Contract which does not implement the Universal Upgradeable Proxy Standard. However, as occurred in the parity wallet hack, it is still possible to perform irreparable damage to the Logic Contract itself. - -In order to prevent damage to the Logic Contract, we recommend restricting permissions for any potentially damaging functions to `onlyOwner`, and giving away ownership of the Logic Contract immediately upon deployment to a null address (e.g., address(1)). Potentially damaging functions include native functions such as `SELFDESTRUCT`, as well functions whose code may originate externally such as `CALLCODE`, and `delegatecall()`. In the [ERC-20 Token](#erc-20-token) example below, a `LibraryLock` contract is used to prevent destruction of the logic contract. - -## Examples - -### Owned - -In this example, we show the standard ownership example, and restrict the `updateCodeAddress` to only the owner. - -```javascript -contract Owned is Proxiable { - // ensures no one can manipulate this contract once it is deployed - address public owner = address(1); - - function constructor1() public{ - // ensures this can be called only once per *proxy* contract deployed - require(owner == address(0)); - owner = msg.sender; - } - - function updateCode(address newCode) onlyOwner public { - updateCodeAddress(newCode); - } - - modifier onlyOwner() { - require(msg.sender == owner, "Only owner is allowed to perform this action"); - _; - } -} -``` - -### ERC-20 Token - -#### Proxy Contract - -```javascript -pragma solidity ^0.5.1; - -contract Proxy { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - constructor(bytes memory constructData, address contractLogic) public { - // save the code address - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, contractLogic) - } - (bool success, bytes memory _ ) = contractLogic.delegatecall(constructData); // solium-disable-line - require(success, "Construction failed"); - } - - function() external payable { - assembly { // solium-disable-line - let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) - calldatacopy(0x0, 0x0, calldatasize) - let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0) - let retSz := returndatasize - returndatacopy(0, 0, retSz) - switch success - case 0 { - revert(0, retSz) - } - default { - return(0, retSz) - } - } - } -} -``` - -#### Token Logic Contract - -``` javascript - -contract Proxiable { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - - function updateCodeAddress(address newAddress) internal { - require( - bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), - "Not compatible" - ); - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) - } - } - function proxiableUUID() public pure returns (bytes32) { - return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; - } -} - - -contract Owned { - - address owner; - - function setOwner(address _owner) internal { - owner = _owner; - } - modifier onlyOwner() { - require(msg.sender == owner, "Only owner is allowed to perform this action"); - _; - } -} - -contract LibraryLockDataLayout { - bool public initialized = false; -} - -contract LibraryLock is LibraryLockDataLayout { - // Ensures no one can manipulate the Logic Contract once it is deployed. - // PARITY WALLET HACK PREVENTION - - modifier delegatedOnly() { - require(initialized == true, "The library is locked. No direct 'call' is allowed"); - _; - } - function initialize() internal { - initialized = true; - } -} - -contact ERC20DataLayout is LibraryLockDataLayout { - uint256 public totalSupply; - mapping(address=>uint256) public tokens; -} - -contract ERC20 { - // ... - function transfer(address to, uint256 amount) public { - require(tokens[msg.sender] >= amount, "Not enough funds for transfer"); - tokens[to] += amount; - tokens[msg.sender] -= amount; - } -} - -contract MyToken is ERC20DataLayout, ERC20, Owned, Proxiable, LibraryLock { - - function constructor1(uint256 _initialSupply) public { - totalSupply = _initialSupply; - tokens[msg.sender] = _initialSupply; - initialize(); - setOwner(msg.sender); - } - function updateCode(address newCode) public onlyOwner delegatedOnly { - updateCodeAddress(newCode); - } - function transfer(address to, uint256 amount) public delegatedOnly { - ERC20.transfer(to, amount); - } -} -``` - -## References - -- ["Escape-hatch" proxy Medium Post](https://medium.com/terminaldotco/escape-hatch-proxy-efb681de108d) - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[1]: https://github.com/maraoz/solidity-proxy/blob/master/contracts/Dispatcher.sol -[2]: https://blog.gnosis.pm/solidity-delegateproxy-contracts-e09957d0f201 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1822.md diff --git a/EIPS/eip-1829.md b/EIPS/eip-1829.md index 0a075ea3cc9b27..cef276e73b5d69 100644 --- a/EIPS/eip-1829.md +++ b/EIPS/eip-1829.md @@ -3,7 +3,7 @@ eip: 1829 title: Precompile for Elliptic Curve Linear Combinations author: Remco Bloemen discussions-to: https://ethereum-magicians.org/t/ewasm-precompile-for-general-elliptic-curve-math/2581 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-03-06 @@ -12,22 +12,18 @@ created: 2019-03-06 # Precompile for Elliptic Curve Linear Combinations ## Simple Summary - -Currently the EVM only supports *secp261k1* in a limited way through `ecrecover` and *altbn128* through two pre-compiles. There are draft proposals to add more curves. There are many more elliptic curve that have useful application for integration with existing systems or newly developed curves for zero-knowledge proofs. +Currently the EVM only supports *secp256k1* in a limited way through `ecrecover` and *altbn128* through two pre-compiles. There are draft proposals to add more curves. There are many more elliptic curves that have useful applications for integration with existing systems or newly developed curves for zero-knowledge proofs. This EIP adds a precompile that allows whole classes of curves to be used. ## Abstract - A precompile that takes a curve and computes a linear combination of curve points. ## Motivation - ## Specification - Given integers `m, α` and `β`, scalars `s_i`, and curve points `A_i` construct the elliptic curve @@ -77,7 +73,7 @@ Conversion from affine coordinates to compressed coordinates is trivial: `y' = 0 **Addition.** Set `s₀ = s₁ = 1`, the output will be `A₀ + A₁`. -**Doubling.** Set `s₀ = 2`. The output will be `2 ⋅ A₀`. (Note: under current gas model this may be more costly than self-addition!) +**Doubling.** Set `s₀ = 2`. The output will be `2 ⋅ A₀`. (Note: under the current gas model, this may be more costly than self-addition!) **Scalar multiplication.** Set only `s₀` and `A₀`. @@ -94,7 +90,6 @@ Conversion from affine coordinates to compressed coordinates is trivial: `y' = 0 * (Please add if you spot more) ## Rationale - **Generic Field and Curve.** Many important optimizations are independent of the field and curve used. Some missed specific optimizations are: @@ -104,17 +99,17 @@ Conversion from affine coordinates to compressed coordinates is trivial: `y' = 0 * Special point addition/doubling [formulas][formulas] for `α = -3`, `α = -1`, `α = 0`, `β = 0`. -[formulas]: http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html +[formulas]: https://www.hyperelliptic.org/EFD/g1p/auto-shortw.html -TODO: The special cases for `α` and `β` might be worth implementing and offered a gas discount. +TODO: The special cases for `α` and `β` might be worth implementing and offering a gas discount. **Compressed Coordinates.** Compressed coordinates allow contract to work with only `x` coordinates and sign bytes. It also prevents errors around points not being on-curve. Conversion to compressed coordinates is trivial. **Linear Combination.** We could instead have a simple multiply `C = r ⋅ A`. In this case we would need a separate pre-compile for addition. In addition, a linear combination allows for optimizations that like Shamir's trick that are not available in a single scalar multiplication. ECDSA requires `s₀ ⋅ A₀ + s₁ ⋅ A₁` and would benefit from this. -The BN254 (aka alt_bn8) multiplication operation introduced by the [EIP-196][eip196] precompile only handles a single scalar multiplication. The missed performance is such that for two or more points it is cheaper to use EVM, as practically demonstrated by [Weierstrudel][ws]. +The BN254 (aka alt_bn8) multiplication operation introduced by the [EIP-196][EIP-196] precompile only handles a single scalar multiplication. The missed performance is such that for two or more points it is cheaper to use EVM, as practically demonstrated by [Weierstrudel][ws]. -[eip196]: https://eips.ethereum.org/EIPS/eip-196 +[EIP-196]: ./eip-196.md [ws]: https://medium.com/aztec-protocol/huffing-for-crypto-with-weierstrudel-9c9568c06901 **Variable Time Math.** When called during a transaction, there is no assumption of privacy and no mitigations for side-channel attacks are necessary. @@ -132,13 +127,10 @@ TODO: Consider a double-word version. 512 bits would cover all known curves exce [cov]: https://safecurves.cr.yp.to/equation.html ## Backwards Compatibility - ## Test Cases - ## Implementation - There will be a reference implementation in Rust based on the existing libraries (in particular those by ZCash and The Matter Inc.). @@ -148,11 +140,11 @@ The reference implementation will be production grade and compile to a native li This EIP overlaps in scope with -* [EIP-196](https://eips.ethereum.org/EIPS/eip-196): ecadd, ecmul for altbn128 +* [EIP-196](./eip-196.md): ecadd, ecmul for altbn128 * [EIP issue 603](https://github.com/ethereum/EIPs/issues/603): ecadd, ecmul for SECP256k1. -* [EIP 665](https://eips.ethereum.org/EIPS/eip-665): ECDSA verify for ED25519. -* [EIP 1108](https://eips.ethereum.org/EIPS/eip-1108): Optimize ecadd and ecmul for altbn128. +* [EIP-665](./eip-665.md): ECDSA verify for ED25519. +* [EIP-1108](./eip-1108.md): Optimize ecadd and ecmul for altbn128. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1844.md b/EIPS/eip-1844.md index 5bb1c2d73ade41..2025c3e05acae0 100644 --- a/EIPS/eip-1844.md +++ b/EIPS/eip-1844.md @@ -1,64 +1,7 @@ --- eip: 1844 -title: ENS Interface Discovery -author: Nick Johnson (@arachnid) -discussions-to: https://ethereum-magicians.org/t/ens-interface-discovery/2924 -status: Draft -type: Standards Track category: ERC -created: 2019-03-15 -requires: 137, 165 +status: Moved --- -## Simple Summary -Defines a method of associating contract interfaces with ENS names and addresses, and of discovering those interfaces. - -## Abstract -This EIP specifies a method for exposing interfaces associated with an ENS name or an address (typically a contract address) and allowing applications to discover those interfaces and interact with them. Interfaces can be implemented either by the target contract (if any) or by any other contract. - -## Motivation -EIP 165 supports interface discovery - determining if the contract at a given address supports a requested interface. However, in many cases it's useful to be able to discover functionality associated with a name or an address that is implemented by other contracts. - -For example, a token contract may not itself provide any kind of 'atomic swap' functionality, but there may be associated contracts that do. With ENS interface discovery, the token contract can expose this metadata, informing applications where they can find that functionality. - -## Specification -A new profile for ENS resolvers is defined, consisting of the following method: - -``` -function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address); -``` - -The EIP-165 interface ID of this interface is `0xb8f2bbb4`. - -Given an ENS name hash `node` and an EIP-165 `interfaceID`, this function returns the address of an appropriate implementer of that interface. If there is no interface matching that interface ID for that node, 0 is returned. - -The address returned by `interfaceImplementer` MUST refer to a smart contract. - -The smart contract at the returned address SHOULD implement EIP-165. - -Resolvers implementing this interface MAY utilise a fallback strategy: If no matching interface was explicitly provided by the user, query the contract returned by `addr()`, returning its address if the requested interface is supported by that contract, and 0 otherwise. If they do this, they MUST ensure they return 0, rather than reverting, if the target contract reverts. - -This field may be used with both forward resolution and reverse resolution. - -## Rationale - -A naive approach to this problem would involve adding this method directly to the target contract. However, doing this has several shortcomings: - - 1. Each contract must maintain its own list of interface implementations. - 2. Modifying this list requires access controls, which the contract may not have previously required. - 3. Support for this must be designed in when the contract is written, and cannot be retrofitted afterwards. - 4. Only one canonical list of interfaces can be supported. - -Using ENS resolvers instead mitigates these shortcomings, making it possible for anyone to associate interfaces with a name, even for contracts not previously built with this in mind. - -## Backwards Compatibility -There are no backwards compatibility issues. - -## Test Cases -TBD - -## Implementation -The PublicResolver in the [ensdomains/resolvers](https://github.com/ensdomains/resolvers/) repository implements this interface. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1844.md diff --git a/EIPS/eip-1872.md b/EIPS/eip-1872.md index 8ef9e265f4ab6f..7fcab2afc6d2c0 100644 --- a/EIPS/eip-1872.md +++ b/EIPS/eip-1872.md @@ -2,8 +2,8 @@ eip: 1872 title: Ethereum Network Upgrade Windows author: Danno Ferrin (@shemnon) -discussions-to: https://ethereum-magicians.org/t/eip-ethereum-network-upgrade-windows/ -status: Draft +discussions-to: https://ethereum-magicians.org/t/eip-1872-ethereum-network-upgrade-windows/2993 +status: Stagnant type: Meta created: 2018-03-25 --- @@ -213,5 +213,4 @@ follows: ## Copyright -Copyright and related rights waived via -[CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1884.md b/EIPS/eip-1884.md index 19faa3578d7cda..e085625dc199b9 100644 --- a/EIPS/eip-1884.md +++ b/EIPS/eip-1884.md @@ -1,13 +1,13 @@ --- eip: 1884 -title: Repricing for trie-size-dependent opcodes +title: Repricing for trie-size-dependent opcodes author: Martin Holst Swende (@holiman) type: Standards Track category: Core discussions-to: https://ethereum-magicians.org/t/opcode-repricing/3024 -status: Draft +status: Final created: 2019-03-28 -requires: 150 +requires: 150, 1052 --- @@ -36,7 +36,8 @@ At block `N`, - The `SLOAD` (`0x54`) operation changes from `200` to `800` gas, - The `BALANCE` (`0x31`) operation changes from `400` to `700` gas, -- A new opcode, `SELFBALANCE` is introduced at `0x46`. +- The `EXTCODEHASH` (`0x3F`) operation changes from `400` to `700` gas, +- A new opcode, `SELFBALANCE` is introduced at `0x47`. - `SELFBALANCE` pops `0` arguments off the stack, - `SELFBALANCE` pushes the `balance` of the current address to the stack, - `SELFBALANCE` is priced as `GasFastStep`, at `5` gas. @@ -81,7 +82,7 @@ state clearing efforts are implemented before that happens. It is comparable to `EXTCODESIZE` and `EXTCODEHASH`, which are priced at `700` already. It has a built-in high variance, since it is often used for checking the balance of `this`, -which is a inherently cheap operation, however, it can be used to lookup the balance of arbitrary account which often require trie (disk) access. +which is an inherently cheap operation, however, it can be used to lookup the balance of arbitrary account which often require trie (disk) access. In hindsight, it might have been a better choice to have two opcodes: `EXTBALANCE(address)` and `SELFBALANCE`, and have two different prices. @@ -91,6 +92,15 @@ opcodes: `EXTBALANCE(address)` and `SELFBALANCE`, and have two different prices. * As for why it is priced at `5` (`GasFastStep`) instead of `2` (`GasQuickStep`), like other similar operations: the EVM execution engine still needs a lookup into the (cached) trie, and `balance`, unlike `gasPrice` or `timeStamp`, is not constant during the execution, so it has a bit more inherent overhead. +### `EXTCODEHASH` + +`EXTCODEHASH` was introduced in Constantinople, with [EIP-1052](./eip-1052.md). It was priced at `400` with the reasoning: + +> The gas cost is the same as the gas cost for the `BALANCE` opcode because the execution of the `EXTCODEHASH` requires the same account lookup as in `BALANCE`. + +Ergo, if we increase `BALANCE`, we should also increase `EXTCODEHASH` + + ## Backwards Compatibility The changes require a hardfork. The changes have the following consequences: @@ -98,13 +108,26 @@ The changes require a hardfork. The changes have the following consequences: - Certain calls will become more expensive. - Default-functions which access the storage and may in some cases require more than`2300` gas (the minimum gas that is always available in calls). - Contracts that assume a certain fixed gas cost for calls (or internal sections) may cease to function. + - A fixed gas cost is specified in [ERC-165](./eip-165.md) and implementations of this interface do use the affected opcodes. + - The ERC-165 method `supportsInterface` must return a `bool` and use at most `30,000` gas. + - The two example implementations from the EIP were, at the time of writing + 1. `586` gas for any input, and + 2. `236` gas, but increases linearly with a higher number of supported interfaces + - It is unlikely that any ERC-165 `supportsInterface` implementation will go above `30.000` gas. That would require that the second variant is used, and thirty:ish interfaces are supported. - However, these operations have already been repriced earlier, so there is a historical precedent that 'the gascost for these operations may change', which should have prevented such fixed-gas-cost assumptions from being implemented. I expect that certain patterns will be less used, for example the use of multiple modifiers which `SLOAD`s the same opcode will be merged into one. It may also lead to less `log` operations containing `SLOAD`ed values that are not strictly necessary. ## Test Cases -No test cases are implemented as of yet. +Testcases that should be implemented: +- Test that `selfbalance == balance(address)`, +- Test that `balance(this)` costs as before, +- Test that `selfbalance` does not pop from stack +- Gascost verification of `SLOAD`, `EXTCODEHASH` and `SELFBALANCE` +- Verify that `SELFBALANCE` is invalid before Istanbul + +Some testcases have been implemented as statetests at https://github.com/holiman/IstanbulTests/tree/master/GeneralStateTests ## Implementation @@ -129,8 +152,9 @@ func opSelfBalance(pc *uint64, interpreter *EVMInterpreter, contract *Contract, - See backwards compatibility section. - There are no special edgecases regarding `SELFBALANCE`, if we define it as `BALANCE` with `address` instead of popping an address from the stack -- since `BALANCE` is already well-defined. - It should be investigated if Solidity contains any hardcoded expectations on the gas cost of these operations. +- In many cases, a recipient of `ether` from a `CALL` will want to issue a `LOG`. The `LOG` operation costs `375` plus `375` per topic. If the `LOG` also wants to do an `SLOAD`, this change may make some such transfers fail. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). -[eip-150]: https://eips.ethereum.org/EIPS/eip-150 +[eip-150]: ./eip-150.md diff --git a/EIPS/eip-1890.md b/EIPS/eip-1890.md index d4a6eb8827c96c..8c3a38b76f303e 100644 --- a/EIPS/eip-1890.md +++ b/EIPS/eip-1890.md @@ -3,7 +3,7 @@ eip: 1890 title: Commitment to Sustainable Ecosystem Funding author: Gregory Markou , Kevin Owocki , Lane Rettig discussions-to: https://t.me/joinchat/DwEd_xahL5hHvzNYH2RnQA -status: Draft +status: Withdrawn type: Standards Track category: Core created: 2019-03-31 @@ -50,4 +50,4 @@ This EIP makes no changes to existing state transitions. Existing consensus test Reference implementations are included for the Trinity, go-ethereum, and parity clients. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1895.md b/EIPS/eip-1895.md index 5c097b75c41159..5c520839e0774b 100644 --- a/EIPS/eip-1895.md +++ b/EIPS/eip-1895.md @@ -3,10 +3,10 @@ eip: 1895 title: Support for an Elliptic Curve Cycle author: Alexandre Belling discussions-to: https://ethresear.ch/t/reducing-the-verification-cost-of-a-snark-through-hierarchical-aggregation/5128 -status: Draft +status: Stagnant type: Standards Track category: Core -created: 2018-31-03 +created: 2018-03-31 --- ## Simple Summary @@ -144,8 +144,6 @@ Proper benchmarks will be done in order to make this choice and to price the ope ## Test Cases - - ## References * *Eli-Ben-Sasson, Alessandro Chiesa, Eran Tromer, Madars Virza, [BCTV14], April 28, 2015, Scalable Zero Knowledge via Cycles of Elliptic Curves : https://eprint.iacr.org/2014/595.pdf* @@ -153,12 +151,10 @@ Proper benchmarks will be done in order to make this choice and to price the ope ## Implementation - - * [go-boojum](https://github.com/AlexandreBelling/go-boojum) : A PoC demo of an application of recursive SNARKs * [libff](https://github.com/scipr-lab/libff) : a C++ library for finite fields and elliptic curves * [coda](https://github.com/CodaProtocol/coda) : a new cryptocurrency protocol with a lightweight, constant sized blockchain. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1898.md b/EIPS/eip-1898.md index 4968105388e80a..4ab7007867da48 100644 --- a/EIPS/eip-1898.md +++ b/EIPS/eip-1898.md @@ -1,25 +1,26 @@ --- eip: 1898 -title: Add `blockHash` to JSON-RPC methods which accept a default block parameter. +title: Add `blockHash` to defaultBlock methods +description: Add `blockHash` option to JSON-RPC methods that currently support defaultBlock parameter. author: Charles Cooper (@charles-cooper) +discussions-to: https://ethereum-magicians.org/t/eip-1898-add-blockhash-option-to-json-rpc-methods-that-currently-support-defaultblock-parameter/11757 +status: Final type: Standards Track category: Interface -status: Draft created: 2019-04-01 requires: 234 --- -## Simple Summary +## Abstract For JSON-RPC methods which currently accept a default block parameter, additionally allow the parameter to be a block hash. -## Abstract - -This EIP can be considered a generalization of [EIP-234](https://github.com/ethereum/EIPs/blob/d053eb66921c5915f3e16d72c7566289e2d7c151/EIPS/eip-234.md). It would enable clients to unambiguously specify the block they want to query for certain JSON-RPC methods, even if the block is not in the canonical chain. This allows clients to maintain a coherent picture of blockchain state that they are interested in, even in the presence of reorgs, without requiring that the node maintain a persistent connection with the client or store any client-specific state. +This EIP can be considered a generalization of [EIP-234](./eip-234.md). It would enable clients to unambiguously specify the block they want to query for certain JSON-RPC methods, even if the block is not in the canonical chain. This allows clients to maintain a coherent picture of blockchain state that they are interested in, even in the presence of reorgs, without requiring that the node maintain a persistent connection with the client or store any client-specific state. ## Specification The following JSON-RPC methods are affected: + - `eth_getBalance` - `eth_getStorageAt` - `eth_getTransactionCount` @@ -27,13 +28,17 @@ The following JSON-RPC methods are affected: - `eth_call` - `eth_getProof` -The following options, quoted from the [JSON-RPC spec](https://github.com/ethereum/wiki/wiki/JSON-RPC#the-default-block-parameter), are currently possible for the defaultBlock parameter: +The following options, quoted from the Ethereum JSON-RPC spec, are currently possible for the defaultBlock parameter: + > - HEX String - an integer block number > - String "earliest" for the earliest/genesis block -> - String "latest" - for the latest mined block +> - String "latest" - for the latest canonical block > - String "pending" - for the pending state/transactions +> - String "safe" - for the most recent safe block +> - String "finalized" - for the most recent finalized block Since there is no way to clearly distinguish between a DATA parameter and a QUANTITY parameter, this EIP proposes a new scheme for the block parameter. The following option is additionally allowed: + - OBJECT - `blockNumber`: QUANTITY - a block number - `blockHash`: DATA - a block hash @@ -43,6 +48,7 @@ If the block is not found, the callee SHOULD raise a JSON-RPC error (the recomme If the tag is `blockHash`, an additional boolean field may be supplied to the block parameter, `requireCanonical`, which defaults to `false` and defines whether the block must be a canonical block according to the callee. If `requireCanonical` is `false`, the callee should raise a JSON-RPC error only if the block is not found (as described above). If `requireCanonical` is `true`, the callee SHOULD additionally raise a JSON-RPC error if the block is not in the canonical chain (the recommended error code is `-32000: Invalid input` and in any case should be different than the error code for the block not found case so that the caller can distinguish the cases). The block-not-found check SHOULD take precedence over the block-is-canonical check, so that if the block is not found the callee raises block-not-found rather than block-not-canonical. To maintain backwards compatibility, the block number MAY be specified either as a hex string or using the new block parameter scheme. In other words, the following are equivalent for the default block parameter: + - `"earliest"` - `"0x0"` - `{ "blockNumber": "0x0" }` @@ -55,6 +61,7 @@ To maintain backwards compatibility, the block number MAY be specified either as Currently, the state-querying JSON-RPC methods specified above have no option to unambiguously specify which block to query the state for. This can cause issues for applications which need to make multiple calls to the RPC. For instance, a wallet which just executed a transfer may want to display the balances of both the sender and recipient. If there is a re-org in between when the balance of the sender is queried via `eth_getBalance` and when the balance of the recipient is queried, the balances may not reconcile. As a slightly more complicated example, the UI for a decentralized exchange (which hosts orders on-chain) may walk a list of orders by calling `eth_call` for each of them to get the order data. Another type of use case is where an application needs to make a decision based on multiple pieces of state, e.g. a payout predicated on simultaneous ownership of two NFTs. In order to ensure that the state is coherent (i.e., `eth_call` was called with exactly the same block for every call), the application may currently use one of several strategies: + - Decide on a block number to use (e.g., the latest block number known to the application). After each `eth_call` using that block number, call `eth_getBlockByNumber`, also with that block number. If the block hash does not match the known hash for that block number, rollback the current activity and retry from the beginning. This adds `O(n)` invocations as baseline overhead and another `O(n)` invocations for every retry needed. Moreover, there is no way to detect the (unlikely but possible) case that the relevant block was reorged out before `eth_call`, and then reorged back in before `eth_getBlockByNumber`. - Rely on logs, which *can* be queried unambiguously thanks to the `blockHash` parameter. However, this requires semantic support from the smart contract; if the smart contract does not emit appropriate events, the client will not be able to reconstruct the specific state it is interested in. - Rely on non-standard extensions like `parity_subscribe`. This requires a persistent connection between the client and node (via IPC or websockets), increases coupling between the client and the node, and cannot handle use cases where there are dependencies between invocations of `eth_call`, for example, walking a linked list. @@ -78,10 +85,11 @@ Backwards compatible. - `eth_getStorageAt [ "0x
", { "blockHash": "0x", "requireCanonical": false }` -> return storage at given address in specified block - `eth_getStorageAt [ "0x
", { "blockHash": "0x", "requireCanonical": true }` -> raise block-not-canonical error -## Implementation +## Security Considerations + +None -None yet. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-190.md b/EIPS/eip-190.md index a56bc332cf5877..1afed0d966ea7c 100644 --- a/EIPS/eip-190.md +++ b/EIPS/eip-190.md @@ -1,96 +1,7 @@ --- eip: 190 -title: Ethereum Smart Contract Packaging Standard -author: Piper Merriam (@pipermerriam), Tim Coulter (@tcoulter), Denis Erfurt (@mhhf), RJ Catalano (@VoR0220), Iuri Matias (@iurimatias) -status: Final -type: Standards Track category: ERC -created: 2017-01-10 +status: Moved --- -# Abstract - -This ERC proposes a specification for Ethereum smart contract packages. - -The specification was collaboratively developed by the following Ethereum development framework maintainers. - -* Tim Coulter (Truffle) -* Denis Erfurt (Dapple) -* Piper Merriam (Populus) -* RJ Catalano (Eris PM) -* Iuri Matias (Embark) - -# Motivation - -Packaging is a core piece of modern software development which is missing from the Ethereum ecosystem. The lack of packaging limits the ability for developers to reuse code which negatively affects productivity and security. - -A key example of this is the ERC20 standard. There are a few well audited reusable token contracts available but most developers end up writing their own because of the difficulty in finding and reusing existing code. - -A packaging standard should have the following positive effects on the ecosystem: - -* Greater overall productivity caused by the ability to reuse existing code. -* Increased security caused by the ability to reuse existing well audited implementations of common patterns (ERC20, crowdfunding, etc). - -Smart contract packaging should also have a direct positive effect on the end user. Wallet software will be able to consume a released package and generate an interface for interacting with any deployed contracts included within that package. With the advent of [ENS](https://github.com/ethereum/EIPs/issues/137) all of the pieces will be in place for a wallet to take a human readable name and present the user with an interface for interacting with the underlying application. - - -# Specification - -The full specification for this standard is maintained separately in the repository [epm/epm-spec](https://github.com/ethpm/epm-spec). - -This EIP refers to the `1.0.0` version of the specification: [https://github.com/ethpm/epm-spec/tree/v1.0.0](https://github.com/ethpm/epm-spec/tree/v1.0.0) - -The specification contains details for a single document referred to as a *"Release Lockfile"*. - -* Release Lockfile Specification: [https://github.com/ethpm/epm-spec/blob/v1.0.0/release-lockfile.spec.md](https://github.com/ethpm/epm-spec/blob/v1.0.0/release-lockfile.spec.md). -* JSON Schema for Release Lockfile: [https://github.com/ethpm/epm-spec/blob/v1.0.0/spec/release-lockfile.spec.json](https://github.com/ethpm/epm-spec/blob/v1.0.0/spec/release-lockfile.spec.json) - -> These documents have not been inlined into this ERC to ensure that there is a single source of truth for the specification. - - -# Use Cases - -This specification covers the following types of smart contract packages. - -1. Packages with contracts intended to be used as base contract such as the common `owned` pattern. -2. Packages with contracts that are ready to use as-is such as an ERC20 token contract. -3. Packages with deployed contracts such as libraries or services. - -Full explanations and examples of these use cases can be found in the [`README.md`](https://github.com/ethpm/epm-spec/blob/v1.0.0/README.md#use-cases) from the `epm/epm-spec` repository. - - -# Package Managers - -The *Release Lockfile* is intended for consumption by package management software. Specific care was made to ensure that all of the following functionality can be implemented by package managers. - - -## Deterministic builds - -Ensures that a package will always resolve to the same set of dependencies and source files. Both source files and dependencies are content addressed to ensure that the referenced resources cannot change. - - -## Bytecode verification - -Contains the appropriate information for a package manager to inspect a deployed contract and verify that its bytecode matches the bytecode that results from compilation and linking of the package source code. - - -## Multi-chain deploys - -Supports deployments across multiple chains, allowing a package to define addresses on both the public mainnet and testnet. - - -## Trusted packages - -Allows for packages which exclude source code or other elements which would be needed for verification of the contract bytecode. This allows for minimalistic packages to be created for special situations where the package manager will not be performing verification. - - -# Framework support and integration - -Support for ERC190 is either implemented or in progress for the following: - -* [Truffle](https://truffleframework.com/) -* [Populus](https://populus.readthedocs.io/en/latest/) -* [Dapple](https://dapple.readthedocs.io/en/master/) -* [Eris PM](https://github.com/eris-ltd/eris-cli) -* [Embark](https://github.com/iurimatias/embark-framework) -* [Browser Solidity](https://github.com/ethereum/remix-ide/issues/386) +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-190.md diff --git a/EIPS/eip-1900.md b/EIPS/eip-1900.md new file mode 100644 index 00000000000000..0cc739bb3846ef --- /dev/null +++ b/EIPS/eip-1900.md @@ -0,0 +1,7 @@ +--- +eip: 1900 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1900.md diff --git a/EIPS/eip-1901.md b/EIPS/eip-1901.md new file mode 100644 index 00000000000000..7585b479f73a02 --- /dev/null +++ b/EIPS/eip-1901.md @@ -0,0 +1,105 @@ +--- +eip: 1901 +title: Add OpenRPC Service Discovery To JSON-RPC Services +author: Shane Jonas (@shanejonas), Zachary Belford (@belfordz) +discussions-to: https://github.com/ethereum/EIPs/issues/1902 +status: Stagnant +type: Standards Track +category: Interface +created: 2019-02-25 +--- + +## Abstract +### What is this? + +This is a proposal to add [OpenRPC](https://github.com/open-rpc/spec) support to existing and future JSON-RPC services by adding the method [`rpc.discover`](https://github.com/open-rpc/spec#service-discovery-method) to the projects [JSON-RPC](https://www.jsonrpc.org/specification) APIs, enabling automation and tooling. + +The OpenRPC Document and generated Documentation that specifies all the methods an EVM-based blockchain should implement can be found [here](https://github.com/etclabscore/ethereum-json-rpc-specification). + +This was first proposed [here as an ECIP](https://github.com/etclabscore/ECIPs/blob/master/ECIPs/ecip-1053.md), but the benefits of this kind of tooling is apparent across Bitcoin, Ethereum Classic, Ethereum and other JSON-RPC accessible blockchains. + +## Motivation + +Although [EIP-1474](./eip-1474.md) outlines a JSON-RPC specification. Ethereum still lacks a machine-readable JSON-RPC Specification that can be used as the industry standard for tooling. This proposal attempts to standardize such a specification in a way that is versionable, and both human and machine readable. + +Ethereum clients can expose RPC endpoints with different method signatures and cause compatibility issues between clients. + +Developers need a reliable developer experience, and an industry standard way to describe Ethereum JSON-RPC 2.0 APIs. + +## Specification + +### What is OpenRPC? + +The [OpenRPC](https://github.com/open-rpc/spec) Specification defines a standard, programming language-agnostic interface description for [JSON-RPC 2.0](https://www.jsonrpc.org/specification) APIs, which allows both humans and computers to discover and understand the capabilities of a service without requiring access to source code, additional documentation, or inspection of network traffic. When properly defined via OpenRPC, a consumer can understand and interact with the remote service with a minimal amount of implementation logic, and share these logic patterns across use cases. Similar to what interface descriptions have done for lower-level programming, the OpenRPC Specification removes guesswork in calling a service. + +##### Structure + +This is the structure of an OpenRPC Document: + +![openrpc-spec-structure](../assets/eip-1901/OpenRPC_structure.png) + +JSON-RPC APIs can support the OpenRPC specification by implementing a service discovery method that will return the [OpenRPC document](https://github.com/open-rpc/spec#openrpc-document) for the JSON-RPC API. The method MUST be named `rpc.discover`. The `rpc.` prefix is a reserved method prefix for [JSON-RPC 2.0 Specification](https://www.jsonrpc.org/specification) system extensions. + +### Use Case + +This is the vision for the use case of OpenRPC and how it would relate to a client implementation like multi-geth: + +![MultGethRpc-usecase](../assets/eip-1901/multi-geth-use-case.png) + +## Rationale + +### Why would we do this? +Services need to figure out how to talk to each other. If we really want to build the next generation of automation, then having up to date libraries, documented APIs, and modern tools are going to provide easy discovery, on-boarding, and enable end user and developer interaction. + +Use cases for machine-readable [JSON-RPC 2.0](https://www.jsonrpc.org/specification) API definition documents include, but are not limited to: + +- A common vocabulary and document will keep developers, testers, architects, and technical writers all in sync. +- Server stubs/skeletons generated in many languages +- Clients generated in many languages +- Mock Server generated in many languages +- Tests generated in many languages +- Documentation Generation + +### Alternative + +[OpenRPC](https://github.com/open-rpc/spec) documents just describe [JSON-RPC](https://www.jsonrpc.org/specification) APIs services, and are represented in JSON format. These documents may be produced and served statically OR generated dynamically from an application and returned via the [`rpc.discover`](https://github.com/open-rpc/spec#service-discovery-method) method. This gives projects and communities the opportunity to adopt tools, documentation, and clients outlined in the [etclabscore/ethereum-json-rpc-specification](./eip-1474.md) before the [`rpc.discover`](https://github.com/open-rpc/spec#service-discovery-method) method is implemented for a particular client. + +## Implementation + +- [Multi-Geth OpenRPC Discovery](https://github.com/multi-geth/multi-geth#openrpc-discovery) + +### Tooling + +#### Interactive Documentation Playground + +You can view the interactive documentation [here](https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/etclabscore/ethereum-json-rpc-specification/master/openrpc.json). + +**OR** + +Using `rpc.discover` via multi-geth, the playground can discover and display the documentation for the Ethereum JSON-RPC API: + +![eth-playground-openrpc](../assets/eip-1901/eth-playground-openrpc.gif) + + +#### Generated Client + +The [clients](https://github.com/etclabscore/ethereum-json-rpc-specification#clients) are generated from the OpenRPC Document openrpc.json outlined in this EIP, and can be used as an alternative to web3.js or ethers.js but for various languages: + +![eth-generated-client-openrpc](../assets/eip-1901/eth-generated-client-openrpc.gif) + +#### Mock Server + +The [OpenRPC mock server](https://github.com/open-rpc/mock-server) provides a mock server for any given OpenRPC Document which allows testing without booting up a real network. + +![inspector-mock-server-openrpc](../assets/eip-1901/inspector-mock-server-openrpc.png) + +## Resources + +- [Multi-Geth OpenRPC Discovery](https://github.com/multi-geth/multi-geth#openrpc-discovery) +- [EDCON 2019 talk on OpenRPC and The Future of JSON-RPC Tooling](https://www.youtube.com/watch?v=UgSPMZ9FQ4Q) +- [etclabscore/ethereum-json-rpc-specification](https://github.com/etclabscore/ethereum-json-rpc-specification) +- [open-rpc.org](https://open-rpc.org) + +## Copyright + + Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file diff --git a/EIPS/eip-191.md b/EIPS/eip-191.md index f3b79ae5ba8bb3..69a96210719f60 100644 --- a/EIPS/eip-191.md +++ b/EIPS/eip-191.md @@ -1,82 +1,7 @@ --- eip: 191 -title: Signed Data Standard -author: Martin Holst Swende (@holiman), Nick Johnson -status: Draft -type: Standards Track category: ERC -created: 2016-01-20 +status: Moved --- -# Abstract - -This ERC proposes a specification about how to handle signed data in Ethereum contracts. - -# Motivation - -Several multisignature wallet implementations have been created which accepts `presigned` transactions. A `presigned` transaction is a chunk of binary `signed_data`, along with signature (`r`, `s` and `v`). The interpretation of the `signed_data` has not been specified, leading to several problems: - -* Standard Ethereum transactions can be submitted as `signed_data`. An Ethereum transaction can be unpacked, into the following components: `RLP` (hereby called `RLPdata`), `r`, `s` and `v`. If there are no syntactical constraints on `signed_data`, this means that `RLPdata` can be used as a syntactically valid `presigned` transaction. -* Multisignature wallets have also had the problem that a `presigned` transaction has not been tied to a particular `validator`, i.e a specific wallet. Example: - 1. Users `A`, `B` and `C` have the `2/3`-wallet `X` - 2. Users `A`, `B` and `D` have the `2/3`-wallet `Y` - 3. User `A` and `B` submites `presigned` transaction to `X`. - 4. Attacker can now reuse their presigned transactions to `X`, and submit to `Y`. - -## Specification - -We propose the following format for `signed_data` - -``` -0x19 <1 byte version> . -``` -Version `0` has `<20 byte address>` for the version specific data, and the `address` is the intended validator. In the case of a Multisig wallet, that is the wallet's own address . - -The initial `0x19` byte is intended to ensure that the `signed_data` is not valid [RLP](https://github.com/ethereum/wiki/wiki/RLP) - -> For a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding. - -That means that any `signed_data` cannot be one RLP-structure, but a 1-byte `RLP` payload followed by something else. Thus, any ERC-191 `signed_data` can never be an Ethereum transaction. - -Additionally, `0x19` has been chosen because since ethereum/go-ethereum#2940 , the following is prepended before hashing in personal_sign: - -``` -"\x19Ethereum Signed Message:\n" + len(message). -``` - -Using `0x19` thus makes it possible to extend the scheme by defining a version `0x45` (`E`) to handle these kinds of signatures. - -### Registry of version bytes - -| Version byte | EIP | Description -| ------------ | -------------- | ----------- -| `0x00` | [191][eip-191] | Data with intended validator -| `0x01` | [712][eip-712] | Structured data -| `0x45` | [191][eip-191] | `personal_sign` messages - -[eip-191]: https://eips.ethereum.org/EIPS/eip-191 -[eip-712]: https://eips.ethereum.org/EIPS/eip-712 - -### Example - -The following snippet has been written in Solidity 0.5.0. - -```solidity -function submitTransactionPreSigned(address destination, uint value, bytes data, uint nonce, uint8 v, bytes32 r, bytes32 s) - public - returns (bytes32 transactionHash) -{ - // Arguments when calculating hash to validate - // 1: byte(0x19) - the initial 0x19 byte - // 2: byte(0) - the version byte - // 3: this - the validator address - // 4-7 : Application specific data - transactionHash = keccak256(abi.encodePacked(byte(0x19),byte(0),address(this),destination, value, data, nonce)); - sender = ecrecover(transactionHash, v, r, s); - // ... -} -``` - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-191.md diff --git a/EIPS/eip-1921.md b/EIPS/eip-1921.md new file mode 100644 index 00000000000000..ee46bc42861c18 --- /dev/null +++ b/EIPS/eip-1921.md @@ -0,0 +1,7 @@ +--- +eip: 1921 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1921.md diff --git a/EIPS/eip-1922.md b/EIPS/eip-1922.md index e0f9d76ae6150f..9bce442d20f524 100644 --- a/EIPS/eip-1922.md +++ b/EIPS/eip-1922.md @@ -1,210 +1,7 @@ --- eip: 1922 -title: zk-SNARK Verifier Standard -author: Michael Connor , Chaitanya Konda , Duncan Westland -discussions-to: https://github.com/ethereum/EIPs/issues/1922 -type: Standards Track category: ERC -status: Draft -created: 2018-09-14 -requires: 165, 196, 197 +status: Moved --- -## Simple Summary - -A standard interface for "Verifier" contracts which verify zk-SNARKs. - -## Abstract -The following standard allows for the implementation of a standard contract API for the verification of zk-SNARKs ("Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge"), also known as "proofs", "arguments", or "commitments". - -This standard provides basic functionality to load all necessary parameters for the verification of any zk-SNARK into a verifier contract, so that the proof may ultimately return a `true` or `false` response; corresponding to whether it has been verified or not verified. - -## Motivation -zk-SNARKs are a promising area of interest for the Ethereum community. Key applications of zk-SNARKs include: -- Private transactions -- Private computations -- Improved transaction scaling through proofs of "bundled" transactions - -A standard interface for verifying all zk-SNARKs will allow applications to more easily implement private transactions, private contracts, and scaling solutions; and to extract and interpret the limited information which gets emitted during zk-SNARK verifications. - -This standard was initially proposed by EY, and was inspired in particular by the requirements of businesses wishing to keep their agreements, transactions, and supply chain activities confidential—all whilst still benefiting from the commonly cited strengths of blockchains and smart contracts. - -:warning: TODO: Explain the benefits to and perspective of a consumer of information. I.e. the thing that interfaces with the standard verifier. - -## Specification -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -Terminology in this specification is used consistently with libsnark, as provided in that project's README. - -* Adhering Contract — A Verifier contract which adheres to this specification. -* Arithmetic circuit: An abstraction of logical statements into addition and multiplication gates. -* Public Inputs: often denoted as a vector 'x' in zk-SNARKs literature, and denoted `inputs` in this interface. An arithmetic circuit can be thought of as taking two parameters; the Public Inputs, 'x', and a secret 'witness', 'w'. This interface standardises functions which can load the `inputs` into an Adhering Contract. -* Proof: A 'prover' who wants to 'prove' knowledge of some secret witness 'w' (which satisfies an arithmetic circuit), generates a `proof` from: the circuit's Proving Key; their secret witness 'w'; and its corresponding Public Inputs 'x'. Together, a pair `(proof, inputs)` of satisfying `inputs` and their corresponding `proof` forms a zk-SNARK. -* Verification Key: A 'trusted setup' calculation creates both a public 'Proving Key' and a public 'Verification Key' from an arithmetic circuit. This interface does not provide a method for loading a Verification Key onto the blockchain. An Adhering Contract SHALL be able to accept arguments of knowledge (`(proof, inputs)` pairs) for at least one Verification Key. We shall call such Verification Keys 'in-scope' Verification Keys. An Adhering Contract MUST be able to interpret unambiguously a unique `verificationKeyId` for each of its 'in-scope' Verification Keys. - -**Every ERC-XXXX compliant verifier contract must implement the `ERCXXXX` and `ERC165` interfaces** (subject to "caveats" below): - - -```solidity -pragma solidity ^0.5.6; - -/// @title EIP-XXXX zk-SNARK Verifier Standard -/// @dev See https://github.com/EYBlockchain/zksnark-verifier-standard -/// Note: the ERC-165 identifier for this interface is 0xXXXXXXXX. -/// ⚠️ TODO: Calculate interface identifier -interface EIPXXXX /* is ERC165 */ { - /// @notice Checks the arguments of Proof, through elliptic curve - /// pairing functions. - /// @dev - /// MUST return `true` if Proof passes all checks (i.e. the Proof is - /// valid). - /// MUST return `false` if the Proof does not pass all checks (i.e. if the - /// Proof is invalid). - /// @param proof A zk-SNARK. - /// @param inputs Public inputs which accompany Proof. - /// @param verificationKeyId A unique identifier (known to this verifier - /// contract) for the Verification Key to which Proof corresponds. - /// @return result The result of the verification calculation. True - /// if Proof is valid; false otherwise. - function verify(uint256[] calldata proof, uint256[] calldata inputs, bytes32 verificationKeyId) external returns (bool result); -} -``` -### Interface -``` solidity -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -## Rationale - - -### Taxonomy - -⚠️ TODO: Add a specific reference to libsnark here, explaining the choice of variable names. - -:warning: TODO: Explain how _C_ may not necessarily be a satisfiable arithmetic circuit of logical statements. As current, this is a limitation to certain kinds of SNARKS. Whereas the source references also mention polynomials, and other applications. - -_C_ — A satisfiable arithmetic circuit abstraction of logical statements. - -_lambda​_ - A random number, generated at the 'setup' phase - commonly referred to as 'toxic waste', because knowledge of _lambda​_ would allow an untrustworthy party to create 'false' proofs which would verify as 'true'. _lambda​_ must be destroyed. - -_pk​_ - The proving key for a particular circuit _C​_. - -_vk_ - The verification key for a particular circuit _C_. - -Both _pk​_ and _vk​_ are generated as a pair by some function _G​_: -_(pk, vk) = G(lambda, C)​_ - -Note: _C_ can be represented unambiguously by either of _pk_ or _vk_. In zk-SNARK constructions, _vk_ is much smaller in size than _pk_, so as to enable succinct verification on-chain. Hence, _vk_ is the representative of _C_ that is 'known' to the contract. Therefore, we can identify each circuit uniquely through some `verificationKeyId`, where `verificationKeyId` serves as a more succinct mapping to _vk_. - -_w_ - A 'private witness' string. A private argument to the circuit _C_ known only to the prover, which, when combined with the `inputs` argument _x_, comprises an argument of knowledge which satisfies the circuit _C_. - -_x_ or `inputs` - A vector of 'Public Inputs'. A public argument to the circuit _C_ which, when combined with the private witness string _w_, comprises an argument of knowledge which satisfies the circuit _C_. - -_pi_ or `proof` - an encoded vector of values which represents the 'prover's' 'argument of knowledge' of values _w_ and _x_ which satisfy the circuit _C_. -_pi = P(pk, x, w)_. - -The ultimate purpose of a Verifier contract, as specified in this EIP, is to verify a proof (of the form _pi​_) through some verification function _V​_. - -_V(vk, x, pi) = 1_, if there exists a _w_ s.t. _C(x,w)=1_. -_V(vk, x, pi) = 0_, otherwise. - -The `verify()` function of this specification serves the purpose of _V​_; returning either `true` (the proof has been verified to satisfy the arithmetic circuit) or `false` (the proof has not been verified). - -### Functions - -#### `verify` -The `verify` function forms the crux this standard. The parameters are intended to be as generic as possible, to allow for verification of any zk-SNARK: - -- `proof` - Specified as `uint256[]`. - `uint256` is the most appropriate type for elliptic curve operations over a finite field. Indeed, this type is used in the predominant 'Pairing library' implementation of zk-SNARKs by Christian Reitweissner. - A one-dimensional dynamic array has been chosen for several reasons: - - Dynamic: There are several possible methods for producing a zk-SNARK proof, including PGHR13, G16, GM17, and future methods might be developed in future. Although each method may produce differently sized proof objects, a dynamic array allows for these differing sizes. - - Array: An array has been chosen over a 'struct' object, because it is currently easier to pass dynamic arrays between functions in Solidity. Any proof 'struct' can be 'flattened' to an array and passed to the `verify` function. Interpretation of that flattened array is the responsibility of the implemented body of the function. Example implementations demonstrate that this can be achieved. - - One-dimensional: A one-dimensional array has been chosen over multi-dimensional array, because it is currently easier to work with one-dimensional arrays in Solidity. Any proof can be 'flattened' to a one-dimensional array and passed to the `verify` function. Interpretation of that flattened array is the responsibility of the implemented body of the Adhering Contract. Example implementations demonstrate that this can be achieved. - -- `inputs` - Specified as `uint256[]`. - `uint256` is the most appropriate type for elliptic curve operations over a finite field. Indeed, this type is used in the predominant 'Pairing library' implementation of zk-SNARKs by Christian Reitweissner. - The number of inputs will vary in size, depending on the number of 'public inputs' of the arithmetic circuit being verified against. In a similar vein to the `proof` parameter, a one-dimensional dynamic array is general enough to cope with any set of inputs to a zk-SNARK. - -- `verificationKeyId` - A verification key (referencing a particular arithmetic circuit) only needs to be stored on-chain once. Any proof (relating to the underlying arithmetic circuit) can then be verified against that verification key. Given this, it would be unnecessary (from a 'gas cost' point of view) to pass a duplicate of the full verification key to the `verify` function every time a new `(proof, inputs)` pair is passed in. We do however need to tell the Adhering Verifier Contract which verification key corresponds to the `(proof, inputs)` pair being passed in. A `verificationKeyId` serves this purpose - it uniquely represents a verification key as a `bytes32` id. A method for uniquely assigning a `verificationKeyId` to a verification key is the responsibility of the implemented body of the Adhering Contract. - - -## Backwards Compatibility -- At the time this EIP was first proposed, there was one implementation on the Ethereum main net - deployed by [EY](https://www.ey.com). This was compiled with Solidity 0.4.24 for compatibility with [Truffle](https://github.com/trufflesuite/truffle) but otherwise compatible with this standard, which is presented at the latest current version of Solidity. -- Dr Christian Reitwiessner's excellent [example](https://gist.github.com/chriseth/f9be9d9391efc5beb9704255a8e2989d) of a Verifier contract and elliptic curve pairing library has been instrumental in the Ethereum community's experimentation and development of zk-SNARK protocols. Many of the naming conventions of this EIP have been kept consistent with his example. -- Existing zk-SNARK compilers such as [ZoKrates](https://github.com/Zokrates/ZoKrates), which produce 'Verifier.sol' contracts, do not currently produce Verifier contracts which adhere to this EIP specification. - - :warning: TODO: Provide a converter contract or technique which allows ZoKrates verifier.sol contracts to adhere with this EIP. - - -## Test Cases - - -Truffle tests of example implementations are included in the test case repository. - -⚠️ TODO: Reference specific test cases because there are many currently in the repository. - - -## Implementations - -Detailed example implementations and Truffle tests of these example implementations are included in this repository. - -:warning: TODO: Update referenced verifier implementations so that they are ready-to-deploy or reference deployed versions of those implementations. At current, the referenced code specifically states "DO NOT USE THIS IN PRODUCTION". - -:warning: TODO: Provide reference to an implementation which interrogates a standard verifier contract that implements this standard. - - -## References - -:warning: TODO: Update references and confirm that each reference is cited (parenthetical documentation not necessary) in the text. - -**Standards** - -1. ERC-20 Token Standard. https://eips.ethereum.org/EIPS/eip-20 - -1. ERC-165 Standard Interface Detection. https://eips.ethereum.org/EIPS/eip-165 -1. ERC-173 Contract Ownership Standard (DRAFT). https://eips.ethereum.org/EIPS/eip-173 -1. ERC-196 Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128. https://eips.ethereum.org/EIPS/eip-196 -1. ERC-197 Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128. https://eips.ethereum.org/EIPS/eip-197 -1. Ethereum Name Service (ENS). https://ens.domains -1. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt - -##### Educational material: zk-SNARKs -1. Zcash. What are zk-SNARKs? https://z.cash/technology/zksnarks.html -1. Vitalik Buterin. zk-SNARKs: Under the Hood. https://medium.com/@VitalikButerin/zk-snarks-under-the-hood-b33151a013f6 -1. Christian Reitweissner. zk-SNARKs in a Nutshell. https://blog.ethereum.org/2016/12/05/zksnarks-in-a-nutshell/ -1. Ben-Sasson, Chiesa, Tromer, et. al. Succinct Non-Interactive Zero Knowledge for a von Neumann Architecture. https://eprint.iacr.org/2013/879.pdf - -##### Notable applications of zk-SNARKs - 1. EY. Implementation of a business agreement through Token Commitment transactions on the Ethereum mainnet. https://github.com/EYBlockchain/ZKPChallenge - 1. Zcash. https://z.cash - 1. Zcash. How Transactions Between Shielded Addresses Work. https://blog.z.cash/zcash-private-transactions/ - -##### Notable projects relating to zk-SNARKs - 1. libsnark: A C++ Library for zk-SNARKs ("project README)". https://github.com/scipr-lab/libsnark - 1. ZoKrates: Scalable Privacy-Preserving Off-Chain Computations. https://www.ise.tu-berlin.de/fileadmin/fg308/publications/2018/2018_eberhardt_ZoKrates.pdf - 1. ZoKrates Project Repository. https://github.com/JacobEberhardt/ZoKrates - 1. Joseph Stockermans. zkSNARKs: Driver's Ed. https://github.com/jstoxrocky/zksnarks_example - 1. Christian Reitweissner - snarktest.solidity. https://gist.github.com/chriseth/f9be9d9391efc5beb9704255a8e2989d - -##### Notable 'alternatives' to zk-SNARKs - areas of ongoing zero-knowledge proof research - 1. Vitalik Buterin. STARKs. https://vitalik.ca/general/2017/11/09/starks_part_1.html - 1. Bu ̈nz, Bootle, Boneh, et. al. Bulletproofs. https://eprint.iacr.org/2017/1066.pdf - 1. Range Proofs. https://www.cosic.esat.kuleuven.be/ecrypt/provpriv2012/abstracts/canard.pdf - 1. Apple. Secure Enclaves. https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_secure_enclave - 1. Intel Software Guard Extensions. https://software.intel.com/en-us/sgx - - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1922.md diff --git a/EIPS/eip-1923.md b/EIPS/eip-1923.md index 3c4f74e52320f6..dd3d9382335887 100644 --- a/EIPS/eip-1923.md +++ b/EIPS/eip-1923.md @@ -1,170 +1,7 @@ --- eip: 1923 -title: zk-SNARK Verifier Registry Standard -author: Michael Connor , Chaitanya Konda , Duncan Westland -discussions-to: https://github.com/ethereum/EIPs/issues/1923 -type: Standards Track category: ERC -status: Draft -created: 2018-12-22 -requires: 165, 196, 197 +status: Moved --- -## Simple Summary - - -A standard interface for a "Verifier Registry"'" contract, through which all zk-SNARK verification activity can be registered. - -## Abstract -The following standard allows for the implementation of a standard contract API for the registration of zk-SNARKs ("Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge"), also known as "proofs", "arguments", or "commitments". - -TODO: Which functionality is exposed in this standard interface? - -## Motivation -zk-SNARKs are a promising area of interest for the Ethereum community. Key applications of zk-SNARKs include: -- Private transactions -- Private computations -- Ethereum scaling through proofs of 'bundled' transactions - -A standard interface for registering all zk-SNARKs will allow applications to more easily implement private transactions, private contracts, and scaling solutions; and to extract and interpret the limited information which gets emitted during zk-SNARK verifications. - -:warning: TODO: Explain the motivation for standardizing a registry, other than simply standardizing the verifier interactions. - -⚠️ TODO: Explain the benefits to and perspective of a consumer of information. I.e. the thing that interfaces with the standard verifier registry. - -## Specification -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - - -```solidity -pragma solidity ^0.5.6; - -/// @title EIP-XXXX zk-SNARK Verifier Registry Standard -/// @dev See https://github.com/EYBlockchain/zksnark-verifier-standard -/// Note: the ERC-165 identifier for this interface is 0xXXXXXXXXX. -/// ⚠️ TODO: Set the interface identifier -interface EIP-XXXX /* is ERC165 */ { - - event NewProofSubmitted(bytes32 indexed _proofId, uint256[] _proof, uint64[] _inputs); - - event NewVkRegistered(bytes32 indexed _vkId); - - event NewVerifierContractRegistered(address indexed _contractAddress); - - event NewAttestation(bytes32 indexed _proofId, address indexed _verifier, bool indexed _result); - - - function getVk(bytes32 _vkId) external returns (uint256[] memory); - - function registerVerifierContract(address _verifierContract) external returns (bool); - - function registerVk(uint256[] calldata _vk, address[] calldata _verifierContracts) external returns (bytes32); - - function submitProof(uint256[] calldata _proof, uint64[] calldata _inputs, bytes32 _vkId) external returns (bytes32); - - function submitProof(uint256[] calldata _proof, uint64[] calldata _inputs, bytes32 _vkId, address _verifierContract) external returns (bytes32); - - function submitProofAndVerify(uint256[] calldata _proof, uint64[] calldata _inputs, bytes32 _vkId, address _verifierContract) external returns (bytes32); - - function attestProof(bytes32 _proofId, bytes32 _vkId, bool _result) external; - - function attestProofs(bytes32[] calldata _proofIds, bytes32[] calldata _vkIds, bool[] calldata _results) external; - - function challengeAttestation(bytes32 _proofId, uint256[] calldata _proof, uint64[] calldata _inputs, address _verifierContract) external; - - function createNewVkId(uint256[] calldata _vk) external pure returns (bytes32); - - function createNewProofId(uint256[] calldata _proof, uint64[] calldata _inputs) external pure returns (bytes32); - -} -``` -### Interface -``` solidity -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -## Rationale - - -⚠️ TODO: Add Rationale section. - -### Backwards Compatibility - - - -⚠️ TODO: Add Backwards Compatibility section. - -### Test Cases - - - -Truffle tests of example implementations are included in this Repo. - -⚠️ TODO: Reference specific test cases because there are many currently in the repository. - - -## Implementations - -Detailed example implementations and Truffle tests of these example implementations are included in this Repo. - -⚠️ TODO: Update referenced verifier registry implementations so that they are ready-to-deploy or reference deployed versions of those implementations. At current, the referenced code specifically states "DO NOT USE THIS IN PRODUCTION". - -⚠️ TODO: Provide reference to an implementation which interrogates a standard verifier registry contract that implements this standard. - - -## References - -⚠️ TODO: Update references and confirm that each reference is cited (parenthetical documentation not necessary) in the text. - -**Standards** - -1. ERC-20 Token Standard. https://eips.ethereum.org/EIPS/eip-20 - -1. ERC-165 Standard Interface Detection. https://eips.ethereum.org/EIPS/eip-165 -2. ERC-173 Contract Ownership Standard (DRAFT). https://eips.ethereum.org/EIPS/eip-173 -3. ERC-196 Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128. https://eips.ethereum.org/EIPS/eip-196 -4. ERC-197 Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128. https://eips.ethereum.org/EIPS/eip-197 -5. Ethereum Name Service (ENS). https://ens.domains -6. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt - -##### Educational material: zk-SNARKs - -1. Zcash. What are zk-SNARKs? https://z.cash/technology/zksnarks.html -2. Vitalik Buterin. zk-SNARKs: Under the Hood. https://medium.com/@VitalikButerin/zk-snarks-under-the-hood-b33151a013f6 -3. Christian Reitweissner. zk-SNARKs in a Nutshell. https://blog.ethereum.org/2016/12/05/zksnarks-in-a-nutshell/ -4. Ben-Sasson, Chiesa, Tromer, et. al. Succinct Non-Interactive Zero Knowledge for a von Neumann Architecture. https://eprint.iacr.org/2013/879.pdf - -##### Notable applications of zk-SNARKs - -1. EY. Implementation of a business agreement through Token Commitment transactions on the Ethereum mainnet. https://github.com/EYBlockchain/ZKPChallenge -2. Zcash. https://z.cash -3. Zcash. How Transactions Between Shielded Addresses Work. https://blog.z.cash/zcash-private-transactions/ - -##### Notable projects relating to zk-SNARKs - -1. libsnark: A C++ Library for zk-SNARKs ("project README)". https://github.com/scipr-lab/libsnark -2. ZoKrates: Scalable Privacy-Preserving Off-Chain Computations. https://www.ise.tu-berlin.de/fileadmin/fg308/publications/2018/2018_eberhardt_ZoKrates.pdf -3. ZoKrates Project Repository. https://github.com/JacobEberhardt/ZoKrates -4. Joseph Stockermans. zkSNARKs: Driver's Ed. https://github.com/jstoxrocky/zksnarks_example -5. Christian Reitweissner - snarktest.solidity. https://gist.github.com/chriseth/f9be9d9391efc5beb9704255a8e2989d - -##### Notable 'alternatives' to zk-SNARKs - areas of ongoing zero-knowledge proof research - -1. Vitalik Buterin. STARKs. https://vitalik.ca/general/2017/11/09/starks_part_1.html -2. Bu ̈nz, Bootle, Boneh, et. al. Bulletproofs. https://eprint.iacr.org/2017/1066.pdf -3. Range Proofs. https://www.cosic.esat.kuleuven.be/ecrypt/provpriv2012/abstracts/canard.pdf -4. Apple. Secure Enclaves. https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_secure_enclave -5. Intel Software Guard Extensions. https://software.intel.com/en-us/sgx - - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1923.md diff --git a/EIPS/eip-1930.md b/EIPS/eip-1930.md index 8223277326e09d..bfb1245e185189 100644 --- a/EIPS/eip-1930.md +++ b/EIPS/eip-1930.md @@ -5,7 +5,7 @@ author: Ronan Sandford (@wighawag) type: Standards Track discussions-to: https://github.com/ethereum/EIPs/issues/1930 category: Core -status: Draft +status: Stagnant created: 2019-04-10 --- @@ -19,18 +19,46 @@ The current CALL, DELEGATE_CALL, STATIC_CALL opcode do not enforce the gas being This is for example the case for meta-transaction where the contract needs to ensure the call is executed exactly as the signing user intended. -But this is also the case for common use cases, like checking "on-chain" if a smart contract support a specific interface (via [EIP-165](http://eips.ethereum.org/EIPS/eip-165) for example). +But this is also the case for common use cases, like checking "on-chain" if a smart contract support a specific interface (via [EIP-165](./eip-165.md) for example). -The solution presented here is to add new opcodes that enforce the amount of gas specified : the call either proceed with the exact amount of gas or do not get executed and the current call revert. +The solution presented here is to add new call semantic that enforce the amount of gas specified : the call either proceed with the exact amount of gas or do not get executed and the current call revert. ### Specification +There are 2 possibilities + +a) one is to add opcode variant that have a stricter gas semantic + +b) The other is to consider a specific gas value range (one that have never been used before) to have strict gas semantic, while leaving other values as before + +Here are the details description + +#### option a) + - add a new variant of the CALL opcode where the gas specified is enforced so that if the gas left at the point of call is not enough to give the specified gas to the destination, the current call revert - add a new variant of the DELEGATE_CALL opcode where the gas specified is enforced so that if the gas left at the point of call is not enough to give the specified gas to the destination, the current call revert - add a new variant of the STATIC_CALL opcode where the gas specified is enforced so that if the gas left at the point of call is not enough to give the specified gas to the destination, the current call revert -In other words, based on [EIP-150](http://eips.ethereum.org/EIPS/eip-150), the current call must revert unless G >= I x 64/63 where G is gas left at the point of call (after deducing the cost of the call itself) and I is the gas specified. +##### Rational for a) +This solution has the merit to avoid any possibility of old contract be affected by the change. On the other hand it introduce 3 new opcodes. With EIP-1702, we could render the old opcode obsolete though. + +#### option b) + +For all opcode that allow to pass gas to another contract, do the following: +- If the most significant bit is one, consider the 31 less significant bit as the amount of gas to be given to the receiving contract in the strict sense. SO like a) if the gas left at the point of call is not enough to give the specified gas to the destination, the current call revert. +- If the 2nd most significant bit is zero, consider the whole value to behave like before, that is, it act as a maximum value, and even if not enough gas is present, the gas that can be given is given to the receiving contract + +##### Rational for b) +This solution relies on the fact that no contract would have given any value bigger or equal to 0x8000000000000000000000000000000000000000000000000000000000000000 + +Note that solidity for example do not use value like 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF as it is more expensive than passing the gasLeft. + +Its main benefit though is that it does not require extra opcodes. + +#### strict gas semantic + +To be precise, regarding the strict gas semantic, based on [EIP-150](./eip-150.md), the current call must revert unless G >= I x 64/63 where G is gas left at the point of call (after deducing the cost of the call itself) and I is the gas specified. So instead of ``` @@ -52,36 +80,19 @@ if !callCost.IsUint64() || gas < callCost.Uint64() { } ``` -Since checks on gas break current implementation of `eth_estimateGas`, the opcodes need to also use the mechanism described in [EIP-2075](https://github.com/ethereum/EIPs/pull/2075) to ensure `eth_estimateGas` return a value that is sufficient for the transaction to succeed. It must thus set `minimalGas` to equal the max of the current value of `minimalGas` and the sum of the gas spent so far added to the gas required. - -More precisely, as described in EIP-2075: - -Let specify `minimalGas` as a new variable that the EVM need to keep track for the purpose of `eth_estimateGas`. At the start of a tx, it is set to zero. - -At the end of an `eth_estimateGas` call, the gas spent is compared to `minimalGas`. The bigger value of the two is returned as "estimate". It does not have any other role in the context of a transaction call, its only purpose is to fix the current behavior of `eth_estimateGas` so that call to the opcodes describe here return a useful estimate - -If there is enough gas, the gas amount specified will be added to the gas spent up to that point. If that amount is bigger than minimalGas it replaces it. In other words: - -```minimalGas = max(minimalGas, X + )``` -where X is the value passed to REQUIRE_GAS - -As mentioned the result of an `eth_estimateGas` is now - -```max(, minimalGas)``` - ### Rationale -Currently the gas specified as part of these opcodes is simply a maximum value. And due to the behavior of [EIP-150](http://eips.ethereum.org/EIPS/eip-150) it is possible for an external call to be given less gas than intended (less than the gas specified as part of the CALL) while the rest of the current call is given enough to continue and succeed. Indeed since with EIP-150, the external call is given at max ```G - Math.floor(G/64)``` where G is the gasleft() at the point of the CALL, the rest of the current call is given ```Math.floor(G/64)``` which can be plenty enough for the transaction to succeed. For example, when G = 6,400,000 the rest of the transaction will be given 100,000 gas plenty enough in many case to succeed. +Currently the gas specified as part of these opcodes is simply a maximum value. And due to the behavior of [EIP-150](./eip-150.md) it is possible for an external call to be given less gas than intended (less than the gas specified as part of the CALL) while the rest of the current call is given enough to continue and succeed. Indeed since with EIP-150, the external call is given at max ```G - Math.floor(G/64)``` where G is the gasleft() at the point of the CALL, the rest of the current call is given ```Math.floor(G/64)``` which can be plenty enough for the transaction to succeed. For example, when G = 6,400,000 the rest of the transaction will be given 100,000 gas plenty enough in many case to succeed. This is an issue for contracts that require external call to only fails if they would fails with enough gas. This requirement is present in smart contract wallet and meta transaction in general, where the one executing the transaction is not the signer of the execution data. Because in such case, the contract needs to ensure the call is executed exactly as the signing user intended. -But this is also true for simple use case, like checking if a contract implement an interface via EIP-165. Indeed as specified by such EIP, the ```supporstInterface``` method is bounded to use 30,000 gas so that it is theorically possible to ensure that the throw is not a result of a lack of gas. Unfortunately due to how the different CALL opcodes behave contracts can't simply rely on the gas value specified. They have to ensure by other means that there is enough gas for the call. +But this is also true for simple use case, like checking if a contract implement an interface via EIP-165. Indeed as specified by such EIP, the ```supporstInterface``` method is bounded to use 30,000 gas so that it is theoretically possible to ensure that the throw is not a result of a lack of gas. Unfortunately due to how the different CALL opcodes behave contracts can't simply rely on the gas value specified. They have to ensure by other means that there is enough gas for the call. -Indeed, if the caller do not ensure that 30,000 gas or more is provided to the callee, the callee might throw because of a lack of gas (and not because it does not support the interface), and the parent call will be given up to 476 gas to continue. This would result in the caller interepreting wrongly that the callee is not implementing the interface in question. +Indeed, if the caller do not ensure that 30,000 gas or more is provided to the callee, the callee might throw because of a lack of gas (and not because it does not support the interface), and the parent call will be given up to 476 gas to continue. This would result in the caller interpreting wrongly that the callee is not implementing the interface in question. -While such requirement can be enforced by checking the gas left according to EIP-150 and the precise gas required before the call (see solution presented in that [bug report](https://web.solidified.io/contract/5b4769b1e6c0d80014f3ea4e/bug/5c83d86ac2dd6600116381f9) or after the call (see the native meta transaction implementation [here](https://github.com/pixowl/thesandbox-contracts/blob/623f4d4ca10644dcee145bcbd9296579a1543d3d/src/Sand/erc20/ERC20MetaTxExtension.sol#L176), it would be much better if the EVM allowed us to strictly specify how much gas is to be given to the CALL so contract implementations do not need to follow [EIP-150](http://eips.ethereum.org/EIPS/eip-150) behavior and the current gas pricing so closely. +While such requirement can be enforced by checking the gas left according to EIP-150 and the precise gas required before the call (see solution presented in that [bug report](https://web.solidified.io/contract/5b4769b1e6c0d80014f3ea4e/bug/5c83d86ac2dd6600116381f9) or after the call (see the native meta transaction implementation [here](https://github.com/pixowl/thesandbox-contracts/blob/623f4d4ca10644dcee145bcbd9296579a1543d3d/src/Sand/erc20/ERC20MetaTxExtension.sol#L176), it would be much better if the EVM allowed us to strictly specify how much gas is to be given to the CALL so contract implementations do not need to follow [EIP-150](./eip-150.md) behavior and the current gas pricing so closely. -This would also allow the behaviour of [EIP-150](http://eips.ethereum.org/EIPS/eip-150) to be changed without having to affect contract that require this strict gas behaviour. +This would also allow the behaviour of [EIP-150](./eip-150.md) to be changed without having to affect contract that require this strict gas behaviour. As mentioned, such strict gas behaviour is important for smart contract wallet and meta transaction in general. The issue is actually already a problem in the wild as can be seen in the case of Gnosis safe which did not consider the behavior of EIP-150 and thus fails to check the gas properly, requiring the safe owners to add otherwise unnecessary extra gas to their signed message to avoid the possibility of losing funds. See https://github.com/gnosis/safe-contracts/issues/100 @@ -116,11 +127,13 @@ This solution does not require to compute a ```E``` value and thus do not relies But this check still pass if the gas given was less AND the external call reverted or succeeded EARLY (so that the gas left after the call > txGas / 63). This can be an issue if the code executed as part of the CALL is reverting as a result of a check against the gas provided. Like a meta transaction in a meta transaction. -Similarly to the the previous solution, an EVM mechanism would be much better. +Similarly to the previous solution, an EVM mechanism would be much better. ## Backwards Compatibility -Backwards compatible as it introduce new opcodes. +for specification a) : Backwards compatible as it introduce new opcodes. + +for specification b) : Backwards compatible as it use value range outside of what is used by existing contract (to be verified) ## Test Cases @@ -130,8 +143,8 @@ None fully implemented yet. But see Specifications for an example in geth. ## References -1. EIP-150, http://eips.ethereum.org/EIPS/eip-150 +1. EIP-150, ./eip-150.md ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1948.md b/EIPS/eip-1948.md new file mode 100644 index 00000000000000..6658ba14e44a09 --- /dev/null +++ b/EIPS/eip-1948.md @@ -0,0 +1,7 @@ +--- +eip: 1948 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1948.md diff --git a/EIPS/eip-1959.md b/EIPS/eip-1959.md index 40af70b401ca76..5bec07770af010 100644 --- a/EIPS/eip-1959.md +++ b/EIPS/eip-1959.md @@ -5,7 +5,7 @@ author: Ronan Sandford (@wighawag) category: Core type: Standards Track discussions-to: https://ethereum-magicians.org/t/eip-1959-valid-chainid-opcode/3170 -status: Draft +status: Stagnant created: 2019-04-20 requires: 155 --- @@ -18,9 +18,9 @@ To protect off-chain messages from being reused across different chain, a mechan This EIP adds an opcode that returns whether the specific number passed in has been a valid chainID (EIP-155 unique identifier) in the history of the chain (including the current chainID). ## Motivation -[EIP-155](https://eips.ethereum.org/EIPS/eip-155) proposes to use the chain ID to prevent replay attacks between different chains. It would be a great benefit to have the same possibility inside smart contracts when handling signatures, especially for Layer 2 signature schemes using [EIP-712](https://eips.ethereum.org/EIPS/eip-712). +[EIP-155](./eip-155.md) proposes to use the chain ID to prevent replay attacks between different chains. It would be a great benefit to have the same possibility inside smart contracts when handling signatures, especially for Layer 2 signature schemes using [EIP-712](./eip-712.md). -[EIP-1344](https://eips.ethereum.org/EIPS/eip-1344) is attempting to solve this by giving smart contract access to the tip of the chainID history. This is insufficient as such value is changing. Hence why EIP-1344 describes a contract based solution to work around the problem. It would be better to solve it in a simpler, cheaper and safer manner, removing the potential risk of misuse present in EIP-1344. +[EIP-1344](./eip-1344.md) is attempting to solve this by giving smart contract access to the tip of the chainID history. This is insufficient as such value is changing. Hence why EIP-1344 describes a contract based solution to work around the problem. It would be better to solve it in a simpler, cheaper and safer manner, removing the potential risk of misuse present in EIP-1344. ## Specification Adds a new opcode ```VALID_CHAINID``` at 0x46, which uses 1 stack argument : a 32 bytes value that represent the chainID to test. It will push ```0x1``` onto the stack if the uint256 value is part of the history (since genesis) of chainIDs of that chain, ```0x0``` otherwise. @@ -34,11 +34,11 @@ Note though that the alternative to keep track of old chainID is to implement a ## Rationale The only approach available today is to specify the chain ID at compile time. Using this approach will result in problems after a contentious hardfork as the contract can't accept message signed with a new chainID. -The approach proposed by EIP-1344 is to give access to the latest chainID. This is in itself not sufficient and pose the opposite of the problem mentioned above since as soon as a hardfork that change the chainID happens, every L2 messages signed as per [EIP-712](https://eips.ethereum.org/EIPS/eip-712) (with the previous chainID) will fails to be accepted by the contracts after the fork. +The approach proposed by EIP-1344 is to give access to the latest chainID. This is in itself not sufficient and pose the opposite of the problem mentioned above since as soon as a hardfork that change the chainID happens, every L2 messages signed as per [EIP-712](./eip-712.md) (with the previous chainID) will fails to be accepted by the contracts after the fork. That's why in the rationale of EIP-1344 it is mentioned that users need to implement/use a mechanism to verify the validity of past chainID via a trustless cache implemented via smart contract. -While this works (except for a temporary gap where the immediately previous chainID is not considered valid), this is actually a required procedure for all contracts that want to accept L2 messages since without it, messages signed before an hardfork that updated the chainID would be rejected. In other words, EIP-1344 expose such risk and it is easy for contract to not consider it by simply checking ```chainID == CHAIN_ID()``` without considering past chainIDs. +While this works (except for a temporary gap where the immediately previous chainID is not considered valid), this is actually a required procedure for all contracts that want to accept L2 messages since without it, messages signed before a hardfork that updated the chainID would be rejected. In other words, EIP-1344 expose such risk and it is easy for contract to not consider it by simply checking ```chainID == CHAIN_ID()``` without considering past chainIDs. Indeed letting contracts access the latest chainID for L2 message verification is dangerous. The latest chainID is only the tip of the chainID history. As a changing value, the latest chainID is thus not appropriate to ensure the validity of L2 messages. @@ -76,4 +76,4 @@ Similarly to EIP-1344, it might be beneficial to update EIP-712 (still in Draft) This was previously suggested as part of [EIP-1344 discussion](https://ethereum-magicians.org/t/eip-1344-add-chain-id-opcode/1131/39). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-196.md b/EIPS/eip-196.md index 70170741e05792..6538d198b1db10 100644 --- a/EIPS/eip-196.md +++ b/EIPS/eip-196.md @@ -1,8 +1,7 @@ --- eip: 196 -title: Precompiled contracts for addition and scalar multiplication - on the elliptic curve alt_bn128 -author: Christian Reitwiessner +title: Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128 +author: Christian Reitwiessner type: Standards Track category: Core status: Final @@ -103,4 +102,4 @@ In both codebases, a specific group on the curve alt_bn128 is used and is called ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1962.md b/EIPS/eip-1962.md index 93a6937c8af9a9..5a69e321a551f9 100644 --- a/EIPS/eip-1962.md +++ b/EIPS/eip-1962.md @@ -5,14 +5,14 @@ author: Alex Vlasov (@shamatar) discussions-to: https://ethereum-magicians.org/t/generalised-precompile-for-elliptic-curve-arithmetics-and-pairings-working-group/3208/2 type: Standards Track category: Core -status: Draft +status: Stagnant created: 2019-04-22 requires: 1109 --- # Simple summary -This proposal is an extension and formalization of [EIP1829](https://eips.ethereum.org/EIPS/eip-1829) with an inclusion of pairings. [EIP1109](https://eips.ethereum.org/EIPS/eip-1109) is required due to low cost of some operations compared to the `STATICCALL` opcode (more information in the corresponding section below). +This proposal is an extension and formalization of [EIP-1829](./eip-1829.md) with an inclusion of pairings. [EIP-1109](./eip-1109.md) is required due to low cost of some operations compared to the `STATICCALL` opcode (more information in the corresponding section below). ## Abstract @@ -25,127 +25,40 @@ This EIP proposes a new precompile to bring cryptographic functionality desired - Implementation pairing operation over elliptic curves from the following "families" with parameters such as base field, extension tower structure, coefficients defined in runtime: - BLS12 - BN - - MNT4/6 -- Implementation pairing operation over elliptic curves found by Cocks-Pinch method. Limit k <= 8. + - MNT4/6 (Ate pairing) Full functionality of the precompile is described below in `Specification` section. ## Motivation -- There is a pending proposal to implement base elliptic curve arithmetic is covered by [EIP1829](https://eips.ethereum.org/EIPS/eip-1829) and will allow to implement various privacy-preserving protocols with a reasonable gas costs per operation. +- There is a pending proposal to implement base elliptic curve arithmetic is covered by [EIP-1829](./eip-1829.md) and will allow to implement various privacy-preserving protocols with a reasonable gas costs per operation. - Pairings are an important extension for basic arithmetic and so this new precompile is proposed with the following benefits: - Extended set of curves will be available to allow Ethereum users to choose their security parameters and required functionality. - Generic approach of this precompile will allow Ethereum users to experiment with newly found curves of their choice and new constructions constructions without waiting for new forks. - EC arithmetic is indeed re-implemented in this precompile, but it's strictly required. Most of the pairing-based protocols still need to perform standard EC multiplications or additions and thus such operations must be available on generic set of curves. - Gas costs - this EIP is designed to estimate gas-cost of performed operation as early as possible during the call and base if solely on specified parameters and operation type. This is a strict requirement for any precompile to allow Ethereum nodes to efficiently reject transactions and operations as early as possible. -Functionality of this newly proposed precompile is different from [EIP1829](https://eips.ethereum.org/EIPS/eip-1829) in the following aspects: +Functionality of this newly proposed precompile is different from [EIP-1829](./eip-1829.md) in the following aspects: - Operation on arbitrary-length modulus (up to some upper-limit) for a base field and scalar field of the curve - Pairing operations are introduced - Different ABI due to variable parameter length ## Specification -If `block.number >= XXXXX`, define a new precompile with an address `0x..` and the following functionality. - -This specification will not yet provide concrete numbers for every operation, but will first introduce interfaces and gas calculation approaches. +If `block.number >= XXXXX`, define a set of `10` new precompiles with an addresses `[0x.., 0x.., ...]` and the following functionality. -In every call to the precompile the first byte specifies an operation that should be performed: -- `0x01`: Point addition -- `0x02`: Single point multiplication -- `0x03`: Multiexponentiation -- `0x04`: Pairing +- Addition of points on the curve defined over base field +- Multiplication of a point on the curve defined over base field +- Multiexponentiation for `N` pairs of `(scalar, point)` on the curve defined over base field +- Addition of points on the curve defined over quadratic or cubic extension of the base field +- Multiplication of a point on the curve defined over quadratic or cubic extension of the base field +- Multiexponentiation for `N` pairs of `(scalar, point)` on the curve defined over quadratic or cubic extension of the base field +- Pairing operation on the curve of `BLS12` family +- Pairing operation on the curve of `BN` family +- Pairing operation on the curve of `MNT4` family +- Pairing operation on the curve of `MNT6` family -For parameter encoding there is no dense bit packing. All the parameters (sizes, scalars, field elements, etc.) are Big Endian (BE) encoded unsigned integers. - -Points are always encoded in affine coordinates as `(x, y)`. Extension field elements are always encoded as `(c0, c1, c2, ...)` where the element itself is interpreted as `c0 + c1 * u + c2 * u^2 + ...`. - -During the execution all the parameters that should be interpreted as "points" are first checked that those are "on curve", otherwise error is thrown. - -Maximum proposed field bit size is 1023 bits. - -### Binary interface for non-pairing operations - -Every operation of such kind should specify curve parameters right after the "operation" byte: -- 1 byte that encodes byte size of the modulus for a base field. Will be referred as "field element length". -- BE encoded modulus. Field modulo this parameter is referred as the "base field". -- BE encoded parameter `A` for a curve in the Weierstrass form. May be zero but still must take the whole field element length. Must be less than modulus, no reduction should be performed by the precompile. -- BE encoded parameter `B` for a curve in the Weierstrass form. May be zero but still must take the whole field element length. Must be less than modulus, no reduction should be performed by the precompile. -- 1 byte that encodes byte size of the main group on the curve (over which arithmetic should happen). Will be referred as "scalar element length". -- BE encoded size of the main group. Will be referred as "scalar field size". - -While "scalar field size" is not used anywhere in principal operations (point additions, multiplications, multiexponentiations) do not depend on it, this parameter is required to calculate a gas cost for this operation (that's not true for point addition, but interface should be kept universal). E.g. for a naive "double and add" point multiplication approach the worst case scenario is when "add" operation is performed as many times a possible, it can be estimated as if the scalar had the same bit length as a size of the main group, but consisted of only `1` in it's bit decomposition. - -#### Point addition - -After the curve parameters (from above) two points must be specified to perform an addition. Output is a point in affine coordinates. - -#### Point multiplication - -After the curve parameters (from above) one point and one scalar must be specified to perform a multiplication. Output is a point in affine coordinates. Scalar must be less than the size of the group, otherwise error is thrown. - -#### Multiexponentiation - -After the curve parameters (from above) a list of `N` pairs `(point, scalar)` must be specified to perform a multiexponentiation. Output is a point in affine coordinates. Scalars must be less than the size of the group, otherwise error is thrown. For efficiency reasons this operations should use Peppinger algorithm with huge performance benefits. - -#### Gas calculation for non-pairing operations - -For all the operations above arithmetic is performed in a field specified by modulus. Number of operations for point addition is known beforehand, so the bit length (or byte length, more likely) of the modulus clearly must be one of the parameters. Second parameter is length of the bit (or byte) length of the scalar field. Third parameter is number of `(point, scalar)` pairs for multiexponentiation. - -Let's denote field element byte length as `fe_length`, -scalar length as `scalar_length` and number of points as `N`. Concrete coefficients that are to be determined will be labeled as `C_*`. Notation `quadratic` is to indicate a function that is quadratic over it's parameter. - -Quadratic dependency over field element byte length is due to multiplication. - -Proposed formulas: -- Point addition: `C_0*quadratic(fe_length)` -- Point multiplication: `C_1 * quadratic(fe_length) * scalar_length` -- Multiexponentiation: `C_2 * N * quadratic(fe_length) * scalar_length` - -Multiexponentiation formula is different due to use of the specialized algorithm. - -### Binary interface for pairing operations - -Pairing operations have other parameters required to estimate gas costs, so common part of the interface is different from non-pairing operations - -- 1 byte that encodes byte size of the modulus for a base field. Will be referred as "field element length". -- BE encoded modulus. Field modulo this parameter is referred as the "base field". -- BE encoded parameter `A` for a curve in the Weierstrass form. May be zero but still must take the whole field element length. Must be less than modulus, no reduction should be performed by the precompile. -- BE encoded parameter `B` for a curve in the Weierstrass form. May be zero but still must take the whole field element length. Must be less than modulus, no reduction should be performed by the precompile. -- 1 byte that encodes curve "family" - - `0x01` BLS12 - - `0x02` BN - - `0x03` MNT4 - - `0x04` MNT6 - - `0x05` Cocks-Pinch (Tate pairing) - -Parameters for a pairing are encoded as a list of `N` pairs `(p1, p2)` with `p1` being point from `G1` (curve over base field) in affine coordinates, and `p2` being point from `G2` (over the extension). - -Pairing operation consists of two major contributors: -- Miller loop. This part does depend from the number of pairs `N` and has number of steps that is specific for every curve family. For example, BLS12 family is generated by a single scalar `x` (standard notation) that determines number of steps in this loop. Any such parameters must be provided in the binary interface for gas costs estimation. -- Final exponentiation. This part does not depend from the number of pairs. Length of the loop for this operation is different for different families and can either be calculated in from other parameters or specified in the interface. In any case, gas costs can be estimated upfront. - -Below there will be proposed interface for BLS12 family of curves with other interfaces being built in a similar manner. - -#### BLS12 family pairing operation interface - -- 1 byte, length of the `x` parameter. -- BE encoding of parameter `x` (unsigned). -- 1 byte, sign of parameter `x`. `0x00` is `+`, `0x01` is `-`. -- 1 byte, specifies type of the pairing. Either `0x01` or `0x02`. This type depends of the curve and does not affect the gas cost. -- structure of the extension tower: - - non-residue for Fp2 extension in BE encoding. This is just a single element in the base field and must be less than modulus. - - non-residue for Fp6 extension (that is "3 over 2"). This is an element in Fp2 and encoded using the rules from the beginning of this EIP. -- Encoding of the "A" parameter in Fp2 for the curve over the extension (Fp2). -- Encoding of the "B" parameter in Fp2 for the curve over the extension (Fp2). - -For BLS12 family `x` parameter is enough for gas costs estimation. It's Hamming weight and bit length determines complexity of the Miller loop. Final exponentiation depends of the base field size. - -Proposed gas cost formula: `C_0 * quadratic(fe_length) + N * C_1 * fe_length * Hamming_and_bit_length(x)` - -#### Pairing operation interface for other families - -Complexity for BN family is also determined by the single scalar parameter, so interface will be similar to BLS12. For MNT4/6 and Cocks-Pinch curves there would be required to specify number of steps in the Miller loop explicitly in the interface. +Due to actuve development of the precompile and a lot of ongoing changes there is a single [source of truth](https://github.com/matter-labs/eip1962/tree/master/documentation). It covers binary interface, gas schedule, integration guide for existing implementations. ### Possible simplifications @@ -164,7 +77,6 @@ In the case of limited set of curve the following set is proposed as a minimal: Only the largest design decisions will be covered: - While there is no arithmetic over the scalar field (which is modulo size of the main group) of the curve, it's required for gas estimation purposes. -- One may separate interfaces for additions, multiplications and multiexponentiations and estimate gas costs differently for every operation, but it would bring confusion for users and will make it harder to use a precompile from the smart-contract. - Multiexponentiation is a separate operation due to large cost saving - There are no point decompressions due to impossibility to get universal gas estimation of square root operation. For a limited number of "good" cases prices would be too different, so specifying the "worst case" is expensive and inefficient, while introduction of another level if complexity into already complicated gas costs formula is not worth is. @@ -222,4 +134,4 @@ test tests::bench_wnaf_multiexp_bn254 ... bench: 9,161,281 n ``` ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file +Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file diff --git a/EIPS/eip-1965.md b/EIPS/eip-1965.md index aad5ea94dd499a..dc8b91caed4df9 100644 --- a/EIPS/eip-1965.md +++ b/EIPS/eip-1965.md @@ -5,23 +5,26 @@ author: Ronan Sandford (@wighawag) category: Core type: Standards Track discussions-to: https://ethereum-magicians.org/t/eip-1965-valid-chainid-for-specific-blocknumber-protect-all-forks/3181 -status: Draft +status: Stagnant created: 2019-04-20 requires: 155 --- ## Abstract + This EIP adds a precompile that returns whether a specific chainID (EIP-155 unique identifier) is valid at a specific blockNumber. ChainID are assumed to be valid up to the blockNumber at which they get replaced by a new chainID. ## Motivation -[EIP-155](https://eips.ethereum.org/EIPS/eip-155) proposes to use the chain ID to prevent the replay of transactions between different chains. It would be a great benefit to have the same possibility inside smart contracts when handling off-chain message signatures, especially for Layer 2 signature schemes using [EIP-712](https://eips.ethereum.org/EIPS/eip-712). -[EIP-1344](http://eips.ethereum.org/EIPS/eip-1344) is attempting to solve this by giving smart contract access to the tip of the chainID history. This is insuficient as such value is changing. Hence why EIP-1344 describes a contract based solution to work around the problem. It would be better to solve it in a simpler, cheaper and safer manner, removing the potential risk of misuse present in EIP-1344. Furthermore EIP-1344 can't protect replay properly for minority-led hardfork as the caching system cannot guarantee accuracy of the blockNumber at which the new chainID has been introduced. +[EIP-155](./eip-155.md) proposes to use the chain ID to prevent the replay of transactions between different chains. It would be a great benefit to have the same possibility inside smart contracts when handling off-chain message signatures, especially for Layer 2 signature schemes using [EIP-712](./eip-712.md). + +[EIP-1344](./eip-1344.md) is attempting to solve this by giving smart contract access to the tip of the chainID history. This is insufficient as such value is changing. Hence why EIP-1344 describes a contract based solution to work around the problem. It would be better to solve it in a simpler, cheaper and safer manner, removing the potential risk of misuse present in EIP-1344. Furthermore EIP-1344 can't protect replay properly for minority-led hardfork as the caching system cannot guarantee accuracy of the blockNumber at which the new chainID has been introduced. -[EIP-1959](https://github.com/ethereum/EIPs/pull/1959) solves the issue of EIP-1344 but do not attempt to protect from minority-led hardfork as mentioned in the rationale. We consider this a mistake, since it remove some freedom to fork. We consider that all fork should be given equal oportunities. And while there will always be issues we can't solve for the majority that ignore a particular fork, **users that decide to use both the minority-fork and the majority-chain should be protected from replay without having to wait for the majority chain to update its chainID.** +[EIP-1959](./eip-1959.md) solves the issue of EIP-1344 but does not attempt to protect from minority-led hardfork as mentioned in the rationale. We consider this a mistake, since it removes some freedom to fork. We consider that all fork should be given equal opportunities. And while there will always be issues we can't solve for the majority that ignore a particular fork, **users that decide to use both the minority-fork and the majority-chain should be protected from replay without having to wait for the majority chain to update its chainID.** ## Specification -Adds a new precompile which uses 2 argument : a 32 bytes value that represent the chainID to test and a 32 bytes value representing the blockNumber at which the chainID is tested. It return 0x1 if the chainID is valid at the specific blockNumber, 0x0 otherwise. Note that chainID are considered valid up to the blockNumber at which they are replaced. So they are valid for every blockNumber past their replacement. + +Adds a new precompile which uses 2 arguments : a 32 bytes value that represents the chainID to test and a 32 bytes value representing the blockNumber at which the chainID is tested. It returns 0x1 if the chainID is valid at the specific blockNumber, 0x0 otherwise. Note that chainID are considered valid up to the blockNumber at which they are replaced. So they are valid for every blockNumber past their replacement. The operation will costs no more than `G_blockhash` + `G_verylow` to execute. This could be lower as chainID are only introduced during hardfork. @@ -33,19 +36,19 @@ Note though that the alternative to keep track of old chainID is to implement a The rationale at EIP-1959 applies here as well too : -- An opcode is better than a caching system for past chainID, It is cheaper, safer and do not include gaps. -- Direct access to the latest chainID is dangerous since it make it easy for contract to use it as a replay protection mechanism while preventing otherwise valid old messages to be valid after a fork that change the chainID. This can have disastrous consequences on users. -- all off-chain messaged signed before a fork should be valid across all side of the fork. +- An opcode is better than a caching system for past chainID, It is cheaper, safer and does not include gaps. +- Direct access to the latest chainID is dangerous since it makes it easy for contracts to use it as a replay protection mechanism while preventing otherwise valid old messages to be valid after a fork that changes the chainID. This can have disastrous consequences on users. +- all off-chain messages signed before a fork should be valid across all side of the fork. -The only difference is that this current proposal propose a solution to protect hardfork led by a minority. +The only difference is that this current proposal proposes a solution to protect hardfork led by a minority. To summarize there is 2 possible fork scenario : -1) The majority decide to make an hardfork but a minority disagree with it (ETC is such example). The fork is planned for block X. If the majority is not taking any action to automate the process of assigning a different chainID for both, the minority has plenty of time to plan for a chainID upgrade to happen at that same block X. Now if they do not do it, their users will face the problem that their messages will be replayable on the majority chain (Note that this is not true the other way around as we assume the majority decided to change the chainID). As such there is no reason that they’ll leave it that way. +1) The majority decide to make a hardfork but a minority disagree with it (ETC is such example). The fork is planned for block X. If the majority is not taking any action to automate the process of assigning a different chainID for both, the minority has plenty of time to plan for a chainID upgrade to happen at that same block X. Now if they do not do it, their users will face the problem that their messages will be replayable on the majority chain (Note that this is not true the other way around as we assume the majority decided to change the chainID). As such there is no reason that they will leave it that way. -2) A minority decide to create an hardfork that the majority disagree with (or simply ignore). Now, the same as above can happen but since we are talking about a minority there is a chance that the majority do not care about the minority. In that case, there would be no incentive for the majority to upgrade the chainID. This means that user of both side of the fork will have the messages meant for the majority chain replayable on the minority-chain (even if this one changed its chainID) unless extra precaution is taken. +2) A minority decide to create a hardfork that the majority disagree with (or simply ignore). Now, the same as above can happen but since we are talking about a minority there is a chance that the majority does not care about the minority. In that case, there would be no incentive for the majority to upgrade the chainID. This means that users of both sides of the fork will have the messages meant for the majority chain replayable on the minority-chain (even if this one changed its chainID) unless extra precaution is taken. -The solution is to add the blockNumber representing the time at which the message was signed and use it as an argument to the opcode proposed here. This way, when the minority forks with a new chainID, the previous chainID become invalid from that time onward. So new messages destinated to the majority chain can't be replayed on the minority fork. +The solution is to add the blockNumber representing the time at which the message was signed and use it as an argument to the opcode proposed here. This way, when the minority forks with a new chainID, the previous chainID become invalid from that time onward. So new messages destined to the majority chain can't be replayed on the minority fork. ## Backwards Compatibility @@ -57,7 +60,9 @@ Since chainID and blockNumber will vary, they should not be part of the domain s While the pair could be optional for contract that do not care about replays or have other ways to prevent them, if chainID is present, the blockNumber must be present too. And if any of them is present, wallet need to ensure that the chainID is indeed the latest one of the chain being used, while the blockNumber is the latest one at the point of signing. During fork transition, the wallet can use the blockNumber to know which chainID to use. ## References + This was previously suggested as part of [EIP1959 discussion](https://ethereum-magicians.org/t/eip-1959-valid-chainid-opcode/3170). ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1967.md b/EIPS/eip-1967.md new file mode 100644 index 00000000000000..48b32f9e9dec16 --- /dev/null +++ b/EIPS/eip-1967.md @@ -0,0 +1,7 @@ +--- +eip: 1967 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1967.md diff --git a/EIPS/eip-197.md b/EIPS/eip-197.md index df55a8ba2e3afb..9f9b3d33440e7c 100644 --- a/EIPS/eip-197.md +++ b/EIPS/eip-197.md @@ -1,7 +1,6 @@ --- eip: 197 -title: Precompiled contracts for optimal ate pairing check - on the elliptic curve alt_bn128 +title: Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128 author: Vitalik Buterin , Christian Reitwiessner type: Standards Track category: Core @@ -138,4 +137,4 @@ Implementations are available here: ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1973.md b/EIPS/eip-1973.md index 64c7a9cf15cb61..8ee3f7066323e4 100644 --- a/EIPS/eip-1973.md +++ b/EIPS/eip-1973.md @@ -1,271 +1,7 @@ --- -eip: 1973 -title: Scalable Rewards -author: Lee Raj (@lerajk), Qin Jian (@qinjian) -type: Standards Track +eip: 1973 category: ERC -status: Draft -created: 2019-04-01 +status: Moved --- -## Simple Summary - - A mintable token rewards interface that mints 'n' tokens per block which are distributed equally among the 'm' participants in the DAPP's ecosystem. - -## Abstract - - The mintable token rewards interface allows DApps to build a token economy where token rewards are distributed equally among the active participants. The tokens are minted based on per block basis that are configurable (E.g. 10.2356 tokens per block, 0.1 token per block, 1350 tokens per block) and the mint function can be initiated by any active participant. The token rewards distributed to each participant is dependent on the number of participants in the network. At the beginning, when the network has low volume, the tokens rewards per participant is high but as the network scales the token rewards decreases dynamically. - - - ## Motivation - -Distributing tokens through a push system to a large amount of participants fails due to block gas limit. As the number of participants in the network grow to tens of thousands, keeping track of the iterable registry of participants and their corresponding rewards in a push system becomes unmanagable. E.g. Looping through 5000 addresses to distribute 0.0000001 reward tokens is highly inefficient. Furthermore, the gas fees in these transactions are high and needs to be undertaken by the DApp developer or the respective company, leading to centralization concerns. - -A pull system is required to keep the application completely decentralized and to avoid the block gas limit problem. However, no standard solution has been proposed to distribute scalable rewards to tens of thousands participants with a pull system. This is what we propose with this EIP through concepts like TPP, round mask, participant mask. - -## Specification - -### Definitions - - `token amount per participant in the ecosytem or TPP (token per participant)`: TPP = (token amount to mint / total active participants) - - `roundMask`: the cumulative snapshot of TPP over time for the token contract. E.g. transactionOne = 10 tokens are minted with 100 available participants (TPP = 10 / 100) , transactionTwo = 12 tokens are minted with 95 participants (TPP = 12 / 95 ) - - roundMask = (10/100) + (12/95) - - `participantMask`: is used to keep track of a `msg.sender` (participant) rewards over time. When a `msg.sender` joins or leaves the ecosystem, the player mask is updated - - participantMask = previous roundMask OR (current roundMask - TPP) - - `rewards for msg.sender`: roundMask - participantMask - - E.g. Let's assume a total of 6 transactions (smart contract triggers or functions calls) are in place with 10 existing participants (denominator) and 20 tokens (numerator) are minted per transaction. At 2nd transaction, the 11th participant joins the network and exits before 5th transaction, the 11th participant's balance is as follows: - - ``` - t1 roundMask = (20/10) - t2 roundMask = (20/10) + (20/11) - t3 roundMask = (20/10) + (20/11) + (20/11) - t4 roundMask = (20/10) + (20/11) + (20/11) + (20/11) - t5 roundMask = (20/10) + (20/11) + (20/11) + (20/11)+ (20/10) - t6 roundMask = (20/10) + (20/11) + (20/11) + (20/11)+ (20/10) + (20/10) - ``` - - Total tokens released in 6 transactions = 60 tokens - - As the participant joins at t2 and leaves before t5, the participant deserves the rewards between t2 and t4. When the participant joins at t2, the 'participantMask = (20/10)', when the participant leaves before t5, the cumulative deserved reward tokens are : - - rewards for msg.sender: `[t4 roundMask = (20/10) + (20/11)+ (20/11) + (20/11)] - [participantMask = (20/10)] = [rewards = (20/11)+ (20/11) + (20/11)]` - - When the same participant joins the ecosystem at a later point (t27 or t35), a new 'participantMask' is given that is used to calculate the new deserved reward tokens when the participant exits. This process continues dynamically for each participant. - - `tokensPerBlock`: the amount of tokens that will be released per block - - `blockFreezeInterval`: the number of blocks that need to pass until the next mint. E.g. if set to 50 and 'n' tokens were minted at block 'b', the next 'n' tokens won't be minted until 'b + 50' blocks have passed - - `lastMintedBlockNumber`: the block number on which last 'n' tokens were minted - - `totalParticipants` : the total number of participants in the DApp network - - `tokencontractAddress` : the contract address to which tokens will be minted, default is address(this) - -``` -SOLIDITY - -pragma solidity ^0.5.2; - -import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol"; -import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; - -contract Rewards is ERC20Mintable, ERC20Detailed { - -using SafeMath for uint256; - -uint256 public roundMask; -uint256 public lastMintedBlockNumber; -uint256 public totalParticipants = 0; -uint256 public tokensPerBlock; -uint256 public blockFreezeInterval; -address public tokencontractAddress = address(this); -mapping(address => uint256) public participantMask; - -/** - * @dev constructor, initializes variables. - * @param _tokensPerBlock The amount of token that will be released per block, entered in wei format (E.g. 1000000000000000000) - * @param _blockFreezeInterval The amount of blocks that need to pass (E.g. 1, 10, 100) before more tokens are brought into the ecosystem. - */ - constructor(uint256 _tokensPerBlock, uint256 _blockFreezeInterval) public ERC20Detailed("Simple Token", "SIM", 18){ -lastMintedBlockNumber = block.number; -tokensPerBlock = _tokensPerBlock; -blockFreezeInterval = _blockFreezeInterval; -} - -/** - * @dev Modifier to check if msg.sender is whitelisted as a minter. - */ -modifier isAuthorized() { -require(isMinter(msg.sender)); -_; -} - -/** - * @dev Function to add participants in the network. - * @param _minter The address that will be able to mint tokens. - * @return A boolean that indicates if the operation was successful. - */ -function addMinters(address _minter) external returns (bool) { -_addMinter(_minter); -totalParticipants = totalParticipants.add(1); -updateParticipantMask(_minter); -return true; -} - - -/** - * @dev Function to remove participants in the network. - * @param _minter The address that will be unable to mint tokens. - * @return A boolean that indicates if the operation was successful. - */ -function removeMinters(address _minter) external returns (bool) { -totalParticipants = totalParticipants.sub(1); -_removeMinter(_minter); -return true; -} - - -/** - * @dev Function to introduce new tokens in the network. - * @return A boolean that indicates if the operation was successful. - */ -function trigger() external isAuthorized returns (bool) { -bool res = readyToMint(); -if(res == false) { -return false; -} else { -mintTokens(); -return true; -} -} - -/** - * @dev Function to withdraw rewarded tokens by a participant. - * @return A boolean that indicates if the operation was successful. - */ -function withdraw() external isAuthorized returns (bool) { -uint256 amount = calculateRewards(); -require(amount >0); -ERC20(tokencontractAddress).transfer(msg.sender, amount); -} - -/** - * @dev Function to check if new tokens are ready to be minted. - * @return A boolean that indicates if the operation was successful. - */ -function readyToMint() public view returns (bool) { -uint256 currentBlockNumber = block.number; -uint256 lastBlockNumber = lastMintedBlockNumber; -if(currentBlockNumber > lastBlockNumber + blockFreezeInterval) { -return true; -} else { -return false; -} -} - -/** - * @dev Function to calculate current rewards for a participant. - * @return A uint that returns the calculated rewards amount. - */ -function calculateRewards() private returns (uint256) { -uint256 playerMask = participantMask[msg.sender]; -uint256 rewards = roundMask.sub(playerMask); -updateParticipantMask(msg.sender); -return rewards; -} - -/** - * @dev Function to mint new tokens into the economy. - * @return A boolean that indicates if the operation was successful. - */ -function mintTokens() private returns (bool) { -uint256 currentBlockNumber = block.number; -uint256 tokenReleaseAmount = (currentBlockNumber.sub(lastMintedBlockNumber)).mul(tokensPerBlock); -lastMintedBlockNumber = currentBlockNumber; -mint(tokencontractAddress, tokenReleaseAmount); -calculateTPP(tokenReleaseAmount); -return true; -} - - /** -* @dev Function to calculate TPP (token amount per participant). -* @return A boolean that indicates if the operation was successful. -*/ -function calculateTPP(uint256 tokens) private returns (bool) { -uint256 tpp = tokens.div(totalParticipants); -updateRoundMask(tpp); -return true; -} - - /** -* @dev Function to update round mask. -* @return A boolean that indicates if the operation was successful. -*/ -function updateRoundMask(uint256 tpp) private returns (bool) { -roundMask = roundMask.add(tpp); -return true; -} - - /** -* @dev Function to update participant mask (store the previous round mask) -* @return A boolean that indicates if the operation was successful. -*/ -function updateParticipantMask(address participant) private returns (bool) { -uint256 previousRoundMask = roundMask; -participantMask[participant] = previousRoundMask; -return true; -} - -} -``` - -## Rationale - -Currently, there is no standard for a scalable reward distribution mechanism. In order to create a sustainable cryptoeconomic environment within DAPPs, incentives play a large role. However, without a scalable way to distribute rewards to tens of thousands of participants, most DAPPs lack a good incentive structure. The ones with a sustainable cryptoeconomic environment depend heavily on centralized servers or a group of selective nodes to trigger the smart contracts. But, in order to keep an application truly decentralized, the reward distribution mechanism must depend on the active participants itself and scale as the number of participants grow. This is what this EIP intends to accomplish. - -## Backwards Compatibility - -Not Applicable. - -## Test Cases - -WIP, will be added. - -## Implementation - -WIP, a proper implementation will be added later.A sample example is below: - -`etherscan rewards contract` : https://ropsten.etherscan.io/address/0x8b0abfc541ab7558857816a67e186221adf887bc#tokentxns - -`Step 1` : deploy Rewards contract with the following parameters_tokensPerBlock = 1e18, _blockFreezeInterval = 1 - -`Step 2` : add Alice(0x123) and Bob(0x456) as minters, addMinters(address _minter) - -`Step 3` : call trigger() from Alice / Bob's account. 65 blocks are passed, hence 65 SIM tokens are minted. The RM is 32500000000000000000 - -`Step 4` : Alice withdraws and receives 32.5 SIM tokens (65 tokens / 2 participants) and her PM = 32500000000000000000 - -`Step 5` : add Satoshi(0x321) and Vitalik(0x654) as minters, addMinters(address _minter) - -`Step 6` : call trigger() from Alice / Bob's / Satoshi / Vitalik account. 101 blocks are passed, hence 101 SIM tokens are minted. The RM is 57750000000000000000 - -`Step 7` : Alice withdraws and receives 25.25 SIM tokens (101 tokens / 4 participants) and her PM = 57750000000000000000 - -`Step 8` : Bob withdraws and receives 57.75 SIM tokens ((65 tokens / 2 participants) + (101 tokens / 4 participants)). Bob's PM = 57750000000000000000 - -## Copyright - -Copyright and related rights waived via CC0. - -## References - -1. Scalable Reward Distribution on the Ethereum Blockchain by Bogdan Batog, Lucian Boca and Nick Johnson - -2. Fomo3d DApp, https://fomo3d.hostedwiki.co/ \ No newline at end of file +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1973.md diff --git a/EIPS/eip-198.md b/EIPS/eip-198.md index a57c4cf194b2c8..5c8f066acb210c 100644 --- a/EIPS/eip-198.md +++ b/EIPS/eip-198.md @@ -1,7 +1,7 @@ --- eip: 198 title: Big integer modular exponentiation -author: Vitalik Buterin +author: Vitalik Buterin (@vbuterin) status: Final type: Standards Track category: Core @@ -101,4 +101,4 @@ The bit-based exponent calculation is done specifically to fairly charge for the # Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1985.md b/EIPS/eip-1985.md index 8f3eca24a883bb..9bb02f1635f7b6 100644 --- a/EIPS/eip-1985.md +++ b/EIPS/eip-1985.md @@ -3,7 +3,7 @@ eip: 1985 title: Sane limits for certain EVM parameters author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast) discussions-to: https://ethereum-magicians.org/t/eip-1985-sane-limits-for-certain-evm-parameters/3224 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-08-01 @@ -25,23 +25,24 @@ by eliminating unrealistic edge cases. ## Specification If `block.number >= {FORK_BLOCK}`, the following value ranges are introduced. -They restrict the results (i.e. values pushed to the stack) of the opcodes listed below. +They restrict the results (i.e. values pushed to the stack) of the instructions listed below. 1. *gas*, *gas limit*, *block gas limit* - is a range between `0` and `9223372036854775807` (`2**63 - 1`). - It affects following the opcodes: + is a range between `0` and `0x7fffffffffffffff` (`2**63 - 1`, `9223372036854775807`). + It affects the following instructions: - `GASLIMIT` (`0x45`), - `GAS` (`0x5a`). 2. *block number*, *timestamp* - is a range between `0` and `9223372036854775807` (`2**63 - 1`). - It affects the following opcodes: + is a range between `0` and `0x7fffffffffffffff` (`2**63 - 1`, `9223372036854775807`). + It affects the following instructions: - `TIMESTAMP` (`0x42`), - `NUMBER` (`0x43`). 3. *account address* - is a range between `0` and `1461501637330902918203684832716283019655932542975` (`2**160 - 1`). - It affects the following opcodes: + is a range between `0` and `0xffffffffffffffffffffffffffffffffffffffff` (`2**160 - 1`, `1461501637330902918203684832716283019655932542975`) + i.e. the address occupies the 160 low bits of the 256-bit value and the remaining top 96 bits must be zeros. + It affects the following instructions: - `ADDRESS` (`0x30`), - `ORIGIN` (`0x32`), - `CALLER` (`0x33`), @@ -49,14 +50,15 @@ They restrict the results (i.e. values pushed to the stack) of the opcodes liste - `CREATE` (`0xf0`), - `CREATE2` (`0xf5`). -4. *buffer size* - is a range between `0` and `4294967295` (`2**32 - 1`). - It affects the following opcodes: +4. *buffer size*, *code size*, *memory size* + is a range between `0` and `0xffffffff` (`2**32 - 1`, `4294967295`). + It affects the following instructions: - `CALLDATASIZE` (`0x36`), - `CODESIZE` (`0x38`), - `EXTCODESIZE` (`0x3b`), - `RETURNDATASIZE` (`0x3d`), - - `MSIZE` (`0x59`). + - `MSIZE` (`0x59`), + - `PC` (`0x58`). ## Rationale @@ -84,10 +86,24 @@ IEEE Std 1003.1-2001 (POSIX.1) leaves that definition implementation defined. The size of addresses is specified in the [Yellow Paper] as 20 bytes. E.g. the `COINBASE` instruction is specified to return *H*c ∈ 𝔹20 which has 20 bytes. +### Memory size + +Memory expansion cost is not linear and is determined by the following formula: + cost = cost_per_word * number_of_words + (number_of_words ^ 2 / 512) + +Expanding to over `2^32 - 1` bytes would cost `35184774742016` gas. This number fits into the gas limit imposed above (`2 ^ 63 - 1`) and would cost around 35184 Ether in a transaction to exhaust, with a 1 GWei gas cost, which can be attained on mainnet. + +However, setting the limit `2^32 - 1` is beneficial from a VM design perspective and we believe limiting memory should be done via carefully selecting the block gas limit. + +### Code size + +[EIP-170](./eip-170.md) has implemented a code size limit of 0x6000, however even before that, it was practically impossible to deploy a code blob exceeding `2**32 - 1` bytes in size. + ### Comparing current implementations - Timestamp is implemented as a 64-bit value in [Aleth], [geth] and [Parity] - Block gas limit is implemented as a 64-bit in [Aleth] and [geth] +- Memory, buffer and code sizes are implemented as 64-bit values in [geth] ## Backwards Compatibility @@ -103,14 +119,15 @@ TBA ## References -[EIP-106](https://github.com/ethereum/EIPs/issues/106) proposed the block gas limit to be limited at `2**63 - 1`. +- [EIP-92](https://github.com/ethereum/EIPs/issues/92) proposed the transaction gas limit to be limited at `2**63 - 1` and had a lengthy discussion about other limits. +- [EIP-106](https://github.com/ethereum/EIPs/issues/106) proposed the block gas limit to be limited at `2**63 - 1`. ## TODO 1. Does the gas limit apply to the gas argument for call instructions? ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). [EVMC]: https://github.com/ethereum/evmc [Aleth]: https://github.com/ethereum/aleth diff --git a/EIPS/eip-1996.md b/EIPS/eip-1996.md new file mode 100644 index 00000000000000..3305a10c98c649 --- /dev/null +++ b/EIPS/eip-1996.md @@ -0,0 +1,7 @@ +--- +eip: 1996 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1996.md diff --git a/EIPS/eip-2.md b/EIPS/eip-2.md index bbdf97deae53d0..fd1da487b992ff 100644 --- a/EIPS/eip-2.md +++ b/EIPS/eip-2.md @@ -1,7 +1,7 @@ --- eip: 2 title: Homestead Hard-fork Changes -author: Vitalik Buterin +author: Vitalik Buterin (@vbuterin) status: Final type: Standards Track category: Core @@ -10,7 +10,7 @@ created: 2015-11-15 ### Meta reference -[Homestead](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-606.md). +[Homestead](./eip-606.md). ### Parameters @@ -27,7 +27,7 @@ If `block.number >= HOMESTEAD_FORK_BLKNUM`, do the following: 1. The gas cost *for creating contracts via a transaction* is increased from 21,000 to 53,000, i.e. if you send a transaction and the to address is the empty string, the initial gas subtracted is 53,000 plus the gas cost of the tx data, rather than 21,000 as is currently the case. Contract creation from a contract using the `CREATE` opcode is unaffected. 2. All transaction signatures whose s-value is greater than `secp256k1n/2` are now considered invalid. The ECDSA recover precompiled contract remains unchanged and will keep accepting high s-values; this is useful e.g. if a contract recovers old Bitcoin signatures. 3. If contract creation does not have enough gas to pay for the final gas fee for adding the contract code to the state, the contract creation fails (i.e. goes out-of-gas) rather than leaving an empty contract. -4. Change the difficulty adjustment algorithm from the current formula: `block_diff = parent_diff + parent_diff // 2048 * (1 if block_timestamp - parent_timestamp < 13 else -1) + int(2**((block.number // 100000) - 2))` (where the ` + int(2**((block.number // 100000) - 2))` represents the exponential difficulty adjustment component) to `block_diff = parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99) + int(2**((block.number // 100000) - 2))`, where `//` is the integer division operator, eg. `6 // 2 = 3`, `7 // 2 = 3`, `8 // 2 = 4`. The `minDifficulty` still defines the minimum difficulty allowed and no adjustment may take it below this. +4. Change the difficulty adjustment algorithm from the current formula: `block_diff = parent_diff + parent_diff // 2048 * (1 if block_timestamp - parent_timestamp < 13 else -1) + int(2**((block.number // 100000) - 2))` (where the `int(2**((block.number // 100000) - 2))` represents the exponential difficulty adjustment component) to `block_diff = parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99) + int(2**((block.number // 100000) - 2))`, where `//` is the integer division operator, eg. `6 // 2 = 3`, `7 // 2 = 3`, `8 // 2 = 4`. The `minDifficulty` still defines the minimum difficulty allowed and no adjustment may take it below this. # Rationale diff --git a/EIPS/eip-20-token-standard.md b/EIPS/eip-20-token-standard.md deleted file mode 100644 index b77c0de5b610d8..00000000000000 --- a/EIPS/eip-20-token-standard.md +++ /dev/null @@ -1 +0,0 @@ -Moved to [EIP 20](https://eips.ethereum.org/EIPS/eip-20). diff --git a/EIPS/eip-20.md b/EIPS/eip-20.md index a84396df6856f1..3f36b8ed23d8d4 100644 --- a/EIPS/eip-20.md +++ b/EIPS/eip-20.md @@ -1,193 +1,7 @@ --- eip: 20 -title: ERC-20 Token Standard -author: Fabian Vogelsteller , Vitalik Buterin -type: Standards Track category: ERC -status: Final -created: 2015-11-19 +status: Moved --- -## Simple Summary - -A standard interface for tokens. - - -## Abstract - -The following standard allows for the implementation of a standard API for tokens within smart contracts. -This standard provides basic functionality to transfer tokens, as well as allow tokens to be approved so they can be spent by another on-chain third party. - - -## Motivation - -A standard interface allows any tokens on Ethereum to be re-used by other applications: from wallets to decentralized exchanges. - - -## Specification - -## Token -### Methods - -**NOTES**: - - The following specifications use syntax from Solidity `0.4.17` (or above) - - Callers MUST handle `false` from `returns (bool success)`. Callers MUST NOT assume that `false` is never returned! - - -#### name - -Returns the name of the token - e.g. `"MyToken"`. - -OPTIONAL - This method can be used to improve usability, -but interfaces and other contracts MUST NOT expect these values to be present. - - -``` js -function name() public view returns (string) -``` - - -#### symbol - -Returns the symbol of the token. E.g. "HIX". - -OPTIONAL - This method can be used to improve usability, -but interfaces and other contracts MUST NOT expect these values to be present. - -``` js -function symbol() public view returns (string) -``` - - - -#### decimals - -Returns the number of decimals the token uses - e.g. `8`, means to divide the token amount by `100000000` to get its user representation. - -OPTIONAL - This method can be used to improve usability, -but interfaces and other contracts MUST NOT expect these values to be present. - -``` js -function decimals() public view returns (uint8) -``` - - -#### totalSupply - -Returns the total token supply. - -``` js -function totalSupply() public view returns (uint256) -``` - - - -#### balanceOf - -Returns the account balance of another account with address `_owner`. - -``` js -function balanceOf(address _owner) public view returns (uint256 balance) -``` - - - -#### transfer - -Transfers `_value` amount of tokens to address `_to`, and MUST fire the `Transfer` event. -The function SHOULD `throw` if the message caller's account balance does not have enough tokens to spend. - -*Note* Transfers of 0 values MUST be treated as normal transfers and fire the `Transfer` event. - -``` js -function transfer(address _to, uint256 _value) public returns (bool success) -``` - - - -#### transferFrom - -Transfers `_value` amount of tokens from address `_from` to address `_to`, and MUST fire the `Transfer` event. - -The `transferFrom` method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. -This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. -The function SHOULD `throw` unless the `_from` account has deliberately authorized the sender of the message via some mechanism. - -*Note* Transfers of 0 values MUST be treated as normal transfers and fire the `Transfer` event. - -``` js -function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) -``` - - - -#### approve - -Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount. If this function is called again it overwrites the current allowance with `_value`. - -**NOTE**: To prevent attack vectors like the one [described here](https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/) and discussed [here](https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729), -clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to `0` before setting it to another value for the same spender. -THOUGH The contract itself shouldn't enforce it, to allow backwards compatibility with contracts deployed before - -``` js -function approve(address _spender, uint256 _value) public returns (bool success) -``` - - -#### allowance - -Returns the amount which `_spender` is still allowed to withdraw from `_owner`. - -``` js -function allowance(address _owner, address _spender) public view returns (uint256 remaining) -``` - - - -### Events - - -#### Transfer - -MUST trigger when tokens are transferred, including zero value transfers. - -A token contract which creates new tokens SHOULD trigger a Transfer event with the `_from` address set to `0x0` when tokens are created. - -``` js -event Transfer(address indexed _from, address indexed _to, uint256 _value) -``` - - - -#### Approval - -MUST trigger on any successful call to `approve(address _spender, uint256 _value)`. - -``` js -event Approval(address indexed _owner, address indexed _spender, uint256 _value) -``` - - - -## Implementation - -There are already plenty of ERC20-compliant tokens deployed on the Ethereum network. -Different implementations have been written by various teams that have different trade-offs: from gas saving to improved security. - -#### Example implementations are available at -- [OpenZeppelin implementation](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/9b3710465583284b8c4c5d2245749246bb2e0094/contracts/token/ERC20/ERC20.sol) -- [ConsenSys implementation](https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol) - - -## History - -Historical links related to this standard: - -- Original proposal from Vitalik Buterin: https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs/499c882f3ec123537fc2fccd57eaa29e6032fe4a -- Reddit discussion: https://www.reddit.com/r/ethereum/comments/3n8fkn/lets_talk_about_the_coin_standard/ -- Original Issue #20: https://github.com/ethereum/EIPs/issues/20 - - - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-20.md diff --git a/EIPS/eip-2003.md b/EIPS/eip-2003.md new file mode 100644 index 00000000000000..2081a82ccf3e7c --- /dev/null +++ b/EIPS/eip-2003.md @@ -0,0 +1,135 @@ +--- +eip: 2003 +title: EVMC modules for implementations of precompiled contracts +author: Paweł Bylica (@chfast), Alex Beregszaszi (@axic) +discussions-to: https://github.com/ethereum/evmc/issues/259 +status: Stagnant +type: Standards Track +category: Interface +created: 2019-05-09 +requires: 1352 +--- + +## Abstract + +[EVMC] specifies a generic API for Ethereum execution engines. +This EIP specifies a way of providing implementations of Ethereum precompiled contracts +using the [EVMC VM API]. + + +## Specification + +For the complete [EVMC] specification visit the [EVMC documentation] first. +This EIP is based on and is compatible with EVMC ABI version 6. + +The EVMC module with implementations of precompiled contracts SHOULD: + +1. Advertise the [`EVMC_CAPABILITY_PRECOMPILES`] capability + in the [`get_capabilities()`] method. + +2. Implement the [`execute()`] method in the following way: + + 1. Validate the incoming execution request requirements: + + 1. The message kind ([`evmc_message::kind`]) is a call ([`EVMC_CALL`]). + + 2. The call destination address ([`evmc_message::destination`]) + is within the range of precompiled contracts defined by [EIP-1352]. + + 3. There is no code provided (the `code` argument is `NULL` and `code_size` argument is `0`). + + If the requirements are not fulfilled, abort execution with the [`EVMC_REJECTED`] status code. + + 2. Check if the call destination address ([`evmc_message::destination`]) + targets existing precompiled contract. + Consider the EVM revision ([`evmc_revision`]) requested by + the `rev` parameter of [`execute()`]. + + If yes, execute as follows: + + 1. Inspect the input data ([`evmc_message::input_data`], [`evmc_message::input_size`]) + and calculate the _gas cost_ of the execution. + + 2. Compute the amount of _gas left_ after execution by + subtracting the _gas cost_ from the call gas limit ([`evmc_message::gas`]). + + 3. If _gas left_ is negative, + abort execution with the [`EVMC_OUT_OF_GAS`] status code. + + 4. Otherwise, + execute the code of the precompiled contract, + return the [`EVMC_SUCCESS`] status code, the output and _gas left_ + ([`evmc_result::output_data`], [`evmc_result::output_size`], [`evmc_result::gas_left`]). + + 3. Otherwise, emulate execution of empty code by returning + the [`EVMC_SUCCESS`] status code + and _gas left_ equal the call gas limit ([`evmc_message::gas`]). + +Precompiled contract implementations are allowed to return two more EVMC error codes: +- [`EVMC_FAILURE`] if the failure was caused due to something other than out of gas (e.g. input validation error) +- [`EVMC_REVERT`] if the precompile doesn't want to forfeit all supplied gas (as of May 2019 no such precompile exists) + +The Client is not required to provide the Host interface ([`evmc_context`] argument of [`execute()`] is set to NULL). +Therefore, the precompiled contracts implementation MUST NOT access the `evmc_context`. + + +## Rationale + +It is very unlikely that any precompile will need to access or modify a contract state. +Not requiring the Client to implement the EVMC Host interface removes the big portion of work +needed for full EVMC integration. + + +## Test Cases + +EVMC provides the [evmc-vmtester] tool for checking compatibility with the EVMC specification. + + +## Implementations + +- [Example of Precompiles VM implementation][example_precompiles_vm.cpp] +- [ewasm precompiles] +- Aleth code for precompiles +- Parity code for precompiles +- [EIP-1962 implemented as an EVMC precompile module](https://github.com/axic/eip1962-evmc) + + +## References + +- [EVMC – Ethereum Client-VM Connector API][EVMC] +- [EVMC documentation] +- [EVMC VM Implementation Guide][EVMC VM API] +- [EIP 1352: Specify restricted address range for precompiles/system contracts][EIP-1352] + + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + + +[EIP-1352]: ./eip-1352.md +[EVMC]: https://github.com/ethereum/evmc +[EVMC documentation]: https://ethereum.github.io/evmc/ +[EVMC VM API]: https://ethereum.github.io/evmc/vmguide.html +[evmc-vmtester]: https://evmc.ethereum.org/vmtester.html +[example_precompiles_vm.cpp]: https://github.com/ethereum/evmc/blob/master/examples/example_precompiles_vm/example_precompiles_vm.cpp +[ewasm precompiles]: https://github.com/ewasm/ewasm-precompiles + +[`EVMC_CALL`]: https://ethereum.github.io/evmc/group__EVMC.html#ggab2fa68a92a6828064a61e46060abc634abcf3ae29d9a88ff70b98374fc665694a +[`EVMC_CAPABILITY_PRECOMPILES`]: https://ethereum.github.io/evmc/group__EVMC.html#gga44f9ecb88cf6422a0072936494fd6ac7a43ea2aa7b099a2d67bc53c118ff3683d +[`EVMC_FAILURE`]: https://ethereum.github.io/evmc/group__EVMC.html#gga4c0be97f333c050ff45321fcaa34d920aed5b2a4afa5a47af732569445920a4a9 +[`EVMC_OUT_OF_GAS`]: https://ethereum.github.io/evmc/group__EVMC.html#gga4c0be97f333c050ff45321fcaa34d920abfc47f75656c996c0b29c0553c00fc18 +[`EVMC_REJECTED`]: https://ethereum.github.io/evmc/group__EVMC.html#gga4c0be97f333c050ff45321fcaa34d920a2f3e0d8777f8d974ead27ae2a6eb2005 +[`EVMC_REVERT`]: https://ethereum.github.io/evmc/group__EVMC.html#gga4c0be97f333c050ff45321fcaa34d920aed708e84d49cc1270e54ec20b0ca0a05 +[`EVMC_SUCCESS`]: https://ethereum.github.io/evmc/group__EVMC.html#gga4c0be97f333c050ff45321fcaa34d920a4bc3069fec2bab2a55355a72b7db68b7 +[`execute()`]: https://ethereum.github.io/evmc/structevmc__instance.html#a0823ebff21f9b0395b157e8c6b14a207 +[`get_capabilities()`]: https://ethereum.github.io/evmc/structevmc__instance.html#ae63b9ca898aa41cbd1e2fe86ca8f4e1c +[`evmc_message::destination`]: https://ethereum.github.io/evmc/structevmc__message.html#a88ecfaa03a85a31c6da36fa043b98cea +[`evmc_message::input_data`]: https://ethereum.github.io/evmc/structevmc__message.html#a1adee3454b105eb29cd659ee0cf65c77 +[`evmc_message::input_size`]: https://ethereum.github.io/evmc/structevmc__message.html#a2cf1deebd0dbbb20f25ecdfa299f4b5d +[`evmc_message::gas`]: https://ethereum.github.io/evmc/structevmc__message.html#ae8deff46588584fa27890e74c82db5e7 +[`evmc_message::kind`]: https://ethereum.github.io/evmc/structevmc__message.html#a691cb93e81d6dfd4fd7e2fa3d06a6bfa +[`evmc_result::gas_left`]: https://ethereum.github.io/evmc/structevmc__result.html#af8478c93dbcc3cb2876037c5a5afd4c0 +[`evmc_result::output_data`]: https://ethereum.github.io/evmc/structevmc__result.html#a61978e85f9d795a7b9695b9cbf1748d6 +[`evmc_result::output_size`]: https://ethereum.github.io/evmc/structevmc__result.html#a93bb7419aff492cdef754421c6d74e26 +[`evmc_revision`]: https://ethereum.github.io/evmc/group__EVMC.html#gae5759b1590071966ccf6a505b52a0ef7 diff --git a/EIPS/eip-2009.md b/EIPS/eip-2009.md new file mode 100644 index 00000000000000..8fe47e1a42df3d --- /dev/null +++ b/EIPS/eip-2009.md @@ -0,0 +1,7 @@ +--- +eip: 2009 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2009.md diff --git a/EIPS/eip-2014.md b/EIPS/eip-2014.md index 95c88d908f0e8a..3eacb6bdfe27f5 100644 --- a/EIPS/eip-2014.md +++ b/EIPS/eip-2014.md @@ -3,7 +3,7 @@ eip: 2014 title: Extended State Oracle author: Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/eip-2014-extended-state-oracle/3301 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-10 @@ -11,7 +11,6 @@ requires: 140 --- ## Simple Summary - ## Abstract @@ -72,23 +71,27 @@ This will be translated into sending the bytes `5cf0e8a4` to the ESO and returni **Note:** It should be possible to introduce another interface checking the validity of a chain identifier in the chain history or for a given block (see [EIP-1959] and [EIP-1965]). ## Rationale - + +TBA ## Backwards Compatibility - + +TBA ## Test Cases - + +TBA ## Implementation - + +TBA ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). [Contract ABI Encoding]: https://solidity.readthedocs.io/en/latest/abi-spec.html -[EIP-140]: https://eips.ethereum.org/EIPS/eip-140 -[EIP-210]: https://eips.ethereum.org/EIPS/eip-210 -[EIP-1344]: https://eips.ethereum.org/EIPS/eip-1344 +[EIP-140]: ./eip-140.md +[EIP-210]: ./eip-210.md +[EIP-1344]: ./eip-1344.md [EIP-1959]: https://github.com/ethereum/EIPs/pull/1959 [EIP-1965]: https://github.com/ethereum/EIPs/pull/1965 diff --git a/EIPS/eip-2015.md b/EIPS/eip-2015.md index f3f0a1878575d9..d5b4d3aaecb308 100644 --- a/EIPS/eip-2015.md +++ b/EIPS/eip-2015.md @@ -1,81 +1,74 @@ --- eip: 2015 -title: Wallet Update Chain JSON-RPC Method (`wallet_updateChain`) -author: Pedro Gomes (@pedrouid) +title: wallet_updateEthereumChain RPC Method +description: Adds an RPC method to switch between EVM-compatible chains +author: Pedro Gomes (@pedrouid), Erik Marks (@rekmarks), Pandapip1 (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/eip-2015-wallet-update-chain-json-rpc-method-wallet-updatechain/3274 -status: Draft +status: Stagnant type: Standards Track -category: ERC +category: Interface created: 2019-05-12 -requires: 155, 1474 +requires: 155 --- -## Simple Summary -Wallets can update the active chain when connected to a Dapp but not vice-versa, with `wallet_updateChain` the Dapp will be able to request this change from the Wallet. - ## Abstract -Dapp can request the Wallet to switch chains by providing the minimal parameters of `chainId`, `networkId`, `rpcUrl` and `nativeCurrency`. The Wallet will display a UI element to inform the user of this change. -## Motivation -Wallet and Dapp communication rely on the present provider that acts as middleware between the two. Using JSON-RPC methods, the Dapp is able to access not only the active accounts but also the active chain. With [EIP-1102](https://eips.ethereum.org/EIPS/eip-1102) we introduced the ability for Dapps to request access to the active accounts and the Wallet is able to provide a simple UI to inform the user of this action however the same is not currently possible for switching chains. The current pattern is to display some UI to request the user to switch chains within the Dapp, however this could be easily improved by triggering a UI from the Wallet side that can be approved or rejected by the user instead. +This EIP adds a wallet-namespaced RPC endpoint, `wallet_updateEthereumChain`, providing a standard interface for switching chains. The method takes the minimal parameters of `chainId`, `chainName`, `rpcUrl`, `nativeCurrency` and `blockExplorerUrl`. ## Specification -The JSON RPC method will be part of `wallet_` namespaced methods which aim to improve the UX and interoperability between Dapps and Wallets. - -### Required Parameters -- chainId (number): the id of the chain complaint with EIP-155 -- networkId (number): the id of the chain's network -- rpcUrl (string): the url endpoint for RPC requests for this chain -- nativeCurrency (Object): includes two fields for `name` (string) and `symbol` (string) - - -### Best Practices -- The Wallet should display a UI view similar to a [EIP-1102](https://eips.ethereum.org/EIPS/eip-1102) informing the user that the currently connected Dapp wants to switch to the specified chain. -- the Wallet should default the rpcUrl to any existing endpoints matching a chainId known previously to the wallet, otherwise it will use the provided rpcUrl as a fallback. -- the Wallet should call the rpcUrl with `net_version` and `eth_chainId` to verify the provided chainId and networkId match the responses from the rpcUrl -- the Wallet should change all nativeCurrency symbols to the provided parameter - -### Example 1 -A JSON-RPC request from a Dapp to switch the Ethereum Goerli chain would be as follows: -```json -{ - "id":1, - "jsonrpc": "2.0", - "method": "wallet_updateChain", - "params": [ - { - "chainId": 5, - "networkId": 5, - "rpcUrl": "https://goerli.infura.io/v3/406405f9c65348f99d0d5c27104b2213", - "nativeCurrency": { - "name": "Goerli ETH", - "symbol": "gorETH" - } - } - ] + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. + +This proposal adds a method to a wallet's web3 provider API: `wallet_updateEthereumChain`. + +### `wallet_updateEthereumChain` + +The `wallet_updateEthereumChain` method is used to switch to a network, and registering it with the wallet if it isn't already recognized. + +The `wallet_updateEthereumChain` method takes one parameter, an `EthereumChainSwitchRequest` object, defined below: + +```typescript +interface NativeCurrencyData { + name: string; + symbol: string; + decimals: number; } -``` -### Example 2 -A JSON-RPC request from a Dapp to switch the POA Network's xDAI chain would be as follows: -```json -{ - "id":1, - "jsonrpc": "2.0", - "method": "wallet_updateChain", - "params": [ - { - "chainId": 100, - "networkId": 100, - "rpcUrl": "https://dai.poa.network", - "nativeCurrency": { - "name": "xDAI", - "symbol": "xDAI" - } - } - ] +interface EthereumChainSwitchRequest { + chainId: string; + chainName?: string; + rpcUrls?: string[]; + nativeCurrency?: NativeCurrencyData; + blockExplorerUrl?: string; } ``` +The `chainId` is the `0x`-prefixed [EIP-155](./eip-155.md)-compliant chain ID. The `chainName` is a suggested human-readable name of the chain, to be displayed to the user. The `rpcUrls` array is a list of RPC endpoints for the given `chainId`. The `nativeCurrency` object suggests how the native currency should be displayed. Its parameters, `name`, `symbol`, and `decimals`, should be interpreted like in [ERC-20](./eip-20.md). Finally, the `blockExplorerUrl` should link to a block explorer compatible with the given `chainId`. + +All keys other than the `chainId` are optional. All keys other than `chainId` are suggestions to the wallet. Wallets can choose to ignore or display other data to users. Wallets should prompt the user before switching or adding chains. Wallets should also store a default list of data for commonly-used chains, in order to avoid phishing attacks. Wallets MUST sanitize each RPC url before using it to send other requests, including ensuring that it responds correctly to the `net_version` and `eth_chainId` methods. + +The `wallet_updateEthereumChain` method returns `true` if the active chain matches the requested chain, regardless of whether the chain was already active or was added to the wallet previously. If the user rejects the request, it must return an error with code `4001`. + +## Rationale + +The `wallet_updateEthereumChain` method is designed to be as simple as possible, while still providing the necessary information for a wallet to switch to a new chain. The `chainId` is the only required parameter, as it is the only parameter that is guaranteed to be unique. The `chainName` is included to provide a human-readable name for the chain, and the `rpcUrls` array is included to provide a list of RPC endpoints for the chain. The `nativeCurrency` object is included to provide a suggestion for how the native currency should be displayed. Finally, the `blockExplorerUrl` is included to provide a link to a block explorer for the chain. + +The `wallet_updateEthereumChain` method is namespaced under `wallet_` to avoid conflicts with other methods. The `wallet_` prefix is used by other methods that are wallet-specific, such as `wallet_addEthereumChain` and `wallet_switchEthereumChain`. + +## Backwards Compatibility + +This EIP is fully backwards compatible. + +## Security Considerations + +### Server-Side Request Forgery (SSRF) + +The `rpcUrls` parameter is a list of RPC endpoints for the chain. Wallets should sanitize each RPC url before using it to send other requests, including ensuring that it responds correctly to the `net_version` and `eth_chainId` methods. + +### Phishing + +Wallets should store a default list of data for commonly-used chains, in order to avoid phishing attacks. + ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2018.md b/EIPS/eip-2018.md new file mode 100644 index 00000000000000..dce10628acf0ae --- /dev/null +++ b/EIPS/eip-2018.md @@ -0,0 +1,7 @@ +--- +eip: 2018 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2018.md diff --git a/EIPS/eip-2019.md b/EIPS/eip-2019.md new file mode 100644 index 00000000000000..c4ad7b3c4f315d --- /dev/null +++ b/EIPS/eip-2019.md @@ -0,0 +1,7 @@ +--- +eip: 2019 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2019.md diff --git a/EIPS/eip-2020.md b/EIPS/eip-2020.md new file mode 100644 index 00000000000000..9cdaef6e9f076d --- /dev/null +++ b/EIPS/eip-2020.md @@ -0,0 +1,7 @@ +--- +eip: 2020 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2020.md diff --git a/EIPS/eip-2021.md b/EIPS/eip-2021.md new file mode 100644 index 00000000000000..a4f4befe9f91ca --- /dev/null +++ b/EIPS/eip-2021.md @@ -0,0 +1,7 @@ +--- +eip: 2021 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2021.md diff --git a/EIPS/eip-2025.md b/EIPS/eip-2025.md new file mode 100644 index 00000000000000..445a348a54c1dc --- /dev/null +++ b/EIPS/eip-2025.md @@ -0,0 +1,212 @@ +--- +eip: 2025 +title: Block Rewards Proposal for funding Eth1.x +author: James Hancock (@madeoftin) +discussions-to: https://github.com/MadeofTin/EIPs/issues +status: Withdrawn +type: Standards Track +category: Core +created: 2019-04-20 +requires: 1890 +--- + +## Simple Summary + +Add `0.0055 ETH` per block for 18 months (A total of 17050 ETH) as a developer block reward reserved for funding specific Ethereum1.X working groups. The working groups are State rent (750k), Better sync (360k), Finality gadget (360k), Fee market (360k), Testing infrastructure (360k). Governance of the funds will be through a multisig of trusted individuals from the ecosystem including client teams, the foundation, and the community. + +[EIP-1890](./eip-1890.md) proposes a mechanism to capture a portion of block rewards for sustainably funding ongoing network development. That EIP sets values and addresses to zero and so does not actually collect any rewards. This proposal is to explicitly set those values and begin collecting a portion of block rewards for 18 months in order to fund Ethereum 1.X working groups and organization efforts. This funding will be used to repay an initial loan provided by investors in the community funding this work with a small amount of interest. After 18 months the block reward would again reduce to zero. + +## Abstract + +This EIP extends the mechanism established in EIP-1890 to add `0.0055 ETH` to the block reward for a specific distribution period of `3,100,000 BLOCKS`(≈ 18 months). The `RECIPIENT_ADDRESS` is set to a smart contract with hardcoded denominations that distributes incoming ETH to a set of addresses for the purpose of Eth1.X development. The emission schedule would start at the hard fork block number and continue for `3,100,000 BLOCKS` (≈ 18 months) at which point the address and amount would again return to 0. Any further distribution would require a future hard fork. + +## Motivation + +The context for this proposal came from attending the [Core Dev Eth1.X Meeting](https://www.youtube.com/watch?v=Au1Qll-86v0) in Berlin. Development is needed to move Eth1.X forward, and I observed that a lack of funding is the primary barrier to this work. This work can only be effectively conducted by working groups forming around these issues, and these working groups need funding in order to pay dedicated contractors and project managers. This proposal is a plan for funding these groups and supporting their operation. + +## Specification + +Two constants will be introduced: + +- `REWARD_DURATION_IN_BLOCKS`, which specifies the number of blocks after `ISTANBUL_BLOCK_HEIGHT` when the reward collection will terminate (i.e., at block `ISTANBUL_BLOCK_HEIGHT + REWARD_DURATION_IN_BLOCKS`) +- `BENEFICIARY_ADDRESSES`, a list of tuples containing the address and the amount to be transferred to this address per block. These amounts will be determined as the loan is collected from participating organizations and the addresses for repayment will be specified by them. The total of the amounts will sum to 0.0055. At the end of `REWARD_DURATION_IN_BLOCKS` the loan will be completely repaid. + +``` + +REWARD_DURATION_IN_BLOCKS = 3100000 +DEVFUND_BLOCK_REWARD = 0.0055 + + + +BENEFICIARY_ADDRESSES = [ + (
, ), + (
, ) +] +``` + +Beginning with block `ISTANBUL_BLOCK_HEIGHT`, the reward is added to the participating addresses within `BENEFICIARY_ADDRESSES` at each block until the end of the `REWARD_DURATION_IN_BLOCKS`. + +``` +IF (CURRENT_BLOCK - ISTANBUL_BLOCK_HEIGHT <= REWARD_DURATION_IN_BLOCKS) + +FOR BENEFICIARY in BENEFICIARY_ADDRESSES: + BENEFICIARY[0].balance += BENEFICIARY[1] + +``` + +## Rewards Distribution Rationale + +``` + Development loan repayment: 0.005 ETH per block: 15500 ETH total + Development loan interest (10% total over the period, simple interest): 0.0005 ETH per block: 1550 ETH total + + Total Block Reward Increase = `0.0055` ETH per block: 17050 ETH Total +``` + +*With a price of Ethereum at $150.00 this will raise approx USD $2,325,000.00 for developing Eth1.X over the next 18 months.* + +![Block Rewards Distribution](../assets/eip-2025/block_rewards_distribution.png) *Specific Addresses to be determined + +- [FAQ - Why hardcoded values?]( #why-hardcoded-values ) + + +## Rationale + +There has been great public debate concerning EIP-1890, and one of the primary concerns is that it is difficult to evaluate the proposal without more complete information on how funds would be raised, how they would be administered, and how they would be used. There is a need for funding Eth1.x development and it is currently unclear where those funds will come from. This proposal is intended to give a more comprehensive proposal for its funding. In the case that ETH1.x is fully funded before the Istanbul upgrade I will withdraw this EIP. Until that point I intend to continue championing this proposal as a valid funding mechanism for this work. + +### Why a loan? + +The Eth1x initiative needs funding now, not in 18 months. A loan is necessary to complete certain stages of work before the funding mechanism begins to provide funds. A loan would provide this necessary funding today, and the investors willing to front this cost can recoup their contribution + a reward of *a fixed interest rate* for the risk on their loan. This arrangement will make it easier to find investors willing to participate who have sufficient funds. + +### Loan Repayment + +![Loan State Diagram](../assets/eip-2025/loan_state.png) + +There is a risk that the investors lose part of their contribution in the case that this EIP is rejected by the community between the time the funds have been collected and the beginning of the payout schedule. In this case all remaining funds will be returned to the contributors. The interest on the loan is an incentive for investors to participate in spite of this risk. Their downside is limited to the amount of funds spent before this EIP is accepted or rejected, which should be no more than about 5%, while their upside consists of the 10% simple interest paid over the period. + +### Development Loan + + +`Development Loan: 0.005` over 3.1 Million blocks = 15500 ETH + +**Funding Working Groups on 1.X** + +- Funding Contractors, Coordinators, and project managers +- Working Groups defined with clear mandates + +Budget + +Working groups + + - State rent (750k) + - Better sync (360k) + - finality gadget (360k) + - Fee market (360k) + - testing infrastructure (360k) + + +**ETH1.X Core Dev Gatherings** + +Funding hosting, traveling, and accommodations for necessary in-person gatherings of ETH1.X core developers similar to the Stanford and Berlin ETH1.X Core Dev Meeting held earlier this year. + +At the end of the 18 Months, the whole process would be torn down to prevent any internal tyranny of structurelessness forming within. + + + +- [FAQ - How will the funding of the devs be organized?]( #how-will-funding-the-devs-be-organized) + +## Accountability + +The funds will be transferred into DAI and secured in a multi-sig comprised of members of the community. Representatives from the following groups will receive a key. + + + - EIP Editors + - Geth + - Parity + - ConsenSys/PegaSys (PegaSys) + - The Ethereum Foundation (Hudson Jameson) + - Community + +## Personal Notes and Disclosure + +I want to address any concerns about conflicts of interests directly. My participation with Eth1.X currently has been as a volunteer. I am in talks about a possible funded role helping with testing and coordination. If my work for with Eth1.x is funded, I will accept no additional funding collected by the mechanism proposed in this EIP. + +Eth1.X is the now of Ethereum and I would like to see it succeed. This is the intent of my proposal. + +### COI + +Previously I was PM for Tennagraph, a signalling solution for Ethereum. An Aragon grant funded this project and was distributed through Giveth and an AragonDAO. I have not received any funding from the project beyond this grant. All of this is verifiable on-chain. I am stepping down from any paid role on the project to continue as an advisor. I am also stepping down as a moderator for stances as there is a COI moderating stances for EIPs I am working with directly. + +### Disclaimer + +I do not claim to represent the community with my views; any members who wish to join supporting me with this proposal are free to do so. This is as fair of a proposal as I can personally conceive. + +## Backwards Compatibility + +This EIP has no impact on backwards compatibility. + +## Test Cases + +Not Implemented + +## Implementation + +Not Implemented + +## FAQ + +### Why Hardcoded Values? + +Why not use a smart contract with some governance mechanism to allow changing the distribution of funds? Wouldn’t that be more flexible and effective? + +*TLDR: This EIP is not about governance reform* + +First, the payment of the loan will be hardcoded. Once agreed, the terms must be kept to give the lenders confidence in the repayment of the loan. As long as blocks are created the debt will be paid back. This is the essence of a trustless smart contract. + +After the loan, there is the option to allow the amounts (limited to less than .05ETH), and the locations (orgs that receive ecosystem funding) to be changed throughout the emission schedule. It is pretty easy to imagine a smart contract or DAO fulfilling this role. However, there are three classes of options available today we can consider when governing changes. + +- **Give the Keys to the Hands of the Few (Oligarchy)** + +Create a multisig that allows a group of individuals to update the smart contract. The most likely candidates for this are the Core Devs themselves, but it could also be a trusted few from the community/stakeholders. No matter how you slice it, there is a fundamental issue in deciding who gets to decide. There currently is not a trusted/adopted governance mechanism to make these decisions within the Ethereum ecosystem. Also, preventing changing the contract in self interest is difficult without a well-engineered governance system of checks and balances. This EIP does not claim nor aim to solve these issues. + +- **Give the Keys to the Hands of the Many (Plutarchy)** + +Allow ethereum holders with coin votes to update the smart contract. Using holographic consensus could overcome the issue of voter turnout as it scales as participation scales, even to the size of the whole network. This has some benefits as the entire network can participate. However, the problem is that some individuals in the network are over represented -- the wealthy. Without a solution to identity that has been agreed to and implemented by the entire Ethereum Network, there is no way around giving more power in votes to the rich. This EIP does not claim, nor aim to solve these issues. + +- **Use Ethereum Governance as it is Today** + +Criticisms or support aside, there is a system that governs Ethereum today. It is a mix of rough consensus among core devs, miners running nodes, clients implementing changes, and stakeholders adopting those changes. It includes yelling or not yelling on twitter and reddit. It is complicated and I don’t claim to understand it. Even without a clear view of how it works, there is evidence of its existence. This evidence is there are changes that have allowed to be implemented, and changes that have not allowed to be implemented in Ethereum. + +I do not aim to change Ethereum governance. Because this EIP has hardcoded values, it must go through the existing governance process, whatever that is, before it is implemented. It will then continue to operate until the end of the emission schedule. This is intentional. This makes it uncapturable. No party other then the ecosystem itself can modify the contract once it has been deployed. + +This EIP is not about governance reform. + +### Why not allow current client implementors fund this work? (EF, Consensys, Parity, etc...) + +Historically there has been a precedent that the Ethereum Foundation is solely responsible for funding the development of Ethereum. This process has evolved as the development has become more distributed. Aya Miyaguchi observed in a recent [Coindesk article](https://www.coindesk.com/ethereum-foundation-director-sets-new-vision-for-blockchain-non-profit), “it really is not only Ethereum Foundation people who are building [Ethereum]”. Yes, we could rely on the Ethereum Foundation to fund Eth1.X. But, why should we? This is a call for the network to come together and fund its own development. Ethereum *the network* is not owned by any one organization or group of people. We are lucky to have the EF and I consider this EIP in support of their coordination efforts. + +### How Will Funding the Devs be Organized + +I do not profess to know the best way to organize these funds. There is work already in progress to organize these efforts championed by Alexey Akhunov. The following is a quote from a [recent medium article](https://medium.com/@akhounov/ethereum-1x-as-an-attempt-to-change-the-process-783efa23cf60): + +> “Going from funding a few implementation teams continuously and letting them do 'their stuff' to funding more specific and temporary initiatives requires looking at funding through different lenses. How much 'due diligence' and oversight is too much (in terms of overhead), who can decide whether working groups actually deliver, etc. This is also solvable, and also more on this will come later (not in this post)." + +My suggestion would be to create an Eth1.X core developer DAO using [DaoStack](https://daostack.io/) to coordinate membership and payment of the Core Devs, but ultimately they are capable of determining the system that works best for them. As long as the system is transparent and mature enough to distribute funds when the time comes, this is sufficient for now. + +### Isn't a loan considered a security, or is it? + +I am not a lawyer and will seek further guidance from lawyers in the field on this point in particular. From the research I have done and conversations I have had there is a very good argument that a loan of this nature will not be considered a security by the US Supreme Court. +As the result of [REVES ET AL. v . ERNST YOUNG 1990](https://casetext.com/case/reves-v-ernst-young), the court stated that a home loan, consumer financing, a loan secured by a lien on a small business or some assets of a small business, short term notes, or notes that formalize a debt incurred in the ordinary course of business are not securities. If the note resembles the items listed above (home loans, etc.) then the note will not be deemed a security. The Supreme Court provided four factors to determine if a note sufficiently resembles the types of notes that are not classified as securities. ([source](https://www.invigorlaw.com/loan-subject-securities-regulations/)) + +**Family Resemblance Test** + + 1) The intentions of the company and the individual—if the company raised money for general use in a business enterprise, then the note is more likely to be a security; if the individual agreed to the loan primarily for the profit the note was expected to generate, the note is more likely to be a security. + 2) The plan of distribution—the more widely the note is offered, the more likely it is to be found a security. + 3) The expectations of the investing public—if the investors thought they were investing in a business to make a profit on their investment, the note is more likely to be found a security. + 4) Other risk-reducing factor—if the note is collateralized or otherwise less risky than common notes, the note is less likely to be found to be a security. + +The loan is for the specific use of supporting Eth1.X research and development. The distribution will not be widely offered and the note will be collateralized by the network itself, provided in ETH and repaid in ETH. In coordinating the collection of these funds recognise I may be legally liable for some of this work and I will do all of the due dilegence I can, seek legal counsel, and accept any legal repercussions resulting from this work. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2026.md b/EIPS/eip-2026.md index 376c8c8da5795a..e230dae7c2dbcc 100644 --- a/EIPS/eip-2026.md +++ b/EIPS/eip-2026.md @@ -3,25 +3,20 @@ eip: 2026 title: State Rent H - Fixed Prepayment for accounts author: Alexey Akhunov (@AlexeyAkhunov) discussions-to: https://ethereum-magicians.org/t/eip-2026-fixed-rent-prepayment-for-all-accounts-change-h-from-state-rent-v3-proposal/3273 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-14 --- - - ## Simple Summary - Creation of new accounts (both contracts and non-contracts) requires a fixed one-off rent prepayment. Pre-existed accounts require the same prepayment upon the first modification. The act of rent prepayment causes the addition of an extra field to accounts, called `rentbalance`. This field becomes part of state. ## Abstract - This is part of the State Rent roadmap. This particular change introduces a fixed charge for state expansion that comes from adding new accounts to the state. Theoretically, it puts a bound on the number of accounts that can be ever created, because that fixed charge cannot be recycled via mining. ## Motivation - The penalty is levied to the transaction sender. Rather than raising the gas cost of account creation (that would direct levy towards the miner), this change directs prepayment into the account's special field, `rentbalance`. It addresses several shortcomings of the simple raising of the gas cost: 1. Prepayments cannot be recycled via mining, which puts a theoretical bound on number of accounts in the state (though it is unlikely to ever be reached). 2. It is not possible for miners to circumvent the penalty or to extend such circumventions onto other users (via private fee rebates, for example). @@ -30,10 +25,9 @@ The penalty is levied to the transaction sender. Rather than raising the gas cos 5. Prepayments on pre-existing accounts are necessary to prevent hoarding of accounts ahead of this change. ## Specification - On and after block `H`, every newly created account gets a new field `rentbalance` of type unsigned 256-bit integer. On and after block `H`, any operation that leads to the creation of a new account, deducts the amount `ACCOUNT_PREPAYMENT` from `tx.origin`. This amount is added to the `rentbalance` field of the created account. -On and after block `H`, any operation that modifies an account that does not yet have `rentbalance` field, deducts the amount `ACCOUNT_PREPAYEMENT` from `tx.origin`. This amount is added to the `rentbalance` field of the modified account. This is a anti-hoarding measure. +On and after block `H`, any operation that modifies an account that does not yet have `rentbalance` field, deducts the amount `ACCOUNT_PREPAYEMENT` from `tx.origin`. This amount is added to the `rentbalance` field of the modified account. This is an anti-hoarding measure. Operations leading to the creations of a new account: 1. Creation of a non-contract account by sending non-zero ETH to an address with no associated account @@ -46,26 +40,22 @@ After prepayments are introduced, there can be two reasons for ether to be deduc After prepayments are introduced, `gaslimit` * `gasprice` will still represent the maximum amount of wei spend, but it will be used for both gas purchases and prepayments, as necessary. ## Rationale - Prior to rent prepayments, other alternatives were considered: 1. Simple raising of the gas cost - discussed in the Motivation section. 1. In [first version of State Rent proposal](https://github.com/ledgerwatch/eth_state/blob/master/State_rent.pdf), there was no notion of extra levy upon account creation. It created a slight usability issue, where newly created contracts with 0 endowment would be evicted in the same block (when rent is introduced). It delays the benefits of the State Rent programme until the actual introduction of rent (in second or third hard-fork). 2. In the [second version of State Rent proposal](https://github.com/ledgerwatch/eth_state/blob/master/State_Rent_2.pdf), there was a notion of lock-up. It is very similar to rent prepayment, with the different that lock-up would not be covering future rent payments. -An alternative approach to limiting the prepayments (instead of the using `gaslimit` * `gasprice` as the limit) is to introduce a new dedicated field `prepaymenlimit` into the transaction. This field would only limit prepayments). Such approach would require changes in the transaction format, as well as changes in the user interface for transaction sender, and having two counters during the transaction execution - one for gas, and one for prepayments. +An alternative approach to limiting the prepayments (instead of the using `gaslimit` * `gasprice` as the limit) is to introduce a new dedicated field `prepaymenlimit` into the transaction. This field would only limit prepayments. Such approach would require changes in the transaction format, as well as changes in the user interface for transaction sender, and having two counters during the transaction execution - one for gas, and one for prepayments. ## Backwards Compatibility - This change is not backwards compatible and requires hard fork to be activated. It might have some adverse effects on the existing contracts, due to more gas needed to be allocated for the creation of new accounts. These adverse effects need to analysed in more detail. ## Test Cases - Tests cases will be generated out of a reference implementation. ## Implementation - There will be proof of concept implementation to refine and clarify the specification. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2027.md b/EIPS/eip-2027.md index eb7b4ced6bd712..9faf2ab6a2307b 100644 --- a/EIPS/eip-2027.md +++ b/EIPS/eip-2027.md @@ -3,22 +3,18 @@ eip: 2027 title: State Rent C - Net contract size accounting author: Alexey Akhunov (@AlexeyAkhunov) discussions-to: https://ethereum-magicians.org/t/eip-2027-net-contract-size-accounting-change-c-from-state-rent-v3-proposal/3275 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-14 --- - - ## Simple Summary - Ethereum starts counting the number of storage slots filled and emptied in the contracts. Since the number of pre-existing slots is not currently accounted in the state, effectively, only net change in the number of slots is tracked. In the subsequent change, called *Gross contract size accounting*, the total number of storage slots starts being tracked. ## Abstract - This is part of the State Rent roadmap. This particular change introduces initial, net accounting of the number of the contract storage slots. Though not very useful on its own, it makes it possible to introduce gross accounting of the number of storage slots, which is useful for number of things: 1. Gas cost of operations suchs as `SLOAD` and `SSTORE` will need to be increased to compensate for extra bandwidth consumed by the block proofs. Although in @@ -27,12 +23,10 @@ the beginning the cost would be fixed, it will later be automatically calibrated contract storage present in the state (and therefore being provable via Merkle proofs). ## Motivation - Ethereum currently does not track the number of contract storage slots at all, and producing such number given the downloaded state cannot be done in constant *O(1)* time. ## Specification - Each contract (account with `codeHash` field not equal to 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, which the hash of the empty code) gets a new uint64 field, called `storagesize`. On and after block `C`, the semantics of the operation `SSTORE` (`location`, `value`) changes as follows: - If previous value of the [`location`] is 0, and value is not 0, *increment* `storagesize` (semantics of *increment* described below) - If previous value of the [`location`] is not 0, and value is 0, *decrement* `storagesize` (semantics of *decrement* described below) @@ -54,21 +48,17 @@ Current suggestion is to have `HUGE_NUMBER` = 2^63, which is binary representati The idea is to make it decidable later whether the storagesize was ever incremented/decremented (presence of the field), and whether it has been converted from net to gross (by value being smaller than `HUGE_NUMBER/2` - because it will not be possible for any contract be larger than 2^62 at the block `C`). ## Rationale - A mechanism for estimation of contract storage size has been proposed [here](https://medium.com/@akhounov/estimation-approximate-of-the-size-of-contracst-in-ethereum-4642fe92d6fe). But it does have a big drawback of introducing a lot of complexity into the consensus (in the form of estimation algorithm, which has quite a few edge cases to cater for different sizes of the storage). ## Backwards Compatibility - This change is not backwards compatible and requires hard fork to be activated. Since the newly introduced field is not observable, this change does not impact any operations of the existing smart contracts. ## Test Cases - Tests cases will be generated out of a reference implementation. ## Implementation - There will be proof of concept implementation to refine and clarify the specification. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2028.md b/EIPS/eip-2028.md index 65d535b9e36288..707e63ce5bd00a 100644 --- a/EIPS/eip-2028.md +++ b/EIPS/eip-2028.md @@ -1,16 +1,16 @@ --- eip: 2028 -title: Calldata gas cost reduction -author: Alexey Akhunov (@AlexeyAkhunov), Eli Ben Sasson , Tom Brand , Avihu Levy +title: Transaction data gas cost reduction +author: Alexey Akhunov (@AlexeyAkhunov), Eli Ben Sasson , Tom Brand , Louis Guthmann , Avihu Levy discussions-to: https://ethereum-magicians.org/t/eip-2028-calldata-gas-cost-reduction/3280 -status: Draft +status: Final type: Standards Track category: Core created: 2019-05-03 --- ## Simple Summary -We propose to reduce the gas cost of Calldata (`GTXDATANONZERO`) from its current value of 68 gas per byte to a lower cost, to be backed by mathematical modeling and empirical estimates. The mathematical model is the one used in the works of Sompolinsky and Zohar [1] and Pass, Seeman and Shelat [2], which relates network security to network delay. We shall (1) evaluate the theoretical impact of lower Calldata gas cost on network delay using this model, (2) validate the model empirically, and (3) base the proposed gas cost on our findings. +We propose to reduce the gas cost of Calldata (`GTXDATANONZERO`) from its current value of 68 gas per byte to 16 gas per byte, to be backed by mathematical modeling and empirical estimates. The mathematical model is the one used in the works of Sompolinsky and Zohar [1] and Pass, Seeman and Shelat [2], which relates network security to network delay. We shall (1) evaluate the theoretical impact of lower Calldata gas cost on network delay using this model, (2) validate the model empirically, and (3) base the proposed gas cost on our findings. ## Motivation There are a couple of main benefits to accepting this proposal and lowering gas cost of Calldata @@ -22,7 +22,7 @@ On-Chain Scalability: Generally speaking, higher bandwidth of Calldata improves * Stateless clients: The same model will be used to determine the price of the state access for the stateless client regime, which will be proposed in the State Rent (from version 4). There, it is expected that the gas cost of state accessing operation will increase roughly proportional to the extra bandwidth required to transmit the “block proofs” as well as extra processing required to verify those block proofs. ## Specification -The gas per non-zero byte is reduced from 68 to TBD. Gas cost of zero bytes is unchanged. +The gas per non-zero byte is reduced from 68 to 16. Gas cost of zero bytes is unchanged. ## Rationale Roughly speaking, reducing the gas cost of Calldata leads to potentially larger blocks, which increases the network delay associated with data transmission over the network. This is only part of the full network delay, other factors are block processing time (and storage access, as part of it). Increasing network delay affects security by lowering the cost of attacking the network, because at any given point in time fewer nodes are updated on the latest state of the blockchain. @@ -45,7 +45,7 @@ Notice, as a sanity check, that when there is no delay (D=0) then _beta_ equals ### Security of the network An attacker attempting to reorganize the main chain needs to generate blocks at a rate that is greater than _beta_. -Fixing the difficulty level of the PoW puzzle, the total hash rate in the system is correlated to _lambda_. Thus, _beta_ / _lambda_ is defined as the the *efficiency* of the system, as it measures the fraction of total hash power that is used to generate the main chain of the network. +Fixing the difficulty level of the PoW puzzle, the total hash rate in the system is correlated to _lambda_. Thus, _beta_ / _lambda_ is defined as the *efficiency* of the system, as it measures the fraction of total hash power that is used to generate the main chain of the network. Rearranging (*) gives the following lower bound on efficiency in terms of delay: @@ -62,14 +62,18 @@ To suggest the gas cost of calldata we shall conduct two types of tests: 1. Network tests, conducted on the Ethereum mainnet, used to estimate the effect on increasing block size on _D_p_ and _D_t_, on the overall network delay D and the efficiency ratio (**), as well as delays between different mining pools. Those tests will include regression tests on existing data, and stress tests to introduce extreme scenarios. 2. Local tests, conducted on a single node and measuring the processing time as a function of Calldata amount and general computation limits. +## Reference Implementation +[Parity](https://github.com/liorgold2/parity-ethereum/pull/1) +[Geth](https://github.com/liorgold2/go-ethereum/pull/1) + ## References [1] Yonatan Sompolinsky, Aviv Zohar: [Secure High-Rate Transaction Processing in Bitcoin](https://eprint.iacr.org/2013/881.pdf). Financial Cryptography 2015: 507-527 [2] Rafael Pass, Lior Seeman, Abhi Shelat: [Analysis of the Blockchain Protocol in Asynchronous Networks](https://eprint.iacr.org/2016/454.pdf), ePrint report 2016/454 -[3] Christian Decker, Roger Wattenhofer: [Information propagation in the Bitcoin network](http://www.gsd.inesc-id.pt/~ler/docencia/rcs1314/papers/P2P2013_041.pdf). P2P 2013: 1-10 +[3] Christian Decker, Roger Wattenhofer: [Information propagation in the Bitcoin network](https://www.gsd.inesc-id.pt/~ler/docencia/rcs1314/papers/P2P2013_041.pdf). P2P 2013: 1-10 [4] Vitalik Buterin: [Uncle Rate and Transaction Fee Analysis](https://blog.ethereum.org/2016/10/31/uncle-rate-transaction-fee-analysis/) ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2029.md b/EIPS/eip-2029.md index 5a2c49345efecd..d3cacaa692ef3e 100644 --- a/EIPS/eip-2029.md +++ b/EIPS/eip-2029.md @@ -3,32 +3,26 @@ eip: 2029 title: State Rent A - State counters contract author: Alexey Akhunov (@AlexeyAkhunov) discussions-to: https://ethereum-magicians.org/t/eip-2029-state-counters-contract-change-a-from-state-rent-v3-proposal/3279 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-15 --- - - ## Simple Summary - A smart contract is deployed on all Ethereum networks, at a pre-determined address, with the code that simply reads the slot in its storage specified by the only parameter. Later, this contract becomes "special" in that Ethereum start writing state counters (number of total transactions, number of accounts, etc.) into that contract. ## Abstract - This is part of the State Rent roadmap. This particular change introduces a place in the Ethereum state where various state counters can be stored. At this point, the most important counter is the total number of transactions happened, and this counter will be used to populate the nonces of newly created non-contract accounts. This way of populating nonce ensures replay protection for accounts that were evicted and then brought back by sending ether to them. ## Motivation - Ethereum currently does not have a special place in the state for tracking state counters such as number of transactions or number of accounts. ## Specification - Prior to the block A, a contract is deployed with the following code: `0x60 0x20 0x60 0x00 0x80 0x80 0x35 0x54 0x90 0x52 0xF3`, which corresponds to this assembly: `PUSH1 32 PUSH1 0 DUP1 DUP1 CALLDATALOAD SLOAD SWAP1 MSTORE RETURN` @@ -37,25 +31,21 @@ Call to this contract accepts one 32-byte argument, `x`, and returns the value o This contract is deployed using `CREATE2` opcode in such a way that it has the same address on any network. ## Rationale - Two alternative solutions were considered so far: 1. Extending the structure of the Ethereum state to introduce more fields, and hence change the way the state root is constructed. The main downside of this approach is the impact on the software what is currently coupled with the particular way the state root is constructed. Particularly it affects the software that deals with merkle proofs derived from the state root. -2. Extended State Oracle ([EIP-2014](https://eips.ethereum.org/EIPS/eip-2014)). Under such proposal, there will be a precompile contract with standardised interface, capable of returning +2. Extended State Oracle ([EIP-2014](./eip-2014.md)). Under such proposal, there will be a precompile contract with standardised interface, capable of returning current values of the counters. However, the actual data being returned by such oracle is not explicitly in the state, and is not Merkelised. It means that all the counters need to be added to the snapshots when the snapshot sync is perform, so they still present in the state, but implicitly. ## Backwards Compatibility - This change is backwards compatible and does not require hard fork to be activated. ## Test Cases - Tests cases will be created to ensure that the state counter contract returns its storage items correctly. ## Implementation - Implementation is envisaged as a transaction that can be posted from any Ethereum address and will cause the deployment of the state counter contract. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2031.md b/EIPS/eip-2031.md index 894eb0d9fc0325..ceb2723f79ddf4 100644 --- a/EIPS/eip-2031.md +++ b/EIPS/eip-2031.md @@ -3,39 +3,32 @@ eip: 2031 title: State Rent B - Net transaction counter author: Alexey Akhunov (@AlexeyAkhunov) discussions-to: https://ethereum-magicians.org/t/eip-2031-net-transaction-counter-change-b-from-state-rent-v3-proposal/3283 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-15 requires: 2029 --- - - ## Simple Summary - Ethereum starts to track the number of transactions inside its state (for now, only number of transactions after this change is introduced, therefore it is called *Net* transaction count). -It is done by incrementing a storage slot in the special contract, called *State counter contract* ([EIP-2029](https://eips.ethereum.org/EIPS/eip-2029)). +It is done by incrementing a storage slot in the special contract, called *State counter contract* ([EIP-2029](./eip-2029.md)). ## Abstract - It is part of the State Rent roadmap. This particular change makes any Ethereum transaction increment the transaction counter, which is a special storage slot in the *State counter contract*. This counter will be used to populate the nonces of newly created non-contract accounts. This way of populating nonce ensures replay protection for accounts that were evicted and then brought back by sending ether to them. ## Motivation - Ethereum currently does not have a special place in the state for tracking number of transactions. ## Specification - A new field, with the location 0 (that means it resides in the storage slot 0 in the state counter contract, and can be read by calling that contract with argument being 32 zero bytes), is added to the state counter contract. It will eventually contain `txCount`, the total number of transactions processed up until that point. On an after block B, or after the deployment of the state counter contract (which comes first), the field `txCount` is incremented after each transaction. Updating `txCount` means updating the storage of state counter contract at the location 0. These changes are never reverted. ## Rationale - Two main alternatives were proposed for the replay protection of the accounts that were evicted by subsequently brought back by sending ether to them: 1. Temporal replay protection. The nonce of the new accounts (and those brought back) is still zero, but a new `valid-until` field is introduced, making transactions invalid for inclusion after the time specified in this field. This, however, has unwanted side effected related to the fact that account @@ -45,17 +38,14 @@ an arbitrary parameter, which is the maximum number of transaction in the block, This is mostly a concern for private networks at the moment, because they will potentially have significantly more transactions in a block. ## Backwards Compatibility - This change is not backwards compatible and requires hard fork to be activated. ## Test Cases - Tests cases will be generated out of a reference implementation. ## Implementation - There will be proof of concept implementation to refine and clarify the specification. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2035.md b/EIPS/eip-2035.md index 6b0eac7f5866a4..11342e67c6f3c4 100644 --- a/EIPS/eip-2035.md +++ b/EIPS/eip-2035.md @@ -3,21 +3,17 @@ eip: 2035 title: Stateless Clients - Repricing SLOAD and SSTORE to pay for block proofs author: Alexey Akhunov (@AlexeyAkhunov) discussions-to: https://ethereum-magicians.org/t/eip-2035-stateless-clients-repricing-sload-and-sstore-to-pay-for-block-proofs/3284 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-16 --- - - ## Simple Summary - The gas cost of EVM opcodes `SLOAD` and `SSTORE` increases in order to accommodate extra bandwidth required to propagate block proof together with the block headers and block bodies, as explained [here](https://medium.com/@akhounov/data-from-the-ethereum-stateless-prototype-8c69479c8abc). ## Abstract - It is part of the State Rent roadmap. This particular change prepares Ethereum for introduction of the block proofs (current understanding is that they can be introuced without a hard fork). The introduction of the block proofs allows any Ethereum node that wishes to receive them, to process transactions in the blocks without needing to access the Ethereum state. All necessary information for the execution (and the proof of validity) is continued in the @@ -28,29 +24,26 @@ but block proofs will make it optional to have access to contract storage for ex affected. ## Motivation - There is [empirical analysis](https://github.com/holiman/vmstats/blob/master/README.md) showing that `SLOAD` opcode is currently underpriced in terms of execution latency it adds to the block processing. The hypothesis is that it is due to the latency of the database accesses. In the same analysis, `SSTORE` is not considered, because its effect on the database accesses can be (and are in many implementations) delayed until the end of the block. Stateless clients approach to the contract storage will largely negate that latency because no database accesses will be required. Instead, bandwidth consumption goes up. There is emprical analysis (unpublished, but will be) suggesting that 1 uncached `SSTORE` or `SLOAD` adds at most 1 kB to the block proofs. At the current cost of data transmission (68 gas per byte), this translates to the increase of gas cost of both -operations by 69k gas. However, in light of proposal in [EIP-2028](https://eips.ethereum.org/EIPS/eip-2028), the increase can be made much smaller. +operations by 69k gas. However, in light of proposal in [EIP-2028](./eip-2028.md), the increase can be made much smaller. ## Specification - Not very formal at the moment, but will be formalised with more research and prototyping. Gas of operations `SLOAD` and `SSTORE` increases by `X` gas when the storage slots accessed (read by `SLOAD` or written by `SSTORE`) were not previously accessed (by another `SLOAD` or `SSTORE`) during the same transaction. Future variant (will be possible after the implementation of the *Gross contract size acccounting*) is researched, where the increase is varied depending on the size of the contract storage, i.e. `SLOAD` and `SSTORE` for smaller contracts will be cheaper. ## Rationale - -[EIP-1884](https://eips.ethereum.org/EIPS/eip-1884) seeks to increase the gas cost of `SLOAD` but using a different justification +[EIP-1884](./eip-1884.md) seeks to increase the gas cost of `SLOAD` but using a different justification (latency of the execution as described in the Motivation). This EIP is likely to increase the cost of `SLOAD` by a larger amount, therefore partially (because EIP-1884 also proposed other increases) supersedes EIP-1884. -[EIP-2028](https://eips.ethereum.org/EIPS/eip-2028) describes the model that can be used for deciding the gas cost of data transmission. It is relevant +[EIP-2028](./eip-2028.md) describes the model that can be used for deciding the gas cost of data transmission. It is relevant because in the stateless client regime `SSTORE` and `SLOAD` operations add more data to be transmitted (as well as computation to verify the proofs). The main alternate design is the rent proportional to the size of the contract storage, which unfortunately introduces a serious griefing @@ -58,10 +51,9 @@ vulnerability problem, and so far the solution seems to be in redesigning and re However, this approach is likely to be very expensive on the non-technical (ecosystem) level. ## Backwards Compatibility - This change is not backwards compatible and requires hard fork to be activated. There might also be an adverse effect of this change on the already deployed contract. It is expected that after this EIP and -[EIP-2026](https://eips.ethereum.org/EIPS/eip-2026) (rent prepayment for accounts), the recommendation will be made to raise the gas limit. This can somewhat dampen the +[EIP-2026](./eip-2026.md) (rent prepayment for accounts), the recommendation will be made to raise the gas limit. This can somewhat dampen the adverse effect of EIP. The most problematic cases would be with the contracts that assume certain gas costs of `SLOAD` and `SSTORE` and hard-code them in their internal gas computations. For others, the cost of interacting with the contract storage will rise and may make some dApps based on such interactions, non-viable. This is a trade off to avoid even bigger @@ -69,13 +61,11 @@ adverse effect of the rent proportional to the contract storage size. However, m analyse the potentially impacted contracts. ## Test Cases - Tests cases will be generated out of a reference implementation. ## Implementation - There will be proof of concept implementation to refine and clarify the specification. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2045.md b/EIPS/eip-2045.md new file mode 100644 index 00000000000000..e5a8b602ad6a5b --- /dev/null +++ b/EIPS/eip-2045.md @@ -0,0 +1,121 @@ +--- +eip: 2045 +title: Particle gas costs for EVM opcodes +author: Casey Detrio (@cdetrio), Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-2045-fractional-gas-costs/3311 +status: Stagnant +type: Standards Track +category: Core +created: 2019-05-17 +--- + +## Abstract +According to recent benchmarks, EVM opcodes for computation (`ADD`, `SUB`, `MUL`, etc.) are generally overpriced relative to opcodes for storage I/O (`SLOAD`, `SSTORE`, etc.). Currently the minimum gas cost is 1 (i.e. one unit of gas), and most computational opcodes have a cost near to 1 (e.g. 3, 5, or 8), so the range in possible cost reduction is limited. A new minimum unit of gas, called a "particle", which is a fraction of 1 gas, would expand the range of gas costs and thus enable reductions below the current minimum. + +## Motivation +The transaction capacity of an Ethereum block is determined by the gas cost of transactions relative to the block gas limit. One way to boost the transaction capacity is to raise the block gas limit. Unfortunately, raising the block gas limit would also increase the rate of state growth, unless the costs of state-expanding storage opcodes (`SSTORE`, `CREATE`, etc.) are simultaneously increased to the same proportion. Increasing the cost of storage opcodes may have adverse side effects, such as shifting the economic assumptions around gas fees of deployed contracts, or possibly breaking invariants in current contract executions (as mentioned in [EIP-2035](./eip-2035.md)[1](#eip2035), more research is needed on the potential effects of increasing the cost of storage opcodes). + +Another way to boost the transaction capacity of a block is to reduce the gas cost of transactions. Reducing the gas costs of computational opcodes while keeping the cost of storage opcodes the same, is effectively equivalent to raising the block gas limit and simultaneously increasing the cost of storage opcodes. However, reducing the cost of computational opcodes might avoid the adverse side effects of an increase in cost of storage opcodes (again, more research is needed on this topic). + +Currently, computational opcode costs are already too close to the minimum unit of 1 gas to achieve the large degree of cost reductions that recent benchmarks[2](#evmbenchmarks) indicate would be needed to tune opcode gas costs to the performance of optimized EVM implementations. A smaller minimum unit called a "particle", which is a fraction (or subdivision) of 1 gas, would enable large cost reductions. + +## Specification +A new gas counter `particlesUsed` is added to the EVM, in addition to the existing gas counter `gasUsed`. The unit 1 gas is equal to 10000 particles (`PARTICLES_PER_GAS`). The `particlesUsed` counter is only increased for opcodes priced in particles (i.e. opcodes that cost less than 1 gas). If increasing `particlesUsed` results in an excess of 1 gas, then 1 gas is added to `gasUsed` (and deducted from `particlesUsed`). + +Where the current gas logic looks like this: +```python +def vm_execute(ext, msg, code): + # Initialize stack, memory, program counter, etc + compustate = Compustate(gas=msg.gas) + codelen = len(code) + + while compustate.pc < codelen: + opcode = code[compustate.pc] + compustate.pc += 1 + + compustate.gasUsed += opcode.gas_fee + + # out of gas error + if compustate.gasUsed > compustate.gasLimit: + return vm_exception('OUT OF GAS') + + if op == 'STOP': + return peaceful_exit() + elif op == 'ADD': + stk.append(stk.pop() + stk.pop()) + elif op == 'SUB': + stk.append(stk.pop() - stk.pop()) + elif op == 'MUL': + stk.append(stk.pop() * stk.pop()) + +..... +``` + +The new gas logic using particles might look like this: +```python +PARTICLES_PER_GAS = 10000 + +def vm_execute(ext, msg, code): + # Initialize stack, memory, program counter, etc + compustate = Compustate(gas=msg.gas) + codelen = len(code) + + while compustate.pc < codelen: + opcode = code[compustate.pc] + compustate.pc += 1 + + if opcode.gas_fee: + compustate.gasUsed += opcode.gas_fee + elif opcode.particle_fee: + compustate.particlesUsed += opcode.particle_fee + if compustate.particlesUsed >= PARTICLES_PER_GAS: + # particlesUsed will be between 1 and 2 gas (over 10000 but under 20000) + compustate.gasUsed += 1 + # remainder stays in particle counter + compustate.particlesUsed = compustate.particlesUsed % PARTICLES_PER_GAS + + # out of gas error + if compustate.gasUsed > compustate.gasLimit: + return vm_exception('OUT OF GAS') + + if op == 'STOP': + return peaceful_exit() + elif op == 'ADD': + stk.append(stk.pop() + stk.pop()) + elif op == 'SUB': + stk.append(stk.pop() - stk.pop()) + elif op == 'MUL': + stk.append(stk.pop() * stk.pop()) + +..... +``` + +The above pseudocode is written for clarity. A more performant implementation might instead keep a single `particlesUsed` counter by multiplying opcode gas costs by 10000 and the `gasLimit` by 10000, and convert particles back to gas with `ceil(particlesUsed / PARTICLES_PER_GAS)` at the end of execution. It may also be more performant to use a `PARTICLES_PER_GAS` ratio that is a power of 2 (such as 8192 or 16384) instead of 10000; the spec above is a draft and updates in response to feedback are expected. + +#### Opcode cost changes +Many computational opcodes will undergo a cost reduction, with new costs suggested by benchmark analyses. For example, the cost of `DUP` and `SWAP` are reduced from 3 gas to 3000 particles (i.e. 0.3 gas). The cost of `ADD` and `SUB` are reduced from 3 gas to 6000 particles. The cost of `MUL` is reduced from 5 gas to 5000 particles (i.e. 0.5 gas). + +## Rationale +Adoption of fractional gas costs should only be an implementation detail inside the EVM, and not alter the current user experience around transaction gas limits and block gas limits. The concept of `particles` need not be exposed to Ethereum users nor most contract authors, but only to EVM implementers and contract developers concerned with optimized gas usage. Furthermore, only the EVM logic for charging gas per opcode executed should be affected by this change. All other contexts dealing with gas and gas limits, such as block headers and transaction formats, should be unaffected. + +### Ewasm +The term "particles" was first introduced for Ewasm[3](#particle) to enable gas accounting for low cost wasm instructions, while remaining compatible with EVM gas costs. This EIP proposes introducing particles as a new minimum gas unit for EVM opcodes, and is not related to Ewasm. + +## Backwards Compatibility +This change is not backwards compatible and requires a hard fork to be activated. + +## Test Cases +TODO + +## Implementation +TODO + +## References +1. [EIP-2035](./eip-2035.md): Stateless Clients - Repricing SLOAD and SSTORE to pay for block proofs + +2. https://github.com/ewasm/benchmarking + +3. The term "particle" was inspired by a proposal for [Ewasm gas costs](https://github.com/ewasm/design/blob/e77d8e3de42784f40a803a23f58ef06881142d9f/determining_wasm_gas_costs.md). + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2046.md b/EIPS/eip-2046.md index ca35c7eefe8e8a..91171d02593dd5 100644 --- a/EIPS/eip-2046.md +++ b/EIPS/eip-2046.md @@ -3,7 +3,7 @@ eip: 2046 title: Reduced gas cost for static calls made to precompiles author: Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/eip-2046-reduced-gas-cost-for-static-calls-made-to-precompiles/3291 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-17 @@ -54,7 +54,7 @@ TBA ## References -This has been previously suggested as part of [EIP-1109](https://github.com/ethereum/EIPs/pull/1109) and [EIP-1231](https://github.com/ethereum/EIPs/pull/1231). +This has been previously suggested as part of [EIP-1109](./eip-1109.md) and [EIP-1231](https://github.com/ethereum/EIPs/pull/1231). However EIP-1109 was later changed to a very different approach. The author [has suggested to change EIP-1109](https://ethereum-magicians.org/t/eip-1109-remove-call-costs-for-precompiled-contracts/447/7). ## Acknowledgements @@ -63,7 +63,7 @@ Jordi Baylina (@jbaylina) and Matthew Di Ferrante (@mattdf) who have proposed th ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). [Yellow Paper]: https://github.com/ethereum/yellowpaper -[EIP-1352]: https://eips.ethereum.org/EIPS/eip-1352 +[EIP-1352]: ./eip-1352.md diff --git a/EIPS/eip-205.md b/EIPS/eip-205.md index 09c5e3666bb6d6..6b7887551ff154 100644 --- a/EIPS/eip-205.md +++ b/EIPS/eip-205.md @@ -1,69 +1,7 @@ --- eip: 205 -title: ENS support for contract ABIs -author: Nick Johnson -type: Standards Track category: ERC -status: Draft -created: 2017-02-06 -requires: 137, 181 +status: Moved --- -## Simple Summary -This EIP proposes a mechanism for storing ABI definitions in ENS, for easy lookup of contract interfaces by callers. - -## Abstract -ABIs are important metadata required for interacting with most contracts. At present, they are typically supplied out-of-band, which adds an additional burden to interacting with contracts, particularly on a one-off basis or where the ABI may be updated over time. The small size of ABIs permits an alternative solution, storing them in ENS, permitting name lookup and ABI discovery via the same process. - -ABIs are typically quite compact; the largest in-use ABI we could find, that for the DAO, is 9450 bytes uncompressed JSON, 6920 bytes uncompressed CBOR, and 1128 bytes when the JSON form is compressed with zlib. Further gains on CBOR encoding are possible using a CBOR extension that permits eliminating repeated strings, which feature extensively in ABIs. Most ABIs, however, are far shorter than this, consisting of only a few hundred bytes of uncompressed JSON. - -This EIP defines a resolver profile for retrieving contract ABIs, as well as encoding standards for storing ABIs for different applications, allowing the user to select between different representations based on their need for compactness and other considerations such as onchain access. - -## Specification -### ABI encodings -In order to allow for different tradeoffs between onchain size and accessibility, several ABI encodings are defined. Each ABI encoding is defined by a unique constant with only a single bit set, allowing for the specification of 256 unique encodings in a single uint. - -The currently recognised encodings are: - -| ID | Description | -|----|----------------------| -| 1 | JSON | -| 2 | zlib-compressed JSON | -| 4 | CBOR | -| 8 | URI | - -This table may be extended in future through the EIP process. - -Encoding type 1 specifies plaintext JSON, uncompressed; this is the standard format in which ABIs are typically encoded, but also the bulkiest, and is not easily parseable onchain. - -Encoding type 2 specifies zlib-compressed JSON. This is significantly smaller than uncompressed JSON, and is straightforward to decode offchain. However, it is impracticalfor onchain consumers to use. - -Encoding type 4 is [CBOR](http://cbor.io/). CBOR is a binary encoding format that is a superset of JSON, and is both more compact and easier to parse in limited environments such as the EVM. Consumers that support CBOR are strongly encouraged to also support the [stringref extension](http://cbor.schmorp.de/stringref) to CBOR, which provides significant additional reduction in encoded size. - -Encoding type 8 indicates that the ABI can be found elsewhere, at the specified URI. This is typically the most compact of the supported forms, but also adds external dependencies for implementers. The specified URI may use any schema, but HTTP, IPFS, and Swarm are expected to be the most common. - -### Resolver profile -A new resolver interface is defined, consisting of the following method: - - function ABI(bytes32 node, uint256 contentType) constant returns (uint256, bytes); - -The interface ID of this interface is 0x2203ab56. - -contentType is a bitfield, and is the bitwise OR of all the encoding types the caller will accept. Resolvers that implement this interface must return an ABI encoded using one of the requested formats, or `(0, "")` if they do not have an ABI for this function, or do not support any of the requested formats. - -The `abi` resolver profile is valid on both forward and reverse records. - -### ABI lookup process - -When attempting to fetch an ABI based on an ENS name, implementers should first attempt an ABI lookup on the name itself. If that lookup returns no results, they should attempt a reverse lookup on the Ethereum address the name resolves to. - -Implementers should support as many of the ABI encoding formats as practical. - -## Rationale - -Storing ABIs onchain avoids the need to introduce additional dependencies for applications wishing to fetch them, such as swarm or HTTP access. Given the typical compactness of ABIs, we believe this is a worthwhile tradeoff in many cases. - -The two-step resolution process permits different names to provide different ABIs for the same contract, such as in the case where it's useful to provide a minimal ABI to some callers, as well as specifying ABIs for contracts that did not specify one of their own. The fallback to looking up an ABI on the reverse record permits contracts to specify their own canonical ABI, and prevents the need for duplication when multiple names reference the same contract without the need for different ABIs. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-205.md diff --git a/EIPS/eip-2069.md b/EIPS/eip-2069.md new file mode 100644 index 00000000000000..193f98e920a68a --- /dev/null +++ b/EIPS/eip-2069.md @@ -0,0 +1,106 @@ +--- +eip: 2069 +title: Recommendation for using YAML ABI in ERCs/EIPs +author: Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-2069-recommendation-for-using-yaml-abi-in-specifications/3347 +status: Stagnant +type: Informational +created: 2017-02-11 +--- + +## Simple Summary + +Recommendation for including contract ABI descriptions in EIPs and ERCs as YAML. + +## Motivation + +In the past, most ERCs/EIPs included an ABI description purely as a Solidity contract and/or interface. This has several drawbacks: + +- Prefers a single language over others and could hinder the development of new languages. +- Locks the specification to a certain version of the Solidity language. +- Allows the use of syntactical elements and features of the Solidity language, which may not be well representable in the ABI. This puts other languages at even more disadvantage. + +This proposal aims to solve all these issues. + +## Specification + +The [Standard Contract ABI] is usually represented as a JSON object. This works well and several tools – including compilers and clients – support it to handle data encoding. + +One shortcoming of the JSON description is its inability to contain comments. To counter this, we suggest the use of YAML for providing user readable specifications. Given YAML was designed to be compatible with JSON, several tools exist to convert between the two formats. + +The following example contains a single function, `transfer` with one input and one output in YAML: + +```yaml +# The transfer function. Takes the recipient address +# as an input and returns a boolean signaling the result. +- name: transfer + type: function + payable: false + constant: false + stateMutability: nonpayable + inputs: + - name: recipient + type: address + - name: amount + type: uint256 + outputs: + - name: '' + type: bool +``` + +Specifications are encouraged to include comments in the YAML ABI. + +For details on what fields and values are valid in the ABI, please consult the [Standard Contract ABI] specification. + +The same in JSON: + +```json +[ + { + "name": "transfer", + "type": "function", + "payable": false, + "constant": false, + "stateMutability": "nonpayable", + "inputs": [ + { + "name": "recipient", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "", + "type": "bool" + } + ] + } +] +``` + +## Rationale + +The aim was to choose a representation which is well supported by tools and supports comments. While inventing a more concise description language seems like a good idea, it felt as an unnecessary layer of complexity. + +## Backwards Compatibility + +This has no effect on backwards compatibility. + +## Test Cases + +TBA + +## Implementation + +[yamabi] is a Javascript tool to convert between the above YAML and the more widely used JSON format. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + +[Standard Contract ABI]: https://solidity.readthedocs.io/en/latest/abi-spec.html +[yamabi]: https://github.com/axic/yamabi/ diff --git a/EIPS/eip-2070.md b/EIPS/eip-2070.md new file mode 100644 index 00000000000000..a3c30508a2d6ee --- /dev/null +++ b/EIPS/eip-2070.md @@ -0,0 +1,25 @@ +--- +eip: 2070 +title: "Hardfork Meta: Berlin" +author: Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/hardfork-meta-eip-2070-berlin-discussion/3561 +type: Meta +status: Withdrawn +created: 2019-05-20 +requires: 1679 +--- + +## Abstract + +This meta-EIP specifies the changes included in the Ethereum hardfork named Berlin. + +## Specification + +- Codename: Berlin + +In the current stage of coordination, the changes are tracked and discussed in the [eth1.0-specs](https://github.com/ethereum/eth1.0-specs) repository. +For an accurate status please refer to the [`berlin.md`](https://github.com/ethereum/eth1.0-specs/blob/master/network-upgrades/mainnet-upgrades/berlin.md) file. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2098.md b/EIPS/eip-2098.md new file mode 100644 index 00000000000000..1fd5c74486e65e --- /dev/null +++ b/EIPS/eip-2098.md @@ -0,0 +1,7 @@ +--- +eip: 2098 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2098.md diff --git a/EIPS/eip-210.md b/EIPS/eip-210.md index abba50af202e53..838c23021cc850 100644 --- a/EIPS/eip-210.md +++ b/EIPS/eip-210.md @@ -4,7 +4,7 @@ title: Blockhash refactoring author: Vitalik Buterin (@vbuterin) type: Standards Track category: Core -status: Draft +status: Stagnant created: 2017-02-10 --- @@ -29,11 +29,11 @@ If `block.number >= CONSTANTINOPLE_FORK_BLKNUM`, then when processing a block, b * `GAS`: 1000000 * `TO`: BLOCKHASH_CONTRACT_ADDR * `VALUE`: 0 -* `DATA`: <32 bytes corresponding to the block's prevhash> +* `DATA`: <32 bytes corresponding to the block's prevhash> If `block.number >= CONSTANTINOPLE_FORK_BLKNUM + 256`, then the BLOCKHASH opcode instead returns the result of executing a call (NOT a transaction) with the parameters: -* `SENDER`: +* `SENDER`: <account from which the opcode was called> * `GAS`: 1000000 * `TO`: BLOCKHASH_CONTRACT_ADDR * `VALUE`: 0 diff --git a/EIPS/eip-211.md b/EIPS/eip-211.md index 6e05501759231e..29f8c19219d016 100644 --- a/EIPS/eip-211.md +++ b/EIPS/eip-211.md @@ -6,7 +6,6 @@ type: Standards Track category: Core status: Final created: 2017-02-13 -replaces: 5 --- ## Simple Summary @@ -61,4 +60,4 @@ This proposal introduces two new opcodes and stays fully backwards compatible ap ## Implementation ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2124.md b/EIPS/eip-2124.md new file mode 100644 index 00000000000000..32479f557f4dc5 --- /dev/null +++ b/EIPS/eip-2124.md @@ -0,0 +1,311 @@ +--- +eip: 2124 +title: Fork identifier for chain compatibility checks +author: Péter Szilágyi , Felix Lange +discussions-to: https://github.com/ethereum/EIPs/issues/2125 +status: Final +type: Standards Track +category: Networking +created: 2019-05-03 +--- + +## Simple Summary + +Currently nodes in the Ethereum network try to find each other by establishing random connections to remote machines "looking" like an Ethereum node (public networks, private networks, test networks, etc), hoping that they found a useful peer (same genesis, same forks). This wastes time and resources, especially for smaller networks. + +To avoid this overhead, Ethereum needs a mechanism that can precisely identify whether a node will be useful, as early as possible. Such a mechanism requires a way to summarize chain configurations, as well as a way to disseminate said summaries in the network. + +This proposal focuses only on the definition of said summary - a generally useful *fork identifier* - and it's validation rules, allowing it to be embedded into arbitrary network protocols (e.g. [discovery ENRs](./eip-778.md) or `eth/6x` handshakes). + +## Abstract + +There are many public and private Ethereum networks, but the discovery protocol doesn't differentiate between them. The only way to check if a peer is good or bad (same chain or not), is to establish a TCP/IP connection, wrap it with RLPx cryptography, then execute an `eth` handshake. This is an extreme cost to bear if it turns out that the remote peer is on a different network and it's not even precise enough to differentiate Ethereum and Ethereum Classic. This cost is magnified for small networks, where a lot more trial and errors are needed to find good nodes. + +Even if the peer **is** on the same chain, during non-controversial consensus upgrades, not everybody updates their nodes in time (developer nodes, leftovers, etc). These stale nodes put a meaningless burden on the peer-to-peer network, since they just latch on to good nodes, but don't accept upgraded blocks. This causes valuable peer slots and bandwidth to be lost until the stale nodes finally update. This is a serious issue for test networks, where leftovers can linger for months. + +This EIP proposes a new identity scheme to both precisely and concisely summarize the chain's current status (genesis and all applied forks). The conciseness is particularly important to make the identity useful across datagram protocols too. The EIP solves a number of issues: + + * If two nodes are on different networks, they should never even consider connecting. + * If a hard fork passes, upgraded nodes should reject non-upgraded ones, but **NOT** before. + * If two chains share the same genesis, but not forks (ETH / ETC), they should reject each other. + +This EIP does not attempt to solve the clean separation of 3-way-forks! If at the same future block number, the network splits into three (non-fork, fork-A and fork-B), separating the forkers from each another will need case-by-case special handling. Not handling this keeps the proposal pragmatic, simple and also avoids making it too easy to fork off mainnet. + +To keep the scope limited, this EIP only defines the identity scheme and validation rules. The same scheme and algorithm can be embedded into various networking protocols, allowing both the `eth/6x` handshake to be more precise (Ethereum vs. Ethereum Classic); as well as the discovery to be more useful (reject surely peers without ever connecting). + +## Motivation + +Peer-to-peer networking is messy and hard due to firewalls and network address translation (NAT). Generally only a small fraction of nodes have publicly routed addresses and P2P networks rely mainly on these for forwarding data for everyone else. The best way to maximize the utility of the public nodes is to ensure their resources aren't wasted on tasks that are worthless to the network. + +By aggressively cutting off incompatible nodes from each other we can extract a lot more value from the public nodes, making the entire P2P network much more robust and reliable. Supporting this network partitioning at a discovery layer can further enhance performance as we avoid the costly crypto and latency/bandwidth hit associated with establishing a stream connection in the first place. + +## Specification + +Each node maintains the following values: + +- **`FORK_HASH`**: IEEE CRC32 checksum (`[4]byte`) of the genesis hash and fork blocks numbers that already passed. + - The fork block numbers are fed into the CRC32 checksum in ascending order. + - If multiple forks are applied at the same block, the block number is checksummed only once. + - Block numbers are regarded as `uint64` integers, encoded in big endian format when checksumming. + - If a chain is configured to start with a non-Frontier ruleset already in its genesis, that is NOT considered a fork. +- **`FORK_NEXT`**: Block number (`uint64`) of the next upcoming fork, or `0` if no next fork is known. + +E.g. `FORK_HASH` for mainnet would be: + +- forkhash₀ = `0xfc64ec04` (Genesis) = `CRC32()` +- forkhash₁ = `0x97c2c34c` (Homestead) = `CRC32( || uint64(1150000))` +- forkhash₂ = `0x91d1f948` (DAO fork) = `CRC32( || uint64(1150000) || uint64(1920000))` + +The *fork identifier* is defined as `RLP([FORK_HASH, FORK_NEXT])`. This `forkid` is cross validated (**NOT** naively compared) to assess a remote chain's compatibility. Irrespective of fork state, both parties must come to the same conclusion to avoid indefinite reconnect attempts from one side. + +#### Validation rules + +- 1) If local and remote `FORK_HASH` matches, compare local head to `FORK_NEXT`. + - The two nodes are in the same fork state currently. They might know of differing future forks, but that's not relevant until the fork triggers (might be postponed, nodes might be updated to match). + - 1a) A remotely announced but remotely not passed block is already passed locally, disconnect, since the chains are incompatible. + - 1b) No remotely announced fork; or not yet passed locally, connect. + +- 2) If the remote `FORK_HASH` is a subset of the local past forks and the remote `FORK_NEXT` matches with the locally following fork block number, connect. + - Remote node is currently syncing. It might eventually diverge from us, but at this current point in time we don't have enough information. +- 3) If the remote `FORK_HASH` is a superset of the local past forks and can be completed with locally known future forks, connect. + - Local node is currently syncing. It might eventually diverge from the remote, but at this current point in time we don't have enough information. +- 4) Reject in all other cases. + +#### Stale software examples + +The examples below try to exhaust the fork combination possibilities that arise when nodes do not run matching software versions, but otherwise follow the same chain (mainnet nodes, testnet nodes, etc). + +| Past forks | Future forks | Head | Remote `FORK_HASH` | Remote `FORK_NEXT` | Connect | Reason | +|:---:|:---:|:---:|:---:|:---:|:---:|:---:| +| A | | | A | | Yes (1b) | Same forks, same sync state. | +| A | | < B | A | B | Yes (1b) | Remote is advertising a future fork, but that is uncertain. | +| A | | >= B | A | B | No (1a) | Remote is advertising a future fork that passed locally. | +| A | B | | A | | Yes (1b) | Local knows about a future fork, but that is uncertain. | +| A | B | | A | B | Yes (1b) | Both know about a future fork, but that is uncertain. | +| A | B1 | < B2 | A | B2 | Yes (1b) | Both know about differing future forks, but those are uncertain. | +| A | B1 | >= B2 | A | B2 | No (1a) | Both know about differing future forks, but the remote one passed locally. | +| [A,B] | | | A | B | Yes (2) | Remote out of sync. | +| [A,B,C] | | | A | B | Yes¹ (2) | Remote out of sync. Remote will need a software update, but we don't know it yet. | +| A | B | | A ⊕ B | | Yes (3) | Local out of sync. | +| A | B,C | | A ⊕ B | | Yes (3) | Local out of sync. Local also knows about a future fork, but that is uncertain yet. | +| A | | | A ⊕ B | | No (4) | Local needs software update. | +| A | B | | A ⊕ B ⊕ C | | No² (4) | Local needs software update. | +| [A,B] | | | A | | No (4) | Remote needs software update. | + +*Note, there's one asymmetry in the table, marked with ¹ and ². Since we don't have access to a remote node's future fork list (just the next one), we can't detect that it's software is stale until it syncs up. This is acceptable as 1) the remote node will disconnect from us anyway, and 2) this is a temporary fluke during sync, not permanent with a leftover node.* + +## Rationale + +##### Why flatten `FORK_HASH` into 4 bytes? Why not share the entire genesis and fork list? + +Whilst the `eth` devp2p protocol permits arbitrarily much data to be transmitted, the discovery protocol's total space allowance for all ENR entries is 300 bytes. + +Reducing the `FORK_HASH` into a 4 bytes checksum ensures that we leave ample room in the ENR for future extensions; and 4 bytes is more than enough for arbitrarily many Ethereum networks from a (practical) collision perspective. + +##### Why use IEEE CRC32 as the checksum instead of Keccak256? + +We need a mechanism that can flatten arbitrary data into 4 bytes, without ignoring any of the input. Any other checksum or hashing algorithm would work, but since nodes can lie at any time, there's no value in cryptographic hash functions. + +Instead of just taking the first 4 bytes of a Keccak256 hash (seems odd) or XOR-ing all the 4-byte groups (messy), CRC32 is a better alternative, as this is exactly what it was designed for. IEEE CRC32 is also used by ethernet, gzip, zip, png, etc, so every programming language support should not be a problem. + +##### We're not using `FORK_NEXT` for much, can't we get rid of it somehow? + +We need to be able to differentiate whether a remote node is out of sync or whether its software is stale. Sharing only the past forks cannot tell us if the node is legitimately behind or stuck. + +##### Why advertise only one next fork, instead of "hashing" all known future ones like the `FORK_HASH`? + +Opposed to past forks that have already passed (for us locally) and can be considered immutable, we don't know anything about future ones. Maybe we're out of sync or maybe the fork didn't pass yet. If it didn't pass yet, it might be postponed, so enforcing it would split the network apart. It could also happen that we're not yet aware of all future forks (haven't updated our software in a while). + +## Backwards Compatibility + +This EIP only defines an identity scheme, it does not define functional changes. + +## Test Cases + +Here's a full suite of tests for all possible fork IDs that Mainnet, Ropsten, Rinkeby and Görli can advertise given the Petersburg fork cap (time of writing). + +```go +type testcase struct { + head uint64 + want ID +} +tests := []struct { + config *params.ChainConfig + genesis common.Hash + cases []testcase +}{ + // Mainnet test cases + { + params.MainnetChainConfig, + params.MainnetGenesisHash, + []testcase{ + {0, ID{Hash: 0xfc64ec04, Next: 1150000}}, // Unsynced + {1149999, ID{Hash: 0xfc64ec04, Next: 1150000}}, // Last Frontier block + {1150000, ID{Hash: 0x97c2c34c, Next: 1920000}}, // First Homestead block + {1919999, ID{Hash: 0x97c2c34c, Next: 1920000}}, // Last Homestead block + {1920000, ID{Hash: 0x91d1f948, Next: 2463000}}, // First DAO block + {2462999, ID{Hash: 0x91d1f948, Next: 2463000}}, // Last DAO block + {2463000, ID{Hash: 0x7a64da13, Next: 2675000}}, // First Tangerine block + {2674999, ID{Hash: 0x7a64da13, Next: 2675000}}, // Last Tangerine block + {2675000, ID{Hash: 0x3edd5b10, Next: 4370000}}, // First Spurious block + {4369999, ID{Hash: 0x3edd5b10, Next: 4370000}}, // Last Spurious block + {4370000, ID{Hash: 0xa00bc324, Next: 7280000}}, // First Byzantium block + {7279999, ID{Hash: 0xa00bc324, Next: 7280000}}, // Last Byzantium block + {7280000, ID{Hash: 0x668db0af, Next: 0}}, // First and last Constantinople, first Petersburg block + {7987396, ID{Hash: 0x668db0af, Next: 0}}, // Today Petersburg block + }, + }, + // Ropsten test cases + { + params.TestnetChainConfig, + params.TestnetGenesisHash, + []testcase{ + {0, ID{Hash: 0x30c7ddbc, Next: 10}}, // Unsynced, last Frontier, Homestead and first Tangerine block + {9, ID{Hash: 0x30c7ddbc, Next: 10}}, // Last Tangerine block + {10, ID{Hash: 0x63760190, Next: 1700000}}, // First Spurious block + {1699999, ID{Hash: 0x63760190, Next: 1700000}}, // Last Spurious block + {1700000, ID{Hash: 0x3ea159c7, Next: 4230000}}, // First Byzantium block + {4229999, ID{Hash: 0x3ea159c7, Next: 4230000}}, // Last Byzantium block + {4230000, ID{Hash: 0x97b544f3, Next: 4939394}}, // First Constantinople block + {4939393, ID{Hash: 0x97b544f3, Next: 4939394}}, // Last Constantinople block + {4939394, ID{Hash: 0xd6e2149b, Next: 6485846}}, // First Petersburg block + {6485845, ID{Hash: 0xd6e2149b, Next: 6485846}}, // Last Petersburg block + {6485846, ID{Hash: 0x4bc66396, Next: 0}}, // First Istanbul block + {7500000, ID{Hash: 0x4bc66396, Next: 0}}, // Future Istanbul block + }, + }, + // Rinkeby test cases + { + params.RinkebyChainConfig, + params.RinkebyGenesisHash, + []testcase{ + {0, ID{Hash: 0x3b8e0691, Next: 1}}, // Unsynced, last Frontier block + {1, ID{Hash: 0x60949295, Next: 2}}, // First and last Homestead block + {2, ID{Hash: 0x8bde40dd, Next: 3}}, // First and last Tangerine block + {3, ID{Hash: 0xcb3a64bb, Next: 1035301}}, // First Spurious block + {1035300, ID{Hash: 0xcb3a64bb, Next: 1035301}}, // Last Spurious block + {1035301, ID{Hash: 0x8d748b57, Next: 3660663}}, // First Byzantium block + {3660662, ID{Hash: 0x8d748b57, Next: 3660663}}, // Last Byzantium block + {3660663, ID{Hash: 0xe49cab14, Next: 4321234}}, // First Constantinople block + {4321233, ID{Hash: 0xe49cab14, Next: 4321234}}, // Last Constantinople block + {4321234, ID{Hash: 0xafec6b27, Next: 5435345}}, // First Petersburg block + {5435344, ID{Hash: 0xafec6b27, Next: 5435345}}, // Last Petersburg block + {5435345, ID{Hash: 0xcbdb8838, Next: 0}}, // First Istanbul block + {6000000, ID{Hash: 0xcbdb8838, Next: 0}}, // Future Istanbul block + }, + }, + // Goerli test cases + { + params.GoerliChainConfig, + params.GoerliGenesisHash, + []testcase{ + {0, ID{Hash: 0xa3f5ab08, Next: 1561651}}, // Unsynced, last Frontier, Homestead, Tangerine, Spurious, Byzantium, Constantinople and first Petersburg block + {1561650, ID{Hash: 0xa3f5ab08, Next: 1561651}}, // Last Petersburg block + {1561651, ID{Hash: 0xc25efa5c, Next: 0}}, // First Istanbul block + {2000000, ID{Hash: 0xc25efa5c, Next: 0}}, // Future Istanbul block + }, + }, +} +``` + + Here's a suite of tests of the different states a Mainnet node might be in and the different remote fork identifiers it might be required to validate and decide to accept or reject: + +```go +tests := []struct { + head uint64 + id ID + err error +}{ + // Local is mainnet Petersburg, remote announces the same. No future fork is announced. + {7987396, ID{Hash: 0x668db0af, Next: 0}, nil}, + + // Local is mainnet Petersburg, remote announces the same. Remote also announces a next fork + // at block 0xffffffff, but that is uncertain. + {7987396, ID{Hash: 0x668db0af, Next: math.MaxUint64}, nil}, + + // Local is mainnet currently in Byzantium only (so it's aware of Petersburg), remote announces + // also Byzantium, but it's not yet aware of Petersburg (e.g. non updated node before the fork). + // In this case we don't know if Petersburg passed yet or not. + {7279999, ID{Hash: 0xa00bc324, Next: 0}, nil}, + + // Local is mainnet currently in Byzantium only (so it's aware of Petersburg), remote announces + // also Byzantium, and it's also aware of Petersburg (e.g. updated node before the fork). We + // don't know if Petersburg passed yet (will pass) or not. + {7279999, ID{Hash: 0xa00bc324, Next: 7280000}, nil}, + + // Local is mainnet currently in Byzantium only (so it's aware of Petersburg), remote announces + // also Byzantium, and it's also aware of some random fork (e.g. misconfigured Petersburg). As + // neither forks passed at neither nodes, they may mismatch, but we still connect for now. + {7279999, ID{Hash: 0xa00bc324, Next: math.MaxUint64}, nil}, + + // Local is mainnet Petersburg, remote announces Byzantium + knowledge about Petersburg. Remote + // is simply out of sync, accept. + {7987396, ID{Hash: 0xa00bc324, Next: 7280000}, nil}, + + // Local is mainnet Petersburg, remote announces Spurious + knowledge about Byzantium. Remote + // is definitely out of sync. It may or may not need the Petersburg update, we don't know yet. + {7987396, ID{Hash: 0x3edd5b10, Next: 4370000}, nil}, + + // Local is mainnet Byzantium, remote announces Petersburg. Local is out of sync, accept. + {7279999, ID{Hash: 0x668db0af, Next: 0}, nil}, + + // Local is mainnet Spurious, remote announces Byzantium, but is not aware of Petersburg. Local + // out of sync. Local also knows about a future fork, but that is uncertain yet. + {4369999, ID{Hash: 0xa00bc324, Next: 0}, nil}, + + // Local is mainnet Petersburg. remote announces Byzantium but is not aware of further forks. + // Remote needs software update. + {7987396, ID{Hash: 0xa00bc324, Next: 0}, ErrRemoteStale}, + + // Local is mainnet Petersburg, and isn't aware of more forks. Remote announces Petersburg + + // 0xffffffff. Local needs software update, reject. + {7987396, ID{Hash: 0x5cddc0e1, Next: 0}, ErrLocalIncompatibleOrStale}, + + // Local is mainnet Byzantium, and is aware of Petersburg. Remote announces Petersburg + + // 0xffffffff. Local needs software update, reject. + {7279999, ID{Hash: 0x5cddc0e1, Next: 0}, ErrLocalIncompatibleOrStale}, + + // Local is mainnet Petersburg, remote is Rinkeby Petersburg. + {7987396, ID{Hash: 0xafec6b27, Next: 0}, ErrLocalIncompatibleOrStale}, + + // Local is mainnet Petersburg, far in the future. Remote announces Gopherium (non existing fork) + // at some future block 88888888, for itself, but past block for local. Local is incompatible. + // + // This case detects non-upgraded nodes with majority hash power (typical Ropsten mess). + {88888888, ID{Hash: 0x668db0af, Next: 88888888}, ErrLocalIncompatibleOrStale}, + + // Local is mainnet Byzantium. Remote is also in Byzantium, but announces Gopherium (non existing + // fork) at block 7279999, before Petersburg. Local is incompatible. + {7279999, ID{Hash: 0xa00bc324, Next: 7279999}, ErrLocalIncompatibleOrStale}, +} +``` + +Here's a couple of tests to verify the proper RLP encoding (since `FORK_HASH` is a 4 byte binary but `FORK_NEXT` is an 8 byte quantity): + +```go +tests := []struct { + id ID + want []byte +}{ + { + ID{Hash: 0, Next: 0}, + common.Hex2Bytes("c6840000000080"), + }, + { + ID{Hash: 0xdeadbeef, Next: 0xBADDCAFE}, + common.Hex2Bytes("ca84deadbeef84baddcafe"), + }, + { + ID{Hash: math.MaxUint32, Next: math.MaxUint64}, + common.Hex2Bytes("ce84ffffffff88ffffffffffffffff"), + }, +} +``` + +## Implementation + +Geth: https://github.com/ethereum/go-ethereum/tree/master/core/forkid + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2135.md b/EIPS/eip-2135.md new file mode 100644 index 00000000000000..731777c2aea3e3 --- /dev/null +++ b/EIPS/eip-2135.md @@ -0,0 +1,7 @@ +--- +eip: 2135 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2135.md diff --git a/EIPS/eip-214.md b/EIPS/eip-214.md index 9a91ccc43fe765..009d0e1ce76b2c 100644 --- a/EIPS/eip-214.md +++ b/EIPS/eip-214.md @@ -1,7 +1,7 @@ --- eip: 214 title: New opcode STATICCALL -author: Vitalik Buterin , Christian Reitwiessner ; +author: Vitalik Buterin , Christian Reitwiessner type: Standards Track category: Core status: Final @@ -48,4 +48,4 @@ To be written. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2157.md b/EIPS/eip-2157.md new file mode 100644 index 00000000000000..0a6c2541e17816 --- /dev/null +++ b/EIPS/eip-2157.md @@ -0,0 +1,7 @@ +--- +eip: 2157 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2157.md diff --git a/EIPS/eip-2159.md b/EIPS/eip-2159.md new file mode 100644 index 00000000000000..ca57907ded2b17 --- /dev/null +++ b/EIPS/eip-2159.md @@ -0,0 +1,59 @@ +--- +eip: 2159 +title: Common Prometheus Metrics Names for Clients +author: Adrian Sutton (@ajsutton) +discussions-to: https://ethereum-magicians.org/t/common-chain-metrics/3415 +status: Final +type: Standards Track +category: Interface +created: 2019-07-01 +--- + +## Simple Summary +Standardized names of common metrics for Ethereum clients to use with Prometheus, a widely used monitoring and alerting solution. + +## Abstract +Many Ethereum clients expose a range of metrics in a format compatible with Prometheus to allow operators to monitor the client's behaviour and performance and raise alerts if the chain isn't progressing or there are other indications of errors. +While the majority of these metrics are highly client-specific, reporting on internal implementation details of the client, some are applicable to all clients. +By standardizing the naming and format of these common metrics, operators are able to monitor the operation of multiple clients in a single dashboard or alerting configuration. + +## Motivation +Using common names and meanings for metrics which apply to all clients allows node operators to monitor clusters of nodes using heterogeneous clients using a single dashboard and alerting configuration. +Currently there are no agreed names or meanings, leaving client developers to invent their own making it difficult to monitor a heterogeneous cluster. + +## Specification +The table below defines metrics which may be captured by Ethereum clients which expose metrics to Prometheus. Clients may expose additional metrics however these should not use the `ethereum_` prefix. + +| Name | Metric type | Definition | JSON-RPC Equivalent | +|----------------------------------|-------------|-------------------------------------------------------------------|---------------------------------------------------------------------| +| ethereum_blockchain_height | Gauge | The current height of the canonical chain | `eth_blockNumber` | +| ethereum_best_known_block_number | Gauge | The estimated highest block available | `highestBlock` of `eth_syncing` or `eth_blockNumber` if not syncing | +| ethereum_peer_count | Gauge | The current number of peers connected | `net_peerCount` | +| ethereum_peer_limit | Gauge | The maximum number of peers this node allows to connect | No equivalent | + +Note that `ethereum_best_known_block_number` always has a value. When the `eth_syncing` JSON-RPC method would return `false`, the current chain height is used. + +## Rationale +The defined metrics are independent of Ethereum client implementation but provide sufficient information to create an overview dashboard to support monitoring a group of Ethereum nodes. + +There is a similar, though more prescriptive, specification for beacon chain client metrics. +The specific details of how to expose the metrics has been omitted as there is variance in existing implementations and standardising this does not provide any significant benefit. + +## Backwards Compatibility +This is *not* a consensus affecting change. + +Clients may already be publishing these metrics using different names and changing to the new form may break existing alerts or dashboards. Clients that want to avoid this incompatibility can expose the metrics under both the old and new names. + +Clients may also be publishing metrics with a different meaning using these names. Backwards compatibility cannot be preserved in this case. + + +## Implementation +Pantheon switched to using these standard metric names in its 1.2 release: https://github.com/PegaSysEng/pantheon/pull/1634. + +## References + + 1. Prometheus. https://prometheus.io + 2. Beacon chain metrics specification. https://github.com/ethereum/eth2.0-metrics/blob/master/metrics.md + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2193.md b/EIPS/eip-2193.md new file mode 100644 index 00000000000000..a27b4aa888bb95 --- /dev/null +++ b/EIPS/eip-2193.md @@ -0,0 +1,7 @@ +--- +eip: 2193 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2193.md diff --git a/EIPS/eip-2200.md b/EIPS/eip-2200.md new file mode 100644 index 00000000000000..39fb53be512985 --- /dev/null +++ b/EIPS/eip-2200.md @@ -0,0 +1,322 @@ +--- +eip: 2200 +title: Structured Definitions for Net Gas Metering +author: Wei Tang (@sorpaas) +discussions-to: https://github.com/sorpaas/EIPs/issues/1 +status: Final +type: Standards Track +category: Core +created: 2019-07-18 +--- + +## Simple Summary + +This is an EIP that implements net gas metering. It's a combined +version of [EIP-1283] and [EIP-1706], with a structured definition so as +to make it interoperable with other gas changes such as [EIP-1884]. + +## Abstract + +This EIP provides a structured definition of net gas metering changes +for `SSTORE` opcode, enabling new usages for contract storage, and +reducing excessive gas costs where it doesn’t match how most +implementation works. + +This is a combination of [EIP-1283] and [EIP-1706]. + +## Motivation + +This EIP proposes a way for gas metering on `SSTORE`, using information +that is more universally available to most implementations, and +require as little change in implementation structures as possible. + +* Storage slot’s original value. +* Storage slot’s current value. +* Refund counter. + +Usages that benefits from this EIP’s gas reduction scheme includes: + +* Subsequent storage write operations within the same call frame. This + includes reentry locks, same-contract multi-send, etc. +* Exchange storage information between sub call frame and parent call + frame, where this information does not need to be persistent outside + of a transaction. This includes sub-frame error codes and message + passing, etc. + +The original definition of EIP-1283 created a danger of a new kind of +reentrancy attacks on existing contracts as Solidity by default grants +a "stipend" of 2300 gas to simple transfer calls. This danger is +easily mitigated if `SSTORE` is not allowed in low gasleft state, +without breaking the backward compatibility and the original intention +of EIP-1283. + +This EIP also replaces the original EIP-1283 value definitions of gas +by parameters, so that it's more structured, and easier to define +changes in the future. + +## Specification + +Define variables `SLOAD_GAS`, `SSTORE_SET_GAS`, `SSTORE_RESET_GAS` and +`SSTORE_CLEARS_SCHEDULE`. The old and new values for those variables +are: + +* `SLOAD_GAS`: changed from `200` to `800`. +* `SSTORE_SET_GAS`: `20000`, not changed. +* `SSTORE_RESET_GAS`: `5000`, not changed. +* `SSTORE_CLEARS_SCHEDULE`: `15000`, not changed. + +Change the definition of EIP-1283 using those variables. The new +specification, combining EIP-1283 and EIP-1706, will look like +below. The terms *original value*, *current value* and *new value* are +defined in EIP-1283. + +Replace `SSTORE` opcode gas cost calculation (including refunds) with +the following logic: + +* If *gasleft* is less than or equal to gas stipend, fail the current + call frame with 'out of gas' exception. +* If *current value* equals *new value* (this is a no-op), `SLOAD_GAS` + is deducted. +* If *current value* does not equal *new value* + * If *original value* equals *current value* (this storage slot has + not been changed by the current execution context) + * If *original value* is 0, `SSTORE_SET_GAS` is deducted. + * Otherwise, `SSTORE_RESET_GAS` gas is deducted. If *new value* is + 0, add `SSTORE_CLEARS_SCHEDULE` gas to refund counter. + * If *original value* does not equal *current value* (this storage + slot is dirty), `SLOAD_GAS` gas is deducted. Apply both of the + following clauses. + * If *original value* is not 0 + * If *current value* is 0 (also means that *new value* is not + 0), remove `SSTORE_CLEARS_SCHEDULE` gas from refund + counter. + * If *new value* is 0 (also means that *current value* is not + 0), add `SSTORE_CLEARS_SCHEDULE` gas to refund counter. + * If *original value* equals *new value* (this storage slot is + reset) + * If *original value* is 0, add `SSTORE_SET_GAS - SLOAD_GAS` to + refund counter. + * Otherwise, add `SSTORE_RESET_GAS - SLOAD_GAS` gas to refund + counter. + +An implementation should also note that with the above definition, if +the implementation uses call-frame refund counter, the counter can go +negative. If the implementation uses transaction-wise refund counter, +the counter always stays positive. + +## Rationale + +This EIP mostly achieves what a transient storage tries to do +([EIP-1087] and [EIP-1153]), but without the complexity of introducing the +concept of "dirty maps", or an extra storage struct. + +* We don't suffer from the optimization limitation of + EIP-1087. EIP-1087 requires keeping a dirty map for storage changes, + and implicitly makes the assumption that a transaction's storage + changes are committed to the storage trie at the end of a + transaction. This works well for some implementations, but not for + others. After [EIP-658], an efficient storage cache implementation + would probably use an in-memory trie (without RLP encoding/decoding) + or other immutable data structures to keep track of storage changes, + and only commit changes at the end of a block. For them, it is + possible to know a storage's original value and current value, but + it is not possible to iterate over all storage changes without + incurring additional memory or processing costs. +* It never costs more gas compared with the current scheme. +* It covers all usages for a transient storage. Clients that are easy + to implement EIP-1087 will also be easy to implement this + specification. Some other clients might require a little bit extra + refactoring on this. Nonetheless, no extra memory or processing cost + is needed on runtime. + +Regarding `SSTORE` gas cost and refunds, see Appendix for proofs of +properties that this EIP satisfies. + +* For *absolute gas used* (that is, actual *gas used* minus *refund*), + this EIP is equivalent to EIP-1087 for all cases. +* For one particular case, where a storage slot is changed, reset to + its original value, and then changed again, EIP-1283 would move more + gases to refund counter compared with EIP-1087. + +Examine examples provided in EIP-1087's Motivation (with `SLOAD_GAS` being +`200`): + +* If a contract with empty storage sets slot 0 to 1, then back to 0, + it will be charged `20000 + 200 - 19800 = 400` gas. +* A contract with empty storage that increments slot 0 5 times will be + charged `20000 + 5 * 200 = 21000` gas. +* A balance transfer from account A to account B followed by a + transfer from B to C, with all accounts having nonzero starting and + ending balances, it will cost `5000 * 3 + 200 - 4800 = 10400` gas. + +In order to keep in place the implicit reentrancy protection of +existing contracts, transactions should not be allowed to modify state +if the remaining gas is lower than the gas stipend given to +"transfer"/"send" in Solidity. These are other proposed remediations +and objections to implementing them: + +* Drop EIP-1283 and abstain from modifying `SSTORE` cost + * EIP-1283 is an important update + * It was accepted and implemented on test networks and in clients. +* Add a new call context that permits LOG opcodes but not changes to state. + * Adds another call type beyond existing regular/staticcall +* Raise the cost of `SSTORE` to dirty slots to >=2300 gas + * Makes net gas metering much less useful. +* Reduce the gas stipend + * Makes the stipend almost useless. +* Increase the cost of writes to dirty slots back to 5000 gas, but add + 4800 gas to the refund counter + * Still doesn’t make the invariant explicit. + * Requires callers to supply more gas, just to have it refunded +* Add contract metadata specifying per-contract EVM version, and only + apply `SSTORE` changes to contracts deployed with the new version. + +## Backwards Compatibility + +This EIP requires a hard fork to implement. No gas cost increase is +anticipated, and many contracts will see gas reduction. + +Performing `SSTORE` has never been possible with less than 5000 gas, so +it does not introduce incompatibility to the Ethereum Mainnet. Gas +estimation should account for this requirement. + +## Test Cases + +| Code | Used Gas | Refund | Original | 1st | 2nd | 3rd | +|------------------------------------|----------|--------|----------|-----|-----|-----| +| `0x60006000556000600055` | 1612 | 0 | 0 | 0 | 0 | | +| `0x60006000556001600055` | 20812 | 0 | 0 | 0 | 1 | | +| `0x60016000556000600055` | 20812 | 19200 | 0 | 1 | 0 | | +| `0x60016000556002600055` | 20812 | 0 | 0 | 1 | 2 | | +| `0x60016000556001600055` | 20812 | 0 | 0 | 1 | 1 | | +| `0x60006000556000600055` | 5812 | 15000 | 1 | 0 | 0 | | +| `0x60006000556001600055` | 5812 | 4200 | 1 | 0 | 1 | | +| `0x60006000556002600055` | 5812 | 0 | 1 | 0 | 2 | | +| `0x60026000556000600055` | 5812 | 15000 | 1 | 2 | 0 | | +| `0x60026000556003600055` | 5812 | 0 | 1 | 2 | 3 | | +| `0x60026000556001600055` | 5812 | 4200 | 1 | 2 | 1 | | +| `0x60026000556002600055` | 5812 | 0 | 1 | 2 | 2 | | +| `0x60016000556000600055` | 5812 | 15000 | 1 | 1 | 0 | | +| `0x60016000556002600055` | 5812 | 0 | 1 | 1 | 2 | | +| `0x60016000556001600055` | 1612 | 0 | 1 | 1 | 1 | | +| `0x600160005560006000556001600055` | 40818 | 19200 | 0 | 1 | 0 | 1 | +| `0x600060005560016000556000600055` | 10818 | 19200 | 1 | 0 | 1 | 0 | + +## Implementation + +To be added. + +## Appendix: Proof + +Because the *storage slot's original value* is defined as the value +when a reversion happens on the *current transaction*, it's easy to +see that call frames won't interfere `SSTORE` gas calculation. So +although the below proof is discussed without call frames, it applies +to all situations with call frames. We will discuss the case +separately for *original value* being zero and not zero, and use +*induction* to prove some properties of `SSTORE` gas cost. + +*Final value* is the value of a particular storage slot at the end of +a transaction. *Absolute gas used* is the absolute value of *gas used* +minus *refund*. We use `N` to represent the total number of `SSTORE` +operations on a storage slot. For states discussed below, refer to +*State Transition* in *Explanation* section. + +Below we do the proof under the assumption that all parameters are +unchanged, meaning `SLOAD_GAS` is `200`. However, note that the proof +still applies no matter how `SLOAD_GAS` is changed. + +### Original Value Being Zero + +When *original value* is 0, we want to prove that: + +* **Case I**: If the *final value* ends up still being 0, we want to charge `200 * + N` gases, because no disk write is needed. +* **Case II**: If the *final value* ends up being a non-zero value, we want to + charge `20000 + 200 * (N-1)` gas, because it requires writing this + slot to disk. + +#### Base Case + +We always start at state A. The first `SSTORE` can: + +* Go to state A: 200 gas is deducted. We satisfy *Case I* because + `200 * N == 200 * 1`. +* Go to state B: 20000 gas is deducted. We satisfy *Case II* because + `20000 + 200 * (N-1) == 20000 + 200 * 0`. + +#### Inductive Step + +* From A to A. The previous gas cost is `200 * (N-1)`. The current + gas cost is `200 + 200 * (N-1)`. It satisfy *Case I*. +* From A to B. The previous gas cost is `200 * (N-1)`. The current + gas cost is `20000 + 200 * (N-1)`. It satisfy *Case II*. +* From B to B. The previous gas cost is `20000 + 200 * (N-2)`. The + current gas cost is `200 + 20000 + 200 * (N-2)`. It satisfy + *Case II*. +* From B to A. The previous gas cost is `20000 + 200 * (N-2)`. The + current gas cost is `200 - 19800 + 20000 + 200 * (N-2)`. It satisfy + *Case I*. + +### Original Value Not Being Zero + +When *original value* is not 0, we want to prove that: + +* **Case I**: If the *final value* ends up unchanged, we want to + charge `200 * N` gases, because no disk write is needed. +* **Case II**: If the *final value* ends up being zero, we want to + charge `5000 - 15000 + 200 * (N-1)` gas. Note that `15000` is the + refund in actual definition. +* **Case III**: If the *final value* ends up being a changed non-zero + value, we want to charge `5000 + 200 * (N-1)` gas. + +#### Base Case + +We always start at state X. The first `SSTORE` can: + +* Go to state X: 200 gas is deducted. We satisfy *Case I* because + `200 * N == 200 * 1`. +* Go to state Y: 5000 gas is deducted. We satisfy *Case III* because + `5000 + 200 * (N-1) == 5000 + 200 * 0`. +* Go to state Z: The absolute gas used is `5000 - 15000` where 15000 + is the refund. We satisfy *Case II* because `5000 - 15000 + 200 * + (N-1) == 5000 - 15000 + 200 * 0`. + +#### Inductive Step + +* From X to X. The previous gas cost is `200 * (N-1)`. The current gas + cost is `200 + 200 * (N-1)`. It satisfy *Case I*. +* From X to Y. The previous gas cost is `200 * (N-1)`. The current gas + cost is `5000 + 200 * (N-1)`. It satisfy *Case III*. +* From X to Z. The previous gas cost is `200 * (N-1)`. The current + absolute gas cost is `5000 - 15000 + 200 * (N-1)`. It satisfy *Case + II*. +* From Y to X. The previous gas cost is `5000 + 200 * (N-2)`. The + absolute current gas cost is `200 - 4800 + 5000 + 200 * (N-2)`. It + satisfy *Case I*. +* From Y to Y. The previous gas cost is `5000 + 200 * (N-2)`. The + current gas cost is `200 + 5000 + 200 * (N-2)`. It satisfy *Case + III*. +* From Y to Z. The previous gas cost is `5000 + 200 * (N-2)`. The + current absolute gas cost is `200 - 15000 + 5000 + 200 * (N-2)`. It + satisfy *Case II*. +* From Z to X. The previous gas cost is `5000 - 15000 + 200 * + (N-2)`. The current absolute gas cost is `200 + 10200 + 5000 - + 15000 + 200 * (N-2)`. It satisfy *Case I*. +* From Z to Y. The previous gas cost is `5000 - 15000 + 200 * + (N-2)`. The current absolute gas cost is `200 + 15000 + 5000 - + 15000 + 200 * (N-2)`. It satisfy *Case III*. +* From Z to Z. The previous gas cost is `5000 - 15000 + 200 * + (N-2)`. The current absolute gas cost is `200 + 5000 - 15000 + 200 * + (N-2)`. It satisfy *Case II*. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + +[EIP-1283]: ./eip-1283.md +[EIP-1706]: ./eip-1706.md +[EIP-1884]: ./eip-1884.md +[EIP-1087]: ./eip-1087.md +[EIP-1153]: ./eip-1153.md +[EIP-658]: ./eip-658.md diff --git a/EIPS/eip-2228.md b/EIPS/eip-2228.md new file mode 100644 index 00000000000000..c8ac1a4cf1972f --- /dev/null +++ b/EIPS/eip-2228.md @@ -0,0 +1,95 @@ +--- +eip: 2228 +title: Canonicalize the name of network ID 1 and chain ID 1 +author: William Entriken (@fulldecent) +discussions-to: https://github.com/ethereum/EIPs/issues/2228 +status: Final +type: Informational +created: 2019-08-04 +--- + +## Simple Summary + +The Ethereum network with network ID 1 and chain ID 1 is named Ethereum Mainnet. + +## Abstract + +The name for the Ethereum network with network ID 1 and chain ID 1 shall be Ethereum Mainnet or just Mainnet. This is a proper noun. + +This standard specifies the name for this network and provides reference examples in an effort to standardize the word choice and provide a common language for use to refer to this network. + +## Motivation + +The Ethereum network with network ID 1 and chain ID 1 is referenced using several conflicting names across EIPs, client implementations, and information published on the internet at large. In several locations, even documents written by the same author use inconsistent names to refer to the Ethereum network with network ID 1 and chain ID 1. Names in use at the time of this writing include: + +* "main net" +* "mainnet" +* "Main net" +* "Mainnet" + +## Specification + +The network name for network ID 1 and chain ID 1 shall be Ethereum Mainnet, or just Mainnet if the context is known to be discussing Ethereum networks. This IS a proper noun. Several examples are given below which differentiate between usage of the name of the network versus a descriptive reference to the network. + +Any name or word styling (i.e. capitalization of the letters) of the network which is inconsistent with the test cases cited below shall NOT be used. + +### Trademark note + +"Ethereum" is trademarked by the Ethereum Foundation. For more information on your obligations when mentioning "Ethereum", and possibly "Ethereum Mainnet", see: + +* USPTO registration number 5110579 by Ethereum Foundation +* The note "you must not use [this mark] without the prior written permission of the Foundation" on the Ethereum Foundation website, Terms of Use page + +## Rationale + +Choosing common word use promotes interoperability of implementations and increases customer awareness. Also, it adds a sense of professionalism when customers see the same word and word styling (i.e. capitalization of letters) across different implementations. + +Anybody that has travelled to certain countries and seen an "IPhone [sic]" repair store should immediately recognize that this is off-brand and unofficial. Likewise, the astute customer of Ethereum should recognize if they see the network referred to using inconsistent names in different software, so let's avoid this. + +## Backwards Compatibility + +- MetaMask previously used "Main Ethereum Network" in the account network chooser. MetaMask has been updated consistent with this EIP. + +- References to Mainnet that are inconsistent with this specification are made in: [EIP-2](./eip-2.md), [EIP-779](./eip-779.md), [EIP-150](./eip-150.md), [EIP-155](./eip-155.md), [EIP-190](./eip-190.md), [EIP-225](./eip-225.md), [EIP-1013](./eip-1013.md), [EIP-2028](./eip-2028.md), and [EIP-2387](./eip-2387.md). For consistency, we recommend the editor will update EIPs to consistently use the name as specified in this EIP. + +## Test Cases + +### Examples referencing the name of the network ✅ + +> The contract was deployed to Ethereum Mainnet. + +> Ethereum runs many applications, this Dapp was deployed to Mainnet. + +No specification is made on whether Dapp, dapp, dApp, etc. is preferred. + +> SWITCH TO MAINNET + +This example shows a user interface which is in uppercase. To be semantically correct, this could be written in HTML as `Switch to Mainnet`. + +> switch to mainnet + +This example shows a user interface which is in lowercase. To be semantically correct, this could be written in HTML as `Switch to Mainnet`. + +### Examples referencing the network in a descriptive way ✅ + +> Mainnet has ### times the number of transactions as the test networks. + +### Examples of other correct word usage ✅ + +> The main network on Ethereum is Mainnet + +This shows that "main" is used as a descriptive word, but Mainnet is the specific network which is having network ID 1 and chain ID 1. + +### Examples of poor word choice (avoid this) ❌ + +> Deploy your contract to the Ethereum main network. + +This is referring to a "main" network which is context-dependent. If you were reading this text on a page about Ethereum Classic, they would be referring to network ID 2 and chain ID 62. Therefore this word usage is less crisp. Do NOT use wording like this. + +> Connect to mainnet. + +These words literally mean nothing. The lowercase, not-proper-noun word "mainnet" is not a plain English word and it should not be in any dictionary. Do NOT use wording like this. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-223.md b/EIPS/eip-223.md new file mode 100644 index 00000000000000..6096d61cbca7c3 --- /dev/null +++ b/EIPS/eip-223.md @@ -0,0 +1,7 @@ +--- +eip: 223 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-223.md diff --git a/EIPS/eip-2242.md b/EIPS/eip-2242.md new file mode 100644 index 00000000000000..7dc308cef0e5c7 --- /dev/null +++ b/EIPS/eip-2242.md @@ -0,0 +1,60 @@ +--- +eip: 2242 +title: Transaction Postdata +author: John Adler (@adlerjohn) +discussions-to: https://ethereum-magicians.org/t/eip-2242-transaction-postdata/3557 +status: Stagnant +type: Standards Track +category: Core +created: 2019-08-16 +--- + +## Simple Summary +An additional, optional transaction field is added for "postdata," data that is posted on-chain but that cannot be read from the EVM. + +## Abstract +A paradigm shift in how blockchains are used has been seen recently in Eth 2.0, with the rise of [_Execution Environments_](https://notes.ethereum.org/w1Pn2iMmSTqCmVUTGV4T5A?view) (EEs), and [_stateless clients_](https://ethresear.ch/t/the-stateless-client-concept/172). This shift involves blockchains serving as a secure data availability and arbitration layer, _i.e._, they provide a globally-accepted source of available data, and process fraud/validity and data availability proofs. This same paradigm can be applied on Eth 1.x, replacing EEs with [trust-minimized side chains](https://ethresear.ch/t/building-scalable-decentralized-payment-systems-request-for-feedback/5312). + +## Motivation +While [EIP-2028](./eip-2028.md) provides a reduction in gas cost of calldata, and is a step in the right direction of encouraging use of history rather than state, the EVM does not actually need to see all data that is posted on-chain. Following the principle of "don't pay for what you don't use," a distinct way of posting data on-chain, but without actually being usable within the EVM, is needed. + +For [trust-minimized side chains with fraud proofs](https://ethresear.ch/t/minimal-viable-merged-consensus/5617), we simply need to ensure that the side chain block proposer has attested that _some_ data is available. Authentication can be performed as part of a fraud proof should that data end up invalid. Note that [trust-minimized side chains with validity proofs](https://ethresear.ch/t/on-chain-scaling-to-potentially-500-tx-sec-through-mass-tx-validation/3477) can't make use of the changes proposed in this EIP, as they required immediate authentication of the posted data. This will be [the topic of a future EIP](https://ethresear.ch/t/multi-threaded-data-availability-on-eth-1/5899). + +## Specification +We propose a consensus modification, beginning at `FORK_BLKNUM`: + +An additional optional field, `postdata`, is added to transactions. Serialized transactions now have the format: +``` +"from": bytes20, +"to": bytes20, +"startGas": uint256, +"gasPrice": uint256, +"value": uint256, +"data": bytes, +"nonce": uint256, +["postdata": bytes], +``` +with witnesses signing over the [RLP encoding](https://github.com/ethereum/wiki/wiki/RLP) of the above. `postdata` is data that is posted on-chain, for later historical retrieval by layer-2 systems. + +`postdata` is an RLP-encoded twople `(version: uint64, data: bytes)`. +1. `version` is `0`. +1. `data` is an RLP-encoded list of binary data. This EIP does not interpret the data in any way, simply considering it as a binary blob, though future EIPs may introduce different interpretation schemes for different values of `version`. + +The gas cost of the posted data is `1 gas per byte`. This cost is deducted from the `startGas`; if the remaining gas is non-positive the transaction immediately reverts with an out of gas exception. + +## Rationale +The changes proposed are as minimal and non-disruptive to the existing EVM and transaction format as possible while also supporting possible [future extensions](https://ethresear.ch/t/multi-threaded-data-availability-on-eth-1/5899) through a version code. + +## Backwards Compatibility +The new transaction format is backwards compatible, as the new `postdata` field is optionally appended to existing transactions. + +The proposed changes are not forwards-compatible, and will require a hard fork. + +## Test Cases +TODO + +## Implementation +TODO + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-225.md b/EIPS/eip-225.md index 2404a73bd4fa6e..b14fa30a4edd23 100644 --- a/EIPS/eip-225.md +++ b/EIPS/eip-225.md @@ -3,7 +3,7 @@ eip: 225 title: Clique proof-of-authority consensus protocol author: Péter Szilágyi discussions-to: https://github.com/ethereum/EIPs/issues/225 -status: Draft +status: Final type: Standards Track category: Core created: 2017-03-06 @@ -98,6 +98,7 @@ We define the following constants: * Suggested `32 bytes` to retain the current extra-data allowance and/or use. * **`EXTRA_SEAL`**: Fixed number of extra-data suffix bytes reserved for signer seal. * `65 bytes` fixed as signatures are based on the standard `secp256k1` curve. + * Filled with zeros on genesis block. * **`NONCE_AUTH`**: Magic nonce number `0xffffffffffffffff` to vote on adding a new signer. * **`NONCE_DROP`**: Magic nonce number `0x0000000000000000` to vote on removing a signer. * **`UNCLE_HASH`**: Always `Keccak256(RLP([]))` as uncles are meaningless outside of PoW. @@ -110,19 +111,19 @@ We also define the following per-block constants: * **`BLOCK_NUMBER`**: Block height in the chain, where the height of the genesis is block `0`. * **`SIGNER_COUNT`**: Number of authorized signers valid at a particular instance in the chain. - * **`SIGNER_INDEX`**: Index of the block signer in the sorted list of current authorized signers. + * **`SIGNER_INDEX`**: Zero-based index of the block signer in the sorted list of current authorized signers. * **`SIGNER_LIMIT`**: Number of consecutive blocks out of which a signer may only sign one. * Must be `floor(SIGNER_COUNT / 2) + 1` to enforce majority consensus on a chain. We repurpose the `ethash` header fields as follows: - * **`beneficiary`**: Address to propose modifying the list of authorized signers with. + * **`beneficiary`** / **`miner`**: Address to propose modifying the list of authorized signers with. * Should be filled with zeroes normally, modified only while voting. * Arbitrary values are permitted nonetheless (even meaningless ones such as voting out non signers) to avoid extra complexity in implementations around voting mechanics. * **Must** be filled with zeroes on checkpoint (i.e. epoch transition) blocks. - * Transaction execution **must** use the actual block signer (see `extraData`) for the `COINBASE` opcode. + * Transaction execution **must** use the actual block signer (see `extraData`) for the `COINBASE` opcode and transaction fees **must** be attributed to the signer account. * **`nonce`**: Signer proposal regarding the account defined by the `beneficiary` field. - * Should be **`NONCE_DROP`** to propose deauthorizing `beneficiary` as a existing signer. + * Should be **`NONCE_DROP`** to propose deauthorizing `beneficiary` as an existing signer. * Should be **`NONCE_AUTH`** to propose authorizing `beneficiary` as a new signer. * **Must** be filled with zeroes on checkpoint (i.e. epoch transition) blocks. * **Must** not take up any other value apart from the two above (for now). @@ -130,7 +131,7 @@ We repurpose the `ethash` header fields as follows: * First **`EXTRA_VANITY`** bytes (fixed) may contain arbitrary signer vanity data. * Last **`EXTRA_SEAL`** bytes (fixed) is the signer's signature sealing the header. * Checkpoint blocks **must** contain a list of signers (`N*20 bytes`) in between, **omitted** otherwise. - * The list of signers in checkpoint block extra-data sections **must** be sorted in ascending order. + * The list of signers in checkpoint block extra-data sections **must** be sorted in ascending byte order. * **`mixHash`**: Reserved for fork protection logic, similar to the extra-data during the DAO. * **Must** be filled with zeroes during normal operation. * **`ommersHash`**: **Must** be **`UNCLE_HASH`** as uncles are meaningless outside of PoW. @@ -141,11 +142,11 @@ We repurpose the `ethash` header fields as follows: ### Authorizing a block -To authorize a block for the network, the signer needs to sign the block's hash containing **everything except the signature itself**. The means that the hash contains every field of the header (`nonce` and `mixDigest` included), and also the `extraData` with the exception of the 65 byte signature suffix. The fields are hashed in the order of their definition in the yellow paper. +To authorize a block for the network, the signer needs to sign the block's sighash containing **everything except the signature itself**. This means that this hash contains every field of the header (`nonce` and `mixDigest` included), and also the `extraData` with the exception of the 65 byte signature suffix. The fields are hashed in the order of their definition in the yellow paper. Note that this sighash differs from the final block hash which also includes the signature. -This hash is signed using the standard `secp256k1` curve, and the resulting 65 byte signature (`R`, `S`, `V`, where `V` is `0` or `1`) is embedded into the `extraData` as the trailing 65 byte suffix. +The sighash is signed using the standard `secp256k1` curve, and the resulting 65 byte signature (`R`, `S`, `V`, where `V` is `0` or `1`) is embedded into the `extraData` as the trailing 65 byte suffix. -To ensure malicious signers (loss of signing key) cannot wreck havoc in the network, each singer is allowed to sign **maximum one** out of **`SIGNER_LIMIT`** consecutive blocks. The order is not fixed, but in-turn signing weighs more (**`DIFF_INTURN`**) than out of turn one (**`DIFF_NOTURN`**). +To ensure malicious signers (loss of signing key) cannot wreck havoc in the network, each signer is allowed to sign **maximum one** out of **`SIGNER_LIMIT`** consecutive blocks. The order is not fixed, but in-turn signing weighs more (**`DIFF_INTURN`**) than out of turn one (**`DIFF_NOTURN`**). #### Authorization strategies @@ -191,7 +192,7 @@ This list may be expired after a certain number of blocks / epochs, but it's imp ## Test Cases ```go -// block represents a single block signed by a parcitular account, where +// block represents a single block signed by a particular account, where // the account may or may not have cast a Clique vote. type block struct { signer string // Account that signed this particular block @@ -211,7 +212,9 @@ tests := []struct { { // Single signer, no votes cast signers: []string{"A"}, - blocks: []block{{signer: "A"}}, + blocks: []block{ + {signer: "A"} + }, results: []string{"A"}, }, { // Single signer, voting to add two others (only accept first, second needs 2 votes) @@ -446,9 +449,9 @@ tests := []struct { }, failure: errUnauthorizedSigner, }, { - // An authorized signer that signed recenty should not be able to sign again + // An authorized signer that signed recently should not be able to sign again signers: []string{"A", "B"}, - blocks []block{ + blocks: []block{ {signer: "A"}, {signer: "A"}, }, @@ -464,7 +467,7 @@ tests := []struct { {signer: "A"}, }, failure: errRecentlySigned, - },, + }, } ``` @@ -472,4 +475,4 @@ tests := []struct { A reference implementation is part of [go-ethereum](https://github.com/ethereum/go-ethereum/tree/master/consensus/clique) and has been functioning as the consensus engine behind the [Rinkeby](https://www.rinkeby.io) testnet since April, 2017. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2255.md b/EIPS/eip-2255.md new file mode 100644 index 00000000000000..14d31a8f67727d --- /dev/null +++ b/EIPS/eip-2255.md @@ -0,0 +1,151 @@ +--- +eip: 2255 +title: Wallet Permissions System +description: An interface to restrict access to sensitive methods +author: Dan Finlay (@danfinlay), Erik Marks (@rekmarks), Gavin John (@Pandapip1) +discussions-to: https://ethereum-magicians.org/t/web3-login-permissions/3583 +status: Final +type: Standards Track +category: Interface +created: 2019-08-22 +requires: 1193 +--- + +## Abstract + +This EIP adds two new wallet-namespaced RPC endpoints, `wallet_getPermissions` and `wallet_requestPermissions`, providing a standard interface for requesting and checking permissions. + +## Motivation + +Wallets are responsible for mediating interactions between untrusted applications and users' keys through appropriate user consent. Today, wallets always prompt the user for every action. This provides security at the cost of substantial user friction. We believe that a single permissions request can achieve the same level of security with vastly improved UX. + +The pattern of permissions requests (typically using Oauth2) is common around the web, making it a very familiar pattern: + +![Facebook Permissions](../assets/eip-2255/facebook_permissions.png) + +![Log in With Apple](../assets/eip-2255/log_in_with_apple.jpeg) + +Many web3 applications today begin their sessions with a series of repetitive requests: + +- Reveal your wallet address to this site. +- Switch to a preferred network. +- Sign a cryptographic challenge. +- Grant a token allowance to our contract. +- Send a transaction to our contract. + +Many of these (and possibly all), and many more (like decryption), could be generalized into a set of human-readable permissions prompts on the original sign-in screen, and additional permissions could be requested only as needed: + +![Sample prompt screenshot](../assets/eip-2255/permissions.png) + +Each of these permissions could be individually rejected, or even _attenuated_--adjusted to meet the user's terms (for example, a sign-in request could have a user-added expiration date, and a token allowance could be adjusted by the user when it is requested). + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. + +This proposal adds two new methods to a wallet's web3 provider API: `wallet_getPermissions` and `wallet_requestPermissions`. + +### `wallet_getPermissions` + +The `wallet_getPermissions` method is used for getting an array of current permissions (empty by default). It takes no parameters and returns an array of `Permission` objects. + +#### `wallet_getPermissions` Returns + +The format of the returned permissions MUST be an array of `Permission` objects, which are defined as follows: + +```typescript +interface Caveat { + type: string; + value: any; +} + +interface Permission { + invoker: string; + parentCapability: string; + caveats: Caveat[]; +} +``` + +The `invoker` is a URI used to identify the source of the current dapp (e.g. `https://your-site.com/`). The term `parentCapability` refers to the method that is being permitted (e.g. `eth_accounts`). The `caveats` array represents the specific restrictions applied to the permitted method. The `type` of a `Caveat` is a string, and the `value` is an arbitrary JSON value. The `value` of a `Caveat` is only meaningful in the context of the `type` of the `Caveat`. + +### `wallet_requestPermissions` + +The `wallet_requestPermissions` method is used for an application to request additional permissions. It MUST take a single parameter, a `PermissionRequest` object, and MUST return an array of `RequestedPermission` objects. + +#### `wallet_requestPermissions` Parameters + +The `wallet_requestPermissions` method takes a single parameter, a `PermissionRequest` object, which is defined as follows: + +```typescript +interface PermissionRequest { + [methodName: string]: { + [caveatName: string]: any; + }; +} +``` + +The `methodName` is the name of the method for which the permission is being requested (e.g. `eth_accounts`). The `caveatName` is the name of the caveat being applied to the permission (e.g. `requiredMethods`). The caveat value is the value of the caveat (e.g. `["signTypedData_v3"]`). + +Attempted requests to a restricted method must fail with an error, until a `wallet_requestPermissions` request is made and accepted by the user. + +If a `wallet_requestPermissions` request is rejected, it should throw an error with a `code` value equal to `4001` as per [EIP-1193](./eip-1193.md). + +#### `wallet_requestPermissions` Returns + +The `wallet_requestPermissions` method returns an array of `RequestedPermission` objects, which are defined as follows: + +```typescript +interface RequestedPermission { + parentCapability: string; + date?: number; +} +``` + +The `parentCapability` is the name of the method for which the permission is being requested (e.g. `eth_accounts`). The `date` is the timestamp of the request, in Unix time, and is optional. + +## Rationale + +While the current model of getting user consent on a per-action basis has high security, there are huge usability gains to be had bo getting more general user consent which can cover broad categories of usage, which can be expressed in a more human-readable way. This pattern has a variety of benefits to offer different functions within a web3 wallet. + +The `requestPermissions` method can be expanded to include other options related to the requested permissions, for example, sites could request accounts with specific abilities. For example, a website like an exchange that requires `signTypedData_v3` (which is not supported by some hardware wallets), might want to specify that requirement. This would allow wallets to display only compatible accounts, while preserving the user's privacy and choice regarding how they are storing their keys. + +## Test Cases + +### Requesting permissions + +The following example should prompt the user to approve the `eth_accounts` permission, and return the permission object if approved. + +```javascript +provider.request({ + method: 'requestPermissions', + params: [ + { + 'eth_accounts': { + requiredMethods: ['signTypedData_v3'] + } + } + ] +}); +``` + +### Getting permissions + +The following example should return the current permissions object. + +```javascript +provider.request({ + method: 'getPermissions' +}); +``` + +## Security Considerations + +### Server-Side Request Forgery (SSRF) + +This consideration is applicable if the favicon of a website is to be displayed. + +Wallets should be careful about making arbitrary requests to URLs. As such, it is recommended for wallets to sanitize the URI by whitelisting specific schemes and ports. A vulnerable wallet could be tricked into, for example, modifying data on a locally-hosted redis database. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2256.md b/EIPS/eip-2256.md new file mode 100644 index 00000000000000..eb556fff2523d8 --- /dev/null +++ b/EIPS/eip-2256.md @@ -0,0 +1,197 @@ +--- +eip: 2256 +title: wallet_getOwnedAssets JSON-RPC Method +author: Loredana Cirstea (@loredanacirstea) +discussions-to: https://ethereum-magicians.org/t/eip-2256-add-wallet-getownedassets-json-rpc-method/3600 +status: Stagnant +type: Standards Track +category: Interface +created: 2019-08-29 +requires: 55, 155, 1474 +--- + +## Simple Summary + +This is a proposal for a new JSON-RPC call for retrieving from a wallet a selection of owned assets by an Ethereum address, with the user's permission. + +## Abstract + +There is no standardized way for a dApp to request a list of owned assets from a user. Now, each dApp needs to keep a list of all the popular or existing assets and check the user's balance against the blockchain, for each of these assets. This leads to duplicated effort across dApps. It also leads to the user being presented with asset options that the user does not care about, from various, unwanted airdrops. + +## Motivation + +There are financial dApps that require a list of owned assets from a user, for various purposes - calculating taxes, selecting customized payment options, etc. Each of these dApps are now forced to keep a list of popular assets (smart contract addresses, ABIs) and retrieve the user's data from the blockchain, for each asset. This leads to effort duplication and nonoptimal UX where the user is presented with either more or less asset options than the user would like - various airdrops, incomplete list of assets kept by the dApp. + +This list of owned assets can be retrieved from the wallet used by the user. The wallet can allow the user to manage only the assets that the user is interested in. Therefore, a new JSON-RPC method is proposed: `wallet_getOwnedAssets`. This method is complementary to [EIP-747](./eip-747.md), which proposes a way for sites to suggest users new assets to watch on their wallet. + +## Specification + +New JSON-RPC method to be added to web3 browsers: `wallet_getOwnedAssets`. This method is for dApp-wallet communication and only targets the assets that have already been whitelisted by the wallet, for the user account. + +**Arguments:** +- type `address`, Ethereum address that owns the assets +- options object, optional: + - `chainId` - type `uint`, chain id respecting [EIP-155](./eip-155.md); optional + - `limit` - type `uint`, the maximum number of owned assets expected by the dApp to be returned; optional + - `types` - type `string[]`, array of asset interface identifiers such as `['ERC20', 'ERC721']`; optional + - `justification` - type `string`, human-readable text provided by the dApp, explaining the intended purpose of this request; optional but recommended + +**Result:** +- array with asset records: + - `address` - type `address`, Ethereum checksummed address + - `chainId` - type `uint`, identifier for the chain on which the assets are deployed + - `type` - type `string`, asset interface ERC identifier; e.g. `ERC20`; optional - [EIP-1820](./eip-1820.md) could be used + - `options` - an object with asset-specific fields; `ERC20` tokens example: + - `name` - type `string`, token name; optional if the token does not implement it + - `symbol` - type `string`, token symbol; optional if the token does not implement it + - `icon`- type `base64`, token icon; optional + - `balance` - type `uint`, the number of tokens that the user owns, in the smallest token denomination + - `decimals` - type `uint`, the number of decimals implemented by the token; optional + +### Examples + +**1) A request to return all of the user's owned assets:** +```json +{ + "id":1, + "jsonrpc": "2.0", + "method": "wallet_getOwnedAssets", + "params": [ + "0x3333333333333333333333333333333333333333", + { + "justification": "The dApp needs to know about all your assets in order to calculate your taxes properly." + } + ] +} +``` +Result: + +```json +{ + "id":1, + "jsonrpc": "2.0", + "result": [ + { + "address": "0x0000000000000000000000000000000000000001", + "chainId": 1, + "type": "ERC20", + "options": { + "name": "TokenA", + "symbol": "TKA", + "icon": "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==", + "balance": 1000000000000, + "decimals": 18 + } + }, + { + "address": "0x0000000000000000000000000000000000000002", + "chainId": 3, + "type": "ERC20", + "options": { + "name": "TokenB", + "symbol": "TKB", + "icon": "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==", + "balance": 2000000000000, + "decimals": 18 + } + }, + { + "address": "0x0000000000000000000000000000000000000003", + "chainId": 42, + "type": "ERC721", + "options": { + "name": "TokenC", + "symbol": "TKC", + "icon": "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==", + "balance": 10 + } + }, + ] +} +``` + +**2) A request to return one `ERC20` owned asset, deployed on `chainId` 1:** +```json +{ + "id":1, + "jsonrpc": "2.0", + "method": "wallet_getOwnedAssets", + "params": [ + "0x3333333333333333333333333333333333333333", + { + "chainId": 1, + "limit": 1, + "types": ["ERC20"], + "justification": "Select your token of choice, in order to pay for our services." + } + ] +} +``` +Result: + +```json +{ + "id":1, + "jsonrpc": "2.0", + "result": [ + { + "address": "0x0000000000000000000000000000000000000001", + "chainId": 1, + "type": "ERC20", + "options": { + "name": "TokenA", + "symbol": "TKA", + "icon": "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==", + "balance": 1000000000000, + "decimals": 18 + } + } + ] +} +``` + +### UI Best Practices + +The wallet should display a UI to the user, showing the request. +The user can: +- accept the request, in which case the dApp receives all the requested assets +- reject the request +- amend the request by lowering the number of owned assets returned to the dApp + + +If all owned assets are requested, the total number of owned assets will be shown to the user. The user can also choose to select the assets that will be returned to the dApp, amending the request. + +If a selection is requested, the user will select from the list of owned assets. + +As an optimization, wallets can keep a list of frequently used assets by the user, and show that list first, with the option of expanding that list with owned assets that the user uses less frequently. + +## Rationale + +In order to avoid duplication of effort for dApps that require keeping a list of all or popular assets and to provide optimal UX, the `wallet_getOwnedAssets` JSON-RPC method is proposed. + +The `chainId` and `types` optional parameters enable dApps to provide options in order to restrict the selection list that the user will be presented with by the wallet, in accordance with the dApp's functionality. The `limit` parameter enables the dApp to tell the user an upper limit of accounts that the user can select. It remains to be seen if a lower bound should also be provided. At the moment, this lower bound can be considered as being `1`. + +The `options` response field provides the dApp with asset-specific options, enabling better UX through using the same visual and text identifiers that the wallet uses, making it easier for the user to understand the dApp's UI. + +The `address`, `type` response fields provide enough information about the asset, enabling dApps to provide additional asset-specific functionality. + +The `balance` response field is an optimization, allowing dApps to show the user's balance without querying the blockchain. Usually, this information is already public. + + +## Backwards Compatibility + +Not relevant, as this is a new method. + + +## Test Cases + +To be done. + + +## Implementation + +To be done. + + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2266.md b/EIPS/eip-2266.md new file mode 100644 index 00000000000000..ae3e2df3601021 --- /dev/null +++ b/EIPS/eip-2266.md @@ -0,0 +1,7 @@ +--- +eip: 2266 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2266.md diff --git a/EIPS/eip-2294.md b/EIPS/eip-2294.md new file mode 100644 index 00000000000000..c67d3bfcd8cd86 --- /dev/null +++ b/EIPS/eip-2294.md @@ -0,0 +1,61 @@ +--- +eip: 2294 +title: Explicit bound to Chain ID size +description: Adds a maximum value to the Chain ID parameter to avoid potential encoding issues that may occur when using large values of the parameter. +author: Zainan Victor Zhou (@xinbenlv), Alex Beregszaszi (@axic), Bryant Eisenbach (@fubuloubu) +discussions-to: https://ethereum-magicians.org/t/eip-2294-explicit-bound-to-chain-id/11090 +status: Stagnant +type: Informational +created: 2019-09-19 +requires: 155 +--- + +## Abstract + +This EIP informationally defines the "Safe Range" and "Max Range" of ChainId based on a few known restrictions such as [EIP-155](./eip-155.md) and major wallet and JSON-RPC representation of ChainId. + +## Motivation + +1. We want chainId to be safe across the different components of the ecosystem such as smart contract, wallet, dApp and JSON-RPC etc. +2. We want to enable Cross-Chain function call +3. We want to ensure [EIP-712](./eip-712.md) domains have a clear definition of how to pack ChainID. +4. Enable possible expansion of chains, such as increasing amount of L2s, L3s, or shards of Ethereum mainnets. +5. Enable hashed based temporary chain: There have been suggestions of using a hash-based identifier in place on Chain ID to allow the value to adapt over time to different contentious forks and other scenarios. This proposal does not describe this behavior, but ~63 bits of entropy should be enough to ensure that no collisions are likely for reasonable (e.g. non-malicious) uses of this feature for that purpose. + +## Specification + +We declared the following chainID range + +1. (1, 2^31 - 1): "Safe Range", the higher bound is decided by Javascript number +2. (1, MAX_CHAIN_ID); "Max Range", in which `MAX_CHAIN_ID := floor(MAX_UINT64 / 2) - 36 = 9,223,372,036,854,775,771`: + +## Rationale + +### Beyond "Max Range", the EIP-155 will overflow as discussed below + +The `MAX_CHAIN_ID` is calculated to avoid overflow when performing uint64 math. For reference, a value of 0 or less is also disallowed. + +Due to how the calculation for chain ID is performed, the maximum value seen during the arithmetic is `CHAIN_ID * 2 + 36`, so clients must test to ensure no overflow conditions are encountered when the highest value is used. No underflow is possible. + +EIP-155 introduces the Chain ID parameter, which is an important parameter used for domain separation (replay protection) of Ethereum protocol signed messages. However, it does not specify any properties about the size that this parameter takes. Allowing it to be 256-bit wide means that the RLP encoding of a transaction must use >256-bit arithmetic to calculate the v field. + +and suggests a reasonable maximum enforced size in order to ensure that there are no issues when encoding this parameter. This would allow a sufficient amount of different values for this parameter, which is typically chosen by community consensus as a genesis parameter for a given chain and thus does not change often. + +Without a well-chosen value of Chain ID, there could be differences in the implementation of [EIP-155](./eip-155.md) (and [EIP-1344](./eip-1344.md) by derivative) in both client codebase and external tooling that could lead to consensus-critical vulnerabilities being introduced to the network. By making this limit explicit, we avoid this scenario for Ethereum and any project which uses the Ethereum codebase. + +Also, the field `chainID` has experienced increasing usage and dependencies, due more and more contracts are depending on [EIP-1344](./eip-1344.md) to expose CHAIN ID in the smart contract execution. For example when used with [EIP-712](./eip-712.md), [ERC-1271](./eip-1271.md) for on-contract signature verification, chainId has been increasingly introduced for replay attack prevention. It's security critical to ensure clients depending on the chainId computation in cryptography yields identical result for verification in +all cases. + +## Backwards Compatibility + +This EIP introduces a change that affects previous implementations of this feature. However, as of time of writing(2022-10-18) no known chain makes use of a value outside of the suggested bounds, there should not be an issue in adopting this limit on the size of this parameter, therefore the impact should be non-existent. + +If any other chain is operating with an incompatible `chainId`, we advised they make proper arrangement when this EIP becomes adopted. + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2304.md b/EIPS/eip-2304.md new file mode 100644 index 00000000000000..5dadd8d6646379 --- /dev/null +++ b/EIPS/eip-2304.md @@ -0,0 +1,7 @@ +--- +eip: 2304 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2304.md diff --git a/EIPS/eip-2309.md b/EIPS/eip-2309.md new file mode 100644 index 00000000000000..5f69168969c98f --- /dev/null +++ b/EIPS/eip-2309.md @@ -0,0 +1,7 @@ +--- +eip: 2309 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2309.md diff --git a/EIPS/eip-2315.md b/EIPS/eip-2315.md new file mode 100644 index 00000000000000..2da8392004a06c --- /dev/null +++ b/EIPS/eip-2315.md @@ -0,0 +1,445 @@ +--- +eip: 2315 +title: Simple Subroutines for the EVM +description: Two opcodes for efficient, safe, and static subroutines. +author: Greg Colvin (@gcolvin), Martin Holst Swende (@holiman), Brooklyn Zelenka (@expede), John Max Skaller +discussions-to: https://ethereum-magicians.org/t/eip-2315-simple-subroutines-for-the-evm/3941 +status: Withdrawn +type: Standards Track +category: Core +created: 2019-10-17 +requires: 3540, 3670, 4200 +withdrawal-reason: This proposal has been superseded by the EOF proposals. +--- + +## Abstract + +This proposal provides a _complete_, _efficient_, _safe_ and _static_ control-flow facility. + +It introduces two new opcodes to support calling and returning from subroutines: + +* `RJUMPSUB relative_offset` -- relative jump to subroutine +* `RETURNSUB` -- return to `PC` after most recent `RJUMPSUB`. + +It depends on the two new opcodes proposed by [EIP-4200](./eip-4200.md) to support static jumps: + +* `RJUMP relative_offset` — relative jump to `PC + relative_offset` +* `RJUMPI relative_offset` — conditional relative jump + +It deprecates `JUMP` and `JUMPI`, allowing valid code to support streaming, one-pass, and other near-linear compilers. + +In concert with [EIP-3540](./eip-3540.md) and [EIP-3670](./eip-3670.md) it ensures, at initialization time, that valid code will not execute invalid instructions or jump to invalid locations, will not underflow stack, will maintain consistent numbers of inputs and outputs for subroutines, and will have bounded stack height in the absence of recursion. + +This is among the simplest possible proposals that meets these requirements. + +## Motivation + +### A complete control-flow facility. + +Jumps, conditional jumps and subroutines were proposed by Alan Turing in 1945 as a means of organizing the logic of the code and the design of the memory crystals for his Automatic Computing Engine: +> We wish to be able to arrange that sequences of orders can divide at various points, continuing in different ways according to the outcome of the calculations to date... We also wish to be able to arrange for the splitting up of operations into subsidiary operations... To start on a subsidiary operation we need only make a note of where we left off the major operation and then apply the first instruction of the subsidiary. When the subsidiary is over we look up the note and continue with the major operation. +> +> — Alan Turing — in B.E. Carpenter, R.W. Doran, "The other Turing machine." The Computer Journal, Volume 20, Issue 3, January 1977. + +In more contemporary terms, we have sequences of instructions, jumps and conditional jumps that divide sequences into blocks, subroutine calls, and a stack of addresses to return to. The details vary, but similar facilities have proven their value across a long line of important machines over the last 75 years, including most all of the machines we have programmed or implemented -- physical machines including the Burroughs 5000, CDC 7600, IBM 360, DEC PDP-11 and VAX, Motorola 68000, Sun SPARC, and Intel x86s, as well as virtual machines for Scheme, Forth, Pascal, Java, Wasm, and others. + +Unlike these machines, the Ethereum Virtual Machine _does not_ provide subroutine operations. Instead, they must be synthesized using the dynamic `JUMP` instruction, which takes its destination on the stack. Further, the EVM provides _only_ dynamic jumps, impeding the static analysis we need. + +### Efficient control-flow. + +Efficient to write by hand, compile from high level labguages, validate at deploy time, interpret by VMs, and compile to machine code. + +Static jumps, conditional jumps, and subroutines are sufficient and efficient in space and time, as shown by historical experience and as we will show for the EVM below. + +### Safe control-flow. + +The EVM has unusually high requirements for safety. Not only do many smart contracts control inordinately large amounts of valuable Ether, but once placed on the blockchain any defects are visible to attackers and cannot be repaired. We propose to statically validate important safety constraints on code at initialization time. + +### Static control-flow. + +The EVM's dynamic jumps cause two major problems. First, the need to synthesize static jumps and subroutines with dynamic jumps wastes space and gas with needlessly complex code, as we will show below. + +Worse, jumps that can dynamically branch to any destination in the code can cause quadratic "path explosions" when traversing the flow of control. For Ethereum, this is a denial-of-service vulnerability that prevents us, at initialization time, from validating the safe use of EVM code and from compiling EVM code to machine code. + +We _need_ static control-flow to validate program safety and to compile EVM bytecode to machine code -- in time and space linear in the size of the code. + +## Specification + +### Opcodes + +#### `RJUMPSUB (0x5f) relative_offset` + +Transfers control to a subroutine. + +1. Decode the `relative_offset` from the immediate data at `PC`. +2. Push the current `PC + 3` to the `return stack`. +3. Set `PC` to `PC + relative_offset`. + +The `relative_offset` is relative to the current `PC`. The offset is encoded as a two-byte, twos-complement signed integer, stored MSB-first. + +The gas cost is _low_. + +#### `RETURNSUB (0x5e)` + +Returns control to the caller of a subroutine. + +1. Pop the `return stack` to `PC`. + +The gas cost is _verylow_. + +_Notes:_ + +* _Values popped off the `return stack` do not need to be validated, since they are alterable only by `RJUMPSUB` and `RETURNSUB`._ +* _The description above lays out the semantics of these instructions in terms of a `return stack`. But the actual state of the `return stack` is not observable by EVM code or consensus-critical to the protocol. (For example, a node implementer may code `RJUMPSUB` to unobservably push `PC` on the `return stack` rather than `PC + 1`, which is allowed so long as `RETURNSUB` observably returns control to the `PC + 3` location.)_ + +### Validity + +_Execution_ is defined in the Yellow Paper as a sequence of changes in the EVM state. The conditions on valid code are preserved by state changes. At runtime, if execution of an instruction would violate a condition the execution is in an exceptional halting state. The Yellow Paper defines six such states. + +1. Insufficient gas +2. More than 1024 stack items +3. State modification during a static call +4. Insufficient stack items +5. Invalid jump destination +6. Invalid instruction + +We would like to consider EVM code valid iff no execution of the program can lead to an exceptional halting state. In practice, we must test at runtime for the first three conditions. We don’t know how much gas there will be, we don’t know how deep a recursion may go, analysis of stack depth even for non-recursive programs is nontrivial, and we don't know whether a call will be static. All of the remaining conditions MUST be validated statically, in time and space quasi-linear in the size of the code. + +#### Static Constraints on Valid Code + +* Every instruction MUST be valid: + * The `JUMP` and `JUMPI` instructions ARE NOT valid. +* Every jump MUST be valid: + * The `RJUMP`, `RJUMPI`, or `RJUMPSUB` instructions MUST NOT address immediate data or addresses outside of their code section. +* The stacks MUST be valid: + * The number of items on the `data stack` MUST always be positive. + * The number of items on the `return stack `MUST always be positive. +* The data stack MUST be consistently aligned: + * The data stack height is + * the absolute difference between the current `stack pointer` and the `stack pointer` on entry to the current subroutine. + * It MUST be the same for every reachable path through a given `PC` and + * MUST NOT exceed 1024. + +## Rationale + +This is a purely semantic specification, placing no constraints on the syntax of code sections beyond being a sequence of opcodes and immediate data – a subroutine is not a contiguous sequence of bytecode, it is a subgraph of the bytecode's control-flow graph. The EVM is a simple state machine. We only promise that valid code will not, as it were, jam up the gears of the machine. + +By avoiding syntactic constraints we allow for optimizations like tail call elimination, multiple-entry subroutines, moving "cold" code out of line, and other ways of reducing redundancy and keeping "hot" code in cache. Since we wish to support one-pass compilation of EVM code to machine code it is crucial that the EVM code be as well optimized as possible up front. + +### Validation + +Rather than enforce constraints via syntax, we enforce them via validation. + +The constraints on valid code cover all of the exceptional halting states that we can validate and allow code to be validated and compiled in time and space quasi-linear in the size of the code. + +The `RJUMP`, `RJUMPI` and `RJUMPSUB` instructions take their *relative_offset* as immediate arguments, which cannot change at runtime. Having constant destinations for all jumps means that all jump destinations can be validated at initialization time, not runtime. Dynamic jumps can branch to any destination in the code, so exploitable quadratic "path explosions" are possible when traversing the control flow graph. Deprecating `JUMP` and `JUMPI` prevents this. + +Requiring a consistently aligned `data stack` + +* prevents stack underflow +* ensures that all calls to a subroutine have the same number of inputs and the same number of outputs and +* ensures that stack height is bounded in the absence of recursion. + +Requiring a consistently aligned `data stack` also allows some algorithms that traverse the control-flow graph -- including code validation and compilation -- to break cycles at joins, again preventing quadratic path explosion. When a traversal gets to a `PC` it has visited before it is either at the beginning of a loop or the entry to a function. Since the stack height at that `PC` is constant we know that loops will not grow stack, and that the number of arguments to a subroutine will always be the same -- there may be no need to traverse that path again. + +_Note: The JVM and Wasm enforce similar constraints for similar reasons._ + +### Alternative Designs + +There are a few major designs for a subroutine facility, two of which are considered here. The others are mostly not appropriate for the EVM, such as the Wheeler Jump -- self-modifying code that writes return addresses into called subroutines. + +*1. Keep return addresses on a dedicated return stack.* Turing's design is often used by stack machines, including those for Forth, Java, Wasm, and others. The data stack is used for computation, with a dedicated stack for return addresses. A single instruction suffices to call, and another to return from a routine. + +*2. Keep return addresses on the data stack.* This design is often used by register machines, including those from CDC, IBM, DEC, Intel, and ARM. The registers are used primarily for computation, and the stack maintains call frames for return addresses, arguments, and local variables. On the EVM there are no registers for computation, so using the stack for both purposes can cause the sort of inefficiencies we see below. Pascal p-code does use this design, but as part of a complex calling convention with dedicated registers. + +#### We prefer the dedicated return stack. + +* It maintains a clear separation between calculation and flow of control: + * the data stack is free of vulnerable return addresses and + * it's impossible to overwrite the return stack. +* It improves efficiency: + * it uses native arithmetic rather than 256-bit EVM instructions for the return address, + * doesn't use up a `data stack` slot for the return address and + * needs less motion of 256-bit data on the stack. + +### Efficiency + +We illustrate here how subroutine instructions can be used to reduce the complexity and gas costs of both ordinary and optimized subroutine calls compared to using `JUMP`. + +#### **Simple Subroutine Call** + +Consider these examples of a fairly minimal subroutine, including the code to call it. + +Subroutine call, using `RJUMPSUB`: +``` +SQUARE: + dup1 ; 3 gas + mul ; 5 gas + returnsub ; 3 gas + +CALL_SQUARE: + push 0x02 ; 3 gas + rjumpsub SQUARE ; 5 gas +``` +_Total gas: 19_ + +Subroutine call, using `JUMP`: +``` +SQUARE: + jumpdest ; 1 gas + swap1 ; 3 gas + dup1 ; 3 gas + mul ; 5 gas + swap1 ; 3 gas + jump ; 8 gas + +CALL_SQUARE: + jumpdest ; 1 gas + push 0x02 ; 3 gas + push RTN_CALL: ; 3 gas + push SQUARE ; 3 gas + jump ; 8 gas +RTN_CALL: + jumpdest ; 1 gas +``` +_Total: 41 gas_. + +Using `RJUMPSUB` versus `JUMP` saves _41 - 19 = 22 gas_ — a _54%_ improvement. + +#### **Tail Call Optimization** + +Of course in cases like this one we can optimize the tail call, so that the return from `SQUARE` actually returns from `TEST_SQUARE`. + +Tail call optimization, using `RJUMPSUB` and `RETURNSUB`: +```SQUARE: + dup1 ; 3 gas + mul ; 5 gas + returnsub ; 3 gas + +CALL_SQUARE: + push 0x02 ; 3 gas + rjump SQUARE ; 3 gas +``` +_Total: 17 gas_ + + +Tail call optimization, using `JUMP`: +``` +SQUARE: + jumpdest ; 1 gas + swap1 ; 3 gas + dup1 ; 3 gas + mul ; 5 gas + swap2 ; 3 gas + jump ; 8 gas + +CALL_SQUARE: + jumpdest ; 1 gas + push 0x02 ; 3 gas + push SQUARE ; 3 gas + jump ; 8 gas +``` +_Total: 38 gas_ + +Using `RJUMPSUB` versus `JUMP` saves _38 - 17 = 21 gas_ — a _55%_ improvement. + +#### Efficiency Caveats + +We can see that these instructions provide a simpler and more gas-efficient subroutine mechanism than using `JUMP` — in our examples they cut gas use by about half. + +Clearly, the benefits of this efficiency are greater for programs that have been factored into smaller subroutines. How small? Wrapping code in a subroutine costs only _8 gas_ using `RJUMPSUB` and `RETURNSUB` versus _30 gas_ using `JUMP`, `PUSH` and `SWAP` as above. + +### Costs + +The _low_ cost of `RJUMPSUB` versus the _mid_ cost of `JUMP` is justified by needing only to decode the immediate two byte destination to the `PC` and push the return address on the `return stack`, all using native arithmetic, versus using the data stack with emulated 256-bit instructions. + +The _verylow_ cost of `RETURNSUB` is justified by needing only to pop the `return stack` into the `PC`. Benchmarking will be needed to tell if the costs are well-balanced. + +## Backwards Compatibility + +These changes affect the semantics of existing EVM code: bytes that would have been interpreted as valid jump destinations may now be interpreted as immediate data. Since this proposal depends on the Ethereum Object Format to signal the change this is not a practical issue. + +## Test Cases + +### Simple routine + +This should jump into a subroutine, back out and stop. + +Bytecode: `0x5f0003005e` (`RJUMPSUB 3, RETURNSUB, STOP`) + +| Pc | Op | Cost | Stack | RStack | +|-------|-------------|------|-----------|-----------| +| 0 | RJUMPSUB | 5 | [] | [] | +| 2 | STOP | 0 | [] | [] | +| 3 | RETURNSUB | 3 | [] | [] | + +Output: 0x +Consumed gas: `10` + +### Two levels of subroutines + +This should execute fine, going into one two depths of subroutines + +Bytecode: `0x5f00045F00025200` (`RJUMPSUB 4, RJUMPSUB 2, RETURNSUB, RETURNSUB, STOP`) + +| Pc | Op | Cost | Stack | RStack | +|-------|-------------|------|-----------|-----------| +| 0 | RJUMPSUB | 5 | [] | [] | +| 3 | RJUMPSUB | 5 | [] | [] | +| 4 | RETURNSUB | 5 | [] | [] | +| 5 | RETURNSUB | 5 | [] | [] | +| 6 | STOP | 0 | [] | [] | + +Consumed gas: `20` + +### Failure 1: invalid jump + +This should fail, since the given location is outside of the code-range. + +Bytecode: `0X5fff`(`RJUMPSUB -1`) + +| Pc | Op | Cost | Stack | RStack | +|-------|-------------|------|-----------|-----------| +| 0 | RJUMPSUB | 10 | [] | [] | + +``` +Error: at pc=0, op=RJUMPSUB: invalid jump destination +``` + +### Failure 2: shallow `return stack` + +This should fail at first opcode, due to shallow `return_stack` + +Bytecode: `0x5e` (`RETURNSUB`) + +| Pc | Op | Cost | Stack | RStack | +|-------|-------------|------|-----------|-----------| +| 0 | RETURNSUB | 5 | [] | [] | + +``` +Error: at pc=0, op=RETURNSUB: invalid retsub +``` + +### Subroutine at end of code + +In this example the RJUMPSUB is on the last byte of code. When the subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, and not exit with error + +Bytecode: `0x5c00045e5fffff` (`RJUMP 4, RETURNSUB, RJUMPSUB -1`) + +| Pc | Op | Cost | Stack | RStack | +|-------|-------------|------|-----------|-----------| +| 0 | RJUMP | 5 | [] | [] | +| 3 | RETURNSUB | 5 | [] | [] | +| 4 | RJUMPSUB | 5 | [] | [] | +| 7 | STOP | 0 | [] | [] | + +Consumed gas: `15` + +## Reference Implementation + +The following is a pseudo-Python implementation of an algorithm for predicating code validity. An equivalent algorithm must be run at initialization time. + +This algorithm performs a symbolic execution of the program that recursively traverses the _code_, emulating its control flow and stack use and checking for violations of the rules above. + +It runs in time equal to `O(vertices + edges)` in the program's control-flow graph, where edges represent control flow and the vertices represent _basic blocks_ — thus the algorithm takes time proportional to the size of the _code_. It maintains a stack of continuations for conditional jumps, the size of which is at most proportional to the size of the _code_. + +### Validation Function + +** Note: this function is known to be incomplete and incorrect. ** + +For simplicity's sake we assume that all jumpdest analysis and prior validation has been done, including EIP-3540, EIP-3670, and EIP-4200, so EOF headers and sections are well-formed, and there are no invalid instructions or jumps. In practice, all passes of validation can be folded into a single loop no recursion. + +We also assume some helper functions. +* `is_valid(opcode)` returns true iff opcode is valid. +* `is_terminator(opcode)` returns true iff opcode is terminator. +* `is_valid_jumpdest(pc)` returns true iff `pc` is a valid jump destination. +* `immediate_data(pc)` returns the immediate data for the instruction at `pc`. +* `immediate_size(opcode)` returns the size of the immediate data for an opcode. +* `removed_items(opcode)` returns the number of items removed from the `data_stack` by the `opcode`. +* `added_items(opcode)` returns the number of items added to the `data_stack` by the `opcode`. + +``` +# returns true iff code is valid +def validate_code(code: bytes, pc: int, sp: int, bp: int) -> boolean: + continuations = [] + do + while pc < len(code): + opcode = code[pc] + if !is_valid(opcode): + return false + if is_terminator(opcode): + return true + + # check stack height and return if we have been here before + stack_height = sp - bp + if stack_height > 1024 + return false + if pos in stack_heights: + if stack_height != stack_heights[pos]: + return false + return true + else: + stack_heights[pos] = stack_height + + if opcode == RJUMP: + + # reset pc to destination of jump + jumpdest = immediate_data(pc) + pc += jumpdest + if !is_valid_jumpdest(pc) + return false + + elif opcode == RJUMPI: + + jumpdest = pc + immediate_data(pc) + if !is_valid_jumpdest(pc) + return false + + # continue true side of conditional later + continations.push((jumpdest, sp, bp)) + + # continue false side of conditional now + + elif opcode == RJUMPSUB: + + # will enter subroutine at destination + bp = sp + + # push return address and reset pc to destination + jumpdest = pc + immediate_data(pc) + if !is_valid_jumpdest(pc) + return false + push(return_stack, pc + 3) + pc = jumpdest + continue + + elif opcode == RETURNSUB: + + # will return to subroutine at destination + bp = sp + + # pop return address and check for preceding call + pc = pop(return_stack) + if code[pc - 3] != RJUMPSUB: + return false + + # apply instructions to stack + sp -= removed_items(opcode) + if sp < 0 + return false + sp += added_items(opcode) + + # Skip opcode and immediate data + pc += 1 + immediate_size(opcode) + + while (pc, sp, bp) = continuations.pop() + + return true +``` + +## Security Considerations + +These changes introduce new flow control instructions. They do not introduce any new security considerations. This EIP is intended to improve security by validating a higher level of safety for EVM code deployed on the blockchain. The validation algorithm must be quasi-linear in time and space to not be a denial of service vulnerability. The algorithm here makes one linear-time pass of the bytecode, and uses a stack of continuations that cannot exceed the number of `RJUMPI` instructions in the code. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2327.md b/EIPS/eip-2327.md new file mode 100644 index 00000000000000..f2e4449bbefd69 --- /dev/null +++ b/EIPS/eip-2327.md @@ -0,0 +1,49 @@ +--- +eip: 2327 +title: BEGINDATA opcode +author: Martin Lundfall (@MrChico) +discussions-to: https://ethereum-magicians.org/t/new-opcode-begindata/3727 +status: Stagnant +type: Standards Track +category: Core +created: 2019-10-28 +--- + +## Simple Summary +Introduces a new opcode `BEGINDATA`, which indicates that the remaining bytes of the contract should be regarded as data rather than contract code +and cannot be executed. + +## Abstract +It is common for smart contracts to efficiently store data directly in the contract bytecode. Examples include constructor arguments, constant variables, compiler metadata and the contract runtime during the init phase. Currently, such data is not distinguished from normal bytecode and is still being analysed for `JUMPDEST`s by EVM interpreters. This EIP introduces a new opcode `BEGINDATA` at byte `0xb6`, which marks the remainding bytecode as data, indicating to EVM interpreters, static analysis tools and chain explorers that the remaining bytes do not represent opcodes. + +## Motivation +The `BEGINDATA` opcode has been suggested before as part of the EIP `Subroutines and Static Jumps for the EVM` [EIP-615](./eip-615.md) as a way to determine the position of jumptables in contract bytecode. It is here introduced in its own right in order to exclude data from the `JUMPDEST` analysis of contracts, making it impossible to jump to data. This makes it easier for static analysis tools to analyse contracts, allows disassemblers, chain explorers and debuggers to not display data as a mess of INVALID opcodes and may even provide a marginal improvement in performance. It also helps scalability because it improves on-chain evaluation of transactions from other chains in that the validation that the code conforms to a certain pattern does not need to do a full jumpdest analysis to see that data is not executed and thus does not have to conform to the pattern (used by the optimism project). Additionally, it paves the way for suggestions such as [EIP-1712](https://github.com/ethereum/EIPs/pull/1712) to disallow unused opcodes, jumptables [EIP-615](./eip-615.md) and speculative proposals to disallow for deployment of contracts with stack usage violations. + +## Specification +While computing the valid `JUMPDEST`s of a contract, halt analysis once the first `BEGINDATA` is encountered. In other words: A jump to any codelocation equal to or greater than the location of the first `BEGINDATA` causes a `BAD_JUMP_DESTINATION` error. +If `BEGINDATA` is encountered during contract execution, it has the same semantics as `STOP`. It uses 0 gas. + +Bytes past `BEGINDATA` remain accessible via `CODECOPY` and `EXTCODECOPY`. `BEGINDATA` does not influence `CODESIZE` or `EXTCODESIZE`. + +## Rationale +The byte `0xb6` was chosen to align with [EIP-615](./eip-615.md). +The choice to `STOP` if `BEGINDATA` is encountered is somewhat arbitrary. An alternative would be to be to abort the execution with an out-of-gas error. + +## Backwards Compatibility +The proposal will not change any existing contracts unless their current behaviour relies upon the usage of unused opcodes. + +Since contracts have been using data from the very start, in a sense all of them use unused opcodes, +but they would have to use data in a way that it is skipped during execution and jumped over. +The Solidity compiler never generated such code. It has to be evaluated whether contracts created by other means +could have such a code structure. + +## Test Cases +Test cases should include: +1) A contract which jumps to a destination `X`, where `X` has a pc value higher than the `BEGINDATA` opcode, and the byte at `X` is `0x5b`. This should fail with a `BAD_JUMP_DESTINATION` error. +2) A contract which encounters the `BEGINDATA` opcode (should stop executing the current call frame) + +## Implementation +Not yet. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-233.md b/EIPS/eip-233.md index e3d34eed72c639..dd23be517dd580 100644 --- a/EIPS/eip-233.md +++ b/EIPS/eip-233.md @@ -4,7 +4,7 @@ title: Formal process of hard forks author: Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/eip-233-formal-process-of-hard-forks/1387 type: Meta -status: Draft +status: Stagnant created: 2017-03-23 --- @@ -41,7 +41,10 @@ Once a timeline with key dates is agreed upon for other crucial dates. The basic Anyone that wishes to propose a Core EIP for the hard fork should make a PR against the Meta EIP representing the hard fork. The EIP must be published as at least `Draft`. It enters the _Proposed EIPs_ section, along with at least one person who is a point of contact for wanting to include the EIP. -Once the EIP has been accepted by Core Devs, the EIP should be moved to the _Accepted EIPs_ section. If the EIP has major client implementations and no security issues by the timeline date, it is scheduled for inclusion. +EIPs can move states by discussion done on the "[All Core Devs Meetings](https://github.com/ethereum/pm/)": +- If accepted for a hard fork, the EIP should be moved to the _Accepted EIPs_ section. If the EIP has major client implementations and no security issues by the timeline date, it is scheduled for inclusion. +- If rejected from a hard fork, the EIP should be moved to the _Rejected EIPs_ section. +- Once the EIPs in the _Accepted EIPs_ section have successfully launched on a testnet roll out, they are moved to the _Included EIPs_ section. --- @@ -49,7 +52,7 @@ The Meta EIP representing the hard fork should move in to the `Accepted` state o ## Template -A template for the [Istanbul Hardfork Meta 1679](https://eips.ethereum.org/EIPS/eip-1679) is included below ([source file on Github](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1679.md)): +A template for the [Istanbul Hardfork Meta 1679](./eip-1679.md) is included below ([source file on GitHub](./eip-1679.md)): ``` {% raw %} @@ -80,6 +83,10 @@ This meta-EIP specifies the changes included in the Ethereum hardfork named Ista - TBD +### Rejected EIPs + +- TBD + ### Proposed EIPs - TBD @@ -97,7 +104,7 @@ This meta-EIP specifies the changes included in the Ethereum hardfork named Ista ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). {% endraw %} ``` @@ -108,4 +115,4 @@ A meta EIP for coordinating the hard fork should help in visibility and traceabi ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2330.md b/EIPS/eip-2330.md new file mode 100644 index 00000000000000..a648f15e78e970 --- /dev/null +++ b/EIPS/eip-2330.md @@ -0,0 +1,62 @@ +--- +eip: 2330 +title: EXTSLOAD opcode +description: A new EVM opcode to read external contract storage data. +author: Dominic Letz (@dominicletz), Santiago Palladino (@spalladino) +discussions-to: https://ethereum-magicians.org/t/eip-2330-extsload-and-abi-for-lower-gas-cost-and-off-chain-apps/3733 +status: Stagnant +type: Standards Track +category: Core +created: 2019-10-29 +requires: 2929 +--- + +## Abstract + +This proposal adds a new opcode `EXTSLOAD` at `0x5c` which pops two items from the stack: ` ` and pushes one item: ``. The gas cost is sum of account access cost and storage read based on [EIP-2929](./eip-2929.md) Access Lists. + +## Motivation + +While any off-chain application can read all contract storage data of all contracts, this is not possible for deployed smart contracts themselves. These are bound to use contract calls for any interaction including reading data from other contracts. This EIP adds an EVM opcode to directly read external contract storage. + +The gas cost when reading from registry style contract such as [EIP-20s](./eip-20.md), ENS and other data contracts is very high, because they incur cross contract call cost, cost for ABI encoding, decoding and dispatching and finally loading the data. In many cases the underlying storage that is being queried is though just a simple mapping. On top of that, the view function may SLOAD many other slots which caller may not be interested in, which further adds to the gas costs. In these cases a new `EXTSLOAD` call directly accessing the mapping in storage could not only **reduce the gas cost** of the interaction more than 10x, but also it would make the gas cost **predictable** for the reading contract. + +## Specification + +A new EVM instruction `EXTSLOAD (0x5c)` that works like `SLOAD (0x54)` but an additional parameter representing the contract that is to be read from. + +```shell +EXTSLOAD (0x5c) +``` + +The `EXTSLOAD` instruction pops 2 values from the stack, first `contract` a contract address and then second `slot` a storage address within `contract`. As result `EXTSLOAD` pushes on the stack the value from the contract storage of `contract` at the storage `slot` address or `0` in case the account `contract` does not exist. + +### Gas cost pre-verkle + +Gas to be charged before Verkle Tree change is specified as `ACCOUNT_ACCESS_COST + STORAGE_READ_COST` where: + +- `ACCOUNT_ACCESS_COST` is `0` if the account address is already in `accessed_addresses` set, otherwise `COLD_ACCOUNT_ACCESS_COST`. +- `STORAGE_READ_COST` is `WARM_STORAGE_READ_COST` if storage key is already in `accessed_storage_keys` set, otherwise `COLD_STORAGE_READ_COST`. + +### Gas cost post-verkle + +It is important to consider that post Verkle tree change, `ACCOUNT_ACCESS_COST` will not be needed since a single account's storage would be spread across the entire global trie. Hence gas to be charged post Verkle Tree change is just `STORAGE_READ_COST`, which is as specified in [Gas cost pre-verkle](#gas-cost-pre-verkle). + +## Rationale + +- Without this EIP, a contract can still opt-in to make their entire state public, by having a method that simply SLOADs and returns the values ([example](../assets/eip-2330/Extsload.sol)). The complexity of the gas cost can be seen as `1`x CALL cost + `N`x SLOAD cost. Hence, the gas cost specified for using EXTSLOAD opcode on an account for `N` times, the charge of `1`x `COLD_ACCOUNT_ACCESS_COST` and `N`x `STORAGE_READ_COST` is hereby justified. +- Without this EIP, a contract can still use internal state of other contracts. An external party can supply a value and proof to a contract, which the contract can verify using `BLOCKHASH`. This is only possible for the previous blocks and not the latest state (since current blockhash cannot be determined before execution). +- This opcode can be seen as breaking object-oriented (OO) model because it allows to read storage of other contracts. In usual systems using OO is net positive, because there is no limit on machine code and it hardly adds any cost to add more methods or use single method to get a ton of data while the caller needs to just a small portion of data. However on EVM, there are visible costs, i.e. about $0.2 per SLOAD (20 gwei and ETHUSD 2000). Also, OO has caused misleading assumptions for developers where variables marked as "private" in smart contracts are encrypted in some way/impossible to read which has resulted bad designs. Hence, this EIP can be beneficial in terms of making smart contract systems more efficient as well as preventing misconceptions as well. + +## Backwards Compatibility + +This change is fully backwards compatible since it adds a new instruction. + +## Security Considerations + +- Since the opcode is similar to SLOAD, it should be easy to implement in various clients. +- This opcode allows the callee `A` to re-enter a caller contract `B` and read state of `B` and `B` cannot stop `A` from doing that. Since this does not change any state, it should not be a security issue. Contracts generally use re-entrancy guards, but that is only added to write methods. So even currently without EXTSLOAD, `A` can re-enter `B` and read their state exposed by any view methods and it has not been an issue. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2333.md b/EIPS/eip-2333.md new file mode 100644 index 00000000000000..962cb23c8fa536 --- /dev/null +++ b/EIPS/eip-2333.md @@ -0,0 +1,7 @@ +--- +eip: 2333 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2333.md diff --git a/EIPS/eip-2334.md b/EIPS/eip-2334.md new file mode 100644 index 00000000000000..1ef3c8d3734535 --- /dev/null +++ b/EIPS/eip-2334.md @@ -0,0 +1,7 @@ +--- +eip: 2334 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2334.md diff --git a/EIPS/eip-2335.md b/EIPS/eip-2335.md new file mode 100644 index 00000000000000..31c28f3c0cb014 --- /dev/null +++ b/EIPS/eip-2335.md @@ -0,0 +1,7 @@ +--- +eip: 2335 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2335.md diff --git a/EIPS/eip-234.md b/EIPS/eip-234.md index 06f99c5e59ffcc..29ab2346df52e7 100644 --- a/EIPS/eip-234.md +++ b/EIPS/eip-234.md @@ -2,10 +2,12 @@ eip: 234 title: Add `blockHash` to JSON-RPC filter options. author: Micah Zoltu (@MicahZoltu) +discussions-to: https://github.com/ethereum/EIPs/issues/234 type: Standards Track category: Interface -status: Draft +status: Final created: 2017-03-24 +requires: 1474 --- ## Simple Summary @@ -26,7 +28,7 @@ A client (dApp) who needs reliable notification of both log additions (on new bl In order to deal with this while still providing a robust mechanism for internal block/log additional/removal, the client can maintain a blockchain internally (last `n` blocks) and only subscribe/poll for new blocks. When a new block is received, the client can reconcile their internal model with the new block, potentially back-filling parents or rolling back/removing blocks from their internal model to get in sync with the node. This can account for any type of disconnect/reorg/outage scenario and also allows the client (as an added benefit) to talk to a cluster of Ethereum nodes (e.g., via round-robin) rather than being tightly coupled to a single node. -Once the user has a reliable stream of blocks, they can then look at the bloom filter for the new block and if the block *may* have logs of interest they can fetch the filtered logs for that block from the node. The problem that arises is that a re-org may occur between when the client receives the block and when the client fetches the logs for that block. Given the current set of filter options, the client can only ask for logs by block number. In this scenario, the logs they get back will be for a block that *isn't* the block they want the logs for and is instead for a block that was re-orged in (and may not be fully reconciled with the internal client state). This can be partially worked around by looking at the resulting logs themselves and identifying whether or not they are for the block hash requested. However, if the result set is an empty array (no logs fetched) then the client is in a situation where they don't know what block the results are for. The results could have been legitimately empty (bloom filter can yield false positives) for the block in question, or they could be receiving empty logs for a block that they don't know about. At this point, there is no decision the client can make that allows them a guarantee of recovery. They can assume the empty logs were for the correct block, but if they weren't then they will never try to fetch again. This creates a problem if the block was only transiently re-orged out because it may come back before the next block poll so the client will never witness the reorg. They can assume the empty logs were for the wrong block, an refetch them, but they may continue to get empty results putting them right back into the same situation. +Once the user has a reliable stream of blocks, they can then look at the bloom filter for the new block and if the block *may* have logs of interest they can fetch the filtered logs for that block from the node. The problem that arises is that a re-org may occur between when the client receives the block and when the client fetches the logs for that block. Given the current set of filter options, the client can only ask for logs by block number. In this scenario, the logs they get back will be for a block that *isn't* the block they want the logs for and is instead for a block that was re-orged in (and may not be fully reconciled with the internal client state). This can be partially worked around by looking at the resulting logs themselves and identifying whether or not they are for the block hash requested. However, if the result set is an empty array (no logs fetched) then the client is in a situation where they don't know what block the results are for. The results could have been legitimately empty (bloom filter can yield false positives) for the block in question, or they could be receiving empty logs for a block that they don't know about. At this point, there is no decision the client can make that allows them a guarantee of recovery. They can assume the empty logs were for the correct block, but if they weren't then they will never try to fetch again. This creates a problem if the block was only transiently re-orged out because it may come back before the next block poll so the client will never witness the reorg. They can assume the empty logs were for the wrong block, and refetch them, but they may continue to get empty results putting them right back into the same situation. By adding the ability to fetch logs by hash, the client can be guaranteed that if they get a result set, it is for the block in question. If they get an error, then they can take appropriate action (e.g., rollback that block client-side and re-fetch latest). @@ -44,4 +46,4 @@ The only potential issue here is the `fromBlock` and `toBlock` fields. It would ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2364.md b/EIPS/eip-2364.md new file mode 100644 index 00000000000000..981f56d0253b87 --- /dev/null +++ b/EIPS/eip-2364.md @@ -0,0 +1,76 @@ +--- +eip: 2364 +title: "eth/64: forkid-extended protocol handshake" +description: Introduces validation of the `forkid` when handshaking with peers. +author: Péter Szilágyi , Péter Szilágyi (@karalabe), Tim Beiko (@timbeiko) +discussions-to: https://github.com/ethereum/EIPs/issues/2365 +status: Final +type: Standards Track +category: Networking +created: 2019-11-08 +requires: 2124 +--- + +## Abstract + +This EIP specifies the inclusion of the `forkid`, originally defined in [(EIP-2124)](./eip-2124.md), as a new field in the Ethereum wire protocol (`eth`) handshake. This change is implemented as a new version of the wire protocol, `eth/64`. + +## Motivation + +The [`forkid` (EIP-2124)](./eip-2124.md) was designed to permit two Ethereum nodes to quickly and cheaply decide if they are compatible or not, not only at a genesis/networking level, but also from the perspective of the currently passed network updates (i.e. forks). + +[EIP-2124](./eip-2124.md) only defines how the `forkid` is calculated and validated, but does not specify how the `forkid` should be exchanged between peers. This EIP specifies the inclusion of the `forkid` as a new field in the Ethereum wire protocol (`eth`) handshake (releasing a new version, `eth/64`). + +By cross-validating `forkid` during the handshake, incompatible nodes can disconnect before expensive block exchanges and validations take place (PoW check, EVM execution, state reconstruction). This further prevents peer slots from being taken up by nodes that are incompatible, but have not yet been detected as such. + +From a micro perspective, cutting off incompatible nodes from one another ensures that a node only spends its resources on tasks that are genuinely useful to it. The sooner we can decide the remote peer is useless, the less time and processing we expend in vain. + +From a macro perspective, keeping incompatible nodes partitioned from one another ensures that disjoint clusters retain more resources for maintaining their own chain, thus raising the quality of service for all networks globally. + +## Specification + +- Implement `forkid` generation and validation per [EIP-2124](./eip-2124.md). +- Advertise a new `eth` protocol capability (version) at `eth/64`. + - The old `eth/63` protocol should still be kept alive side-by-side, until `eth/64` is sufficiently adopted by implementors. +- Redefine `Status (0x00)` for `eth/64` to add a trailing `forkid` field: + - Old packet: `[protocolVersion, networkId, td, bestHash, genesisHash]` + - New packet: `[protocolVersion, networkId, td, bestHash, genesisHash, forkid]`, + where `forkid` is `[forkHash: [4]byte, forkNext: uint64]` (fields per [EIP-2124](./eip-2124.md) ). + +Whenever two peers connect using the `eth/64` protocol, the updated `Status` message must be sent as the protocol handshake, and each peer must validate the remote `forkid`, disconnecting at a detected incompatibility. + +## Rationale + +The specification is tiny since most parts are already specified in EIP-2124. `eth/63` is not specified as an EIP, but is maintained in the [ethereum/devp2p](https://github.com/ethereum/devp2p) Github repository. + +### EIP-2124 mentions advertising the `forkid` in the discovery protocol too. How does that compare to advertising in the `eth` protocol? Why is the redundancy needed? + +Advertising and validating the `forkid` in the discovery protocol is a more optimal solution, as it can help avoid the cost of setting up the TCP connection and cryptographic RLPx stream, only to be torn down if `eth/64` rejects it. + +Compared to the `eth` protocol however, discovery is a bit fuzzy. The goal there is to suggest potential peers, not to be fool-proof. Information may be outdated, nodes may have changed or disappeared. Discovery can do a rough filtering, but more precision is still needed afterwards. + +Additionally, `forkid` validation via the discovery protocol requires ENR implementation ([EIP-778](./eip-778.md)) and ENR extension support ([EIP-868](./eip-868.md)), which is not mandated by the Ethereum network currently. Lastly, the discovery protocol is just one way to find peers, but systems that cannot use UDP or that rely on other mechanism (e.g. DNS discovery)) still need a way to filter connections. + +### The `forkid` implicitly contains the genesis hash checksummed into the `FORK_HASH` field. Why doesn't this proposal remove the `genesisHash` field from the `eth` handshake? + +Originally this EIP did remove it as redundant data, since filtering based on the `forkid` is a superset of filtering based on genesis hash. The reason for backing out of that decision was that the genesis hash may be useful for other things too, not just connection filtering (network crawlers use it currently to split nodes across networks). + +Although the `forkid` will hopefully take over all the roles of the genesis hash currently in use, there's no reason to be overly aggressive in deduplicating data. It's fine to keep both side-by-side for now, and remove in a future version when 3rd party infrastructures switch over. + +## Backwards Compatibility + +This EIP extends the `eth` protocol handshake in a backwards incompatible way and requires rolling out a new version, `eth/64`. However, `devp2p` supports running multiple versions of the same wire protocol side-by-side, so rolling out `eth/64` does not require client coordination, since non-updated clients can keep using `eth/63`. + +This EIP does not change the consensus engine, thus does _not_ require a hard fork. + +## Test Cases + +For calculating and validating fork IDs, see test cases in [EIP-2124](./eip-2124.md). + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2378.md b/EIPS/eip-2378.md new file mode 100644 index 00000000000000..9388365daf620b --- /dev/null +++ b/EIPS/eip-2378.md @@ -0,0 +1,70 @@ +--- +eip: 2378 +title: EIPs Eligible for Inclusion +author: James Hancock (@MadeofTin) +discussions-to: https://gitter.im/ethereum/EIPs +status: Stagnant +type: Meta +created: 2019-11-13 +--- + +## Simple Summary + +As part of an EIP centric forking model, this EIP tracks the first step in the approval process for any EIP to be included in a fork or upgrade. Specifically, the stage where the Core Developers vet the concept of an EIP and give a "green light" sufficient for EIP authors to move forward in development. + +## Abstract + +The pipeline for Core EIPs, per the EIP-Centric upgrade model, is as follows. +``` +[ DRAFT ] -> [ ELLIGLE FOR INCLUSION ] -> [ IMPLEMENTATION ] -> [ TESTING ] -> [ ACCEPTED ] -> [ DEPLOYED ] +``` + +This EIP documents all EIPs marked as **Eligible For Inclusion** by the All Core Devs. Typically to reach this stage, an EIP must be discussed in brief on an AllCoreDevs Call and motioned by rough consenses to be moved to this stage. Any additions to this list are required to provide a link to the meeting notes when this discussion and decision took place. + +The requirements for **Eligible for Inclusion** is that the AllCoreDevs, representing the major clients and ecosystem stakeholders etc: + + - Are positive towards the EIP, + - Would accept (well written) PRs to include the EIP into the codebase. + - So that it could be toggled on for testing… + - …but not with an actual block number for activation + +## Motivation + +Development of clear specifications and pull requests to existing Ethereum Clients is a large investment of time and resources. The state of *Eligible for Inclusion* is a signal from the Ethereum Core Developers to an EIP Author validiating the idea behind an EIP and confirms investing their time further pursing it is worthwhile. + +## Specification + +| EIP | Title | Pipeline Status | Date of Initial Decision | REF | +| -------- | ----------------------------------------------------- | -------- | ---------- | ---- | +| EIP-663 | Unlimited SWAP and DUP instructions | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-1057 | ProgPoW, a Programmatic Proof-of-Work | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-1380 | Reduced gas cost for call to self | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-1559 | Fee market change for ETH 1.0 chain | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-1702 | Generalized Account Versioning Scheme | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-1962 | EC arithmetic and pairings with runtime definitions | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-1985 | Sane limits for certain EVM parameters | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-2046 | Reduced gas cost for static calls made to precompiles | ELIGIBLE | 2019-11-01 | [🔗](https://github.com/ethereum/pm/blob/master/AllCoreDevs-EL-Meetings/Meeting%2074.md) | +| EIP-2315 | Simple Subroutines for the EVM | ELIGIBLE | 2020-02-21 | [🔗](https://github.com/ethereum/pm/blob/master/All%20Core%20Devs%20Meetings/Meeting%2081.md#decisions) | +| EIP-2537 | Precompile for BLS12-381 curve operations | ELIGIBLE | 2020-03-06 | [🔗](https://github.com/ethereum/pm/blob/master/All%20Core%20Devs%20Meetings/Meeting%2082.md) | + +## Rationale + +**EIP Number** + +**Title** + +**Pipeline Status** : Show the current status in the context of the EIP centric model. The list is sorted by furthest along in the process. + +**Date of Initial Decision** : Date of the initial decision for Eligibility for Inclusion + +**REF** : Link to the decision on the AllCoreDevs Notes + + +## References + + - EIP Centric Forking Model Proposal by @holiman - https://notes.ethereum.org/@holiman/S1ELAYY7S?type=view + + + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2384.md b/EIPS/eip-2384.md new file mode 100644 index 00000000000000..e8079af021c592 --- /dev/null +++ b/EIPS/eip-2384.md @@ -0,0 +1,40 @@ +--- +eip: 2384 +title: Muir Glacier Difficulty Bomb Delay +author: Eric Conner (@econoar) +discussions-to: https://ethereum-magicians.org/t/eip-2384-difficulty-bomb-delay +type: Standards Track +category: Core +status: Final +created: 2019-11-20 +--- + +## Simple Summary +The average block times are increasing due to the difficulty bomb (also known as the "_ice age_") and slowly accelerating. This EIP proposes to delay the difficulty bomb for another 4,000,000 blocks (~611 days). + +## Abstract +Starting with `MUIR_GLACIER_FORK_BLKNUM` the client will calculate the difficulty based on a fake block number suggesting to the client that the difficulty bomb is adjusting 9 million blocks later than the Homestead fork, which is also 7 million blocks later than the Byzantium fork and 4 million blocks later than the Constantinople fork. + +## Motivation +The difficulty bomb started to become noticeable again on October 5th 2019 at block 8,600,000. Block times have been around 13.1s on average and now as of block 8,900,000 are around 14.3s. This will start to accelerate exponentially every 100,000 blocks. Estimating the added impact from the difficulty bomb on block times shows that we will see 20s block times near the end of December 2019 and 30s+ block times starting February 2020. This will start making the chain bloated and more costly to use. It's best to delay the difficulty bomb again to around the time of expected launch of the Eth2 finality gadget. + +## Specification +#### Relax Difficulty with Fake Block Number +For the purposes of `calc_difficulty`, simply replace the use of `block.number`, as used in the exponential ice age component, with the formula: + + fake_block_number = max(0, block.number - 9_000_000) if block.number >= MUIR_GLACIER_FORK_BLKNUM else block.number + +## Rationale +This will delay the ice age by 52 million seconds (approximately 611 days), so the chain would be back at 20 second block times around July 2021. It's important to note this pushes the ice age 4,000,000 blocks from ~block 8,800,000 NOT from when this EIP is activated in a fork. + +## Backwards Compatibility +This EIP is not forward compatible and introduces backwards incompatibilities in the difficulty calculation. Therefore, it should be included in a scheduled hardfork at a certain block number. It's suggested to include this EIP shortly after the Istanbul fork. + +## Test Cases +Test cases shall be created once the specification is to be accepted by the developers or implemented by the clients. + +## Implementation +The implementation in it's logic does not differ from [EIP-649](./eip-649.md) or [EIP-1234](./eip-1234.md); an implementation for Parity-Ethereum is available in [parity-ethereum#9187](https://github.com/paritytech/parity-ethereum/pull/9187). + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2386.md b/EIPS/eip-2386.md new file mode 100644 index 00000000000000..a942265254e8ed --- /dev/null +++ b/EIPS/eip-2386.md @@ -0,0 +1,7 @@ +--- +eip: 2386 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2386.md diff --git a/EIPS/eip-2387.md b/EIPS/eip-2387.md new file mode 100644 index 00000000000000..27a441e7a8686a --- /dev/null +++ b/EIPS/eip-2387.md @@ -0,0 +1,75 @@ +--- +eip: 2387 +title: "Hardfork Meta: Muir Glacier" +author: James Hancock (@madeoftin) +discussions-to: https://ethereum-magicians.org/t/hard-fork-to-address-the-ice-age-eip-2387 +type: Meta +status: Final +created: 2019-11-22 +requires: 1679, 2384 +--- + +## Abstract + +This meta-EIP specifies the changes included in the Ethereum hard fork named Muir Glacier. This hard fork addresses the impending Ice Age on Ethereum Mainnet and includes a commitment to solving the problems with the ice age more permanently. + +## Motivation + +Ethereum achieves a consistent block time due to its' difficulty retargeting algorithm. If a block-time is higher than 20 seconds, it reduces the difficulty, and if a block time is lower than 10 seconds, it increases the difficulty. This mechanism reaches typically an equilibrium of around 13-14 seconds. Included within this mechanism is something we refer to as the Difficulty Bomb or the Ice Age. It artificially adds to the difficulty in such a way that the retargeting mechanism, at some point, can not adapt to the increase, and we see increased block times throughout the network. The ice age increments every 100,000 blocks. It at first is barely noticeable, but once it is visible, there is a drastic effect on block-times in the network. + +The primary problem with the Ice Age is that it is included in the complex mechanism that targets block times, which is an entirely separate in purpose. What is worse is due to being intwined with that algorithm, it is very difficult to simulate or predict its effect on the network. To predict the impact of the ice age, you must both make assumptions about the difficulty of main-net in the future, and predict the effect of changes in difficulty to the impact on the ice age and thus block-times. + +This fork will push back the Iceage as far as far as is reasonable and will give us time to update the Iceage to no longer have these design problems. There are two solutions to consider within that time frame. + + - Update the mechanism so that behavior is predictable. + - Remove the Iceage entirely + +## Specification + +- Codename: Muir Glacier + +### Activation + - `Block >= 9,200,000` on the Ethereum mainnet + - `Block >= 7,117,117` on the Ropsten testnet + - `Block >= N/A` on the Kovan testnet + - `Block >= N/A` on the Rinkeby testnet + - `Block >= N/A` on the Görli testnet + +### Included EIPs + - [EIP-2384](./eip-2384.md): Istanbul/Berlin Difficulty Bomb Delay + +## Rationale + +I want to address the rationale for the intention of the Iceage and the implementation of the Iceage separately. + +**The original intentions of the ice age include:** + + - At the time of upgrades, inhibit unintentional growth of the resulting branching forks leading up to Eth 2.0. * + - Encourage a prompt upgrade schedule for the path to Eth 2.0. * + - Forces the community to come back into agreement repeatedly...and it gives whatever portion of the community that wants to a chance to fork off + - Is a check for the Core Devs in the case that a decision is made to freeze the code base of clients without the blessing of the community. + +*Note: None of these effects the Freedom to Fork. They are meant to encourage core-devs and the community to upgrade along with the network and prevent the case where sleeper forks remain dormant only later to be resurrected. The requirement for an active fork is to change a client in a way to respond to the ice age. This is in fact what Ethereum Classic has done. + +This is not meant to be exhaustive, but the ideas above capture much of what has been written on the original intentions and process of creating the fork. Any additions to this list that need to be made, I am happy to include. Regardless, to effectively implement an updated design for the ice age, all of the intentions need to be revisited and clarified as part of any updates. This clarification will give a clear expectation for the community and core developers moving forward. + +**The implementation** + +The existing implementation of the ice age, while it does work in practice, is unnecessarily complex to model and confusing to communicate to the community. Any updates to the design should be: + + - Easy to model the effect on the network + - Easy to predict when it occurs + +This fork would give us time to address the community to understand their priorities better as far as the intentions of the Ice Age, and give time for proposals for better mechanisms to achieve those goals. + +### POA Testnets + +Muir Glacier never activates on PoA chains – thus will have zero impact on [forkid](./eip-2124.md). + +### Note on Issuance Reduction + +Previous Hardforks to address the Ice Age have also included reductions in the block reward from 5 Eth to 3 Eth to 2 Eth, respectively. In this case, there is no change in issuance, and the block reward remains 2 Eth per block. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2390.md b/EIPS/eip-2390.md new file mode 100644 index 00000000000000..9ab3fca65cf6d3 --- /dev/null +++ b/EIPS/eip-2390.md @@ -0,0 +1,7 @@ +--- +eip: 2390 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2390.md diff --git a/EIPS/eip-2400.md b/EIPS/eip-2400.md new file mode 100644 index 00000000000000..a6d286dd35b776 --- /dev/null +++ b/EIPS/eip-2400.md @@ -0,0 +1,7 @@ +--- +eip: 2400 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2400.md diff --git a/EIPS/eip-2458.md b/EIPS/eip-2458.md new file mode 100644 index 00000000000000..d4ed2d39754ccb --- /dev/null +++ b/EIPS/eip-2458.md @@ -0,0 +1,75 @@ +--- +eip: 2458 +title: Updates and Updated-by Header +author: Edson Ayllon (@edsonayllon) +discussions-to: https://github.com/ethereum/EIPs/issues/2453 +status: Withdrawn +type: Informational +created: 2020-01-06 +--- + +## Simple Summary + +Adds EIP header options `updates` and `updated-by` to frontmatter of `active` EIPs for use as needed. + +## Abstract + +EIP headers `updates` and `updated-by` are used for updating `active` EIPs. This is to make the improvement process of EIPs more modular, and have updates to existing `active` EIPs receive similar exposures to EIPs which replace existing `final` EIPs. + +## Motivation + +Currently, EIP1 specifies EIP headers: `updated`, `replaces`, and `superseded-by`. Headers `replaces` and `superseded-by` indicates when an entire EIP is being replaced by another EIP, indicating when an EIP is now historical, and is updated by a new standard. + +The header `updated` indicates the date an EIP has received an update by EIP authors and editors, an example EIP being EIP1. `updated` is reserved for EIPs in `draft` or `active` status. + +In the case of `active` status, an EIP may receive an update, but these updates don't operate as with EIPs in `final` status, where a historical EIP is created, and the new EIP is referenced by the historical one. While these updates are not kept immutably, updates to active EIPs can be done modularly by creating a new EIP that goes through the standard discussion and auditing process EIPs undergo. The EIP headers `updates` and `updated-by` are to facilitate this modularity. Creating a new EIP also provides sufficient notification to affected stakeholders of an active EIP before that EIP is `updated`. + +## Specification + +### `updated-by` + +`updated-by` is reserved for EIPs in `active` status. For an EIP in status `active`, updates to that EIP, which update the header `updated`, should be started by opening a new EIP to start vetting for that update. When an `active` EIP receives a new entry to header `updated`, an associated `updated-by` EIP listing should be included, where that newly listed EIP has reached `final` status. + +`updates` should be included as an EIP header, as all EIP headers, and include a reference to an EIP designation. When multiple EIP designations are referenced, each should be separated by a comma. Example: + +``` +--- +updated-by: 9999, 9998, 9997 +--- +``` + +### `updates` + +`updates` is reserved for EIPs updating EIPs in `active` status. An EIP listed as `updates` is implied to also be `requires`; only `updates` is needed for those EIP listings. Having an EIP listing `updates` does not necessarily mean that referenced EIP must reference back with an `updated-by` listing. + +`updates` should be included as an EIP header, as all EIP headers, and include a reference to an EIP designation. When multiple EIP designations are referenced, each should be separated by a comma. Example: + +``` +--- +updates: 1 +--- +``` + +## Rationale + +`updates` and `updated-by` apply only to EIPs in `active` status as updates to EIPs in `final` status are already handled by EIP headers `superseded-by` and `replaces`. + +The syntax should align with previous EIP header syntax, as this EIP is not updating syntax, simply adding header options. + +## Backwards Compatibility + +These EIP headers are optional and do not introduce compatibility issues. + + +## Implementation + +An implementation is adding a header option. + +## Security Considerations + +This standard is informational and does not introduce technical security issues. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). + + diff --git a/EIPS/eip-2464.md b/EIPS/eip-2464.md new file mode 100644 index 00000000000000..2cdc86df7f4d18 --- /dev/null +++ b/EIPS/eip-2464.md @@ -0,0 +1,81 @@ +--- +eip: 2464 +title: "eth/65: transaction announcements and retrievals" +description: Introduces `NewPooledTransactionHashes`, `GetPooledTransactions`, and `PooledTransactions`. +author: Péter Szilágyi , Péter Szilágyi (@karalabe), Gary Rong , Tim Beiko (@timbeiko) +discussions-to: https://github.com/ethereum/EIPs/issues/2465 +status: Final +type: Standards Track +category: Networking +created: 2020-01-13 +requires: 2364 +--- + +## Abstract + +This EIP introduces three additional message types into the `eth` protocol (releasing a new version, `eth/65`): `NewPooledTransactionHashes (0x08)` to announce a set of transactions without their content; `GetPooledTransactions (0x09)` to request a batch of transactions by their announced hash; and `PooledTransactions (0x0a)` to reply to a transaction request. This permits reducing the bandwidth used for transaction propagation from linear complexity in the number of peers to square root; and also reducing the initial transaction exchange from 10s-100s MB to `len(pool) * 32B ~= 128KB`. + +## Motivation + +The `eth` network protocol has two ways to propagate a newly mined block: it can be broadcast to a peer in its entirety (via `NewBlock (0x07)` in `eth/64` and prior or it can be announced only (via `NewBlockHashes (0x01)`). This duality allows nodes to do the high-bandwidth broadcasting (10s-100s KB) for a square root number of peers; and the low-bandwidth announcing (10s-100s B) for the remaining linear number of peers. The square root broadcast is enough to reach all well connected nodes, but the linear announce is needed to get across degenerate topologies. This works well. + +The `eth` protocol, however, does not have a similar dual mechanism for propagating transactions, so nodes need to rely on broadcasting (via `Transactions (0x02)`). To cater for degenerate topologies, transactions cannot be broadcast square rooted, rather they need to be transferred linearly to all peers. With N peers, each node will transfer the same transaction N times (counting both directions), whereas 1 would be enough in a perfect world. This is a significant waste. + +A similar issue arises when a new network connection is made between two nodes, as they need to sync up their transaction pools, but the pool is just a soup of dangling transactions. Without a way to deduplicate transactions remotely, each node is forced to naively transfer their entire list of transactions to the other side. With pools containing thousands of transactions, a naive transfer amounts to 10s-100s MB, most of which is useless. There is no better way, however. + +This EIP introduces three additional message types into the `eth` protocol (releasing a new version, `eth/65`): `NewPooledTransactionHashes (0x08)` to announce a set of transactions without their content; `GetPooledTransactions (0x09)` to request a batch of transactions by their announced hash; and `PooledTransactions (0x0a)` to reply to a transaction request. This permits reducing the bandwidth used for transaction propagation from linear complexity in the number of peers to square root; and also reducing the initial transaction exchange from 10s-100s MB to `len(pool) * 32B ~= 128KB`. + +With transaction throughput (and size) picking up in Ethereum, transaction propagation is the current dominant component of the used network resources. Most of these resources are however wasted, as the `eth` protocol does not have a mechanism to deduplicate transactions remotely, so the same data is transferred over and over again across all network connections. + +This EIP proposes a tiny extension to the `eth` protocol, which permits nodes to agree on the set of transactions that need to be transferred across a network connection, before doing the costly exchange. This should help reduce the global (operational) bandwidth usage of the Ethereum network by at least an order of magnitude. + +## Specification + +Add three new message types to the `eth` protocol: + * `NewPooledTransactionHashes (0x08): [hash_0: B_32, hash_1: B_32, ...]` + * Specify one or more transactions that have appeared in the network and which have **not yet been included in a block**. To be maximally helpful, nodes should inform peers of all transactions that they may not be aware of. + * There is **no protocol violating hard cap** on the number of hashes a node may announce to a remote peer (apart from the 10MB `devp2p` network packet limit), but 4096 seems a sane chunk (128KB) to avoid a single packet hogging a network connection. + * Nodes should only announce hashes of transactions that the remote peer could reasonably be considered not to know, but it is better to be over zealous than to have a nonce gap in the pool. + * `GetPooledTransactions (0x09): [hash_0: B_32, hash_1: B_32, ...]` + * Specify one or more transactions to retrieve from a remote peer's **transaction pool**. + * There is **no protocol violating hard cap** on the number of transactions a node may request from a remote peer (apart from the 10MB `devp2p` network packet limit), but the recipient may enforce an arbitrary cap on the reply (size or serving time), which **must not** be considered a protocol violation. To keep wasted bandwidth down (unanswered hashes), 256 seems like a sane upper limit. + * `PooledTransactions (0x0a): [[nonce: P, receivingAddress: B_20, value: P, ...], ...]` + * Specify transactions **from the local transaction pool** that the remote node requested via a `GetPooledTransactions (0x09)` message. The items in the list are transactions in the format described in the main Ethereum specification. + * The transactions **must** be in same order as in the request, but it is **ok** to skip transactions that are not available. This way if the response size limit is reached, requesters will know which hashes to request again (everything from the last returned transaction) and which to assume unavailable (all gaps before the last returned transaction). + * A peer may respond with an empty reply **iff** none of the hashes match transactions in its pool. It is allowed to announce a transaction that will not be served later if it gets included in a block in between. + +## Rationale + +**Q: Why limit `GetPooledTransactions (0x09)` to retrieving items from the pool?** + +Apart from the transaction pool, transactions in Ethereum are always bundled together by the hundreds in block bodies and existing network retrievals honor this data layout. Allowing direct access to individual transactions in the database has no actionable use case, but would expose costly database reads into the network. + +For transaction propagation purposes there is no reason to allow disk access, as any transaction finalized to disk will be broadcast inside a block anyway, so at worse there is a few hundred millisecond delay when a node gets the transaction. + +Block propagation may be made a bit more optimal by transferring the contained transactions on demand only, but that is a whole EIP in itself, so better relax the protocol when all the requirements are known and not in advance. It would probably be enough to maintain a set of transactions included in recent blocks in memory. + +**Q: Should `NewPooledTransactionHashes (0x08)` deduplicate from disk?** + +Similarly to `GetPooledTransactions (0x09)`, `NewPooledTransactionHashes (0x08)` should also only operate on the transaction pool and should ignore the disk altogether. During healthy network conditions, a transaction will propagate through much faster than it's included in a block, so it will essentially be non-existent that a newly announced transaction is already on disk. By avoiding disk deduplication, we can avoid a DoS griefing by remote transaction announces. + +If we want to be really correct and avoid even the slightest data race when deduplicating announcements, we can use the same recently-included-transactions trick that we discussed above to discard announcements that have recently become stale. + +**Q: Why not reuse `Transaction (0x02)` instead of a new `PooledTransactions (0x0a)`?** + +Originally this EIP reused the existing `Transaction (0x02)` message as the reply to the `GetPooledTransactions (0x09)` request. This makes client code more complicated, because nodes constantly gossip `Transaction (0x02)` messages to each other as broadcasts, so it's hard to match up which of the many messages is the actual reply to the request. + +By keeping `Transaction (0x02)` and `PooledTransactions (0x0a)` as separate messages, we can also leave the protocol more flexible for future optimizations (e.g. adding request IDs, which are meaningless for gossip broadcasts). + +## Backwards Compatibility + +This EIP extends the `eth` protocol in a backwards incompatible way and requires rolling out a new version, `eth/65`. However, `devp2p` supports running multiple versions of the same wire protocol side-by-side, so rolling out `eth/65` does not require client coordination, since non-updated clients can keep using `eth/64`. + +This EIP does not change the consensus engine, thus does _not_ require a hard fork. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2470.md b/EIPS/eip-2470.md new file mode 100644 index 00000000000000..65bf8a1aa85fc8 --- /dev/null +++ b/EIPS/eip-2470.md @@ -0,0 +1,7 @@ +--- +eip: 2470 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2470.md diff --git a/EIPS/eip-2474.md b/EIPS/eip-2474.md new file mode 100644 index 00000000000000..042a5c69032d1a --- /dev/null +++ b/EIPS/eip-2474.md @@ -0,0 +1,62 @@ +--- +eip: 2474 +title: Coinbase calls +author: Ricardo Guilherme Schmidt (@3esmit) +discussions-to: https://ethresear.ch/t/gas-abstraction-non-signed-block-validator-only-procedures/4388/2 +status: Stagnant +type: Standards Track +category: Core +created: 2020-01-19 +--- + +## Simple Summary + +Allow contracts to be called directly by `block.coinbase` (block validator), without a transaction. + +## Abstract + +_In proof-of-work blockchains, validators are known as miners._ + +The validator might want to execute functions directly, without having to sign a transaction. Some examples might be presenting a proof in a contract for a change which also benefits the validator. + +A notable example would be when a validator want to act as an [EIP-1077](./eip-1077.md) Gas Relayer, incentivized to pick up fees from meta transactions. +Without this change, they can do so by signing from any address a `gasPrice = 0` transaction with the gas relayed call. +However this brings an overhead of a signed transaction by validator that does nothing, as `msg.sender` is never used, and there is no gas cost to EVM charge. + +This proposal makes possible to remove this unused ecrecover. + +## Motivation + +In order to reduce the overhead of calls that don't use `msg.sender` and are being called by validator with `tx.gasPrice = 0`. + +## Specification + +The calls to be executed by `block.coinbase` would be included first at block, and would consume normally the gas of block, however they won't pay/cost gas, instead the call logic would pay the validator in other form. + +Would be valid to execute any calls without a transaction by the block coinbase, except when the validator call tries to read `msg.sender`, which would throw an invalid jump. + +Calls included by the validator would have `tx.origin = block.coinbase` and `gas.price = 0` for the rest of call stack, the rest follows as normal calls. + +## Rationale + +TBD + +## Backwards Compatibility + +`tx.origin = block.coinbase` could cause some issues on bad designed contracts, such as using `tx.origin` to validate a signature, an analysis on how contracts use tx.origin might be useful to decide if this is a good choice. + +## Test Cases + +TBD + +## Implementation + +TBD + +## Security Considerations + +TBD + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2477.md b/EIPS/eip-2477.md new file mode 100644 index 00000000000000..e5a527b1ae2863 --- /dev/null +++ b/EIPS/eip-2477.md @@ -0,0 +1,7 @@ +--- +eip: 2477 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2477.md diff --git a/EIPS/eip-2481.md b/EIPS/eip-2481.md new file mode 100644 index 00000000000000..c8bc379b8d6dfc --- /dev/null +++ b/EIPS/eip-2481.md @@ -0,0 +1,420 @@ +--- +eip: 2481 +title: eth/66 request identifier +description: Introduces a request id for all requests of the eth protocol +author: Christoph Burgdorf (@cburgdorf) +discussions-to: https://ethereum-magicians.org/t/eip-2481-eth-66-request-identifiers/12132 +status: Final +type: Standards Track +category: Networking +created: 2020-01-17 +requires: 2464 +--- + +## Abstract + +The `eth` protocol defines various request and response commands that are used to exchange data between Ethereum nodes. For example, to ask a peer node for a specific set of headers, a node sends it the [`GetBlockHeaders`](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md#getblockheaders-0x03) command. + +*Citing from the [`GetBlockHeaders` spec definition](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md#getblockheaders-0x03):* + +>`[block: {P, B_32}, maxHeaders: P, skip: P, reverse: P in {0, 1}]` + +>Require peer to return a `BlockHeaders` message. Reply must contain a number of block +headers, of rising number when `reverse` is `0`, falling when `1`, `skip` blocks apart, +beginning at block `block` (denoted by either number or hash) in the canonical chain, and +with at most `maxHeaders` items. + +The node that receives the `GetBlockHeaders` command should answer it with the [`BlockHeaders`](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md#blockheaders-0x04) response command accordingly. + +*Citing from the [`BlockHeaders` spec definition](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md#blockheaders-0x04):* + +>`[blockHeader_0, blockHeader_1, ...]` + +>Reply to `GetBlockHeaders`. The items in the list (following the message ID) are block +headers in the format described in the main Ethereum specification, previously asked for +in a GetBlockHeaders message. This may validly contain no block headers if none of the +requested block headers were found. The number of headers that can be requested in a +single message may be subject to implementation-defined limits. + +Let's consider a client making many simultaneous requests for `GetBlockHeaders` to one of its peers. By nature it can not be guaranteed that the expected responses arrive in the same order as they were sent. For the client to associate the incoming responses to the correct requests it has to loop through all pending requests trying to match it with the incoming response based on its contents. + +This can be particular tricky for responses that are ambiguous such as empty responses. + +This EIP proposes to change the `GetBlockHeaders` and the `BlockHeaders` command to include a `request_id`. + +The `request_id` is a 64-bit integer set by the client when it makes the request. On the responding side, the exact same `request_id` from the incoming request is put back into the response object. + +This change allows the requesting client to match incoming responses **directly** back to their pending requests without going through all of the pending requests to check if they might match based on the response data. + +The selected request/response pair serves as an example for many similar request/response pairs in the `eth` networking protocol. + +## Motivation + +The lack of request identifiers in the request / response paris of the `eth` protocol puts unnecessary burden of code complexity into every Ethereum client. It also makes the communication slightly less efficient. Another argument can be made that the addition of request identifiers makes the protocol more aligned with the `les` protocol which **does** already defines request identifiers for each request / response pair. + +## Specification + +Change the following message types in the `eth` protocol: + +* `GetBlockHeaders (0x03)` + * **Current (eth/65):** `[block: {P, B_32}, maxHeaders: P, skip: P, reverse: P in {0, 1}]` + * **Then (eth/66)**: `[request_id: P, [block: {P, B_32}, maxHeaders: P, skip: P, reverse: P in {0, 1}]]` +* `BlockHeaders (0x04)` + * **Current (eth/65):** `[blockHeader_0, blockHeader_1, ...]` + * **Then (eth/66)**: `[request_id: P, [blockHeader_0, blockHeader_1, ...]]` +* `GetBlockBodies (0x05)` + * **Current (eth/65):** `[hash_0: B_32, hash_1: B_32, ...]` + * **Then (eth/66)**: `[request_id: P, [hash_0: B_32, hash_1: B_32, ...]]` +* `GetPooledTransactions (0x09)`: + * **Current (eth/65)**`[hash_0: B_32, hash_1: B_32, ...]` + * **Then (eth/66)**`[request_id: P, [hash_0: B_32, hash_1: B_32, ...]]` +* `PooledTransactions (0x0a)`: + * **Current (eth/65)**`[[nonce: P, receivingAddress: B_20, value: P, ...], ...]` + * **Then (eth/66)**`[request_id: P, [[nonce: P, receivingAddress: B_20, value: P, ...], ...]]` +* `BlockBodies (0x06)` + * **Current (eth/65):** `[hash_0: B_32, hash_1: B_32, ...]` + * **Then (eth/66)**: `[request_id: P, [hash_0: B_32, hash_1: B_32, ...]]` +* `GetNodeData (0x0d)` + * **Current (eth/65):** `[hash_0: B_32, hash_1: B_32, ...]` + * **Then (eth/66)**: `[request_id: P, [hash_0: B_32, hash_1: B_32, ...]]` +* `NodeData (0x0e)` + * **Current (eth/65):** `[value_0: B, value_1: B, ...]` + * **Then (eth/66)**: `[request_id: P, [value_0: B, value_1: B, ...]]` +* `GetReceipts (0x0f)` + * **Current (eth/65):** `[blockHash_0: B_32, blockHash_1: B_32, ...]` + * **Then (eth/66)**: `[request_id: P, [blockHash_0: B_32, blockHash_1: B_32, ...]]` +* `Receipts (0x10)` + * **Current (eth/65):** `[[receipt_0, receipt_1], ...]` + * **Then (eth/66)**: `[request_id: P, [[receipt_0, receipt_1], ...]]` + + +To elaborate, each command is altered in the following way: + +1. Create a list with the `request_id` being the first element. +2. Make the second element the list that defines the whole command in the current scheme. + +The ``request_id`` has the following characteristics: + +* 64 bit integer +* Doesn't need to be sequential (can be random) +* Does allow duplicates + +## Rationale + +**Q: The efficiency gains might encourage clients to flood their peers with too many simultaneous requests** + +Peers can always throttle or disconnect if they don't feel treated well. This is the same as today. + +**Q: If `les` already defines the commands like this, why not just use the `les` protocol?** + +In practice, peers that serve the `les` protocol are much harder to find in the network. The reasons for this are varied but might boil down to client defaults, immature implementations or missing incentives. + +**Q: Networking works today, isn't this just adding bloat?** + +This is adding a single integer per command while at the same time reducing code complexity and improving networking efficiency. The addition seems justified. + +**Q: Why not demand request ids to be sequential?** + +Assuming request ids start always to count from `0` upon connection, things will become messy when +connections are lost and clients reconnect and start over with the same request ids that they had used +in the previous session. + +**Q: Why allow duplicate request ids?** + +The main benefit is flexibility and simplicity on the implementation side. Clients could decide to share +the same ids across multiple different request types since they are naturally separated anyway. Clients +could even decide to not rely on request ids at all, therefore using the same constant request id across +all requests. + +**Q: Why choose a 64-bit integer for the request ids** + +64-bit integer were chosen to keep compatibility with the `les` protocol. + +## Backwards Compatibility + +This EIP extends the `eth` protocol in a backwards incompatible way and requires rolling out a new version, `eth/66`. However, `devp2p` supports running multiple versions of the same wire protocol side-by-side, so rolling out `eth/66` does not require client coordination, since non-updated clients can keep using `eth/65`. + +This EIP does not change the consensus engine, thus does *not* require a hard fork. + +## Test Cases + +These testcases cover RLP-encoding of all the redefined messages types, where the `rlp` portion is the rlp-encoding of the message defined in the `data` portion. + + +```json +{ + "type": "GetBlockHeadersPacket66", + "rlp": "0xe8820457e4a000000000000000000000000000000000000000000000000000000000deadc0de050580", + "data": { + "RequestId": 1111, + "Origin": { + "Hash": "0x00000000000000000000000000000000000000000000000000000000deadc0de", + "Number": 0 + }, + "Amount": 5, + "Skip": 5, + "Reverse": false + } +} +``` + +```json +{ + "type": "GetBlockHeadersPacket66", + "rlp": "0xca820457c682270f050580", + "data": { + "RequestId": 1111, + "Origin": { + "Hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "Number": 9999 + }, + "Amount": 5, + "Skip": 5, + "Reverse": false + } +} +``` + +```json +{ + "type": "BlockHeadersPacket66", + "rlp": "0xf90202820457f901fcf901f9a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000940000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008208ae820d0582115c8215b3821a0a827788a00000000000000000000000000000000000000000000000000000000000000000880000000000000000", + "data": { + "RequestId": 1111, + "BlockHeadersPacket": [ + { + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "sha3Uncles": "0x0000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "receiptsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "difficulty": "0x8ae", + "number": "0xd05", + "gasLimit": "0x115c", + "gasUsed": "0x15b3", + "timestamp": "0x1a0a", + "extraData": "0x7788", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "nonce": "0x0000000000000000", + "hash": "0x8c2f2af15b7b563b6ab1e09bed0e9caade7ed730aec98b70a993597a797579a9" + } + ] + } +} +``` + +```json +{ + "type": "GetBlockBodiesPacket66", + "rlp": "0xf847820457f842a000000000000000000000000000000000000000000000000000000000deadc0dea000000000000000000000000000000000000000000000000000000000feedbeef", + "data": { + "RequestId": 1111, + "GetBlockBodiesPacket": [ + "0x00000000000000000000000000000000000000000000000000000000deadc0de", + "0x00000000000000000000000000000000000000000000000000000000feedbeef" + ] + } +} +``` + +```json +{ + "type": "BlockBodiesPacket66", + "rlp": "0xf902dc820457f902d6f902d3f8d2f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afbf901fcf901f9a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000940000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008208ae820d0582115c8215b3821a0a827788a00000000000000000000000000000000000000000000000000000000000000000880000000000000000", + "data": { + "RequestId": 1111, + "BlockBodiesPacket": [ + { + "Transactions": [ + { + "nonce": "0x8", + "gasPrice": "0x4a817c808", + "gas": "0x2e248", + "to": "0x3535353535353535353535353535353535353535", + "value": "0x200", + "input": "0x", + "v": "0x25", + "r": "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12", + "s": "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", + "hash": "0x588df025c4c2d757d3e314bd3dfbfe352687324e6b8557ad1731585e96928aed" + }, + { + "nonce": "0x9", + "gasPrice": "0x4a817c809", + "gas": "0x33450", + "to": "0x3535353535353535353535353535353535353535", + "value": "0x2d9", + "input": "0x", + "v": "0x25", + "r": "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "s": "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "hash": "0xf39c7dac06a9f3abf09faf5e30439a349d3717611b3ed337cd52b0d192bc72da" + } + ], + "Uncles": [ + { + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "sha3Uncles": "0x0000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "receiptsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "difficulty": "0x8ae", + "number": "0xd05", + "gasLimit": "0x115c", + "gasUsed": "0x15b3", + "timestamp": "0x1a0a", + "extraData": "0x7788", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "nonce": "0x0000000000000000", + "hash": "0x8c2f2af15b7b563b6ab1e09bed0e9caade7ed730aec98b70a993597a797579a9" + } + ] + } + ] + } +} +``` + +```json +{ + "type": "GetNodeDataPacket66", + "rlp": "0xf847820457f842a000000000000000000000000000000000000000000000000000000000deadc0dea000000000000000000000000000000000000000000000000000000000feedbeef", + "data": { + "RequestId": 1111, + "GetNodeDataPacket": [ + "0x00000000000000000000000000000000000000000000000000000000deadc0de", + "0x00000000000000000000000000000000000000000000000000000000feedbeef" + ] + } +} +``` + +```json +{ + "type": "NodeDataPacket66", + "rlp": "0xce820457ca84deadc0de84feedbeef", + "data": { + "RequestId": 1111, + "NodeDataPacket": [ + "0xdeadc0de", + "0xfeedbeef" + ] + } +} +``` + +```json +{ + "type": "GetReceiptsPacket66", + "rlp": "0xf847820457f842a000000000000000000000000000000000000000000000000000000000deadc0dea000000000000000000000000000000000000000000000000000000000feedbeef", + "data": { + "RequestId": 1111, + "GetReceiptsPacket": [ + "0x00000000000000000000000000000000000000000000000000000000deadc0de", + "0x00000000000000000000000000000000000000000000000000000000feedbeef" + ] + } +} +``` + +```json +{ + "type": "ReceiptsPacket66", + "rlp": "0xf90172820457f9016cf90169f901668001b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f85ff85d940000000000000000000000000000000000000011f842a0000000000000000000000000000000000000000000000000000000000000deada0000000000000000000000000000000000000000000000000000000000000beef830100ff", + "data": { + "RequestId": 1111, + "ReceiptsPacket": [ + [ + { + "root": "0x", + "status": "0x0", + "cumulativeGasUsed": "0x1", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "logs": [ + { + "address": "0x0000000000000000000000000000000000000011", + "topics": [ + "0x000000000000000000000000000000000000000000000000000000000000dead", + "0x000000000000000000000000000000000000000000000000000000000000beef" + ], + "data": "0x0100ff", + "blockNumber": "0x0", + "transactionHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionIndex": "0x0", + "blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "logIndex": "0x0", + "removed": false + } + ], + "transactionHash": "0x00000000000000000000000000000000000000000000000000000000deadc0de", + "contractAddress": "0x0000000000000000000000000000000000011111", + "gasUsed": "0x1b207", + "blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionIndex": "0x0" + } + ] + ] + } +} +``` + +```json +{ + "type": "GetPooledTransactionsPacket66", + "rlp": "0xf847820457f842a000000000000000000000000000000000000000000000000000000000deadc0dea000000000000000000000000000000000000000000000000000000000feedbeef", + "data": { + "RequestId": 1111, + "GetPooledTransactionsPacket": [ + "0x00000000000000000000000000000000000000000000000000000000deadc0de", + "0x00000000000000000000000000000000000000000000000000000000feedbeef" + ] + } +} +``` + +```json +{ + "type": "PooledTransactionsPacket66", + "rlp": "0xf8d7820457f8d2f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "data": { + "RequestId": 1111, + "PooledTransactionsPacket": [ + { + "nonce": "0x8", + "gasPrice": "0x4a817c808", + "gas": "0x2e248", + "to": "0x3535353535353535353535353535353535353535", + "value": "0x200", + "input": "0x", + "v": "0x25", + "r": "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12", + "s": "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", + "hash": "0x588df025c4c2d757d3e314bd3dfbfe352687324e6b8557ad1731585e96928aed" + }, + { + "nonce": "0x9", + "gasPrice": "0x4a817c809", + "gas": "0x33450", + "to": "0x3535353535353535353535353535353535353535", + "value": "0x2d9", + "input": "0x", + "v": "0x25", + "r": "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "s": "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "hash": "0xf39c7dac06a9f3abf09faf5e30439a349d3717611b3ed337cd52b0d192bc72da" + } + ] + } +} +``` + +## Security Considerations + +None + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2488.md b/EIPS/eip-2488.md new file mode 100644 index 00000000000000..5af41eb8bf0775 --- /dev/null +++ b/EIPS/eip-2488.md @@ -0,0 +1,58 @@ +--- +eip: 2488 +title: Deprecate the CALLCODE opcode +author: Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-2488-deprecate-the-callcode-opcode/3957 +status: Stagnant +type: Standards Track +category: Core +created: 2019-12-20 +requires: 7 +--- + +## Abstract + +Deprecate `CALLCODE` in a *somewhat* backwards compatible way, by making it always return failure. + +## Motivation + +`CALLCODE` was part of the Frontier release of Ethereum. In the first few weeks/months it became clear +that it cannot accomplish its intended design goal. This was rectified with introducing `DELEGATECALL` +([EIP-7](./eip-7.md)) in the Homestead update (early 2016). + +`CALLCODE` became never utilized, but it still puts a burden on EVM implementations. + +Disabling it will not improve the situation for any client whose goal is to sync from genesis, but would +help light clients or clients planning to sync from a later point in time. + +## Specification + +If `block.number >= FORK_BLOCK`, the `CALLCODE` (`0xf2`) instruction always returns `0`, which signals failure. + +## Rationale + +It would be possible just to remove the opcode and exceptionally abort if it is encountered. +However, by returning failure, the contract has a chance to act on it and potentially recover. + +## Backwards Compatibility + +This is a breaking change and has a potential to break contracts. The author expects no contracts of any value +should be affected. + +TODO: validate this claim. + +## Security Considerations + +TBA + +## Test Cases + +TBA + +## Implementation + +TBA + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2494.md b/EIPS/eip-2494.md new file mode 100644 index 00000000000000..76f5e329227b25 --- /dev/null +++ b/EIPS/eip-2494.md @@ -0,0 +1,7 @@ +--- +eip: 2494 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2494.md diff --git a/EIPS/eip-2515.md b/EIPS/eip-2515.md new file mode 100644 index 00000000000000..7cdd80d6d6778c --- /dev/null +++ b/EIPS/eip-2515.md @@ -0,0 +1,88 @@ +--- +eip: 2515 +title: Implement Difficulty Freeze +author: James Hancock (@madeoftin) +discussions-to: https://ethereum-magicians.org/t/eip-2515-replace-the-difficulty-bomb-with-a-difficulty-freeze/3995 +status: Stagnant +type: Standards Track +category: Core +created: 2020-02-10 +--- + + +## Simple Summary +The difficulty Freeze is an alternative to the Difficulty Bomb that is implemented within the protocols difficulty adjustment algorithm. The Difficulty Freeze begins at a certain block height, determined in advance, freezes the difficulty and increases by 1% after that block forever. This does not stop the chain, but it incentivizes devs to upgrade at a regular cadence and requires any chain split to address the difficulty freeze. + +## Abstract +The difficulty Freeze is a mechanism that is easy to predict and model, and the pressures of missing it are more readily felt by the core developers and client maintainers. The client maintainers are also positioned as the group that is most able to respond to an incoming Difficulty Freeze. This combined with the predictability is more likely to lead to the timely diffusual of the bomb. + + +## Motivation +The current difficulty bombs' effect on the Block Time Targeting mechanism is rather complex to model, and it has both appeared when it was not expected (Muir Glacier) and negatively affected miners when they are not the target (in the case of delaying forks due to technical difficulties). Miners are affected by a reduction in block rewards due to the increase in block time. Users are affected as a function of the usability of the chain is affected by increased block times. Both of these groups are unable on their own to address the difficulty bomb. In the case of the Difficulty Freeze, the consequences of missing it are more directly felt by the client maintainers and it is more predictiable and so knowing when to make the change is readily apparent. + +## Specification + +Add variable `DIFFICULTY_FREEZE_HEIGHT` + + +The logic of the Difficulty Freeze is defined as follows: + +``` +if (BLOCK_HEIGHT <= DIFFICULTY_FREEZE_HEIGHT): + block_diff = parent_diff + parent_diff // 2048 * max( + 1 - (block_timestamp - parent_timestamp) // 10, -99) + +else: + block_diff = parent_diff + parent_diff * 0.01 +``` + +**Optional Implementation** + +Add the variable `DIFFICULTY_FREEZE_DIFFERENCE` and use the `LAST_FORK_HEIGHT` to calculate when the Difficulty Freeze would occur. + +For example we can set the `DFD = 1,800,000 blocks` or approximately 9 months. The Difficulty Calculation would then be. + +``` +if (BLOCK_HEIGHT <= LAST_FORK_HEIGHT + DIFFICULTY_FREEZE_DIFFERENCE) : + block_diff = parent_diff + parent_diff // 2048 * max( + 1 - (block_timestamp - parent_timestamp) // 10, -99) + +else: + block_diff = parent_diff + parent_diff * 0.01 +``` + +This approach would have the added benefit that updating the Difficulty Freeze is easier as it happens automatically at the time of every upgrade. The trade-off is that the logic for checking is more complex and would require further analysis and test cases to ensure no consensus bugs arise. + +## Rationale +Block height is very easy to predict and evaluate within the system. This removes the effect of the Difficulty Bomb on block time, simplifying the block time targeting mechanism. The addition of an increase in the difficulty was added after feedback that the game theory of the mechanism did not reliably result in . + +https://twitter.com/quentinc137/status/1227110578235330562 + +## Backwards Compatibility +No backward incompatibilities + +## Test Cases +TBD +## Implementation +TBD + +## Security Considerations +The effect of missing the Difficulty Freeze has a different impact than missing the Difficulty Bomb. At the point of a Difficulty freeze, the protocol is no longer able to adapt to changes in hash power on the network. This can lead to one of three scenarios. + + - The Hash rate Increases: + Block Times would increase on the network for short time until the increase in difficulty is too high for the network to add any more miners. + - The Hash rate decreases: + Block times would increase. + - The Hash rate stays the same: + A consistent increase in blocktimes. + +Clients are motivated to have their client sync fully to the network and so are very motivated to keep this situation from occurring. Simultaneously delaying the Difficulty Freeze is most easily implemented by client teams. Therefore the group that is most negatively affected is also the group that can most efficiently address it. + +## Economic Considerations + +Under the current Difficult, Bomb issuance of ETH is reduced as the Ice Age takes affect. Under the Difficulty Freeze, it is more likely that issuance would increase for a short time; however, clients are motivated to prevent this and keep clients syncing effectively. This means it is much less likely to occur. The increase to the difficulty over time will eventually reduce blocktimes and also issuance. + +It is also easy to predict when this change would happen, and stakeholders who are affected (Eth Holders) can keep client developers accountable by observing when the Difficulty Freeze is approaching and yell at them on twitter. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2520.md b/EIPS/eip-2520.md new file mode 100644 index 00000000000000..0ded919d219502 --- /dev/null +++ b/EIPS/eip-2520.md @@ -0,0 +1,7 @@ +--- +eip: 2520 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2520.md diff --git a/EIPS/eip-2525.md b/EIPS/eip-2525.md new file mode 100644 index 00000000000000..ae319b3ee99cb9 --- /dev/null +++ b/EIPS/eip-2525.md @@ -0,0 +1,7 @@ +--- +eip: 2525 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2525.md diff --git a/EIPS/eip-2535.md b/EIPS/eip-2535.md new file mode 100644 index 00000000000000..1c2fb213efceb3 --- /dev/null +++ b/EIPS/eip-2535.md @@ -0,0 +1,7 @@ +--- +eip: 2535 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2535.md diff --git a/EIPS/eip-2537.md b/EIPS/eip-2537.md new file mode 100644 index 00000000000000..bb29a0aa0fd9fa --- /dev/null +++ b/EIPS/eip-2537.md @@ -0,0 +1,389 @@ +--- +eip: 2537 +title: Precompile for BLS12-381 curve operations +description: Adds operation on BLS12-381 curve as a precompile in a set necessary to efficiently perform operations such as BLS signature verification. +author: Alex Vlasov (@shamatar), Kelly Olson (@ineffectualproperty), Alex Stokes (@ralexstokes), Antonio Sanso (@asanso) +discussions-to: https://ethereum-magicians.org/t/eip2537-bls12-precompile-discussion-thread/4187 +status: Final +type: Standards Track +category: Core +created: 2020-02-21 +--- + +## Abstract + +Add functionality to efficiently perform operations over the BLS12-381 curve, including those for BLS signature verification. + +Along with the curve arithmetic, multi-scalar-multiplication operations are included to efficiently aggregate public keys or individual signer's signatures during BLS signature verification. + +## Motivation + +The motivation of this precompile is to add a cryptographic primitive that allows to get 120+ bits of security for operations over pairing friendly curve compared to the existing BN254 precompile that only provides 80 bits of security. + +## Specification + +### Constants + +| Name | Value | Comment | +|---------------------|-------|--------------------| +| BLS12_G1ADD | 0x0b | precompile address | +| BLS12_G1MSM | 0x0c | precompile address | +| BLS12_G2ADD | 0x0d | precompile address | +| BLS12_G2MSM | 0x0e | precompile address | +| BLS12_PAIRING_CHECK | 0x0f | precompile address | +| BLS12_MAP_FP_TO_G1 | 0x10 | precompile address | +| BLS12_MAP_FP2_TO_G2 | 0x11 | precompile address | + +We introduce *seven* separate precompiles to perform the following operations: + +- BLS12_G1ADD - to perform point addition in G1 (curve over base prime field) with a gas cost of `375` gas +- BLS12_G1MSM - to perform multi-scalar-multiplication (MSM) in G1 (curve over base prime field) with a gas cost formula defined in the corresponding section +- BLS12_G2ADD - to perform point addition in G2 (curve over quadratic extension of the base prime field) with a gas cost of `600` gas +- BLS12_G2MSM - to perform multi-scalar-multiplication (MSM) in G2 (curve over quadratic extension of the base prime field) with a gas cost formula defined in the corresponding section +- BLS12_PAIRING_CHECK - to perform a pairing operations between a set of *pairs* of (G1, G2) points a gas cost formula defined in the corresponding section +- BLS12_MAP_FP_TO_G1 - maps base field element into the G1 point with a gas cost of `5500` gas +- BLS12_MAP_FP2_TO_G2 - maps extension field element into the G2 point with a gas cost of `23800` gas + +A mapping functions specification is included as a separate [document](../assets/eip-2537/field_to_curve.md). This mapping function does NOT perform mapping of the byte string into a field element (as it can be implemented in many different ways and can be efficiently performed in EVM), but only does field arithmetic to map a field element into a curve point. Such functionality is required for signature schemes. + +### Curve parameters + +The BLS12 curve is fully defined by the following set of parameters (coefficient `A=0` for all BLS12 curves): + +``` +Base field modulus = p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +Fp - finite field of size p +Curve Fp equation: Y^2 = X^3+B (mod p) +B coefficient = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 +Main subgroup order = q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 +Extension tower +Fp2 construction: +Fp quadratic non-residue = nr2 = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa +Fp2 is Fp[X]/(X^2-nr2) +Curve Fp2 equation: Y^2 = X^3 + B*(v+1) where v is the square root of nr2 +Fp6/Fp12 construction: +Fp2 cubic non-residue c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +Fp2 cubic non-residue c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +Twist parameters: +Twist type: M +B coefficient for twist c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 +B coefficient for twist c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 +Generators: +H1: +X = 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb +Y = 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1 +H2: +X c0 = 0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8 +X c1 = 0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e +Y c0 = 0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801 +Y c1 = 0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be +Pairing parameters: +|x| (miller loop scalar) = 0xd201000000010000 +x is negative = true +``` + +One should note that base field modulus `p` is equal to `3 mod 4` that allows an efficient square root extraction, although as described below gas cost of decompression is larger than gas cost of supplying decompressed point data in `calldata`. + +### Fields and Groups + +Field Fp is defined as the finite field of size `p` with elements represented as integers between 0 and p-1 (both inclusive). + +Field Fp2 is defined as `Fp[X]/(X^2-nr2)` with elements `el = c0 + c1 * v`, where `v` is the formal square root of `nr2` represented as integer pairs `(c0,c1)`. + +Group G1 is defined as a set of Fp pairs (points) `(x,y)` such that either `(x,y)` is `(0,0)` or `x,y` satisfy the curve Fp equation. + +Group G2 is defined as a set of Fp2 pairs (points) `(x',y')` such that either `(x,y)` is `(0,0)` or `(x',y')` satisfy the curve Fp2 equation. + +### Fine points and encoding of base elements + +#### Field elements encoding: + +In order to produce inputs to an operation, one encodes elements of the base field and the extension field. + +A base field element (Fp) is encoded as `64` bytes by performing the BigEndian encoding of the corresponding (unsigned) integer. Due to the size of `p`, the top `16` bytes are always zeroes. `64` bytes are chosen to have `32` byte aligned ABI (representable as e.g. `bytes32[2]` or `uint256[2]` with the latter assuming the BigEndian encoding). The corresponding integer **must** be less than field modulus. + +For elements of the quadratic extension field (Fp2), encoding is byte concatenation of individual encoding of the coefficients totaling in `128` bytes for a total encoding. For an Fp2 element in a form `el = c0 + c1 * v` where `v` is the formal square root of a quadratic non-residue and `c0` and `c1` are Fp elements the corresponding byte encoding will be `encode(c0) || encode(c1)` where `||` means byte concatenation (or one can use `bytes32[4]` or `uint256[4]` in terms of Solidity types). + +*Note on the top `16` bytes being zero*: it is required that an encoded element is "in a field", which means strictly `< modulus`. In BigEndian encoding it automatically means that for a modulus that is just `381` bit long the top `16` bytes in `64` bytes encoding are zeroes and this **must** be checked even if only a subslice of input data is used for actual decoding. + +On inputs that can not be a valid encodings of field elements the precompile *must* return an error. + +#### Encoding of points in G1/G2: + +Points of G1 and G2 are encoded as byte concatenation of the respective encodings of the `x` and `y` coordinates. Total encoding length for a G1 point is thus `128` bytes and for a G2 point is `256` bytes. + +#### Point of infinity encoding: + +Also referred to as the "zero point". For BLS12 curves, the point with coordinates `(0, 0)` (zeroes in Fp or Fp2) is *not* on the curve, so a sequence of `128` resp. `256` zero bytes, which naively would decode as `(0, 0)` is instead used by convention to encode the point of infinity of G1 resp. G2. + +#### Encoding of scalars for multiplication operation: + +A scalar for the multiplication operation is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. The corresponding integer is **not** required to be less than or equal to main subgroup order `q`. + +#### Behavior on empty inputs: + +Certain operations have variable length input, such as MSMs (takes a list of pairs `(point, scalar)`), or pairing (takes a list of `(G1, G2)` points). While their behavior is well-defined (from an arithmetic perspective) on empty inputs, this EIP discourages such use cases and variable input length operations must return an error if the input is empty. + +### ABI for operations + +#### ABI for G1 addition + +G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). Output is an encoding of addition operation result - single G1 point (`128` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point +- Input has invalid length + +Note: + +There is no subgroup check for the G1 addition precompile. + +#### ABI for G1 MSM + +G1 MSM call expects `160*k` (`k` being a **positive** integer) bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of a G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of MSM operation result - a single G1 point (`128` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point +- An input is on the G1 elliptic curve but not in the correct subgroup +- Input has invalid length + +#### ABI for G2 addition + +G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). Output is an encoding of addition operation result - a single G2 point (`256` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point +- Input has invalid length + +Note: + +There is no subgroup check for the G2 addition precompile. + +#### ABI for G2 MSM + +G2 MSM call expects `288*k` (`k` being a **positive** integer) bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of MSM operation result - a single G2 point (`256` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point +- An input is on the G2 elliptic curve but not in the correct subgroup +- Input has invalid length + +#### ABI for pairing check + +Pairing check call expects `384*k` (`k` being a **positive** integer) bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: + +- `128` bytes of G1 point encoding +- `256` bytes of G2 point encoding + +Each point is expected to be in the subgroup of order `q`. + +It checks the equation `e(P1, Q1) * e(P2, Q2) * ... * e(Pk, Qk) == 1` in the pairing target field where `e` is the pairing operation. Output is `32` bytes where first `31` bytes are equal to `0x00` and the last byte is either `0x00` (false) or `0x01` (true). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on its respective elliptic curve nor the infinity point +- An input is on its respective elliptic curve but not in the correct subgroup +- Input has invalid length + +#### ABI for mapping Fp element to G1 point + +Field-to-curve call expects `64` bytes as an input that is interpreted as an element of Fp. Output of this call is `128` bytes and is an encoded G1 point. + +Error cases: + +- Input has invalid length +- Input is not correctly encoded + +#### ABI for mapping Fp2 element to G2 point + +Field-to-curve call expects `128` bytes as an input that is interpreted as an element of Fp2. Output of this call is `256` bytes and is an encoded G2 point. + +Error cases: + +- Input has invalid length +- Input is not correctly encoded + +### Gas burning on error + +Following the current state of all other precompiles, if a call to one of the precompiles in this EIP results in an error then all the gas supplied along with a `CALL` or `STATICCALL` is burned. + +### DDoS protection + +A sane implementation of this EIP *should not* contain potential infinite loops (it is possible and not even hard to implement all the functionality without `while` loops) and the gas schedule accurately reflects the time spent on computations of the corresponding function (precompiles pricing reflects an amount of gas consumed in the worst case where such a case exists). + +### Gas schedule + +Assuming `EcRecover` precompile as a baseline. + +#### G1 addition + +`375` gas + +#### G1 multiplication + +`12000` gas + +#### G2 addition + +`600` gas + +#### G2 multiplication + +`22500` gas + +#### G1/G2 MSM + +MSMs are expected to be performed by Pippenger's algorithm (we can also say that it **must** be performed by Pippenger's algorithm to have a speedup that results in a discount over naive implementation by multiplying each pair separately and adding the results). For this case there was a table prepared for discount in case of `k <= 128` points in the MSM with a discount cap `max_discount` for `k > 128`. + +The call cost is calculated as `(k * multiplication_cost * discount) // multiplier` where `multiplier = 1000`, `k` is a number of (scalar, point) pairs for the call, `multiplication_cost` is a corresponding G1/G2 multiplication cost presented above and `//` is an integer division. + +G1 and G2 are priced separately, each having their own discount table and `max_discount`. + +##### G1 discounts + +Discounts table for G1 MSM as a vector of pairs `[k, discount]`: + +``` +[[1, 1000], [2, 949], [3, 848], [4, 797], [5, 764], [6, 750], [7, 738], [8, 728], [9, 719], [10, 712], [11, 705], [12, 698], [13, 692], [14, 687], [15, 682], [16, 677], [17, 673], [18, 669], [19, 665], [20, 661], [21, 658], [22, 654], [23, 651], [24, 648], [25, 645], [26, 642], [27, 640], [28, 637], [29, 635], [30, 632], [31, 630], [32, 627], [33, 625], [34, 623], [35, 621], [36, 619], [37, 617], [38, 615], [39, 613], [40, 611], [41, 609], [42, 608], [43, 606], [44, 604], [45, 603], [46, 601], [47, 599], [48, 598], [49, 596], [50, 595], [51, 593], [52, 592], [53, 591], [54, 589], [55, 588], [56, 586], [57, 585], [58, 584], [59, 582], [60, 581], [61, 580], [62, 579], [63, 577], [64, 576], [65, 575], [66, 574], [67, 573], [68, 572], [69, 570], [70, 569], [71, 568], [72, 567], [73, 566], [74, 565], [75, 564], [76, 563], [77, 562], [78, 561], [79, 560], [80, 559], [81, 558], [82, 557], [83, 556], [84, 555], [85, 554], [86, 553], [87, 552], [88, 551], [89, 550], [90, 549], [91, 548], [92, 547], [93, 547], [94, 546], [95, 545], [96, 544], [97, 543], [98, 542], [99, 541], [100, 540], [101, 540], [102, 539], [103, 538], [104, 537], [105, 536], [106, 536], [107, 535], [108, 534], [109, 533], [110, 532], [111, 532], [112, 531], [113, 530], [114, 529], [115, 528], [116, 528], [117, 527], [118, 526], [119, 525], [120, 525], [121, 524], [122, 523], [123, 522], [124, 522], [125, 521], [126, 520], [127, 520], [128, 519]] +``` + +`max_discount = 519` + +##### G2 discounts + +Discounts table for G2 MSM as a vector of pairs `[k, discount]`: + +``` +[[1, 1000], [2, 1000], [3, 923], [4, 884], [5, 855], [6, 832], [7, 812], [8, 796], [9, 782], [10, 770], [11, 759], [12, 749], [13, 740], [14, 732], [15, 724], [16, 717], [17, 711], [18, 704], [19, 699], [20, 693], [21, 688], [22, 683], [23, 679], [24, 674], [25, 670], [26, 666], [27, 663], [28, 659], [29, 655], [30, 652], [31, 649], [32, 646], [33, 643], [34, 640], [35, 637], [36, 634], [37, 632], [38, 629], [39, 627], [40, 624], [41, 622], [42, 620], [43, 618], [44, 615], [45, 613], [46, 611], [47, 609], [48, 607], [49, 606], [50, 604], [51, 602], [52, 600], [53, 598], [54, 597], [55, 595], [56, 593], [57, 592], [58, 590], [59, 589], [60, 587], [61, 586], [62, 584], [63, 583], [64, 582], [65, 580], [66, 579], [67, 578], [68, 576], [69, 575], [70, 574], [71, 573], [72, 571], [73, 570], [74, 569], [75, 568], [76, 567], [77, 566], [78, 565], [79, 563], [80, 562], [81, 561], [82, 560], [83, 559], [84, 558], [85, 557], [86, 556], [87, 555], [88, 554], [89, 553], [90, 552], [91, 552], [92, 551], [93, 550], [94, 549], [95, 548], [96, 547], [97, 546], [98, 545], [99, 545], [100, 544], [101, 543], [102, 542], [103, 541], [104, 541], [105, 540], [106, 539], [107, 538], [108, 537], [109, 537], [110, 536], [111, 535], [112, 535], [113, 534], [114, 533], [115, 532], [116, 532], [117, 531], [118, 530], [119, 530], [120, 529], [121, 528], [122, 528], [123, 527], [124, 526], [125, 526], [126, 525], [127, 524], [128, 524]] +``` + +`max_discount = 524` + +#### Pairing check operation + +The cost of the pairing check operation is `32600*k + 37700` where `k` is a number of pairs. + +#### Fp-to-G1 mapping operation + +Fp -> G1 mapping is `5500` gas. + +#### Fp2-to-G2 mapping operation + +Fp2 -> G2 mapping is `23800` gas + +#### Gas schedule clarifications for the variable-length input + +For MSM and pairing functions, the gas cost depends on the input length. The current state of how the gas schedule is implemented in major clients (at the time of writing) is that the gas cost function does *not* perform any validation of the length of the input and never returns an error. So we present a list of rules how the gas cost functions **must** be implemented to ensure consistency between clients and safety. + +##### Gas schedule clarifications for G1/G2 MSM + +Define a constant `LEN_PER_PAIR` that is equal to `160` for G1 operation and to `288` for G2 operation. Define a function `discount(k)` following the rules in the corresponding section, where `k` is number of pairs. + +The following pseudofunction reflects how gas should be calculated: + +``` +k = floor(len(input) / LEN_PER_PAIR); +if k == 0 { + return 0; +} +gas_cost = k * multiplication_cost * discount(k) // multiplier; +return gas_cost; +``` + +We use floor division to get the number of pairs. If the length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on the precompile will return an error. Also, the case when `k = 0` is safe: `CALL` or `STATICCALL` cost is non-zero, and the case with formal zero gas cost is already used in `Blake2f` precompile. In any case, the main precompile routine **must** produce an error on such an input because it violated encoding rules. + +##### Gas schedule clarifications for pairing + +Define a constant `LEN_PER_PAIR = 384`; + +The following pseudofunction reflects how gas should be calculated: + +``` +k = floor(len(input) / LEN_PER_PAIR); +gas_cost = 32600*k + 37700; +return gas_cost; +``` + +We use floor division to get the number of pairs. If the length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on the precompile will return an error (the precompile routine **must** produce an error on such an input because it violated encoding rules). + +## Rationale + +The motivation section covers a total motivation to have operations over the BLS12-381 curves available. We also extend a rationale for more specific fine points. + +### MSM as a separate call + +Explicit separate MSM operation that allows one to save execution time (so gas) by both the algorithm used (namely Pippenger's algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negligible overhead if e.g. for MSM of `100` points would have to call the multiplication precompile `100` times and addition for `99` times (roughly `138600` would be saved). + +### No dedicated MUL call + +Dedicated MUL precompiles which perform single G1/G2 point by scalar multiplication have exactly the same ABI as MSM with `k == 1`. +MSM has to inspect the input length to reject inputs of invalid lengths. Therefore, it should recognize the case of `k == 1` and invoke the underlying implementation of single point multiplication to avoid the overhead of more complex multi-scalar multiplication algorithm. + +## Backwards Compatibility + +There are no backward compatibility questions. + +### Subgroup checks + +MSMs and pairings MUST perform a subgroup check. +Implementations SHOULD use the optimized subgroup check method detailed in a dedicated [document](../assets/eip-2537/fast_subgroup_checks.md). +On any input that fails the subgroup check, the precompile MUST return an error. +As endomorphism acceleration requires input on the correct subgroup, implementers MAY use endomorphism acceleration. + +### Field to curve mapping + +The algorithms and set of parameters for SWU mapping method are provided by a separate [document](../assets/eip-2537/field_to_curve.md) + +## Test Cases + +Due to the large test parameters space, we first provide properties that various operations must satisfy. We use additive notation for point operations, capital letters (`P`, `Q`) for points, small letters (`a`, `b`) for scalars. The generator for G1 is labeled as `G`, the generator for G2 is labeled as `H`, otherwise we assume random points on a curve in a correct subgroup. `0` means either scalar zero or point at infinity. `1` means either scalar one or multiplicative identity. `group_order` is the main subgroup order. `e(P, Q)` means pairing operation where `P` is in G1, `Q` is in G2. + +Required properties for basic ops (add/multiply): + +- Commutativity: `P + Q = Q + P` +- Identity element: `P + 0 = P` +- Additive negation: `P + (-P) = 0` +- Doubling `P + P = 2*P` +- Subgroup check: `group_order * P = 0` +- Trivial multiplication check: `1 * P = P` +- Multiplication by zero: `0 * P = 0` +- Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` + +Required properties for pairing operation: + +- Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` +- Non-degeneracy `e(P, Q) != 1` +- `e(P, 0*Q) = e(0*P, Q) = 1` +- `e(P, -Q) = e(-P, Q)` + +Test vectors can be found [in the test vectors files](../assets/eip-2537/test-vectors.md). + +### Benchmarking test cases + +A set of test vectors for quick benchmarking on new implementations is located in a separate [file](../assets/eip-2537/bench_vectors.md) + +## Reference Implementation + +There are two fully spec compatible implementations on the day of writing: + +- One in Rust language that is based on the [EIP-196](./eip-196.md) code and integrated with OpenEthereum for this library +- One implemented specifically for Geth as a part of the current codebase + +## Security Considerations + +Strictly following the spec will eliminate security implications or consensus implications in a contrast to the previous BN254 precompile. + +Important topic is a "constant time" property for performed operations. We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2539.md b/EIPS/eip-2539.md new file mode 100644 index 00000000000000..3afec1c7d612a0 --- /dev/null +++ b/EIPS/eip-2539.md @@ -0,0 +1,299 @@ +--- +eip: 2539 +title: BLS12-377 curve operations +description: Precompiles for BLS12-377 curve operations +author: Alex Vlasov (@shamatar), hujw77 (@hujw77) +discussions-to: https://ethereum-magicians.org/t/eip-2539-bls12-377-precompile-discussion-thread/4659 +status: Stagnant +type: Standards Track +category: Core +created: 2020-02-26 +requires: 1109, 2046 +--- + +## Abstract + +This precompile adds operation on BLS12-377 curve (from Zexe paper) as a precompile in a set necessary to *efficiently* perform operations such as BLS signature verification and perform SNARKs verifications. Unique properties of BLS12-377 also later allow to have SNARKs that check BLS12-377 pairing in an efficient way and allow e.g. constant-size BLS signature aggregation. + +If `block.number >= X` we introduce *nine* separate precompiles to perform the following operations: + +- BLS12_377_G1ADD - to perform point addition on a curve defined over prime field +- BLS12_377_G1MUL - to perform point multiplication on a curve defined over prime field +- BLS12_377_G1MULTIEXP - to perform multiexponentiation on a curve defined over prime field +- BLS12_377_G2ADD - to perform point addition on a curve twist defined over quadratic extension of the base field +- BLS12_377_G2MUL - to perform point multiplication on a curve twist defined over quadratic extension of the base field +- BLS12_377_G2MULTIEXP - to perform multiexponentiation on a curve twist defined over quadratic extension of the base field +- BLS12_377_PAIRING - to perform a pairing operations between a set of *pairs* of (G1, G2) points +- BLS12_377_MAP_FP_TO_G1 - maps base field element into the G1 point +- BLS12_377_MAP_FP2_TO_G2 - maps extension field element into the G2 point + +Multiexponentiation operation is included to efficiently aggregate public keys or individual signer's signatures during BLS signature verification. + +### Proposed addresses table + +| Precompile | Address | +| ----------------------- | ------- | +| BLS12_377_G1ADD | 0x15 | +| BLS12_377_G1MUL | 0x16 | +| BLS12_377_G1MULTIEXP | 0x17 | +| BLS12_377_G2ADD | 0x18 | +| BLS12_377_G2MUL | 0x19 | +| BLS12_377_G2MULTIEXP | 0x1a | +| BLS12_377_PAIRING | 0x1b | +| BLS12_377_MAP_FP_TO_G1 | 0x1c | +| BLS12_377_MAP_FP2_TO_G2 | 0x1d | + +## Motivation + +Motivation of this precompile is to add a cryptographic primitive that allows to get 120+ bits of security for operations over pairing friendly curve compared to the existing BN254 precompile that only provides 80 bits of security. In addition it allows efficient one-time recursive proof aggregations, e.g. proofs about existence of BLS12-377 based signature. + +## Specification + +Curve parameters: + +BLS12-377 curve is fully defined by the following set of parameters (coefficient `A=0` for all BLS12 curves): + +``` +Base field modulus = 0x01ae3a4617c510eac63b05c06ca1493b1a22d9f300f5138f1ef3622fba094800170b5d44300000008508c00000000001 +B coefficient = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +Main subgroup order = 0x12ab655e9a2ca55660b44d1e5c37b00159aa76fed00000010a11800000000001 +Extension tower: +Fp2 construction: +Fp quadratic non-residue = 0x01ae3a4617c510eac63b05c06ca1493b1a22d9f300f5138f1ef3622fba094800170b5d44300000008508bffffffffffc +Fp6/Fp12 construction: +Fp2 cubic non-residue c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 +Fp2 cubic non-residue c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +Twist parameters: +Twist type: D +B coefficient for twist c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 +B coefficient for twist c1 = 0x010222f6db0fd6f343bd03737460c589dc7b4f91cd5fd889129207b63c6bf8000dd39e5c1ccccccd1c9ed9999999999a +Generators: +G1: +X = 0x008848defe740a67c8fc6225bf87ff5485951e2caa9d41bb188282c8bd37cb5cd5481512ffcd394eeab9b16eb21be9ef +Y = 0x01914a69c5102eff1f674f5d30afeec4bd7fb348ca3e52d96d182ad44fb82305c2fe3d3634a9591afd82de55559c8ea6 +G2: +X c0 = 0x018480be71c785fec89630a2a3841d01c565f071203e50317ea501f557db6b9b71889f52bb53540274e3e48f7c005196 +X c1 = 0x00ea6040e700403170dc5a51b1b140d5532777ee6651cecbe7223ece0799c9de5cf89984bff76fe6b26bfefa6ea16afe +Y c0 = 0x00690d665d446f7bd960736bcbb2efb4de03ed7274b49a58e458c282f832d204f2cf88886d8c7c2ef094094409fd4ddf +Y c1 = 0x00f8169fd28355189e549da3151a70aa61ef11ac3d591bf12463b01acee304c24279b83f5e52270bd9a1cdd185eb8f93 +Pairing parameters: +|x| (miller loop scalar) = 0x8508c00000000001 +x is negative = false +``` + +### Fine points and encoding of base elements + +#### Field elements encoding: + +To encode points involved in the operation one has to encode elements of the base field and the extension field. + +Base field element (Fp) is encoded as `64` bytes by performing BigEndian encoding of the corresponding (unsigned) integer (top `16` bytes are always zeroes). `64` bytes are chosen to have `32` byte aligned ABI (representable as e.g. `bytes32[2]` or `uint256[2]`). Corresponding integer **must** be less than field modulus. + +For elements of the quadratic extension field (Fp2) encoding is byte concatenation of individual encoding of the coefficients totaling in `128` bytes for a total encoding. For an Fp2 element in a form `el = c0 + c1 * v` where `v` is formal quadratic non-residue and `c0` and `c1` are Fp elements the corresponding byte encoding will be `encode(c0) || encode(c1)` where `||` means byte concatenation (or one can use `bytes32[4]` or `uint256[4]` in terms of Solidity types). + +If encodings do not follow this spec anywhere during parsing in the precompile the precompile *must* return an error. + +#### Encoding of points in G1/G2: + +Points in either G1 (in base field) or in G2 (in extension field) are encoded as byte concatenation of encodings of the `x` and `y` affine coordinates. Total encoding length for G1 point is thus `128` bytes and for G2 point is `256` bytes. + +#### Point of infinity encoding: + +Also referred as "zero point". For BLS12 curves point with coordinates `(0, 0)` (formal zeroes in Fp or Fp2) is *not* on the curve, so encoding of such point `(0, 0)` is used as a convention to encode point of infinity. + +#### Encoding of scalars for multiplication operation: + +Scalar for multiplication operation is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. Corresponding integer is **not** required to be less than or equal than main subgroup size. + +### ABI for operations + +#### ABI for G1 addition + +G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). Output is an encoding of addition operation result - single G1 point (`128` bytes). + +Error cases: + - Either of points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for G1 multiplication + +G1 multiplication call expects `160` bytes as an input that is interpreted as byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiplication operation result - single G1 point (`128` bytes). + +Error cases: + - Point being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for G1 multiexponentiation + +G1 multiexponentiation call expects `160*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes). + +Error cases: + - Any of G1 points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for G2 addition + +G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). Output is an encoding of addition operation result - single G2 point (`256` bytes). + +Error cases: + - Either of points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for G2 multiplication + +G2 multiplication call expects `288` bytes as an input that is interpreted as byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiplication operation result - single G2 point (`256` bytes). + +Error cases: + - Point being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for G2 multiexponentiation + +G2 multiexponentiation call expects `288*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes). + +Error cases: + - Any of G2 points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for pairing + +Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: + - `128` bytes of G1 point encoding + - `256` bytes of G2 point encoding + +Output is a `32` bytes where first `31` bytes are equal to `0x00` and the last byte is `0x01` if pairing result is equal to multiplicative identity in a pairing target field and `0x00` otherwise. + +Error cases: + - Invalid encoding of any boolean variable must result in error + - Any of G1 or G2 points being not on the curve must result in error + - Any of G1 or G2 points are not in the correct subgroup + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for mapping Fp element to G1 point + +Field-to-curve call expects `64` bytes as input that is interpreted as an element of the base field. Output of this call is `128` bytes and is G1 point following respective encoding rules. + +Error cases: + - Input has invalid length + - Input is not a valid field element + +#### ABI for mapping Fp2 element to G2 point + +Field-to-curve call expects `128` bytes as input that is interpreted as an element of the quadratic extension field. Output of this call is `256` bytes and is G2 point following respective encoding rules. + +Error cases: + - Input has invalid length + - Input is not a valid field element + +### Prevention of DDoS on error handling + +This precompile performs extensive computations and in case of any errors during execution it MUST consume all gas from the gas schedule for the corresponding operation. + +### Gas schedule + +Assuming a constant `30 MGas/second` following prices are suggested. + +#### G1 addition + +`600` gas + +#### G1 multiplication + +`12000` gas + +#### G2 addition + +`4500` gas + +#### G2 multiplication + +`55000` gas + +#### G1/G2 Multiexponentiation + +Multiexponentiations are expected to be performed by the Peppinger algorithm (we can also say that it **must** be performed by Peppinger algorithm to have a speedup that results in a discount over naive implementation by multiplying each pair separately and adding the results). For this case there was a table prepared for discount in case of `k <= 128` points in the multiexponentiation with a discount cap `max_discount` for `k > 128`. + +To avoid non-integer arithmetic call cost is calculated as `k * multiplication_cost * discount / multiplier` where `multiplier = 1000`, `k` is a number of (scalar, point) pairs for the call, `multiplication_cost` is a corresponding single multiplication call cost for G1/G2. + +Discounts table as a vector of pairs `[k, discount]`: + +``` +[[1, 1200], [2, 888], [3, 764], [4, 641], [5, 594], [6, 547], [7, 500], [8, 453], [9, 438], [10, 423], [11, 408], [12, 394], [13, 379], [14, 364], [15, 349], [16, 334], [17, 330], [18, 326], [19, 322], [20, 318], [21, 314], [22, 310], [23, 306], [24, 302], [25, 298], [26, 294], [27, 289], [28, 285], [29, 281], [30, 277], [31, 273], [32, 269], [33, 268], [34, 266], [35, 265], [36, 263], [37, 262], [38, 260], [39, 259], [40, 257], [41, 256], [42, 254], [43, 253], [44, 251], [45, 250], [46, 248], [47, 247], [48, 245], [49, 244], [50, 242], [51, 241], [52, 239], [53, 238], [54, 236], [55, 235], [56, 233], [57, 232], [58, 231], [59, 229], [60, 228], [61, 226], [62, 225], [63, 223], [64, 222], [65, 221], [66, 220], [67, 219], [68, 219], [69, 218], [70, 217], [71, 216], [72, 216], [73, 215], [74, 214], [75, 213], [76, 213], [77, 212], [78, 211], [79, 211], [80, 210], [81, 209], [82, 208], [83, 208], [84, 207], [85, 206], [86, 205], [87, 205], [88, 204], [89, 203], [90, 202], [91, 202], [92, 201], [93, 200], [94, 199], [95, 199], [96, 198], [97, 197], [98, 196], [99, 196], [100, 195], [101, 194], [102, 193], [103, 193], [104, 192], [105, 191], [106, 191], [107, 190], [108, 189], [109, 188], [110, 188], [111, 187], [112, 186], [113, 185], [114, 185], [115, 184], [116, 183], [117, 182], [118, 182], [119, 181], [120, 180], [121, 179], [122, 179], [123, 178], [124, 177], [125, 176], [126, 176], [127, 175], [128, 174]] +``` + +`max_discount = 174` + +#### Pairing operation + +Cost of the pairing operation is `55000*k + 65000` where `k` is a number of pairs. + +#### Fp-to-G1 mapping operation + +Fp -> G1 mapping is `5500` gas. + +#### Fp2-to-G2 mapping operation + +Fp2 -> G2 mapping is `75000` gas + +## Rationale + +Motivation section covers a total motivation to have operations over BLS12-377 curve available. We also extend a rationale for move specific fine points. + +### Multiexponentiation as a separate call + +Explicit separate multiexponentiation operation that allows one to save execution time (so gas) by both the algorithm used (namely Peppinger algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negigible overhead if e.g. for multiexponentiation of `100` points would have to call the multipication precompile `100` times and addition for `99` times (roughly `138600` would be saved). + +## Backwards Compatibility + +There are no backward compatibility questions. + +### Important notes + +#### Subgroup checks + +Subgroup check **is mandatory** during the pairing call. Implementations *should* use fast subgroup checks: at the time of writing multiplication gas cost is based on `double-and-add` multiplication method that has a clear "worst case" (all bits are equal to one). For pairing operation it's expected that implementation uses faster subgroup check, e.g. by using wNAF multiplication method for elliptic curves that is ~ `40%` cheaper with windows size equal to 4. (Tested empirically. Savings are due to lower hamming weight of the group order and even lower hamming weight for wNAF. Concretely, subgroup check for both G1 and G2 points in a pair are around `35000` combined). + +## Test Cases + +Due to the large test parameters space we first provide properties that various operations must satisfy. We use additive notation for point operations, capital letters (`P`, `Q`) for points, small letters (`a`, `b`) for scalars. Generator for G1 is labeled as `G`, generator for G2 is labeled as `H`, otherwise we assume random point on a curve in a correct subgroup. `0` means either scalar zero or point of infinity. `1` means either scalar one or multiplicative identity. `group_order` is a main subgroup order. `e(P, Q)` means pairing operation where `P` is in G1, `Q` is in G2. + +Requeired properties for basic ops (add/multiply): + - Commutativity: `P + Q = Q + P` + - Additive negation: `P + (-P) = 0` + - Doubling `P + P = 2*P` + - Subgroup check: `group_order * P = 0` + - Trivial multiplication check: `1 * P = P` + - Multiplication by zero: `0 * P = 0` + - Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` + +Required properties for pairing operation: + - Degeneracy `e(P, 0*Q) = e(0*P, Q) = 1` + - Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` (internal test, not visible through ABI) + +Test vector for all operations are expanded in this `csv` files in matter-labs' 1962 proposol. + +## Reference Implementation + +There is a various choice of existing implementations of the curve operations. It may require extra work to add an ABI: + - Code bases with fixed parameters + - Rust: matter-labs + - C++: matter-labs + - Original implementation linked in Zexe paper in Rust: github.com/scipr-lab/zexe + - Standalone in Go: github.com/kilic/bls12-377 + +## Security Considerations + +Strictly following the spec will eliminate security implications or consensus implications in a contrast to the previous BN254 precompile. + +Important topic is a "constant time" property for performed operations. We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2542.md b/EIPS/eip-2542.md new file mode 100644 index 00000000000000..5580dca0503dba --- /dev/null +++ b/EIPS/eip-2542.md @@ -0,0 +1,87 @@ +--- +eip: 2542 +title: New opcodes TXGASLIMIT and CALLGASLIMIT +author: Alex Forshtat +discussions-to: https://ethereum-magicians.org/t/eip-2542-add-txgaslimit-callgaslimit-txgasrefund-opcodes +status: Stagnant +type: Standards Track +category: Core +created: 2020-02-29 +--- + +## Simple Summary +A mechanism to allow smart contracts to access information on gas limits for the current transaction and execution frame. + +## Abstract +Currently, there is an existing opcode `0x45 GASLIMIT` that provides access to the block gas limit. While this information may be useful in some cases, it is probably not a value that smart contract developers may be concerned about. The opcode `0x5a GAS` provides the remaining gas, not the initial one. Also, it is worth noting how existing `0x32 ORIGIN`, `0x33 CALLER`, `0x34 CALLVALUE` and `0x3a GASPRICE` opcodes set a pattern of having access to both the transaction and current execution frame state. +TBD: as 0x30 opcode range is exhausted, the proposed opcodes can be added to 0x50 range, or a new range can be added. + +## Motivation +As concepts of relaying, meta-transactions, gas fees, and account abstraction gain popularity, it becomes critical for some contracts to be able to track gas expenditure with absolute precision. Without access to this data on an EVM level, such contracts resort to approximation, mimicking EVM logic on-chain, and some use-cases even become infeasible. + +## Specification +If block.number >= TBD, add three new opcodes: + +TXGASLIMIT: 0x5c + +Pushes the gas limit of the entire transaction onto the stack. This is a value of the 'startgas' parameter signed by the externally owned account. +Gas costs: 2 (same as `GASLIMIT`) + +CALLGASLIMIT: 0x5d + +Pushes the gas limit of the current execution frame onto the stack. This is the 'callGas' value that was obtained after the application of the EIP-150 “all but one 64th” rule. +Gas costs: 2 (same as `GASLIMIT`) + +Also, consider renaming `0x45 GASLIMIT` to `BLOCKGASLIMIT` to avoid confusion. + +## Rationale +Consider a solidity smart contract that wants to know how much gas the entire transaction or a part of it had consumed. It is not entirely possible with the current EVM. With proposed changes, using a pseudo-Solidity syntax, this information would be easily available: +``` +function keepTrackOfGas(string memory message, uint256 number) public { + ... + uint gasUsed = msg.gasLimit - gasleft(); +} +``` +This is an extremely common use case, and multiple implementations suffer from not taking the non-accessible expenses into consideration. The state-of-the-art solution for the `gasUsed` problem is to access 'gasleft()' as the first line of your smart contract. +Note how variable transaction input size means the gas used by the transaction depends on the number of zero and non-zero bytes of input, as well `GTXDATANONZERO`. Another issue is that Solidity handles `public` methods by loading the entire input from `calldata` to `memory`, spending an unpredictable amount of gas. + +Another application is for a method to have a requirement for a gas limit given to it. This situation arises quite commonly in the context of meta-transactions, where the msg.sender's account holder may not be too interested in the inner transaction's success. Exaggerated pseudocode: + +``` +function verifyGasLimit(uint256 desiredGasLimit, bytes memory signature, address signer, bytes memory someOtherData) public { + require(ecrecover(abi.encodePacked(desiredGasLimit, someOtherData), signature) == signer, "Signature does not match"); + require(tx.gasLimit == desiredGasLimit, "Transaction limit does not match the signed value. The signer did not authorize that."); + ... +} +``` +In this situation it is not possible to rely on 'gasleft()' value, because it is dynamic, depends on opcode and calldata pricing, and cannot be signed. + + +## Backwards Compatibility +This proposal introduces two new opcodes and renames an existing one, but stays fully backwards compatible apart from that. + +## Forwards Compatibility +A major consideration for this proposal is its alignment with one or many possible future modifications to the EVM: + +1. EIP-2489 Deprecate the GAS opcode (a.k.a. 39-UNGAS proposal) + There is a sentiment that the ability of smart contracts to perform "gas introspection" leads to the contracts being dependent on current opcode pricing. + While criticizing said misconception is beyond the scope of this EIP, in case there is a need to make a breaking change to the behavior of the existing `0x5a GAS` opcode, the same considerations will apply to the proposed opcodes. This means this EIP does not add any new restraints on EMV evolution. + +2. Stateless Ethereum + The UNGAS proposal is said to be related to the ongoing project of Stateless Ethereum. It’s not strictly necessary for stateless Ethereum, but it is an idea for how to make future breaking changes to gas schedules easier. + As long as the concept of 'gas limit' is part of the EVM, the author sees no reason proposed opcodes would conflict with Stateless Ethereum. Gas schedules are not exposed by this proposal. + +3. Comparison with other controversial opcodes + There are opcodes that are not proposed for deprecation but face criticism. Examples include `0x32 ORIGIN` being misused by smart contract developers, or `0x46 CHAINID` making some smart-contracts 'unforkable'. + This EIP neither encourages nor enables any bad security practices, and does not introduce any concepts that are new for EVM either. + +## Security considerations + +Existing smart contracts are not affected by this change. +Smart contracts that will use proposed opcodes must not use them for the core of any security features, but only as a source of information about their execution environment. + +## Implementation +The implementations must be completed before any EIP is given status "Final", but it need not be completed before the EIP is accepted. While there is merit to the approach of reaching consensus on the specification and rationale before writing code, the principle of "rough consensus and running code" is still useful when it comes to resolving many discussions of API details. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2544.md b/EIPS/eip-2544.md new file mode 100644 index 00000000000000..98dbdbe943eb3d --- /dev/null +++ b/EIPS/eip-2544.md @@ -0,0 +1,7 @@ +--- +eip: 2544 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2544.md diff --git a/EIPS/eip-2565.md b/EIPS/eip-2565.md new file mode 100644 index 00000000000000..bfd83317efc59a --- /dev/null +++ b/EIPS/eip-2565.md @@ -0,0 +1,104 @@ +--- +eip: 2565 +title: ModExp Gas Cost +author: Kelly Olson (@ineffectualproperty), Sean Gulley (@sean-sn), Simon Peffers (@simonatsn), Justin Drake (@justindrake), Dankrad Feist (@dankrad) +discussions-to: https://ethereum-magicians.org/t/big-integer-modular-exponentiation-eip-198-gas-cost/4150 +status: Final +type: Standards Track +category: Core +created: 2020-03-20 +requires: 198 +--- + +## Simple Summary +Defines the gas cost of the `ModExp` (`0x00..05`) precompile. + +## Abstract +To accurately reflect the real world operational cost of the `ModExp` precompile, this EIP specifies an algorithm for calculating the gas cost. This algorithm approximates the multiplication complexity cost and multiplies that by an approximation of the iterations required to execute the exponentiation. + +## Motivation +Modular exponentiation is a foundational arithmetic operation for many cryptographic functions including signatures, VDFs, SNARKs, accumulators, and more. Unfortunately, the ModExp precompile is currently over-priced, making these operations inefficient and expensive. By reducing the cost of this precompile, these cryptographic functions become more practical, enabling improved security, stronger randomness (VDFs), and more. + +## Specification +As of `FORK_BLOCK_NUMBER`, the gas cost of calling the precompile at address `0x0000000000000000000000000000000000000005` will be calculated as follows: +``` +def calculate_multiplication_complexity(base_length, modulus_length): + max_length = max(base_length, modulus_length) + words = math.ceil(max_length / 8) + return words**2 + +def calculate_iteration_count(exponent_length, exponent): + iteration_count = 0 + if exponent_length <= 32 and exponent == 0: iteration_count = 0 + elif exponent_length <= 32: iteration_count = exponent.bit_length() - 1 + elif exponent_length > 32: iteration_count = (8 * (exponent_length - 32)) + ((exponent & (2**256 - 1)).bit_length() - 1) + return max(iteration_count, 1) + +def calculate_gas_cost(base_length, modulus_length, exponent_length, exponent): + multiplication_complexity = calculate_multiplication_complexity(base_length, modulus_length) + iteration_count = calculate_iteration_count(exponent_length, exponent) + return max(200, math.floor(multiplication_complexity * iteration_count / 3)) +``` + +## Rationale +After benchmarking the ModExp precompile, we discovered that it is ‘overpriced’ relative to other precompiles. We also discovered that the current gas pricing formula could be improved to better estimate the computational complexity of various ModExp input variables. The following changes improve the accuracy of the `ModExp` pricing: + +### 1. Modify ‘computational complexity’ formula to better reflect the computational complexity +The complexity function defined in [EIP-198](./eip-198.md) is as follow: + +``` +def mult_complexity(x): + if x <= 64: return x ** 2 + elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 + else: return x ** 2 // 16 + 480 * x - 199680 +``` +where is `x` is `max(length_of_MODULUS, length_of_BASE)` + +The complexity formula in [EIP-198](./eip-198.md) was meant to approximate the difficulty of Karatsuba multiplication. However, we found a better approximation for modelling modular exponentiation. In the complexity formula defined in this EIP, `x` is divided by 8 to account for the number of limbs in multiprecision arithmetic. A comparison of the current ‘complexity’ function and the proposed function against the execution time can be seen below: + +![Option 1 Graph](../assets/eip-2565/Complexity_Regression.png) + +The complexity function defined here has a better fit vs. the execution time when compared to the [EIP-198](./eip-198.md) complexity function. This better fit is because this complexity formula accounts for the use of binary exponentiation algorithms that are used by ‘bigint’ libraries for large exponents. You may also notice the regression line of the proposed complexity function bisects the test vector data points. This is because the run time varies depending on if the modulus is even or odd. + +### 2. Change the value of GQUADDIVISOR +After changing the 'computational complexity' formula in [EIP-198](./eip-198.md) to the one defined here it is necessary to change `QGUADDIVSOR` to bring the gas costs inline with their runtime. By setting the `QGUADDIVISOR` to `3` the cost of the ModExp precompile will have a higher cost (gas/second) than other precompiles such as ECRecover. + +![Option 2 Graph](../assets/eip-2565/GQuad_Change.png) + +### 3. Set a minimum gas cost to prevent abuse +This prevents the precompile from underpricing small input values. + +## Test Cases +There are no changes to the underlying interface or arithmetic algorithms, so the existing test vectors can be reused. Below is a table with the updated test vectors: + +| Test Case | EIP-198 Pricing | EIP-2565 Pricing | +| ------------- | ------------- | ------------- | +| modexp_nagydani_1_square | 204 | 200 | +| modexp_nagydani_1_qube | 204 | 200 | +| modexp_nagydani_1_pow0x10001 | 3276 | 341 | +| modexp_nagydani_2_square | 665 | 200 | +| modexp_nagydani_2_qube | 665 | 200 | +| modexp_nagydani_2_pow0x10001 | 10649 | 1365 | +| modexp_nagydani_3_square | 1894 | 341 | +| modexp_nagydani_3_qube | 1894 | 341 | +| modexp_nagydani_3_pow0x10001 | 30310 | 5461 | +| modexp_nagydani_4_square | 5580 | 1365 | +| modexp_nagydani_4_qube | 5580 | 1365 | +| modexp_nagydani_4_pow0x10001 | 89292 | 21845 | +| modexp_nagydani_5_square | 17868 | 5461 | +| modexp_nagydani_5_qube | 17868 | 5461 | +| modexp_nagydani_5_pow0x10001 | 285900 | 87381 | + +## Implementations +[Geth](https://github.com/ethereum/go-ethereum/pull/21607) + +[Python](https://gist.github.com/ineffectualproperty/60e34f15c31850c5b60c8cf3a28cd423) + +## Security Considerations +The biggest security consideration for this EIP is creating a potential DoS vector by making ModExp operations too inexpensive relative to their computation time. + +## References +[EIP-198](./eip-198.md) + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2566.md b/EIPS/eip-2566.md new file mode 100644 index 00000000000000..27ad65af53f3e1 --- /dev/null +++ b/EIPS/eip-2566.md @@ -0,0 +1,106 @@ +--- +eip: 2566 +title: Human Readable Parameters for Contract Function Execution +author: Joseph Stockermans (@jstoxrocky) +discussions-to: https://ethereum-magicians.org/t/human-readable-parameters-for-contract-function-execution/4154 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-03-23 +--- + +## Simple Summary +New Ethereum RPC method `eth_sendTransactionToContractFunction` that parallels `eth_sendTransaction` but allows for human-readable contract function execution data to be displayed to users. + +## Abstract +When a dapp prompts a user to execute a smart contract function via a ProviderWallet, confirmation screens displayed in the ProviderWallet layer cannot display the human readable details of the function to be called and the arguments to be passed. This is because the Ethereum RPC method used for contract function execution (`eth_sendTransaction`) accepts information about what function to call in a non-human readable (and non-recoverable) format. As such, when a ProviderWallet receives this non-human readable information from a dapp, they are unable to display a human readable version since they never received one and cannot recover one from the data. + +This creates a poor and potentially dangerous user experience. For example, a malicious dapp could swap out the `address` argument in a token contract's `transfer(address,uint256)` function and reroute the tokens intended for someone else to themselves. This sleight-of-hand would be quiet and unlikely to be picked up by a casual user glancing over the non-human readable data. By adding a new Ethereum RPC method (`eth_sendTransactionToContractFunction`) that accepts the function ABI, ProviderWallets can recreate and display the human readable details of contract function execution to users. + +## Motivation +### ProviderWallet Definition +ProviderWallets like Metamask and Geth are hybrid software that combine an Ethereum API provider with an Ethereum wallet. This allows them to sign transactions on behalf of their users and also broadcast those signed transactions to the Ethereum network. ProviderWallets are used for both convenience and for the protection they give users through human readable confirmation prompts. + +### Existing Solutions +Much discussion has been made in the past few years on the topic of human readable Ethereum transaction data. Aragon's [Radspec](https://github.com/aragon/radspec) addresses this issue by requiring contract developers to amend their contract functions with human readable comments. ProviderWallets can then use Aragon's Radspec software to parse these comments from the contract code and display them to the end user - substituting in argument values where necessary. Unfortunately, this approach cannot work with contracts that do not have Radspec comments (and may require integration with IPFS). + +[EIP 1138](https://github.com/ethereum/EIPs/issues/1138) also addresses this issue directly but contains serious security issues - allowing untrusted dapps to generate the human readable message displayed to users. In a similar train of thought, [Geth's #2940 PR](https://github.com/ethereum/go-ethereum/pull/2940) and [EIPs 191](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-191.md), [712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md) all highlight the Ethereum community's desire for ProviderWallets to better inform users about what data they are actually acting upon. + +Finally, the ProviderWallet Metamask already includes some built-in magic for interactions with ERC20 contracts that allows confirmation prompts to display the intended *token* recipient and *token* value. Although this is accomplished in an ad hoc fashion for ERC20-like contracts only, the motivation is the same: users deserve better information about the execution of contract functions they are relying on ProviderWallets to perform. + +### Background +At one point or another, a dapp will ask a user to interact with a contract. The interaction between dapps and contracts is a large part of the Ethereum ecosystem and is most commonly brokered by a ProviderWallet. When a dapp asks a user to interact with a contract, it will do so by sending the `eth_sendTransaction` method name to the Ethereum API exposed by a ProviderWallet along with the relevant transaction data. The `data` field of the transaction data contains the information necessary for the Ethereum virtual machine to identify and execute the contract's function. This field has a specific formatting that is both non-human readable and non-recoverable to its human readable state. + +The accepted format for `eth_sendTransaction`'s `data` field is the hexadecimal encoding of the first four bytes of the keccak256 digest of the function signature. This abbreviated hash is then concatenated with the ABI encoded arguments to the function. Since the keccak256 digest of the function signature cannot be converted back into the function signature, the `data` field is not only non-human readable, its non-recoverable as well. On top of this, additional insight into the concatenated argument values is further obfuscated as information about their data types are held in the function signature preimage. + +## Specification +This EIP proposes increasing the set of Ethereum RPC methods to include a new method - `eth_sendTransactionToContractFunction`. This method parallels `eth_sendTransaction` with the only difference being the inclusion of the contract function's `abi` field. + +Parameters + +1. `Object` - The transaction object + * `from`: `DATA`, 20 Bytes - The address the transaction is sent from. + * `to`: `DATA`, 20 Bytes - (optional when creating new contract) The address the transaction is directed to. + * `gas`: `QUANTITY` - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas. + * `gasPrice`: `QUANTITY` - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas + * `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction + * `data`: `DATA` - The hash of the invoked method signature and encoded parameters + * `abi`: `DATA` - The function ABI + * `nonce`: `QUANTITY` - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. + +Example Parameters +``` + params: [{ + "from": "0x69e6F1b01f34A702Ce63bA6EF83c64fAEC37a227", + "to": "0xe44127f6fA8A00ee0228730a630fc1F3162C4d52", + "gas": "0x76c0", // 30400 + "gasPrice": "0x9184e72a000", // 10000000000000 + "value": "0x9184e72a", // 2441406250 + "abi": "{ + "inputs": [{ + "name": "_address", + "type": "address" + }, { + "name": "_value", + "type": "uint256" + }], + "name": "transferTokens", + "outputs": [{ + "name": "success", + "type": "bool" + }], + "stateMutability": "nonpayable", + "type": "function" + }", + "data": "0xbec3fa170000000000000000000000006Aa89e52c9a826496A8f311c1a9db62fd477E256000000000000000000000000000000000000000000000000000000174876E800" + }] +``` + +Returns +DATA, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available. + +Example +// Request +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_sendTransactionToContractFunction","params":[{see above}],"id":1}' + +// Result +{ + "id":1, + "jsonrpc": "2.0", + "result": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" +} + +## Rationale +This EIP's proposed `eth_sendTransactionToContractFunction` method is intended to parallel `eth_sendTransaction` as much as possible since both methods result in the same behaviour when executing a contract function. The newly introduced `abi` field is an element of the contract's ABI that corresponds to the intended function. The `data` field is the same `data` field from `eth_sendTransaction`. The `abi` field can be combined with values parsed from the `data` field to recreate human readable contract function execution information. + +## Implementation +The `data` field in `eth_sendTransactionToContractFunction` is the same as that required for `eth_sendTransaction` allowing the transaction to be completed via the existing mechanisms used for `eth_sendTransaction`. The input argument values can be parsed from the `data` field and since we know their types from the `abi` field, the provider wallet can use this info to encode and display the values in an appropriate human readable format. Furthermore, the hashed and truncated function signature in the `data` field can be reconstructed using the information provided in the `abi` field providing an additional check to ensure that the supplied ABI matches the `data` field. + +## Backwards Compatibility +With backwards compatibility in mind, this EIP proposes augmenting the set of Ethereum RPC methods with an additional method instead of mutating the existing method. Precedent for adding a new RPC method comes from [EIP 712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md) in which adding the method `eth_signTypedData` is proposed for confirmation prompt security. As an alternate approach, the `eth_sendTransaction` method could be changed to accept an additional `abi` argument, but this would break all existing code attempting to execute a contract function. + +## Security Considerations +Displaying the contract address, function name, and argument values can provide additional security to users, but it is not a guarantee that a function will execute as the user expects. A poorly implemented contract can still name its function `transfer` and accept `address` and `uint256` arguments - but there is nothing short of contract examination that will let a user know that this contract is indeed a valid ERC20 contract. This EIP does not intend to solve the larger problem around trust in a contract's code, but instead intends to give users better tools to understand exactly what is contained within the data they are broadcasting to the Ethereum network. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2569.md b/EIPS/eip-2569.md new file mode 100644 index 00000000000000..280c82a66eeaa4 --- /dev/null +++ b/EIPS/eip-2569.md @@ -0,0 +1,7 @@ +--- +eip: 2569 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2569.md diff --git a/EIPS/eip-2583.md b/EIPS/eip-2583.md new file mode 100644 index 00000000000000..12689ee89f8e20 --- /dev/null +++ b/EIPS/eip-2583.md @@ -0,0 +1,294 @@ +--- +eip: 2583 +title: Penalty for account trie misses +author: Martin Holst Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/eip-2583-penalties-for-trie-misses/4190 +status: Stagnant +type: Standards Track +category: Core +created: 2020-02-21 +--- + + +## Simple Summary + +This EIP introduces a gas penalty for opcodes which access the account for trie non-existent accounts. + +## Abstract + +This EIP adds a gas penalty for accesses to the account trie, where the address being looked up does not exist. Non-existing accounts can be used in +DoS attacks, since they bypass cache mechanisms, thus creating a large discrepancy between 'normal' mode of execution and 'worst-case' execution of an opcode. + +## Motivation + +As the ethereum trie becomes more and more saturated, the number of disk lookups that a node is required to do in order to access a piece of state increases too. This means that checking e.g. `EXTCODEHASH` of an account at block `5` was _inherently_ a cheaper operation that it is at, say `8.5M`. + +From an implementation perspective, a node can (and does) use various caching mechanisms to cope with the problem, but there's an inherent problem with caches: when they yield a 'hit', they're great, but when they 'miss', they're useless. + +This is attackable. By forcing a node to lookup non-existent keys, an attacker can maximize the number of disk lookups. +Sidenote: even if the 'non-existence' is cached, it's trivial to use a new non-existent key the next time, and never hit the same non-existent key again. Thus, caching 'non-existence' might be dangerous, since it will evict 'good' entries. + +So far, the attempts to handle this problem has been in raising the gas cost, e.g. [EIP-150](./eip-150.md), [EIP-1884](./eip-1884.md). + +However, when determining gas-costs, a secondary problem that arises due to the large discrepancy between 'happy-path' and 'notorious path' -- how do we determine the pricing? + +- The 'happy-path', assuming all items are cached? + - Doing so would that would underprice all trie-accesses, and could be DoS-attacked. +- The 'normal' usage, based on benchmarks of actual usage? + - This is basically what we do now, but that means that intentionally notorious executions are underpriced -- which constitutes a DoS vulnerability. +- The 'paranoid' case: price everything as if caching did not exist? + - This would severely harm basically every contract due to the gas-cost increase. Also, if the gas limits were raised in order to allow the same amount of computation as before, the notorious case could again be used for DoS attacks. + +From an engineering point of view, a node implementor is left with few options: + +- Implement bloom filters for existence. This is difficult, not least because of the problems of reorgs, and the fact that it's difficult to undo bloom filter modifications. +- Implement flattened account databases. This is also difficult, both because of reorgs and also because it needs to be an _additional_ data structure aside from the `trie` -- we need the `trie` for consensus. So it's an extra data structure of around `15G` that needs to be kept in check. This is currently being pursued by the Geth-team. + +This EIP proposes a mechanism to alleviate the situation. + +## Specification + +We define the constant `penalty` as `TBD` (suggested `2000` gas). + +For opcodes which access the account trie, whenever the operation is invoked targeting an `address` which does not exist in the trie, then `penalty` gas is deducted from the available `gas`. + +### Detailed specification + +These are the opcodes which triggers lookup into the main account trie: + +| Opcode | Affected | Comment | +| ----- | ---------| ----------| +| BALANCE| Yes | `balance(nonexistent_addr)` would incur `penalty`| +| EXTCODEHASH| Yes | `extcodehash(nonexistent_addr)` would incur `penalty`| +| EXTCODECOPY| Yes | `extcodecopy(nonexistent_addr)` would incur `penalty`| +| EXTCODESIZE| Yes | `extcodesize(nonexistent_addr)` would incur `penalty`| +| CALL | Yes| See details below about call variants| +| CALLCODE | Yes| See details below about call variants| +| DELEGATECALL | Yes| See details below about call variants| +| STATICCALL | Yes| See details below about call variants| +| SELFDESTRUCT | No| See details below. | +| CREATE | No | Create destination not explicitly settable, and assumed to be nonexistent already.| +| CREATE2 | No | Create destination not explicitly settable, and assumed to be nonexistent already.| + + +### Notes on Call-derivatives + +A `CALL` triggers a lookup of the `CALL` destination address. The base cost for `CALL` is at `700` gas. A few other characteristics determine the actual gas cost of a call: + +1. If the `CALL` (or `CALLCODE`) transfers value, an additional `9K` is added as cost. + 1.1 If the `CALL` destination did not previously exist, an additional `25K` gas is added to the cost. + +This EIP adds a second rule in the following way: + +2. If the call does _not_ transfer value and the callee does _not_ exist, then `penalty` gas is added to the cost. + +In the table below, +- `value` means non-zero value transfer, +- `!value` means zero value transfer, +- `dest` means destination already exists, or is a `precompile` +- `!dest` means destination does not exist and is not a `precompile` + +| Op | value,dest| value, !dest |!value, dest| !value, !dest| +| -- | --------- | -- | --| -- | +|CALL | no change | no change| no change| `penalty`| +|CALLCODE | no change | no change| no change| `penalty`| +|DELEGATECALL | N/A | N/A| no change| `penalty` | +|STATICCALL | N/A | N/A| no change| `penalty` | + +Whether the rules of this EIP is to be applied for regular ether-sends in `transactions` is TBD. See the 'Backwards Compatibility'-section for some more discussion on that topic. + +### Note on `SELFDESTRUCT` + +The `SELFDESTRUCT` opcode also triggers an account trie lookup of the `beneficiary`. However, due to the following reasons, it has been omitted from having a `penalty` since it already costs `5K` gas. + +### Clarifications: + +- The `base` costs of any opcodes are not modified by the EIP. +- The opcode `SELFBALANCE` is not modified by this EIP, regardless of whether the `self` address exists or not. + + +## Rationale + +With this scheme, we could continue to price these operations based on the 'normal' usage, but gain protection from attacks that try to maximize disk lookups/cache misses. +This EIP does not modify anything regarding storage trie accesses, which might be relevant for a future EIP. However, there are a few crucial differences. + + +1. Storage tries are typically small, and there's a high cost to populate a storage trie with sufficient density for it to be in the same league as the account trie. +2. If an attacker wants to use an existing large storage trie, e.g. some popular token, he would typically have to make a `CALL` to cause a lookup in that token -- something like `token.balanceOf()`. + That adds quite a lot of extra gas-impediments, as each `CALL` is another `700` gas, plus gas for arguments to the `CALL`. + +### Determining the `penalty` + +A transaction with `10M` gas can today cause ~`14K` trie lookups. + +- A `penalty` of `1000`would lower the number to ~`5800` lookups, `41%` of the original. +- A `penalty` of `2000`would lower the number to ~`3700` lookups, `26%` of the original. +- A `penalty` of `3000`would lower the number to ~`2700` lookups, `20%` of the original. +- A `penalty` of `4000`would lower the number to ~`2100` lookups, `15%` of the original. + +There exists a roofing function for the `penalty`. Since the `penalty` is deducted from `gas`, that means that a malicious contract can always invoke a malicious relay to perform the trie lookup. Let's refer to this as the 'shielded relay' attack. + +In such a scenario, the `malicious` would spend `~750` gas each call to `relay`, and would need to provide the `relay` with at least `700` gas to do a trie access. + +Thus, the effective `cost` would be on the order of `1500`. It can thus be argued that `penalty` above `~800` would not achieve better protection against trie-miss attacks. + + +## Backwards Compatibility + +This EIP requires a hard-fork. + +### Ether transfers + +A regular `transaction` from one EOA to another, with value, is not affected. + +A `transaction` with `0` value, to a destination which does not exist, would be. This scenario is highly unlikely to matter, since such a `transaction` is useless -- even during success, all it would accomplish would be to spend some `gas`. With this EIP, it would potentially spend some more gas. + +### Layer 2 + +Regarding layer-2 backward compatibility, this EIP is a lot less disruptive than EIPs which modify the `base` cost of an opcode. For state accesses, there are +seldom legitimate scenarios where + +1. A contract checks `BALANCE`/`EXTCODEHASH`/`EXTCODECOPY`/`EXTCODESIZE` of another contract `b`, _and_, +2. If such `b` does not exist, continues the execution + +#### Solidity remote calls +Example: When a remote call is made in Solidity: +``` + recipient.invokeMethod(1) +``` + +- Solidity does a pre-flight `EXTCODESIZE` on `recipient`. +- If the pre-flight check returns `0`, then `revert(0,0)` is executed, to stop the execution. +- If the pre-flight check returns non-zero, then the execution continues and the `CALL` is made. + +With this EIP in place, the 'happy-path' would work as previously, and the 'notorious'-path where `recipient` does not exist would cost an extra `penalty` gas, but the actual execution-flow would be unchanged. + +#### ERC223 + +[ERC223 Token Standard](https://github.com/ethereum/EIPs/issues/223) is, at the time of writing, marked as 'Draft', but is deployed and in use on mainnet today. + +The ERC specifies that when a token `transfer(_to,...)` method is invoked, then: + +> This function must transfer tokens and invoke the function `tokenFallback (address, uint256, bytes)` in `_to`, if `_to` is a contract. +> ... +> NOTE: The recommended way to check whether the `_to` is a contract or an address is to assemble the code of `_to`. If there is no code in `_to`, then this is an externally owned address, otherwise it's a contract. + +The reference implementations from [Dexaran](https://github.com/Dexaran/ERC223-token-standard/tree/development/token/ERC223) and [OpenZeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/1bc923b6a222e79a90f20305a459b0ee779eb918/contracts/token/ERC721/ERC721.sol#L499) both implement the `isContract` check using an `EXTCODESIZE` invocation. + +This scenario _could_ be affected, but in practice should not be. Let's consider the possibilities: + +1. The `_to` is a contract: Then `ERC223` specifies that the function `tokenFallback(...)` is invoked. + - The gas expenditure for that call is at least`700` gas. + - In order for the `callee` to be able to perform any action, best practice it to ensure that it has at least `2300` gas along with the call. + - In summary: this path requires there to be least `3000` extra gas available (which is not due to any `penalty`) +2. The `_to` exists, but is no contract. The flow exits here, and is not affected by this EIP +2. The `_to` does not exist: A `penalty` is deducted. + +In summary, it would seem that `ERC223` should not be affected, as long as the `penalty` does not go above around `3000` gas. + + +### Other + +The contract [`Dentacoin`](https://etherscan.io/address/0x08d32b0da63e2c3bcf8019c9c5d849d7a9d791e6#code) would be affected. + +``` + function transfer(address _to, uint256 _value) returns (bool success) { + ... // omitted for brevity + if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { // Check if sender has enough and for overflows + balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract DCN from the sender + + if (msg.sender.balance >= minBalanceForAccounts && _to.balance >= minBalanceForAccounts) { // Check if sender can pay gas and if recipient could + balances[_to] = safeAdd(balances[_to], _value); // Add the same amount of DCN to the recipient + Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place + return true; + } else { + balances[this] = safeAdd(balances[this], DCNForGas); // Pay DCNForGas to the contract + balances[_to] = safeAdd(balances[_to], safeSub(_value, DCNForGas)); // Recipient balance -DCNForGas + Transfer(msg.sender, _to, safeSub(_value, DCNForGas)); // Notify anyone listening that this transfer took place + + if(msg.sender.balance < minBalanceForAccounts) { + if(!msg.sender.send(gasForDCN)) throw; // Send eth to sender + } + if(_to.balance < minBalanceForAccounts) { + if(!_to.send(gasForDCN)) throw; // Send eth to recipient + } + } + } else { throw; } + } +``` + +The contract checks `_to.balance >= minBalanceForAccounts`, and if the `balance` is too low, some `DCN` is converted to `ether` and sent to the `_to`. This is a mechanism to ease on-boarding, whereby a new user who has received some `DCN` can immediately create a transaction. + +Before this EIP: + +- When sending `DCN` to a non-existing address, the additional `gas` expenditure would be: + - `9000` for an ether-transfer + - `25000` for a new account-creation + - (`2300` would be refunded to the caller later) + - A total runtime `gas`-cost of `34K` gas would be required to handle this case. + +After this EIP: + +- In addition to the `34K` an additional `penalty` would be added. + - Possibly two, since the reference implementation does the balance-check twice, but it's unclear whether the compiled code would indeed perform the check twice. +- A total runtime `gas`-cost of `34K+penalty` (or `34K + 2 * penalty`) would be required to handle this case. + +It can be argued that the extra penalty of `2-3K` gas can be considered marginal in relation to the other `34K` gas already required to handle this. + +## Test Cases + +The following cases need to be considered and tested: + +- That during creation of a brand new contract, within the constructor, the `penalty` should not be applied for calls concerning the self-address. +- TBD: How the `penalty` is applied in the case of a contract which has performed a `selfdestruct` + - a) previously in the same call-context, + - b) previously in the same transaction, + - c) previously in the same block, + For any variant of `EXTCODEHASH(destructed)`, `CALL(destructed)`, `CALLCODE(destructed)` etc. +- The effects on a `transaction` with `0` value going to a non-existent account. + +## Security Considerations + +See 'Backwards Compatibility' + +## Implementation + +Not yet available. + +## Alternative variants + +### Alt 1: Insta-refunds + +Bump all trie accesses with `penalty`. `EXTCODEHASH` becomes `2700` instead of `700`. +- If a trie access hit an existing item, immediately refund penalty (`2K` ) + +Upside: + +- This eliminates the 'shielded relay' attack + +Downside: + +- This increases the up-front cost of many ops (CALL/EXTCODEHASH/EXTCODESIZE/STATICCALL/EXTCODESIZE etc) + - Which may break many contracts. + +### Alt 2: Parent bail + +Use `penalty` as described, but if a child context goes OOG on the `penalty`, then the remainder is subtracted from the +parent context (recursively). + +Upside: + +- This eliminates the 'shielded relay' attack + +Downside: + +- This breaks the current invariant that a child context is limited by whatever `gas` was allocated for it. + - However, the invariant is not _totally_ thrown out, the new invariant becomes that it is limited to `gas + penalty`. +- This can be seen as 'messy' -- since only _some_ types of OOG (penalties) becomes passed up the call chain, but not others, e.g. OOG due to trying + to allocate too much memory. There is a distinction, however: + - Gas-costs which arise due to not-yet-consumed resources do not get passed to parent. For example: a huge allocation is not actually performed if there is insufficient gas. + - Whereas gas-costs which arise due to already-consumed resources _do_ get passed to parent; in this case the penalty is paid post-facto for a trie iteration. + + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2584.md b/EIPS/eip-2584.md new file mode 100644 index 00000000000000..e2a6293027ddd5 --- /dev/null +++ b/EIPS/eip-2584.md @@ -0,0 +1,114 @@ +--- +eip: 2584 +title: Trie format transition with overlay trees +author: Guillaume Ballet (@gballet) +discussions-to: https://ethresear.ch/t/overlay-method-for-hex-bin-tree-conversion/7104 +status: Stagnant +type: Standards Track +category: Core +created: 2020-04-03 +--- + +## Simple Summary + +This EIP proposes a method to convert the state trie format from hexary to binary: new values are directly stored in a binary trie “laid over” the hexary trie. Meanwhile, the hexary trie is converted to a binary trie in the background. When the process is finished, both layers are merged. + +## Abstract + +This EIP describes a four phase process to complete the conversion. + + * In the first phase, all new state writes are made to an overlay binary trie, while the hexary trie is being converted to binary. The block format is changed to have two storage roots: the root of the hexary trie (hereafter called the "base" trie) and the root of the overlay binary trie. + * After enough time has been given to miners to perform the conversion, the second phase begins. The overlay tree is progressively merged back into the newly converted binary base trie. A constant number of entries are deleted from the overlay and inserted into the base trie. + * The third and final phase begins when the overlay trie is empty. The field holding its root is removed from the block header. + +## Motivation + +There is a long running interest in switching the state trie from a hexary format to a binary format, for reasons pertaining to proof and storage sizes. The conversion process poses a catch-up issue, caused by the sheer size of the full state: it can not be translated in a reasonable time (i.e. on the same order of magnitude as the block time). + +## Specification + +This specification follows the notation introduced by the [Yellow Paper](https://ethereum.github.io/yellowpaper). Prior to reading it is advisable to be familiar with the Yellow Paper. + +### Binary tries + +This EIP assumes that a binary trie is defined like the MPT, except that: + + * The series of bytes in I₀ is seen as a series of _bits_ and so ∀i≤256, I₀[i] is the ith bit in key I₀ + * The first item of an **extension** or a **leaf** is replacing nibbles with bits; + * A **branch** is a 2 item structure in which both items correspond to each of the two possible bit values for the keys at this point in their traversal; + * c(𝕴,i) ≡ RLP((u(0), u(1)) at a branch, where u(j) = n({I : I ∈ 𝕴 ⋀ I₀[i] = j}, i+1) + +Let ß be the function that, given a hexary trie, computes the equivalent representation of that trie in the aforementioned binary trie format. + +### Phase 1 + +Let _h₁_ be the previously agreed-upon block height at which phase 1 starts, and _h₂_ the block at which phase 2 starts. For each block of height h₁ ≤ _h_ < h₂: + + 0. A conversion process is started in the background, to turn the hexary trie into its binary equivalent. The end goal of this process is the calculation of the _root hash of the converted binary trie_, denoted Hᵣ². The root of the hexary trie is hereafter called Hᵣ¹⁶. Formally, this process is written as Hᵣ² ≡ ß(Hᵣ¹⁶). + 1. Block headers contain a new Hₒ field, which is the _root of the overlay binary trie_; + 2. Hᵣ ≡ P(H)ᵣ¹⁶, i.e. as long as the conversion from hexary to binary is not complete, the hexary trie root is the same as that of its parent block. + +The following is changed in the execution environment: + + * Upon executing a _state read_, ϒ first searches for the address in the overlay trie. If the key can not be found there, ϒ then searches the base trie as it did at block heights h' < h₁; + * Upon executing a _state write_, ϒ inserts or updates the value into the overlay tree. The base tree is left untouched; + * If an account is deleted, ϒ inserts the empty hash H(∅) at the address of that account in order to mark its deletion; reads from such an address behave the same as a missing account, regardless of what is present in the base trie. + +Phase 1 ends at block height h₂, which is set far enough from h₁ to offer miners enough time to perform the conversion. + +### Phase 2 + + This phase differs from the previous one on the following points: + + * At block height h₂, before the execution of ϒ, Hᵣ ≡ Hᵣ², i.e. the value before the execution of the transition function is set to the root of the converted _binary base trie_; + * Hₒ is still present in the block tree, however the overlay trie content can only be _read from or deleted_; + * At block height h ≥ h₂, before the execution of ϒ, N accounts are being deleted from the binary overlay trie and inserted into the binary base trie; + * Upon executing a _state write_, ϒ will insert or update the value into the _base_ trie. If the search key exists in the overlay trie, it is deleted. + +Account deletion is performed according to the following rules: + + * The first N accounts (in lexicographic order) remaining in the overlay tree are selected; For each of these accounts: + * If the value is the empty hash, remove the account at the same address from the binary base trie; + * Otherwise, insert/update the account at the corresponding address in the base trie with its overlay trie value. + +When the overlay trie is empty, phase 2 ends and phase 3 begins. + +### Phase 3 + +Phase 3 is the same as phase 2, except for the following change: + + * Hₒ is dropped from the block header + +## Rationale + +Methods that have been discussed until now include a "stop the world" approach, in which the chain is stopped for the significant amount of time that is required by the conversion, and a "copy on write" approach, in which branches are converted upon being accessed. +The approach suggested here has the advantage that the chain continues to operate normally during the conversion process, and that the tree is fully converted to a binary format, in a predictable time. + +## Backwards Compatibility + +This requires a fork and will break backwards compatibility, as the hashes and block formats will necessarily be different. This will cause a fork in clients that don't implement the overlay tree, and those that do not accept the new binary root. No mitigation is proposed, as this is a hard fork. + +## Test Cases + + * For testing phase 1, it suffices to check that every key in the hexary trie is also available in the binary trie. A looser but faster test picks 1% of keys in the hexary trie at random, and checks that they are present in the binary trie; + * TBD for phase 2 & 3 + +## Implementation + +A prototype version of the conversion process (phase 1) is available for `geth` in [this PR](https://github.com/holiman/go-ethereum/pull/12). + +## Security Considerations + +There are three attack vectors that I can foresee: + + * A targeted attack that would cause the overlay trie to be unreasonably large. Since gas costs will likely increase during the transition process, lengthening phase 2 will make Ethereum more expensive during an extended period of time. This could be solved by increasing the cost of `SSTORE` during phase 1. + * Conversely, if h₂ comes too soon, a majority of miners might not be able to produce the correct value for Hᵣ² in time. + * If a group of miners representing more than 51% of the network are reporting an invalid value, they could be stealing funds without anyone having a say. + +## Community feedback + + * Preliminary tests indicate that a fast machine can perform the conversion in roughly 30 minutes. + * The initial version of this EIP expected miners to vote on the value of the binary base root. This has been removed because of the complexity of this process, and because this functionality is already guaranteed by the "longest chain" rule. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2593.md b/EIPS/eip-2593.md new file mode 100644 index 00000000000000..c5e1cc6169da6a --- /dev/null +++ b/EIPS/eip-2593.md @@ -0,0 +1,131 @@ +--- +eip: 2593 +title: Escalator fee market change for ETH 1.0 chain +author: Dan Finlay +discussions-to: https://ethresear.ch/t/another-simple-gas-fee-model-the-escalator-algorithm-from-the-agoric-papers/6399 +status: Stagnant +type: Standards Track +category: Core +created: 2020-03-13 +--- + +## Simple Summary +The current "first price auction" fee model in Ethereum is inefficient and needlessly costly to users. This EIP proposes a way to replace this with a mechanism that allows dynamically priced transaction fees and efficient transaction price discovery. + +## Abstract + +Based on [The Agoric Papers](https://agoric.com/papers/incentive-engineering-for-computational-resource-management/full-text/). + +Each transaction would have the option of providing parameters that specify an "escalating" bid, creating a time-based auction for validators to include that transaction. + +This creates highly efficient price discovery, where the price will always immediately fall to the highest bid price, which is not necessarily that user's highest price they would pay. + +![escalator algorithm price chart](https://ethresear.ch/uploads/default/original/2X/0/042795efa4c2680d644bc66386cd2984a70293f8.gif) + +## Motivation +Ethereum currently prices transaction fees using a simple first-price auction, which leads to well documented inefficiencies (some of which are documented in [EIP-1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md)) when users are trying to estimate what price will get a transaction included in a block, especially during times of price volatility and full blocks. + +EIP 1559 is currently being championed as an improvement for the Ethereum protocol, and while I agree that the gas market is very inefficient, since a change like this will affect all client and wallet implementations, the Ethereum community should make sure to make a selection based on solid reasoning and justifications, which I believe 1559 is currently lacking. + +To facilitate a more productive and concrete discussion about the gas fee market, I felt it was important to present an alternative that is clearly superior to the status quo, so that any claimed properties of EIP-1559 can be compared to a plausible alternative improvement. + +I suggest the three gas payment algorithms be compared under all combinations of these conditions: + +- Blocks that are regularly half full, Blocks that are regularly less than half full, and blocks that repeatedly full in a surprising ("black swan") series. +- Users that are willing to wait for a price that may be below the market rate, vs users who value inclusion urgently and are willing to pay above market rate. + +We should then ask: +- Is the user willing to pay the most in a given scenario also likely to have their transaction processed in a time period they find acceptable? +- Are users who want a good price likely to get included in a reasonable period of time? (Ideally within one block) + +I believe that under this analysis we will find that the escalator algorithm outperforms EIP-1559 in both normal and volatile conditions, for both high-stakes transactions and more casual users looking for a good price. + +While I think a deeper simulation/analysis should be completed, I will share my expected results under these conditions. + +Furthermore, by introducing tx fee payment related to the current time, we create an incentive for miners to more honestly report the current time. + +### User Strategies Under Various Conditions and Algorithms + +First I will suggest a likely optimal strategy for different players under the conditions of the different algorithms being considered. + +| Gas Strategy | Current Single-Price | EIP 1559 | Escalator | +|---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Blocks regularly half full, user wants urgent inclusion. | User bids within the range of prices that have been recently accepted, likely over-pays slightly. | User bids one price tier over the current rate, and is likely included. | User bids a range from the low end of recently included to the high end, and is likely included at the lowest rate possible. | +| Blocks regularly half full, user willing to wait for a good price. | User bids below or near the low end of the recently accepted prices, may need to wait for a while. If waiting too long, user may need to re-submit with a higher price. | User bids under or at the current price tier, and may wait for the price to fall. If waiting too long, user may need to re-submit with a higher price. | User bids as low as they'd like, but set an upper bound on how long they're willing to wait before increasing price. | +| Blocks regularly full, user wants urgent inclusion. | User bids over the price of all recently accepted transactions, almost definitely over-paying significantly. | User bids over the current price tier, and needs to increase their `tip` parameter to be competitive on the next block, recreating the single-price auction price problem. | User bids over a price that has been accepted consistently, with an escalating price in case that price is not high enough. | +| Blocks regularly full, user willing to wait for a good price. | User bids below the low end of the recently accepted prices, may need to wait for a while. If waiting too long, user may need to re-submit with a higher price. | User bids under or at the current price tier, and may wait for the price to fall. If waiting too long, user may need to re-submit with a higher price. | User bids as low as they'd like, but set an upper bound on how long they're willing to wait before increasing price. | +| Blocks regularly under-full, user wants urgent inclusion. | User bids within or over the range of prices that have been recently accepted, likely over-pays slightly, and is likely included in the next block. | User bids at or over the current price tier, and is likely included in the next block. | User submits bid starting within recently accepted prices, is likely accepted in the next block. | +| Blocks regularly under-full, user willing to wait for a good price. | User bids below the low end of the recently accepted prices, may need to wait for a while. If waiting too long, user may need to re-submit with a higher price. | User bids at or under the current price tier, and is likely included in the next block. If bidding under and waiting too long, user may need to re-submit with a higher price. | User bids as low as they'd like, but set an upper bound on how long they're willing to wait before increasing price, is likely included in the next few blocks at the lowest possible price. | + +### User Results Under Various Conditions and Algorithms + +Now I will consider the ultimate results of the strategies listed above. Are users happy under these conditions? Did we save users money? Were users who wanted urgent inclusion able to secure it? + +| Gas Strategy | Current Single-Price | EIP 1559 | Escalator | +|---------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------| +| Blocks regularly half full, user wants urgent inclusion. | User pays an expected amount, and gets transaction mined reliably. | User pays an expected amount, and gets transaction mined reliably. | User pays an expected amount, and gets transaction mined reliably. | +| Blocks regularly half full, user willing to wait for a good price. | User can wait for a better price, but may need to resubmit re-signed transactions. | User can wait for a better price, but may need to resubmit re-signed transactions. | User can discover the lowest price within their time preference with a single signature. | +| Blocks regularly full, user wants urgent inclusion. | User over-pays, but reliably gets transaction included. | Due to `tip` parameter "breaking tie" within a block, user over-pays for reliable inclusion. | User is able to balance the amount of overpayment they risk with the urgency they require. | +| Blocks regularly full, user willing to wait for a good price. | User chooses their price, and waits for it, or manually re-submits. | User chooses their price, and waits for it, or manually re-submits. | User chooses their lowest price, but also their highest price and maximum wait time, so no resubmission is needed. | +| Blocks regularly under-full, user wants urgent inclusion. | User over-pays, but reliably gets transaction included. | User bids at or over current price tier, gets transaction mined reliably. | User pays an expected amount, and gets transaction mined reliably. | +| Blocks regularly under-full, user willing to wait for a good price. | User bids below the low end of the recently accepted prices, may need to wait for a while. If waiting too long, user may need to re-submit with a higher price. | User chooses their price, and waits for it, or manually re-submits. | User chooses their lowest price, but also their highest price and maximum wait time, so no resubmission is needed. | + +In all cases, the escalator algorithm as I have described is able to perform optimally. + +The current gas auction model works well under half-full and less conditions, but for users with urgent needs, has the downside of overpayment. For users seeking a low price, the current model has the downside of requiring re-submission, but has the benefit of always giving users a path towards reliable block inclusion. + +EIP-1559 also performs well under normal conditions, but under conditions where blocks are regularly full, the price discovery mechanism breaks, and miners will fall back to the `TIP` parameter to choose the transactions to include, meaning that under network congestion, EIP-1559 forces users to _either_ choose efficient prices or certainty of next-block inclusion. + +EIP-1559 also has all the re-submission issues of the current model in situations where a user would like to pay under the current market rate, but has certain time constraints limiting their patience. The Escalator algorithm is the only strategy listed here that allows users to discover the lowest possible price given the network conditions and their time constraints. + +## Specification +**Client-Wide Parameters** +* `INITIAL_FORK_BLKNUM`: TBD + +**Transaction Parameters** +The transaction `gasPrice` parameter is now optional, and if excluded can be replaced by these parameters instead: + +* `START_PRICE`: The lowest price that the user would like to pay for the transaction. +* `START_TIME`: The first time that this transaction is valid at. +* `MAX_PRICE`: The maximum price the sender would be willing to pay to have this transaction processed. +* `MAX_TIME`: The time at which point the user's `MAX_PRICE` is achieved. The transaction remains valid after this time at that price. + +**Proposal** + +For all blocks where `block.number >= INITIAL_FORK_BLKNUM`: + +When processing a transaction with the new pricing parameters, miners now receive a fee based off of the following linear function, where `BLOCK` is the current block number: + +* IF `BLOCK > MAX_TIME` then `TX_FEE = MAX_PRICE`. +* `TX_FEE = START_PRICE + ((MAX_PRICE - START_PRICE) / (MAX_TIME - START_TIME) * (BLOCK - START_TIME))` + +As a JavaScript function: +```javascript +function txFee (startTime, startPrice, maxTime, maxPrice, currentTime) { + + if (currentTime >= maxTime) return maxPrice + + const priceRange = maxPrice - startPrice + const blockRange = maxTime - startTime + const slope = priceRange / blockRange + + return startPrice + (slope * (currentTime - startTime)) +} +``` + +## Backwards Compatibility + +Since a current `gasPrice` transaction is effectively a flat-escalated transaction bid, it is entirely compatible with this model, and so there is no concrete requirement to deprecate current transaction processing logic, allowing cold wallets and hardware wallets to continue working for the foreseeable future. + +## Test Cases +TBD + +## Implementation +TBD + +## Security Considerations +The security considerations for this EIP are: +- None currently known. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2612.md b/EIPS/eip-2612.md new file mode 100644 index 00000000000000..416c494fd2824e --- /dev/null +++ b/EIPS/eip-2612.md @@ -0,0 +1,7 @@ +--- +eip: 2612 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2612.md diff --git a/EIPS/eip-2615.md b/EIPS/eip-2615.md new file mode 100644 index 00000000000000..34ed14f5f0a143 --- /dev/null +++ b/EIPS/eip-2615.md @@ -0,0 +1,7 @@ +--- +eip: 2615 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2615.md diff --git a/EIPS/eip-2645.md b/EIPS/eip-2645.md new file mode 100644 index 00000000000000..f3cfeef686499d --- /dev/null +++ b/EIPS/eip-2645.md @@ -0,0 +1,7 @@ +--- +eip: 2645 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2645.md diff --git a/EIPS/eip-2657.md b/EIPS/eip-2657.md new file mode 100644 index 00000000000000..83b1c215c78bca --- /dev/null +++ b/EIPS/eip-2657.md @@ -0,0 +1,66 @@ +--- +eip: 2657 +title: Ephemeral Testnet Yolo +author: James Hancock (@madeoftin) +discussions-to: https://gitter.im/ethereum/AllCoreDevs +status: Stagnant +type: Meta +created: 2020-04-19 +--- + +**Disclaimer: This is for testing basic infrastructure. It will be nuked. It is not for deploying dapps, nor does it define what will go into mainnet. For information on network upgrades, please follow the relevant meta EIPs and ongoing discussion on Ethereum/pm.** + +## Abstract + +The specification for Ephemeral Testnet Yolo. Clients who wish to sync need to implement the following features into their client. It is for testing basic infrastructure and will be nuked. + +## Specification + +Name: Yolo +ID: `YOLO-v1` + + - [x] EIP 2537 Commit Hash - [5edff4ae6ff62c7e0bbfad624fc3d0ba7dc84392](https://github.com/ethereum/EIPs/commit/5edff4ae6ff62c7e0bbfad624fc3d0ba7dc84392) + - [x] EIP 2315 Commit Hash - [e8accf22cdc5562d6982c560080c6cd6b7f94867](https://github.com/ethereum/EIPs/commit/e8accf22cdc5562d6982c560080c6cd6b7f94867) + +*[ ] Proposed - [x] Consensus to include.* +## Timeline + + - Deployed: June 3rd 2020 + +## Client Consensus -> Implementation + +YOLO-v1 +| **Client** | Signal | Spec | Merged | Syncing | +|--------------|--------|------|--------|---------| +| Besu | x | x | | | +| EthereumJS | x | | | | +| Geth | x | x | x | x | +| Nethermind | x | x | | | +| OpenEthereum | x | x | | | +| Trinity | | | | | + +**Signal** - +Client intends to participate. *(You are on the bus)* + +**Spec** - +Client is satisfied with the proposed specification. *(You agree with the direction)* + +**Merge** - +Changes are implemented in the client and configurable for YOLO. *(You are ready to hit the gas and go)* + +**Syncing** +Client syncs with the network + + +## Syncing Instructions + +**Geth** +- Yolo V1 testnet is up and running https://yolonet.xyz/ +- Support is baked into Geth master branch via --yolov1 +- Genesis config json is at https://yolonet.xyz/yolo.json +- EF bootnode at enode://9e1096aa59862a6f164994cb5cb16f5124d6c992cdbf4535ff7dea43ea1512afe5448dca9df1b7ab0726129603f1a3336b631e4d7a1a44c94daddd03241587f9@35.178.210.161:30303 +- Stats page secret is YOLOv1, with geth you can --ethstats='yournode:YOLOv1@stats.yolonet.xyz' +- Faucet is unauthenticated, you can reach it from the dashboard + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2666.md b/EIPS/eip-2666.md new file mode 100644 index 00000000000000..3bd458a40aec09 --- /dev/null +++ b/EIPS/eip-2666.md @@ -0,0 +1,133 @@ +--- +eip: 2666 +title: Repricing of precompiles and Keccak256 function +author: Alex Vlasov (@shamatar) +discussions-to: https://ethereum-magicians.org/t/eip2666-global-precompiles-repricing-and-many-more-discussion-thread/4332 +status: Stagnant +type: Standards Track +category: Core +created: 2020-05-22 +requires: 1352, 2046, 2565 +--- + +## Simple Summary + +This EIP tries to set prices of certain precompiles and built-in EVM function to be in line with their performance, consumed resources and newer changes in EVM itself. + +New price formulas are proposed for: +- SHA256 precompile (`0x02`) +- RIPEMD precompile (`0x03`) +- KECCAK256 opcode (`0x20`) + +## Abstract + +Costs of many precompiles and built-in functions are invalid at the current state of the clients. This EIP contains a list of changes to the pricing formulas to better reflect underlying computations' structure. + +## Motivation + +Historical pricing for these functions in EVM does not reflect inner structure of the underlying computations (inner structure of the hash functions). + +- EIP-2046 changes a `STATICCALL (0xfa)` cost to precompile and it may be necessary to adjust costs of some precompiles that *may* have taken old large cost (`700` gas) into account and tried to compensate for it +- Some precompiles are overpriced and their pricing formulas do not reflect the structure of underlying functions +- Keccak256 built-in function (opcode) in EVM has pricing that does not reflect underlying hash function structure + +## Specification + +If `block_number >= X` set the gas cost of the following precompiles and Keccak256 opcode: +- SHA256 (precompile `0x02`): `10 + ((len(input) + 8)/64 + 1) * 9` +- RIPEMD (precompile `0x03`): `6 + ((len(input) + 8)/64 + 1) * 12` +- KECCAK256 (`0x20`): `13 + (len(input)/136 + 1)*15` + +This EIP *ideally* requires that `MODEXP` repricing is [implemented](./eip-2565.md) to also accurately reflect that there is no implicit compensation for an old `STATICCALL (0xfa)` cost (pre-2046). + +## Rationale +Cost of functions being executed must accurately reflect real CPU time spent on computations, so benchmarking was performed for current precompiles and Keccak256 function to measure running time versus input parameters. + +### Detailed summary of repricing approach + +This EIP relies on two facts: +- apriori knowledge of the inner strucute of the hash functions +- benchmarks provided by the client teams for some reasonable range of input lengths for random inputs (random byte strings of a given length) + +### Benchmarks on the most popular clients + +Necessary benchmarks for EIP-2666 were provided by the clients and raw form is assembled in [here](https://docs.google.com/spreadsheets/d/1aCQnk7prrp3Mbcf011BE5zZnkbc3Iw7QAixn6mLbKS0/edit?usp=sharing) + +- SHA256 precompile + +Currently it's `60` gas + `12` gas per `32` byte word (number of words is `ceil(len(input)/word_len)` here and in similar places. If there is no `floor` or `ceil` specifier all divisions below are integer divisions (floor divisions)). Proposed formula is `A * ((len(input) + 8) / 64 + 1) + B`, with coefficients below + +| | | A | B | +|---|---|---|---| +| Geth | | 5 | 3 | +| OE | | 9 | 4 | +| Besu | | 5 | 10 | +| Nethermind | | 10 | 5 | + +EIP-2666 proposes `A = 9`, `B = 10`. There are no large one-off costs in this precompile, so it's EIP-2046 - safe. + +- RIPEMD precompile + +Currently it's `600` gas + `120` gas per `32` byte word. Proposed formula is `A * ((len(input) + 8) / 64 + 1) + B`, with coefficients below + +| | | A | B | +|---|---|---|---| +| Geth | | 12 | 6 | +| OE | | 8 | 2 | +| Besu | | 29 | 16 | +| Nethermind | | 10 | 6 | + +EIP-2666 proposes `A = 12`, `B = 6`. There are no large one-off costs in this precompile, so it's EIP-2046 - safe. Besu expects to have performance improvements by the end of the year. + +- Keccak256 performance + +Currently it's `30` gas + `6` gas per `32` byte word. Proposed formula is `A * (len(input) / 136 + 1) + B`, with coefficients below + +| | | A | B | +|---|---|---|---| +| Geth | | 13 | 13 | +| OE | | 15 | 2 | +| Besu | | 19 | 28 | +| Nethermind | | 16 | 3 | + +EIP-2666 proposes `A = 15`, `B = 13`. There are no large one-off costs in this precompile, so it's EIP-2046 - safe. Besu expects to have performance improvements by the end of the year. + +### Tooling and data + +Reference material (from benchmarks of different clients) with raw data can be found [here](https://docs.google.com/spreadsheets/d/1aCQnk7prrp3Mbcf011BE5zZnkbc3Iw7QAixn6mLbKS0/edit?usp=sharing). + +There is a repository available with inputs for benchmarking and precompiles testing [here](https://github.com/shamatar/bench_precompiles) that can be used by client teams to perform all the necessary measurements. + +Raw Besu [benchmarks](https://gist.github.com/shemnon/0ddba91be501fa23291bdec9107fe99a). + +### Note on formulas structure + +There are terms in formulas that look like `A * 1` and those are explicitly not combined to the `B` coefficient to reflect that hash of an empty byte array requires to perform a round of hashing anyway. + +## Backwards Compatibility +Precompile repricings has happened in a past and can be considered standard procedure. Gas costs of many contracts is expected to reduce that may break re-entrancy protection measures based on fixed gas costs. In any case, such protection should have never been considered good and final. + +## Test Cases + +Let's consider a simple example of Keccak256 hash of `0`, `64` and `160` bytes that can is a simple sanity check for implementation. + +- Hash `0` bytes: + - Old price: `30 + 6 * ceil(0 / 32) = 30` gas + - New price: `15 * (0/136 + 1) + 13 = 28` gas +- Hash `64` bytes + - Old price: `30 + 6 * ceil(64 / 32) = 42` gas + - New price: `15 * (64/136 + 1) + 13 = 28` gas +- Hash `160` bytes + - Old price: `30 + 6 * ceil(160 / 32) = 60` gas + - New price: `15 * (160/136 + 1) + 13 = 43` gas + +## Implementation + +There is no reference implementation at the time of writing as it requires just a simple change of constants in major clients. + +## Security Considerations + +As described in backward compatibility section in some cases reduction of cost may allow e.g. re-entrancy that was not expected before, but we think that re-entrancy protection based on fixed gas costs is anyway flawed design decision. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2677.md b/EIPS/eip-2677.md new file mode 100644 index 00000000000000..f8116f8220c485 --- /dev/null +++ b/EIPS/eip-2677.md @@ -0,0 +1,77 @@ +--- +eip: 2677 +title: Limit size of `initcode` +author: Martin Holst Swende (@holiman), Paweł Bylica (@chfast), Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-2677-limit-size-of-initcode/4550 +status: Withdrawn +type: Standards Track +category: Core +created: 2020-05-18 +withdrawal-reason: Replaced by EIP-3860. +--- + +## Simple Summary + +Enforce a maximum size limit (`max_initcode_size`) of `49152` (`0xc000`) for `initcode`. + +## Abstract + +Enforce a maximum size limit (`max_initcode_size`) for `initcode`. If the size of `initcode` exceeds `max_initcode_size`, then contract creation fails with an out of gas error. + +Since [EIP-170](./eip-170.md) was implemented, there has been a size limit of `24576` (`0x6000`) on contract code. We propose to also limit the size of executable code to `2x` the above limit, i.e. `49152` (`0xc000`). + +This also leads to two nice properties: + +- instruction offset in code fits 16-bit value, +- code size fits 16-bit value. + +## Motivation + +When a client executes `initcode`, the client has to perform a jumpdest analysis. In some cases, the client also performs a `hash` of the code: + +* To use as a key in a mapping containing the result of a jumpdest analysis +* To use for address calculation within `CREATE2`. + +The work performed during a jumpdest analysis scales linearly with the size of the code. Currently, a transaction can expand the memory once, and reuse the same memory segment (with minor modifications) to force the client to perform a lot of analysis/hashing, leading to slow block processing. + +Historically, this was exploited in June 2017, precipitating the 1.6.5-patch release of [geth](https://github.com/ethereum/go-ethereum/releases/tag/v1.6.5) + +The work performed during address calculation within `CREATE2` is charged in proportion with size of the code. + +## Specification + +There are three situations where this is applicable: + +* `CREATE`, +* `CREATE2`, +* creation using a transaction with empty receiver. + +In all these (and future) cases, the EVM should fail with Out Of Gas error if the code has a length more than `max_initcode_size`. + +## Rationale + +TBA + +## Backwards Compatibility + +This EIP requires a "network upgrade", since it modifies consensus-rules. + +## Security Considerations + +For client implementations, this EIP makes attacks based on jumpdest-analysis or hashing of code less problematic, so should increase the robustness of clients. + +For layer 2, this EIP introduces failure-modes where there previously were none. There _could_ exist factory-contracts which deploy multi-level contract hierarchies, such that the code for multiple contracts are included in the initcode of the first contract. The author(s) of this EIP are not aware of any such contracts. + +## Test Cases + +Test cases should include the following cases, + +- `CREATE`/`CREATE2`/`tx create` with `initcode_size` at `max_initcode_size` +- `CREATE`/`CREATE2`/`tx create` with `initcode_size` at `max_initcode_size+1` + +## Implementation + +TBA + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2678.md b/EIPS/eip-2678.md new file mode 100644 index 00000000000000..9d9d8d2c4d1b58 --- /dev/null +++ b/EIPS/eip-2678.md @@ -0,0 +1,7 @@ +--- +eip: 2678 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2678.md diff --git a/EIPS/eip-2680.md b/EIPS/eip-2680.md new file mode 100644 index 00000000000000..637cab1e90dde0 --- /dev/null +++ b/EIPS/eip-2680.md @@ -0,0 +1,7 @@ +--- +eip: 2680 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2680.md diff --git a/EIPS/eip-2681.md b/EIPS/eip-2681.md new file mode 100644 index 00000000000000..db9e1ffc38de76 --- /dev/null +++ b/EIPS/eip-2681.md @@ -0,0 +1,56 @@ +--- +eip: 2681 +title: Limit account nonce to 2^64-1 +author: Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-2681-limit-account-nonce-to-2-64-1/4324 +status: Final +type: Standards Track +category: Core +created: 2020-04-25 +--- + +## Abstract + +Limit account nonce to be between `0` and `2^64-1`. + +## Motivation + +Account nonces are currently specified to be arbitrarily long unsigned integers. Dealing with arbitrary length data in the state witnesses is not optimal, therefore this EIP will allow proofs to represent the nonce in a more optimized way. + +Additionally it could prove beneficial to transaction formats, where some improvements are potentially sought by at least three other proposals. + +Lastly, this facilitates a minor optimisation in clients, because the nonce no longer needs to be kept as a 256-bit number. + +## Specification + +Introduce two new restrictions retroactively from genesis: + +1. Consider any transaction invalid, where the nonce exceeds or equals to `2^64-1`. +2. The `CREATE` and `CREATE2` instructions' execution ends with the result `0` pushed on stack, where the account nonce is `2^64-1`. Gas for initcode execution is not deducted in this case. + +## Rationale + +1. It is unlikely for any nonce to reach or exceed the proposed limit. If one would want to reach that limit via external transactions, it would cost at least `21000 * (2^64-1) = 387_381_625_547_900_583_915_000` gas. + +2. It must be noted that in the past, in the Morden testnet, each new account had a starting nonce of `2^20` in order to differentiate transactions from mainnet transactions. +This mode of replay protection is out of fashion since [EIP-155](./eip-155.md) introduced a more elegant way using chain identifiers. + +3. Most clients already consider the nonce field to be 64-bit, such as go-ethereum. + +4. The reason a transaction with nonce `2^64-1` is invalid, because otherwise after inclusion the sender account's nonce would exceed `2^64-1`. + +## Backwards Compatibility + +While this is a breaking change, no actual effect should be visible: + +1. There is no account in the state currently which would have a nonce exceeding that value. As of November 2020, the account `0xea674fdde714fd979de3edf0f56aa9716b898ec8` is responsible for the highest account nonce at approximately 29 million. + +2. go-ethereum already has this restriction partially in place (`state.Account.Nonce` and `types.txdata.AccountNonce` it as a 64-bit number). + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2696.md b/EIPS/eip-2696.md new file mode 100644 index 00000000000000..fd4323f1c472b6 --- /dev/null +++ b/EIPS/eip-2696.md @@ -0,0 +1,100 @@ +--- +eip: 2696 +title: JavaScript `request` method RPC transport +author: Micah Zoltu (@MicahZoltu), Erik Marks (@rekmarks) +discussions-to: https://github.com/ethereum/EIPs/issues/2697 +status: Final +type: Standards Track +category: Interface +created: 2020-06-04 +--- + +## Simple Summary +A standard for remote procedure calls between an Ethereum Provider and an Ethereum Client when both are able to interface with each other via a shared JavaScript object. + +## Abstract +This standard provides the description of an object that is made available to JavaScript applications which they can use to communicate with the Ethereum blockchain through. This standard only describes the transport mechanism, it does not specify the payloads that are valid nor does it specify how the client or the provider will discover or agree on payload content. + +How/where this Ethereum object is exposed is left to future standards. + +## Motivation +When working within a JavaScript runtime (such as NodeJS, Electron, Browser, etc.) it may be possible for the runtime or a runtime plugin to inject objects into the runtime. Someone authoring a runtime or a runtime plugin may choose to expose an Ethereum Provider to any JavaScript apps or scripts running within that runtime in order to provide indirect access to an Ethereum-like blockchain and potentially signing tools. In order to achieve maximum compatibility between the provider and the client, a standard is necessary for what the shape of that object is. + +## Specification + +### RFC-2119 + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC-2119](https://www.ietf.org/rfc/rfc2119.txt). + +### Interface + +TypeScript interface definition: +```ts +interface RequestArguments { + readonly method: string; + readonly params?: readonly unknown[] | object; +} + +interface EthereumProvider { + request(args: RequestArguments): Promise +} +``` +The Provider **MUST** implement a `request` method on the exposed `EthereumProvider` object. The `request` method **MUST** be callable with a single parameter which contains the arguments for the request as defined in the TypeScript `interface` above. + +If the Provider supports a JSON-RPC (https://www.jsonrpc.org/specification) request as specified elsewhere, then it **MUST** accept a `request` call for that JSON-RPC method with the `RequestArguments.method` argument matching the JSON-RPC `method` string for the RPC call and the `RequestArguments.params` matching the `params` object of the RPC call. The `RequestArguments.params` should be encoded as a JavaScript object matching the specified JSON-RPC type, not encoded as a JSON string as would normally be the case when transporting JSON-RPC. + +#### Example +If the JSON-RPC request would contain a payload like: +```typescript +'{ "jsonrpc": "2.0", "id": 1, "method": "do_work", "params": [ 5, "hello" ] }' +``` +Then the matching `EthereumProvider.request` call would be: +```typescript +declare const provider: EthereumProvider +provider.request({ method: 'method', params: [ 5, 'hello' ] }) +``` + +### Results +If the Provider supports a JSON-RPC request as specified elsewhere, then it **MUST** return an object that matches the expected `result` definition for the associated JSON-RPC request. + +#### Example +If the JSON-RPC response would contain a payload like: +```typescript +'{ "jsonrpc": "2.0", "id": 1, "result": { "color": "red", "value": 5 } }' +``` +Then the matching `EthereumProvider.request` response would be: +```typescript +{ color: 'red', value: 5 } +``` + +### Errors +```ts +interface ProviderRpcError extends Error { + message: string; + code: number; + data?: unknown; +} +``` + +| code | message | meaning | +| -----| --------------------- | ------------------------------------------------------------------------ | +| 4001 | User Rejected Request | The user rejected the request. | +| 4100 | Unauthorized | The requested method and/or account has not been authorized by the user. | +| 4200 | Unsupported Method | The Provider does not support the requested method. | +| 4900 | Disconnected | The Provider is disconnected from all chains. | +| 4901 | Chain Disconnected | The Provider is not connected to the requested chain. | + +If the Provider is unable to fulfill a request for any reason, it **MUST** resolve the promise as an error. The resolved error **MUST** be shaped as a `ProviderRpcError` defined above whenever possible. _While it is impossible to guaranteed that a JavaScript application will never throw an out of memory or stack overflow error, care should be taken to ensure that promise rejections conform to the above shape whenever possible._ + +If a `code` is provided that is listed in the list above, or in the JSON-RPC specification (https://www.jsonrpc.org/specification#error_object), or in the associated JSON-RPC request standard being followed, then the error reason **MUST** align with the established meaning of that code and the `message` **MUST** match the provided `message` + +The `data` field **MAY** contain any data that is relevant to the error or would help the user understand or troubleshoot the error. + +## Rationale +While this standard is perhaps not the greatest mechanism for communicating between an application and a blockchain, it is closely aligned with established practices within the community so migration from existing systems to this one should be relatively easy. Most communication is currently done via JSON-RPC, so aligning with the JSON-RPC standard was desired to enable quick integration with existing systems. + +## Security Considerations +The relationship between Ethereum Provider and client is a trusted one, where it is assumed that the user implicitly trusts the Ethereum Provider which is how it managed to get injected into the client, or the client expressly pulled in a connection to it. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2700.md b/EIPS/eip-2700.md new file mode 100644 index 00000000000000..bd7c590b259a77 --- /dev/null +++ b/EIPS/eip-2700.md @@ -0,0 +1,47 @@ +--- +eip: 2700 +title: JavaScript Provider Event Emitter +author: Micah Zoltu (@MicahZoltu), Erik Marks (@rekmarks) +discussions-to: https://github.com/ethereum/EIPs/issues/2701 +status: Final +type: Standards Track +category: Interface +created: 2020-06-05 +--- + +## Simple Summary +A standard mechanism for JavaScript Ethereum Providers to notify clients about chain state changes when both are able to interface with each other via a shared JavaScript object. + +## Abstract +This standard provides the description of an object that is made available to JavaScript applications which they can use to receive notifications from an Ethereum Provider. This standard only describes the notification mechanism, it does not specify the payloads that are valid nor does it specify how the client or the provider will discover or agree on payload content. + +How/where this Ethereum Provider object is exposed is left to future standards. + +## Motivation +When working within a JavaScript runtime (such as NodeJS, Electron, Browser, etc.) it may be possible for the runtime or a runtime plugin to inject objects into the runtime. Someone authoring a runtime or a runtime plugin may choose to expose an Ethereum Provider to any JavaScript apps or scripts running within that runtime in order to provide notifications of blockchain state changes. In order to achieve maximum compatibility between the provider and the client, a standard is necessary for what the shape of that object is. + +## Specification +### RFC-2119 +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC-2119](https://www.ietf.org/rfc/rfc2119.txt). + +### Interface +```ts +interface EthereumProvider { + on(eventName: string, listener: (...params: unknown[]) => void): void + removeListener(eventName: string, listener: (...params: unknown[]) => void): void +} +``` +The specific events that can be listened to and the shape of their listener callback functions is left to be defined in separate standards. + +If `on` is called with an `eventName` that the provider is familiar with then the provider **MUST** call the provided `listener` when the named event occurs. If the same `listener` is added multiple times to the same event via `on`, the provider **MAY** choose to either callback the listener one time or one time per call to `on`. + +If `removeListener` is called with an `eventName` and `listener` that was previously added via `on` then the provider **MUST** decrease the number of times it calls the `listener` per event by one. + +## Rationale +This EIP is mostly a retrospective EIP meaning it codifies an already existing specification so there isn't a lot of room for improving things such as by using a discriminated union object for listener parameters or having a tighter definition of `on`. The specific events are intentionally left out of this specification as that set will be an ever-evolving collection and having the first few listed here doesn't add value to this specification (especially if, over time, the first few end up deprecated or unused). + +## Security Considerations +The relationship between Ethereum Provider and client is a trusted one, where it is assumed that the user implicitly trusts the Ethereum Provider which is how it managed to get injected into the client, or the client expressly pulled in a connection to it. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2711.md b/EIPS/eip-2711.md new file mode 100644 index 00000000000000..4c6bf2a974509f --- /dev/null +++ b/EIPS/eip-2711.md @@ -0,0 +1,136 @@ +--- +eip: 2711 +title: Sponsored, expiring and batch transactions. +author: Micah Zoltu (@MicahZoltu) +discussions-to: https://ethereum-magicians.org/t/eip-2711-separate-gas-payer-from-msg-sender/4353 +status: Withdrawn +type: Standards Track +category: Core +created: 2020-06-11 +requires: 2718 +--- + +## Simple Summary +Creates a new transaction type that supports sponsored transactions (separate gas payer from sender), batch transactions (multiple transactions executed in sequence), and expiring transactions (transactions which are not valid after a certain timestamp). + +## Abstract +An EIP-2718 transaction with the type number `2` is a new type of transaction that includes support for: +1. **Sponsored Transactions**: an optional additional signature from which the account that will pay for gas (`GAS_PAYER`) can be recovered +2. **Batch Transactions**: multiple transactions from the same sender that will be executed in sequence +3. **Expiring Transactions**: an optional `validUntil` field that makes the transaction invalid after a certain point in time + +## Motivation +### Sponsored Transactions +With the advent of tokens and especially stable coins, it has become common for users to not hold ETH in an account while they may have other assets of value in that account. Some users don't want to be exposed to the perceived volatility of ETH and instead would prefer to transact using other assets. Unfortunately, since gas **MUST** be paid for with ETH, this prevents the user from transacting with their assets without first acquiring some ETH using some other means, and then using that ETH to pay fees. + +This EIP proposes a mechanism by which we can allow people to transact without ever having to own any ETH by allowing someone else to cover gas costs. The arrangements that enable the covering of gas costs is out of scope for this EIP but it could be an extra-protocol monthly subscription, payment could occur as part of the transaction being submitted, the recipient may be willing to cover gas costs, or it could be a free service offered as a value-add by a company that you are working with. + +While it is possible to implement these sort of mechanisms at the individual contract layer, such solutions require integration by just about every contract and those solutions also end up depending on gas costs being stable with time in order to appropriately bake them into contracts without putting either party at risk of malicious participants in the system. For this reason, it is believed that separating out `GAS_PAYER` from `msg.sender` at the protocol layer is valuable. + +### Batch Transactions +Often times an EOA may want to execute a series of transactions with a strong guarantee that they happen in order with nothing occurring between them. For example, one may want to send some tokens to a contract and then follow that up with another transaction that makes a contract call on the destination address that causes those tokens to be registered to them. By supporting transaction batching at layer 1, we can ensure that the user can get strong guarantees at signing time of cross-transaction atomicity. + +### Expiring Transactions +* If any form of dust-account clearing is introduced, e.g. (https://github.com/ethereum/EIPs/issues/168), it will be necessary to introduce a replay protection, such as https://github.com/ethereum/EIPs/issues/169 . Having temporal replay protection removes the need to change nonce-behaviour in the state, since transactions would not be replayable at a later date than explicitly set by the user. +* In many cases, such as during ICOs, a lot of people want their transactions to either become included soon (within a couple of hours) or not at all. Currently, transactions are queued and may not execute for several days, at a cost for both the user (who ends up paying gas for a failing purchase) and the network, dealing with the large transaction queues. +* Node implementations have no commonly agreed metric for which transactions to keep, discard or propagate. Having a TTL on transactions would make it easier to remove stale transactions from the system. + +## Specification +### Definitions +**`TransactionType`** 2. See [EIP-2718](./eip-2718.md) + +**`TransactionSubtype`** is either 1, 2, 3, or 4. + +**`ChainId`** The transaction is valid if this value is `0` or it is included in a block on a chain whose ID is equal to this value. + +**`ValidUntil`** The transaction is valid if this value is `0` or it is included in a block whose `timestamp` is less than or equal to this value. + +**`YParity`** The parity (0 for even, 1 for odd) of the y-value of a secp256k1 signature. + +**`ChildTransaction`** A nested transaction consisting of `[to, value, data]`. + +**`SenderPayload`** Defined based on the `TransactionSubtype` as follows: +1. `[1, ChildTransaction[], nonce, ChainId, ValidUntil, gasLimit, gasPrice]` +2. `[2, ChildTransaction[], nonce, ChainId, ValidUntil, gasLimit, gasPrice]` +3. `[3, ChildTransaction[], nonce, ChainId, ValidUntil, gasLimit]` +4. `[4, ChildTransaction[], nonce, ChainId, ValidUntil]` + +**`SenderSignature`** `[YParity, r, s]` of `secp256k1(keccak256(rlp([TransactionType, SenderPayload])))` + +**`GasPayerPayload`** Defined based on the `TransactionSubtype` as follows: +1. `[]` +2. `[]` +3. `[gasPrice]` +4. `[gasLimit, gasPrice]` + +**`GasPayerSignature`** is `[]` for `TransactionSubType` `1` or `[YParity, r, s]` of `secp256k1(keccak256(rlp([SenderPayload, SenderSignature, GasPayerPayload])))` for others. + +### New Transaction Type + +As of `FORK_BLOCK_NUMBER` an [EIP-2718](./eip-2718.md) transaction with a `TransactionType` of `2` will have its `Payload` interpreted as an RLP encoded tuple of: +``` +[...SenderPayload, ...SenderSignature, ...GasPayerPayload, ...GasPayerSignature] +``` + +The address recovered from `SenderSignature` is the address... +1. ...returned by the `CALLER` opcode (0x33, aka `msg.sender`) during the first call frame of the transaction +2. ...returned by the `ORIGIN` opcode (0x32, aka `tx.origin`) +3. ...whose `nonce` is used +4. ...whose ETH balance is deducted if any value is attached to the transaction +5. ...whose ETH balance is deducted to pay for gas if `GasPayerSignature` is not present + +If `GasPayerSignature` is present, then the address recovered from it is the address... +1. ...whose ETH balance is deducted to pay for gas + +The base gas cost of transactions of this type will be `TRANSACTION_TYPE_2_BASE_GAS_PRICE` + `TRANSACTION_TYPE_2_CHILD_GAS_PRICE` * `n`, rather than the cost associated with transactions of type `0` and legacy transactions. + +### New Transaction Receipt + +As of `FORK_BLOCK_NUMBER` an [EIP-2718](./eip-2718.md) transaction receipt with a `TransactionType` of `2` will have its `Payload` interpreted as a `rlp([status, cumulativeGasUsed, logsBloom, logs][])` where each item of the array corresponds to the child-transaction at matching offset in the transaction type 2 `Payload`. + +## Rationale +### One Monolithic EIP +This EIP could be split up into multiple EIPs, one for each of the subtypes and one for the meta-type. Alternatively, each of the subtypes could be a unique TransactionType. The reason we chose to go with a single EIP with subtypes is because these 4 transactions all have a *lot* in common and each separate EIP would be almost identical to the previous. We felt that in this case, splitting into multiple EIPs wasn't worth the duplication of EIP content. +### ChainID not encoded with `v` +While we could save one byte in the common case by bundling the y-parity bit of the signature with the Chain ID like in EIP-155, this adds complexity to signing tools that the authors deem not worth it given the size of the transaction overall. +### Optionality of ChainID +Sometimes it is useful to have a transaction that *can* be replayed on multiple chains. An example of this is when you construct a vanity signature for a transaction and have the `from` be whatever address that signature recovers to. With the ability to have someone else be a gas payer (setting both the gas limit and the gas price), one can have transactions that deploy contracts which live at the same address on every chain. While this can be accomplished with CREATE2 using legacy transactions, we have the opportunity here to simplify the process and enable potentially other future uses of deterministic transactions by making ChainID optional. +### Optionality of ValidUntil +A user can set `ValidUntil` to a very large number which effectively makes it non-expiring. By making `ValidUntil` optional, we can save some bytes on the wire by allowing such transactions to simply have a `0` (1 byte in RLP) value for this field. +### `SENDER` sets `gasLimit` and `gasPrice` +This type of transaction is useful when the transaction may execute differently depending on what these values are set to. By having the `SENDER` set both, we ensure that the `SENDER` has full control over the transaction details. +### `SENDER` sets `gasLimit`, `GAS_PAYER` sets `gasPrice` +This type of transaction is useful when the transaction may execute differently depending on how much gas it is allowed (e.g., number of loops) but where the `SENDER` would like to give the `GAS_PAYER` the ability to price the transaction to maximize chances of inclusion. +### `GAS_PAYER` sets `gasLimit` and `gasPrice` +This type of transaction allows the `SENDER` to define what they want to do, and leaves all worry about gas to the `GAS_PAYER`. This is useful for transactions where the sender doesn't care how much gas is used or the price that is paid and also either trusts the `GAS_PAYER` to be non-malicious or doesn't care if the `SENDER`'s nonce is increased. Such situations are useful when you have extra-protocol trust between the `SENDER` and `GAS_PAYER` and you want to separate concerns (what to do vs how to get included) for security or complexity reasons. +### Nonces +The inner transaction needs a nonce to protect themselves from replay attacks. Since the inner transaction has a nonce, we get replay protection on the outer transaction as well, so it is not critical for security to have multiple parties provide a nonce. + +We could have the `GAS_PAYER` provide a second nonce, but this would increase the payload size and require `GAS_PAYER` to do replace-by-fee (noisy for gossip) if they want to slip in a new (different inner) transaction with a higher gas price. It would also create the possibility of a deadlock if the `SENDER` nonces aren't ordered the same as the `GAS_PAYER` nonces, and if the `SENDER` nonce isn't the lowest valid nonce for the `SENDER` then the `GAS_PAYER` can't sign and submit yet. Finally, client complexity increases slightly if a transaction has two nonces because you have to protect yourself from deadlocks and do more work to determine validity. +### ValidUntil +For the dust-account clearing usecase, +- This change is much less invasive in the consensus engine. + - No need to maintain a consensus-field of 'highest-known-nonce' or cap the number of transactions from a sender in a block. + - Only touches the transaction validation part of the consensus engine + - Other schemas which uses the `nonce` can have unintended side-effects, + - such as inability to create contracts at certain addresses. + - more difficult to integrate with offline signers, since more elaborate nonce-schemes requires state access to determine. + - More intricate schemes like `highest-nonce` are a lot more difficult, since highest-known-nonce will be a consensus-struct that is incremented and possibly reverted during transaction execution, requiring one more journalled field. + +### ValidUntil as timestamp instead of block number +- The unix time is generally available in most settings, even on a computer which is offline. This means that even a setup where blockchain information is unavailable, the party signing a transaction can generate a transaction with the desired properties. +- The correlation between time and block number is not fixed; even though a 13s blocktime is 'desired', this varies due to both network hashrate and difficulty bomb progression. +- The block number is even more unreliable as a timestamp for testnets and private networks. +- unix time is more user-friendly, a user can more easily decide on reasonable end-date for a transaction, rather than a suitable number of valid blocks. + +## Backwards Compatibility +No known issues. + +## Test Cases + +## Implementation + +## Security Considerations + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2718.md b/EIPS/eip-2718.md new file mode 100644 index 00000000000000..83a19b0fa865dc --- /dev/null +++ b/EIPS/eip-2718.md @@ -0,0 +1,79 @@ +--- +eip: 2718 +title: Typed Transaction Envelope +description: Defines a new transaction type that is an envelope for future transaction types. +author: Micah Zoltu (@MicahZoltu) +discussions-to: https://ethereum-magicians.org/t/eip-2718-typed-transaction-envelope/4355 +status: Final +type: Standards Track +category: Core +created: 2020-06-13 +--- + +## Abstract +`TransactionType || TransactionPayload` is a valid transaction and `TransactionType || ReceiptPayload` is a valid transaction receipt where `TransactionType` identifies the format of the transaction and `*Payload` is the transaction/receipt contents, which are defined in future EIPs. + +## Motivation +In the past, when we have wanted to add new transaction types we have had to ensure they were backward compatible with all other transactions, meaning that you could differentiate them based only on the encoded payload, and it was not possible to have a transaction that matched both types. +This was seen in [EIP-155](./eip-155.md) where the new value was bit-packed into one of the encoded fields. +There are multiple proposals in discussion that define new transaction types such as one that allows EOA accounts to execute code directly within their context, one that enables someone besides `msg.sender` to pay for gas, and proposals related to layer 1 multi-sig transactions. +These all need to be defined in a way that is mutually compatible, which quickly becomes burdensome to EIP authors and to clients who now have to follow complex rules for differentiating transaction type. + +By introducing an envelope transaction type, we only need to ensure backward compatibility with existing transactions and from then on we just need to solve the much simpler problem of ensuring there is no numbering conflict between `TransactionType`s. + +## Specification +### Definitions +* `||` is the byte/byte-array concatenation operator. + +### Transactions +As of `FORK_BLOCK_NUMBER`, the transaction root in the block header **MUST** be the root hash of `patriciaTrie(rlp(Index) => Transaction)` where: +* `Index` is the index in the block of this transaction +* `Transaction` is either `TransactionType || TransactionPayload` or `LegacyTransaction` +* `TransactionType` is a positive unsigned 8-bit number between `0` and `0x7f` that represents the type of the transaction +* `TransactionPayload` is an opaque byte array whose interpretation is dependent on the `TransactionType` and defined in future EIPs +* `LegacyTransaction` is `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + +All signatures for future transaction types **SHOULD** include the `TransactionType` as the first byte of the signed data. +This makes it so we do not have to worry about signatures for one transaction type being used as signatures for a different transaction type. + +### Receipts +As of `FORK_BLOCK_NUMBER`, the receipt root in the block header **MUST** be the root hash of `patriciaTrie(rlp(Index) => Receipt)` where: +* `Index` is the index in the block of the transaction this receipt is for +* `Receipt` is either `TransactionType || ReceiptPayload` or `LegacyReceipt` +* `TransactionType` is a positive unsigned 8-bit number between `0` and `0x7f` that represents the type of the transaction +* `ReceiptPayload` is an opaque byte array whose interpretation is dependent on the `TransactionType` and defined in future EIPs +* `LegacyReceipt` is `rlp([status, cumulativeGasUsed, logsBloom, logs])` + +The `TransactionType` of the receipt **MUST** match the `TransactionType` of the transaction with a matching `Index`. + +## Rationale +### TransactionType only goes up to 0x7f +For the forseable future, 0x7f is plenty and it leaves open a number of options for extending the range such as using the high bit as a continuation bit. +This also prevents us from colliding with legacy transaction types, which always start with a byte `>= 0xc0`. +### **SHOULD** instead of **MUST** for the TransactionType being first byte of signed data +While it is strongly recommended that all future transactions sign the first byte to ensure that there is no problem with signature reuse, the authors acknowledge that this may not always make sense or be possible. +One example where this isn't possible is wrapped legacy transactions that are signature compatible with the legacy signing scheme. +Another potential situation is one where transactions don't have a signature in the traditional sense and instead have some other mechanism for determining validity. +### TransactionType selection algorithm +There was discussion about defining the `TransactionType` identifier assignment/selection algorithm in this standard. +While it would be nice to have a standardized mechanism for assignment, at the time of writing of this standard there is not a strong need for it so it was deemed out of scope. +A future EIP may introduce a standard for TransactionType identifier assignment if it is deemed necessary. +### Opaque byte array rather than an RLP array +By having the second byte on be opaque bytes, rather than an RLP (or other encoding) list, we can support different encoding formats for the transaction payload in the future such as SSZ, LEB128, or a fixed width format. +### ORIGIN and CALLER +There was discussion about having ORIGIN and CALLER opcodes become dependent on the transaction type, so that each transaction type could define what those opcodes returned. +However, there is a desire to make transaction type opaque to the contracts to discourage contracts treating different types of transactions differently. +There also were concerns over backward compatibility with existing contracts which make assumptions about ORIGIN and CALLER opcodes. +Going forward, we will assume that all transaction types will have an address that reasonably represents a `CALLER` of the first EVM frame and `ORIGIN` will be the same address in all cases. +If a transaction type needs to supply additional information to contracts, they will need a new opcode. + +## Backwards Compatibility +Clients can differentiate between the legacy transactions and typed transactions by looking at the first byte. +If it starts with a value in the range `[0, 0x7f]` then it is a new transaction type, if it starts with a value in the range `[0xc0, 0xfe]` then it is a legacy transaction type. +`0xff` is not realistic for an RLP encoded transaction, so it is reserved for future use as an extension sentinel value. + +## Security Considerations +When designing a new 2718 transaction type, it is **STRONGLY** recommended to include the transaction type as the first byte of the signed payload. If you fail to do this, it is possible that your transaction may be signature compatible with transactions of another type which can introduce security vulnerabilities for users. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2733.md b/EIPS/eip-2733.md new file mode 100644 index 00000000000000..067265651ba557 --- /dev/null +++ b/EIPS/eip-2733.md @@ -0,0 +1,292 @@ +--- +eip: 2733 +title: Transaction Package +author: Matt Garnett (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-transaction-package/4365 +status: Withdrawn +type: Standards Track +category: Core +created: 2020-06-16 +requires: 2718 +withdrawal-reason: I have decided to pursue EIP-3074 as the preferred solution to transaction packages. +--- + +## Simple Summary +Creates a new transaction type which executes a package of one or more +transactions, while passing status information to subsequent transactions. + +## Abstract +Introduce a new transaction type which includes a list of transactions that +must be executed serially by clients. Execution information (e.g. success, +gas_used, etc.) will be propagated forward to the next transaction. + +## Motivation +Onboarding new users to Ethereum has been notoriously difficult due to the need +for new users to acquire enough ether to pay for their transactions. This +hurdle has seen a significant allocation of resources over the years to solve. +Today, that solution is meta-transactions. This is, unfortunately, a brittle +solution that requires signatures to be recovered within a smart contract to +authenticate the message. This EIP aims to provide a flexible framework for +relayers to "sponsor" many transactions at once, trustlessly. + +Meta-transactions often use relay contracts to maintain nonces and allow users +to pay for gas using alternative assets. They have historically been designed +to catch reversions in their inner transactions by only passing a portion of +the available gas to the subcall. This allows them to be certain the outer call +will have enough gas to complete any required account, like processing a gas +payment. This type of subcall has been considered bad practice for a long time, +but in the case of where you don't trust the subcalls, it is the only available +solution. + +Transaction packages are an alternative that allow multiple transactions to be +bundled into one package and executed atomically, similarly to how relay +contracts operate. Transactions are able to pass their result to subsequent +transactions. This allows for conditional workflows based on the outcome of +previous transactions. Although this functionality is already possible as +described above, workflows using transaction packages are more robust, because +they are protected from future changes to the gas schedule. + +An important byproduct of this EIP is that it also facilitates bundling +transactions for single users. + +## Specification +Introduce a new [EIP-2718](./eip-2718.md) transaction type where `id = 2`. + +#### Structure +``` +struct TransactionPackage { + chain_id: u256, + children: [ChildPackage], + nonce: u64, + gas_price: u256, + v: u256, + r: u256, + s: u256 +} +``` + +##### Hash +`keccak256(rlp([2, chain_id, children, nonce, gas_price, v, r, s])` + +##### Signature Hash +`keccak256(rlp([2, chain_id, children, nonce, gas_price])` + +##### Receipt +Each `ChildTransaction` transaction will generate a `ChildReceipt` after execution. Each +of these receipts will be aggregated into a `Receipt`. + +``` +type Receipt = [ChildReceipt] +``` + +``` +struct ChildReceipt { + status: u256, + cumulative_gas_used: u256, + logs_bloom: [u8; 256], + logs: [u8] +} +``` + +#### Child Transaction +Let `ChildPackage` be interpreted as follows. + +``` +struct ChildPackage { + type: u8, + nonce: u64, + transactions: [ChildTransaction], + max_gas_price: u256, + v: u256, + r: u256, + s: u256 +} +``` + +``` +struct ChildTransaction { + flags: u8, + to: Address, + value: u256, + data: [u8], + extra: [u8], + gas_limit: u256 +} +``` + +##### Types +The `type` field is used to denote whether the `Child` signer wishes to +delegate the `max_gas_price` and `gas_limit` choice to the `TransactionPackage` +signer. + +| type | signature hash | +|---|---| +| `0x00` | `keccak256(rlp([0, nonce, transactions, max_gas_price])` | +| `0x01` | `keccak256(rlp([1, nonce, transactions_without_gas_limit])` | + +### Validity + +A `TransactionPackage` can be deemed valid or invalid as follows. + +```rust +fn is_valid(config: &Config, state: &State, tx: TransactionPackage) bool { + if ( + config.chain_id() != tx.chain_id || + tx.children.len() == 0 || + state.nonce(tx.from()) + 1 != tx.nonce + ) { + return false; + } + + let cum_limit = tx.children.map(|x| x.gas_limit).sum(); + if state.balance(tx.from()) < cum_limit * tx.gas_price + intrinsic_gas(tx) { + return false; + } + + for child in tx.children { + if ( + child.nonce != state.nonce(child.from()) + 1 || + child.value > state.balance(child.from()) || + child.max_gas_price < tx.gas_price + ) { + return false; + } + + for tx in child.txs { + if ( + tx.flags != 0 || + tx.extra.len() != 0 || + tx.gas_limit < intrinsic_gas(tx) + ) { + return false; + } + } + } + + true +} +``` + +### Results + +Subsequent `ChildTransaction`s will be able to receive the result of the +previous `ChildTransaction` via `RETURNDATACOPY (0x3E)` in first frame of +execution, before making any subcalls. Each element, except the last, will be +`0`-padded left to 32 bytes. + +``` +struct Result { + // Status of the previous transaction + success: bool, + + // Total gas used by the previous transaction + gas_used: u256, + + // Cumulative gas used by previous transactions + cum_gas_used: u256, + + // The size of the return value + return_size: u256, + + // The return value of the previous transaction + return_value: [u8] +} +``` + +### Intrinsic Cost +Let the intrinsic cost of the transaction package be defined as follows: + +``` +fn intrinsic_gas(tx: TransactionPackage) u256 { + let data_gas = tx.children.map(|c| c.txs.map(|t| data_cost(&c.data)).sum()).sum(); + 17000 + 8000 * tx.children.len() + data_gas +} +``` + +### Execution +Transaction packages should be executed as follows: +1. Deduct the cumulative cost from the outer signer's balance. +2. Load the first child package, and execute the first child transaction. +3. Record all state changes, logs, the receipt, and refund any unused gas. +4. If there are no more child transactions, goto `8`. +5. Compute `Result` for the previously executed transaction. +6. Prepare `Result` to be available via return opcodes in the next + transaction's first frame. +7. Execute the next transaction, then goto `3`. +8. Load the next child package, then goto `7`. + +## Rationale + +### Each `Child` has its own signature +For simplicity, the author has chosen to require each child package to specify +its own signature, even if the signer is the same as the package signer. This +choice is made to allow for maximum flexibility, with minimal client changes. +This transaction can still be used by a single user at the cost of only one +additional signature recovery. + +### `ChildPackage` specifies `max_gas_price` instead of `gas_price` +Allowing child packages to specify a range of acceptable gas prices is +strictly more versatile than a static price. It gives relayers more flexibility +in terms of building transaction bundles, and it makes it possible for relayers +to try and achieve the best price for the transaction sender. With a fixed +price, the relayer may require the user to sign multiple different +transactions, with varying prices. This can be avoided by specifying a max +price, and communicating out-of-band how the urgency of the transaction (e.g. +the relayer should package it with the max price immediately vs. slowly +increasing the gas price). +A future transaction type can be specified with only a single +signature, if such an optimization is desired. + +### `ChildPackage` is also typed +The type element serves a modest role in the transaction type, denoting whether +the transaction signer wishes to delegate control of the gas price and gas +limit to the outer signer. This is a useful UX improvement when interacting +with a trusted relayer, as once the user decides to make a transaction the +relayer can ensure it is included on chain by choosing the best gas price and +limit. + +### The `flags` and `extra` fields aren't used +These fields are included to better support future changes to the transaction +type. This would likely be used in conjunction with the `flags` and `type` +fields. A benefit of explicitly defining them is that specialized serialization +of RLP can be avoided, simplifying clients and downstream infrastructure. The +author believe the cost of 2 bytes per transaction is acceptable for smoother +integration of future features. + +## Backwards Compatibility +Contracts which rely on `ORIGIN (0x32) == CALLER (0x33) && RETURNDATASIZE +(0x3D) == 0x00` will now always fail in transaction packages, unless they are +the first executed transaction. It’s unknown if any contracts conduct this +check. + +## Test Cases +TBD + +## Implementation +TBD + +## Security Considerations +### Managing packages efficiently in the mempool +The introduction of a new transaction type brings along new concerns regarding +the mempool. Done naively, it could turn into a DDoS vector for clients. This +EIP has been written to reduce as much validation complexity as possible. + +An existing invariant in the mempool that is desirable for new transactions to +maintain, is that transactions can be validated in constant time. This is also +possible for packaged transactions. There is an inherent 10Mb limit for RLPx +frames, so that would be the upper bound on transactions that could be included +in a package. On the other hand, clients can also just configure their own +bound locally (e.g. packages must be less than 1Mb). Validity can then be +determined by using the function above. + +Once a package has been validated, it must continuously be monitored for nonce +invalidations within its package. One potential way to achieve this efficiently +is to modify the mempool to operate on thin pointers to the underlying +transaction. This will allow packages to ingest as many "single" transactions, +simplifying the facilities for monitoring changes. These "parts" of the package +can maintain a pointer to a structure with pointers to all the parts of the +package. This way, as soon as one part becomes invalid, it can request the +parent to invalidate all outstanding parts of the package. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2746.md b/EIPS/eip-2746.md new file mode 100644 index 00000000000000..ef688895dcf679 --- /dev/null +++ b/EIPS/eip-2746.md @@ -0,0 +1,7 @@ +--- +eip: 2746 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2746.md diff --git a/EIPS/eip-2767.md b/EIPS/eip-2767.md new file mode 100644 index 00000000000000..e78cf4776e1ff8 --- /dev/null +++ b/EIPS/eip-2767.md @@ -0,0 +1,7 @@ +--- +eip: 2767 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2767.md diff --git a/EIPS/eip-2770.md b/EIPS/eip-2770.md new file mode 100644 index 00000000000000..85c594e1ec4b01 --- /dev/null +++ b/EIPS/eip-2770.md @@ -0,0 +1,7 @@ +--- +eip: 2770 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2770.md diff --git a/EIPS/eip-2771.md b/EIPS/eip-2771.md new file mode 100644 index 00000000000000..4d87023ef42f2b --- /dev/null +++ b/EIPS/eip-2771.md @@ -0,0 +1,7 @@ +--- +eip: 2771 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2771.md diff --git a/EIPS/eip-2780.md b/EIPS/eip-2780.md new file mode 100644 index 00000000000000..9541073cd50dbe --- /dev/null +++ b/EIPS/eip-2780.md @@ -0,0 +1,425 @@ +--- +eip: 2780 +title: Reduce intrinsic transaction gas +description: Reduce intrinsic transaction gas and charge 25k when a value transfer creates a new account +author: Matt Garnett (@lightclient), Uri Klarman (@uriklarman), Ben Adams (@benaadams), Maria Inês Silva (@misilva73), Anders Elowsson (@anderselowsson), Anthony Sassano (@sassal) +discussions-to: https://ethereum-magicians.org/t/eip-2780-reduce-intrinsic-cost-of-transactions/4413 +status: Draft +type: Standards Track +category: Core +created: 2020-07-11 +requires: 1559, 2718, 2929, 2930 +--- + +## Abstract + +Reduce the intrinsic cost `TX_BASE_COST` from `21,000` to `4,500` and define a consistent gas accounting model based on actual state operations. This more granular approach makes a simple ETH transfer `6,000` from additional costs related to the `to` account. + +If a non-create transaction has `value > 0` and targets a non-existent account, charge `GAS_NEW_ACCOUNT = 25,000` to align with `CALL` account creation and price in state growth. When this surcharge applies, the recipient pays exactly one cold non-code touch; no code-load cost applies. + +This EIP does not change calldata or access-list metering. It also refines related gas schedule items used in derivation and execution accounting: + +- Split cold-account touches into `COLD_ACCOUNT_COST_CODE = 2,600` and `COLD_ACCOUNT_COST_NOCODE = 500`. +- Introduce `STATE_UPDATE = 1,000` as the price of a single account-leaf write. +- Reprice value-moving calls as account-leaf writes, replacing `CALL_VALUE_COST = 9,000` with `CALL_VALUE_COST = 2 * STATE_UPDATE = 2,000`. +- Specify that a `PAY`-style value-move primitive, if present, does not warm its recipient and never loads code (charged at `COLD_ACCOUNT_COST_NOCODE` if not already warmed). + +Capacity impact (illustrative): + +| Metric | Result | Change | Description | +| --------------------------- | ----------------: | ------: |------------------------------------------------------------- | +| Max (minimal txs) | 13,333 tx / block | +367% | 4,500-gas minimal transactions per 60 M block | +| Max (ETH transfers) | 10,000 tx / block | +250% | 6,000-gas ETH transfers per 60 M block | +| Thoughput (minimal txs) | ~1,111 TPS | +367% | 4,500-gas minimal transactions per 60 M block per 12sec | +| Thoughput (ETH transfers) | ~833 TPS | +250% | 6,000-gas ETH transfers per 60 M block per 12sec | +| Equivalent gas-limit uplift | ≈ +20.8% | - | Effective throughput gain for ave tx usage (e.g., 60 M => ~72.5 M) | + +## Motivation + +**Monetary Context** + +Money has three basic functions: a unit of account, a medium of exchange, and a store of value. ETH already meets the last two by design. It carries value without an issuer and settles with finality. Where it falls short is in everyday exchange - the friction of use rather than the nature of the asset. + +ETH underpins most onchain liquidity. Pairs are denominated in it, and gas is paid in it - a de-facto tax base that anchors value. Bitcoin's monetary role now runs mainly through exchange pairs, hence its drift in focus to store-of-value rather than medium-of-exchange. ETH still clears real activity onchain, yet outside NFTs few people think in ETH terms. In that niche ETH already functions as both unit and medium, but only for high-value items. + +For ETH to operate fully as money, it must also handle small transactions. That was impractical when gas sat at 300 gwei, or even 90 gwei on quiet weekends. Post-4844, blobs absorb L2's "pay at any price" data and higher gaslimits ease congestion; cost, not capacity, is the bottleneck. + +EIP-2780 lowers that fixed cost. By aligning the base gas with the real work of a transaction and by correcting `CALL` value pricing, it removes the legacy penalty on simple payments. Small transfers become viable again without subsidising calldata or storage. The same logic charges properly for new-account creation, so state growth remains priced in. + +- **Unit of account:** When transfers are cheap and regular, people price in ETH because they use it directly. This proposal turns that habit into equilibrium rather than idealism. + +- **Medium of exchange:** Reducing `TX_BASE_COST` eliminates the old friction that slowed native circulation. Settlement becomes frequent, not occasional. + +- **Store of value:** Honest pricing reinforces confidence that ETH's cost structure is grounded in real computation, not arbitrary constants. + +- **Velocity:** Lower friction raises the rate of final settlement; more frequent, smaller clears in native ETH, without altering calldata or storage economics. + +- **Monetary competition:** Stablecoins and LSTs are welcome, but they compete for onchain "moneyness". Making native ETH easy to spend keeps it central; not just the fuel, but the money of the system. + +**Note:** This proposal doesn't target ETH specifically, the lower base cost applies to every transaction type. However since `TX_BASE_COST` makes up nearly all of an ETH transfer's gas, while it's only a small fraction of contract calls, ETH loses the most friction and gains the most velocity. + +**Specifics** + +The legacy `21,000` base no longer matches the universal work path under warm/cold accounting. Decomposed into signature recovery, one account-leaf write for the sender (nonce + balance coalesced), and one cold non-code touch (sender), the universal path totals `4,500` gas. + +State growth is underpriced for top-level value transfers that create accounts, while `CALL` pays explicit creation. Charging `25,000` when a transfer creates an account aligns entry points and internalizes state growth. + +A lower base removes the distortion that over-incentivized batching solely to dodge `TX_BASE_COST`, without subsidizing calldata or storage. The refinement of value-transfer costs and cold-account pricing makes execution charges proportional to actual state work: account touches and leaf writes. + +We intentionally do **not** charge per-byte gas for the transaction envelope (`nonce`, `gas*`, `to`, `value`, `v`, `r`, `s`). Calldata pricing applies only to `tx.data`. A plain ETH payment has empty `tx.data`, so it pays zero calldata gas. Lowering `TX_BASE_COST` to the universal work path makes ETH payments cheaper without subsidizing arbitrary calldata. + +### Throughput, payload, and basefee dynamics + +This EIP affects three independent levers: + +1. **Gas-limit equivalence:** Reducing the base cost from `21,000` to `4,500` increases transaction capacity at a fixed block gaslimit by approximately +20.8%. + +2. **Payload-size bounds:** Per [EIP-7934](./eip-7934.md) the execution payload cap is `MAX_RLP_BLOCK_SIZE = 10,485,760 - 2,097,152 = 8,388,608` bytes. Payload size, not gas, may become the dominant block-size constraint at high gaslimits. + +3. **Basefee market dynamics:** Lower intrinsic gas reduces the average gas per tx, temporarily increasing utilisation and causing short-term downward adjustment in basefee. Over time, equilibrium restores as inclusion policies adapt. + +These levers are independent; this proposal changes only intrinsic gas, not calldata metering or access-list pricing. + +### Monetary Effects + +Reducing ETH transfer cost from `21,000` => `6,000` gas increases both transaction frequency and viable payment granularity. At a fixed basefee, smaller payments become economical, raising the **velocity of money** - how often ETH changes hands on L1. + +Let $g$ be gas per transaction, $b$ the basefee (in gwei), and $r$ the user's tolerated fee share of payment value. + +$v_{\text{min}} = \frac{g \times b \times 10^{-9}}{r}$ + +Since $g$ drops from $21,000$ to $6,000$: + +$\frac{v_{\text{min,new}}}{v_{\text{min,old}}} = \frac{6{,}000}{21{,}000} \approx 0.29$ + +The minimum economical L1 payment falls by about **71 %**, allowing more, smaller transfers to clear directly in ETH. + +From the quantity relation $M V = P Q$, with $M$ and $P$ roughly constant over short periods: + +$V_{\text{new}} / V_{\text{old}} \approx Q_{\text{new}} / Q_{\text{old}}$ + +Pure ETH-transfer capacity rises roughly **3.5x** (+250 %), and the lower $v_{\text{min}}$ further increases $Q$ as more small-value payments become viable. + +Together these effects lift $V$, more frequent, smaller, native settlements without changing monetary supply. + +ETH thus gains moneyness: + +- **Medium of exchange:** direct use becomes routine, not exceptional. +- **Unit of account:** frequent native settlement encourages ETH-denominated pricing. +- **Store of value:** workload-based fees reinforce trust in cost realism. + +Price volatility may still lead users to prefer stablecoins for predictability, but this change removes unnecessary friction, restoring ETH’s competitiveness wherever volatility is tolerable. + +The `25,000` surcharge for new-account creation continues to price state growth honestly while everyday transfers become cheaper and faster. + +### Equivalent gas-limit increase + +Lowering `TX_BASE_COST` from `21,000` to `4,500` removes up to `16,500` gas per transaction. Using recent totals of 163 Ggas/day and 1.7 M tx/day: + +| Metric | Calculation | Result | Change | +| ---------------------------- | ---------------:| ---------------:| ---------:| +| Avg gas per tx | 163Bn / 1.7M | ≈ 95,882 gas | - | +| New avg gas per tx | 95,882 − 16,500 | ≈ 79,382 gas | - | +| Throughput at fixed gaslimit | 95,882 / 79,382 | ≈ x1.208 | +20.08% | +| Daily tx at same gas usage | 1.7M × 1.208 | ≈ 2.053M tx/day | +340k/day | + +Perfnet measurements show EL clients handle >300 MGas/s for pure ETH transfers. Expressed under a 4.5k base this corresponds to `300 * (4.5/21) ~ 64.3 MGas/s`, i.e. `~771 MGas` per 12 s slot. This indicates sufficient headroom and that the current base is significantly overcharged, so no extra engineering is required to improve performance to support this change. + +Net effect equals raising a 45 M gas limit to ~54.4 M at unchanged calldata and access-list metering. This directly advances Scaling L1. + +## Specification + +After `FORK_BLOCK`, set the following parameters and rules: + +### Parameters + +| Name | Value | Description | +| -------------------------- | -----: | ----------------------------------------------------------------------- | +| `TX_BASE_COST` | 4,500 | Base cost of any transaction | +| `GAS_NEW_ACCOUNT` | 25,000 | Surcharge when a value-transferring transaction creates a new account | +| `STATE_UPDATE` | 1,000 | One account-leaf write in the account trie (nonce and balance coalesce) | +| `COLD_ACCOUNT_COST_CODE` | 2,600 | Cold touch of an account with code | +| `COLD_ACCOUNT_COST_NOCODE` | 500 | Cold touch of an account known to have no code | +| `WARM_STATE_READ` | 100 | Touch of an already-warm account (same as `WARM_STORAGE_READ_COST`) | + +The intrinsic gas accounting defined here overrides [EIP-2929](./eip-2929.md)'s blanket "all tx addresses are warm" rule. + +A transaction’s intrinsic base is decomposed into explicit primitives, so warmth must be priced explicitly. + +- `tx.sender` is charged as a cold non-code account (`COLD_ACCOUNT_COST_NOCODE = 500`), representing the first access and coalesced account-leaf update. + +- `tx.to` is charged based on its type: + + - if a contract create, charge under those rules. + + - if an EOA or an empty account, use `COLD_ACCOUNT_COST_NOCODE = 500`. + + - if a contract, use `COLD_ACCOUNT_COST_CODE = 2,600`. + + - if a precompile, it is warm at tx start and charged zero. + +- Warmth discovered through an access list still applies and overrides the cold cost. + +This decomposition replaces the implicit warmth assumptions of [EIP-2929](./eip-2929.md) and makes the per-account cost explicit in the base or the execution phase as appropriate. + +Notes: + +- `STATE_UPDATE` counts writes at the account-leaf granularity. If a single account's nonce and balance both change in one transition, charge one `STATE_UPDATE`. +- `COLD_ACCOUNT_COST_NOCODE` reflects that non-code accounts do not load code or a storage trie, so have a lower warming cost. +- A regular ETH transfer additionally includes a cold touch of at least `COLD_ACCOUNT_COST_NOCODE` and a `STATE_UPDATE` of the `to` address, so the effective minimal productive tx cost is `6,000`. +- Not including the `to` cold warming and `STATE_UPDATE` in `TX_BASE_COST` means a contract-interaction transaction that does not transfer value does not unnecessarily pay these additional costs. + +### Derivation (non-normative) + +Decomposition of the base cost into universal primitives: + +| Component | Cost | Notes | +| ------------------------ | --------: | -------------------------------------------------- | +| ECRECOVER | 3,000 | Elliptic curve signature recovery | +| STATE_UPDATE | 1,000 | One account-leaf write (nonce + balance coalesced) | +| COLD_ACCOUNT_COST_NOCODE | 500 | Sender is cold and has no code | +| **TX_BASE_COST** | **4,500** | Sum of above (3,000 + 1,000 + 500) | + + +### New-account surcharge + +Apply `GAS_NEW_ACCOUNT` when **all** are true: + +1. The transaction is not a `CREATE` transaction. +2. `value > 0`. +3. `to` is not a precompile. +4. `to` is non-existent per [EIP-161](./eip-161.md) emptiness at the start of transaction execution. + +The `GAS_NEW_ACCOUNT = 25,000`charge covers state growth (new leaf creation and one `STATE_UPDATE`). +An additional `COLD_ACCOUNT_COST_NOCODE = 500` applies for the initial lookup to determine that the account does not exist. + +Thus, the **total** intrinsic gas for a value-transferring transaction to a new account is `30,000` (`4,500 base + 500 lookup + 25,000 new-account surcharge`). + +For reference, the **total** charges for such transfers change from 21,000 to 30,000. + +| Component | Cost | Notes | +| ------------------------ | ----------:| ---------------------------------------- | +| TX_BASE_COST | 4,500 | Base transaction cost | +| COLD_ACCOUNT_COST_NOCODE | 500 | Recipient cold lookup (execution charge) | +| GAS_NEW_ACCOUNT | 25,000 | Account creation, includes leaf write | +| **Total** | **30,000** | Sum of above (4,500 + 500 + 25,000) | + +Notes: + +- If `value = 0` and `to` is empty per [EIP-161](./eip-161.md), no account is created and no surcharge applies. +- `CREATE` transactions are unchanged; their cost already includes account creation. + +### Intrinsic gas computation + +Clients compute intrinsic gas as today for each typed transaction **except**: + +- Replace any hardcoded `21,000` with `TX_BASE_COST = 4,500`. +- Add `GAS_NEW_ACCOUNT` when the *New-account surcharge* conditions hold. + +### Pseudocode (normative): + +```python +def CalculateIntrinsicGas(tx, state_at_start): + gasCost = TX_BASE_COST + + # Existing rules for calldata and access lists remain unchanged by this EIP. + gasCost += GasForCalldata(tx.data) # per active calldata pricing EIPs + if tx.has_access_list(): + gasCost += GasForAccessList(tx.access_list) # per EIP-2930 + + if tx.is_create() == False + and tx.value > 0 + and is_precompile(tx.to) == False + and is_nonexistent_per_eip161(state_at_start, tx.to): + gasCost += GAS_NEW_ACCOUNT + + return gasCost +``` + +### EVM gas schedule adjustments + +These changes refine execution-layer accounting to align with the primitives above. + +- **Value-moving calls.** Replace the legacy `CALL_VALUE_COST = 9,000` with: + + - If recipient exists: `CALL_VALUE_COST = 2 * STATE_UPDATE = 2,000`. + - If recipient is EIP-161-empty: `CALL_VALUE_COST = STATE_UPDATE + GAS_NEW_ACCOUNT = 26,000`. + - This charge is in addition to warm/cold account-touch costs per EIP-2929 and the existing `CALL` base cost. This EIP does not modify the `CALL` base cost. + + The `CALL_VALUE_COST = 2,000` applies for all value-carrying calls, regardless of whether the callee's account has already been updated earlier in the same transaction. This ensures the 2300-gas stipend mechanism remains safe and consistent for simple value forwarding and does not retroactively depend on account-update history. + +- **Cold-account touches.** + + - Use `COLD_ACCOUNT_COST_CODE = 2,600` when touching an account with code. + - Use `COLD_ACCOUNT_COST_NOCODE = 500` when touching an account known to have no code. + +- **Warmth policy.** + + - Access-list entries (charged via [EIP-2930](./eip-2930.md)) and precompiles are warm at tx start. + - `CALL` warms its `to` after charging the appropriate cold cost if cold. + - A `PAY`-style pure value-move primitive, if present, does not warm its recipient and never loads code. It pays `WARM_STATE_READ = 100` if warm for unrelated reasons, else `COLD_ACCOUNT_COST_NOCODE = 500`, plus the value-write cost above. + +- **Self-transfers.** If `from == to`, only one `STATE_UPDATE` occurs. The sender's nonce and balance update are coalesced into the same leaf write. No recipient lookup or separate write is charged. (Is a NOP tx other than charging gas and incrementing nonce). + +### Transaction reference cases + +| Case | Formula | Total Cost | +| ----------------------------------- | ---------------------------------------------------------------- | -------------------------:| +| (NOP) No-transfer to EOA | `TX_BASE_COST` | 4,500 | +| (NOP) No-transfer to empty account | `TX_BASE_COST` | 4,500 | +| (NOP) ETH transfer to self | `TX_BASE_COST` | 4,500 | +| ETH Transfer to existing EOA | `TX_BASE_COST` + `COLD_ACCOUNT_COST_NOCODE` + `STATE_UPDATE` | 6,000 | +| No-transfer to contract | `TX_BASE_COST` + `COLD_ACCOUNT_COST_CODE` + **execution** | 7,100 + **execution** | +| ETH Transfer to contract | `TX_BASE_COST` + `COLD_ACCOUNT_COST_CODE` + `STATE_UPDATE` + **execution** | 8,100 + **execution** | +| ETH Transfer creating new account | `TX_BASE_COST` + `COLD_ACCOUNT_COST_NOCODE` + `GAS_NEW_ACCOUNT` | 30,000 | + +This aligns costs with actual state work rather than legacy flat surcharges. + +### Edits and interactions with other EIPs + +- **[EIP-2930](./eip-2930.md) (Access List).** Intrinsic gas is `TX_BASE_COST` after `FORK_BLOCK`. Access lists keep their existing per-entry charges and warming semantics. +- **[EIP-2929](./eip-2929.md) (Gas cost increases for state access).** Refined by this EIP to price non-code cold touches at `500` and code-account cold touches at `2,600`. +- **[EIP-7702](./eip-7702.md) (Set EOA Code).** `TX_BASE_COST` remains `4,500` even if the sender temporarily assumes code for the transaction. Clients must not perform any disk code-load to determine sender type, since 7702 provides code inline. If the transaction executes code that reads or executes its own code, normal `COLD_ACCOUNT_COST_CODE` or `WARM_STATE_READ` costs apply at execution time as per the standard cold/warm model. +- **Calldata-pricing EIPs (e.g. [EIP-7623](./eip-7623.md)).** Unchanged. This EIP does not alter calldata pricing. + +## Rationale + +Price only what every transaction always does: ECDSA recovery, warming `sender` and `to`, and one account-leaf write for the sender (nonce + balance change). That sums to `4,500` gas. Anything not universal should be metered separately. + +Calldata remains metered per byte. No calldata allowance is folded into the base. This reinforces ETH as money and payments: a plain ETH transfer carries no calldata, executes no bytecode, and touches no contract storage slots. It adds exactly one recipient touch (when not a smart contract) and one recipient leaf write, so its total is `6,000`. + +`CREATE` is unchanged because its cost already includes account creation. Access-list pricing is unchanged. + +Legacy pricing undercharged top-level ETH transfers that created new accounts relative to internal `CALL`-based creations. This EIP corrects that by charging `GAS_NEW_ACCOUNT = 25,000`, identical to the `CALL` account-creation surcharge, ensuring consistent pricing for state growth regardless of entry path. + +This removes cross-subsidies, aligns charges with resources, and keeps costs equal across paths that perform the same state growth. + +Do not fold any calldata allowance into the base. The envelope RLP (`nonce`, `gas*`, `to`, `value`, `v`, `r`, `s`) is not charged as calldata and remains unmetered per byte. Only `tx.data` bytes are metered at the existing calldata schedule, and access lists keep their per-entry costs. A vanilla ETH transfer executes no bytecode and touches no contract storage slots; it performs signature recovery, warms the sender, and updates sender and recipient accounts. It therefore receives the base discount and pays only the additional recipient costs. + +Bundling multiple transfers into a single contract call avoids repeated `TX_BASE_COST`, but those transfers then execute serially inside one EVM context. That blocks parallel execution. With a lower per-tx base cost, users have less incentive to bundle, so more transfers remain independent transactions. Independent transactions can be scheduled across threads, which improves parallelism at the client and execution-layer level. + +Thus, reducing `TX_BASE_COST` not only corrects mispricing but also increases the share of transactions that are naturally parallelizable. + +This EIP composes cleanly with calldata-pricing proposals such as [EIP-7623](./eip-7623.md) and [EIP-7976](./eip-7976.md). Those EIPs affect `tx.data` metering, while this EIP adjusts only transaction-level intrinsic accounting. There is no overlapping scope. + +### Why not charge full tx data as calldata? + +- **Intrinsic coupling to signed fields.** Pricing full-transaction bytes would make intrinsic gas depend on `gas_limit` and variable-length signature elements, creating fixed-point estimation issues and incentives for signature-length selection as well as iteration unstablity as `gas_limit` depends on signiture which contains `gas_limit`. + +- **Serialization neutrality.** A fee rule keyed to RLP size couples costs to one encoding and weakens [EIP-2718](./eip-2718.md) type neutrality and future formats such as SSZ. Calldata is treated as opaque bytes so it avoids this coupling. + +- **Policy targeting and market floor.** Calldata floors (for example [EIP-7623](./eip-7623.md) or [EIP-7976](./eip-7976.md)) price bytes in `tx.data` to bound EL payload and steer data to blobs; envelope bytes are control-plane. The `TX_BASE_COST` is the smallest tx size, and having a low encoding-agnostic intrinsic base keeps the minimum inclusion price coupled to the basefee market, without opening a DoS vector. + +- **Native settlement and unit-of-account.** Even though all transactions receive the same absolute gas reduction, it proportionally improves pristine ETH transfers more. With an ETH transfer at ~6,000 gas vs a permissioned ERC-20/LST/stablecoin transfer at ~48,000 gas, you get ~8x higher payment throughput per unit gas, which reinforces ETH as the settlement asset and reduces reliance on contract-based money (which carries smart contract risk, operator risk, governance risk and censorship risks via smart contract operator). + +![Figure 1](../assets/eip-2780/1.png) + +### Effects on transactions per block + +For execution-payload size, use [EIP-7934](./eip-7934.md)’s 8 MiB uncompressed cap: `8,388,608 bytes`. A typical EIP-1559 ETH transfer encodes at roughly `~110 bytes`, yielding a size cap of `floor(8,388,608 / 110) = 76,260 tx` per block when size, not gas, is the binding constraint. + +There are two useful ceilings to consider: + +- Minimal transaction with no value and no execution: `TX_BASE_COST = 4,500` gas. +- Minimal ETH payment to an existing EOA: `6,000` gas (`TX_BASE_COST + COLD_ACCOUNT_COST_NOCODE + STATE_UPDATE`). + +Counts below are `floor(gaslimit / per-tx-gas)`, then capped by `76,260` when the 8 MiB size limit binds. TPS figures round to the nearest integer. + +#### Scenario A: minimal txs at 4,500 gas + +Binding point for size-cap dominance: `76,260 * 4,500 = 343,170,000` gas. At gaslimits above ~343.17 M, block size, not gas, limits the tx count for 4,500-gas transactions. + +| Block gaslimit | Old tx/bk (21k) | New tx/bk (4.5k) | TPS @ 12s | TPS @ 6s | TPS @ 3s | TPS @ 1.5s | +| -------------: | --------------: | ---------------: | --------: | -------: | -------: | ---------: | +| 45 M | 2,142 | 10,000 | 833 | 1,667 | 3,333 | 6,667 | +| 60 M | 2,857 | 13,333 | 1,111 | 2,222 | 4,444 | 8,889 | +| 100 M | 4,761 | 22,222 | 1,852 | 3,704 | 7,407 | 14,815 | +| 200 M | 9,523 | 44,444 | 3,704 | 7,407 | 14,815 | 29,629 | +| 450 M | 21,428 | †76,260 | 6,355 | 12,710 | 25,420 | 50,840 | + + † Size cap binds at 450 M because 450 M > 343.17 M. + +#### Scenario B: ETH transfers at 6,000 gas + +Binding point for size-cap dominance: `76,260 * 6,000 = 457,560,000` gas. At gaslimits below ~457.56 M, gas limits tx count; above it, the 8 MiB size cap dominates. + +| Block gaslimit | Old tx/bk (21k) | New tx/bk (6k) | TPS @ 12s | TPS @ 6s | TPS @ 3s | TPS @ 1.5s | +| -------------: | --------------: | -------------: | --------: | -------: | -------: | ---------: | +| 45 M | 2,142 | 7,500 | 625 | 1,250 | 2,500 | 5,000 | +| 60 M | 2,857 | 10,000 | 833 | 1,667 | 3,333 | 6,667 | +| 100 M | 4,761 | 16,666 | 1,389 | 2,778 | 5,555 | 11,111 | +| 200 M | 9,523 | 33,333 | 2,778 | 5,556 | 11,111 | 22,222 | +| 450 M | 21,428 | 75,000 | 6,250 | 12,500 | 25,000 | 50,000 | + +#### Changes for common types of txs + +| Transaction Type | Old Cost | New Cost | Change | +| ---------------------------------- | -------: | -------: | -----: | +| Simple ETH transfer (existing EOA) | 21,000 | 6,000 | −71 % | +| ETH transfer creating new EOA | 21,000 | 30,000 | +43 % | +| ERC-20 transfer (typical) | 63,200 | 48,200 | −24 % | +| ERC-20 transfer (Solady) | 33,400 | 18,400 | −45 % | +| Uniswap v3 swap | 184,500 | 169,500 | −8 % | +| Uniswap v3 add-liquidity | 216,900 | 201,900 | −7 % | + + +#### Reference MGas/s for gaslimit vs slot time + +| Block gaslimit | MGas/s @ 12s | MGas/s @ 6s | MGas/s @ 3s | MGas/s @ 1.5s | +| -------------: | -----------: | ----------: | ----------: | ------------: | +| 45 M | 3.75 | 7.50 | 15.00 | 30.00 | +| 60 M | 5.00 | 10.00 | 20.00 | 40.00 | +| 100 M | 8.33 | 16.67 | 33.33 | 66.67 | +| 200 M | 16.67 | 33.33 | 66.67 | 133.33 | +| 450 M | 37.50 | 75.00 | 150.00 | 300.00 | + +## Backwards Compatibility + +This EIP is **not** backward compatible. It is a consensus gas repricing that must be activated at `FORK_BLOCK`. + +Wallets, RPCs, gas estimators, and any logic that assumes a `21,000` base must update. + +## Test Cases + +While the benefits of reducing transactions' intrinsic cost are apparent, such a change should be applied if it imposes no negative externalities, or if such effects are negligible. + +Tests should be created with blocks of just ETH transfers and tested on Perfnet across all EL clients to ensure the pricing is correct. + +Add explicit test vectors (intrinsic gas only): + +1. `value > 0` to an empty EOA (non-existent per EIP-161): intrinsic `30,000` (4,500 base + 500 + 25,000 surcharge). +2. `value > 0` to a precompile: intrinsic `4,500` (no surcharge; precompiles are warm at tx start). +3. `value = 0` to an empty address: intrinsic `4,500` (no creation, no surcharge). +4. `CREATE` transaction: unchanged from prior rules. +5. EIP-7702 transaction with and without access list: intrinsic uses `TX_BASE_COST` plus unchanged access-list costs. +6. Block of txs calling minimal gas contract execution with maximal contract size addresses (so VM is activated for every tx). +7. Warmth and access list interplay + - ETH transfer to existing EOA without access list: charge `COLD_ACCOUNT_COST_NOCODE = 500` for recipient lookup. + - Same transaction with recipient in access list: charge `WARM_STATE_READ = 100`. +8. 7702 interactions + - 7702 tx where sender assumes code and calls nothing: intrinsic = 4,500, no extra cold-code cost. + - 7702 tx where sender assumes code and executes self-code: charge `COLD_ACCOUNT_COST_CODE` when first loaded. +9. Precompile transfers + - `value > 0` to `0x01`–`0x09`: intrinsic = 4,500, no surcharge. +10. Self-transfer `from == to`: total = 4,500. +11. Internal CALL repricing + - Internal `CALL` to existing EOA with value: `CALL_VALUE_COST = 2,000` plus cold/warm costs. + - Internal `CALL` to EIP-161-empty: `CALL_VALUE_COST = 26,000`. +12. Zero-value edge cases `value = 0` to empty address: intrinsic = `4,500`. +13. Perfnet stress + - Fill block with minimal 4,500-gas tx and 6,000-gas ETH transfers; confirm gas vs byte-size binding per [EIP-7934](./eip-7934.md). +14. SELFDESTRUCT test: Create-and-destroy in one tx; confirm normal value-transfer costs apply, no deletion repricing. + +## Security Considerations + +As this significantly increases the max tx per block this carries risk. + +However this pricing should be the same as performing the component changes inside the transaction; and it factors in the additional costs from state growth which were not originally in the transaction base price. + +Current gaslimit testing mostly uses a block with a single transaction; so this should not cause unexpected load compared to what is already being tested. + +The semantics of `SELFDESTRUCT` remain unchanged. Following [EIP-6780](./eip-6780.md), only contracts created within the same transaction may be fully deleted. This EIP does not reprice or modify any `SELFDESTRUCT` side-effects. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2786.md b/EIPS/eip-2786.md new file mode 100644 index 00000000000000..2c8d944931ee6c --- /dev/null +++ b/EIPS/eip-2786.md @@ -0,0 +1,70 @@ +--- +eip: 2786 +title: Ethereum Provider Connect/Disconnect Events +author: Micah Zoltu (@MicahZoltu), Erik Marks (@rekmarks) +discussions-to: https://github.com/ethereum/EIPs/issues/2787 +status: Withdrawn +type: Standards Track +category: Interface +created: 2020-07-15 +requires: 2700 +--- + +## Simple Summary + +When an Ethereum Provider becomes connected or disconnected, it will emit a `connect`/`disconnect` event. + +## Abstract + +The Provider is said to be “connected” when it can service RPC requests to at least one chain. +The Provider is said to be “disconnected” when it cannot service RPC requests to any chain at all. +When the Provider switches from a "connected" state to a "disconnected" state, it will emit a `connect` event. +When the Provider switches from a "disconnected" state to a "connected" state, it will emit a `disconnect` event. + +## Motivation + +When an application is hooked up to an Ethereum provider, there is value in having the application be alerted of connect/disconnect events that may occur so the application can appropriately inform the user of the situation. +It is left up to the application to decide whether to listen in on these events, and how to handle them. + +## Specification + +### Definitions + +#### Connected + +The Provider is considered `connected` when it is able to service RPC requests to at least one chain. + +#### Disconnected + +The Provider is considered `disconnected` when it is unable to service RPC requests to any chain. + +### Events + +#### `connect` + +The Provider **MUST** emit a `connect` event to all attached [EIP-2700](./eip-2700.md) listeners if it transitions from a `disconnected` state to a `connected` state. +All attached listeners **MUST** be called with the parameter `{ chainId }`. +`chainId` **MUST** specify the integer ID of the connected chain encoded as a hexadecimal string. +If the Provider supports the `eth_chainId` JSON-RPC method or a derivation of it, then the `chainId` **MUST** match the return value of `eth_chainId`. +The Provider **MAY** call the attached listeners in any order. + +## Rationale + +This EIP is mostly a retrospective EIP meaning it codifies an already existing specification so there isn’t a lot of room for improving things such as by having a connect/disconnect event per chain. + +## Security Considerations + +The relationship between Ethereum Provider and client is a trusted one, where it is assumed that the user implicitly trusts the Ethereum Provider which is how it managed to get injected into the client, or the client expressly pulled in a connection to it. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + +## Appendix I: Examples + +```javascript +// connect +provider.on('connect', ({ chainId }) => { + console.log(`Provider connected to: ${chainId}`); +}); +``` diff --git a/EIPS/eip-2803.md b/EIPS/eip-2803.md new file mode 100644 index 00000000000000..4804c8d5aefb0a --- /dev/null +++ b/EIPS/eip-2803.md @@ -0,0 +1,50 @@ +--- +eip: 2803 +title: Rich Transactions +description: Support 'rich transactions' by allowing transactions from externally owned accounts to execute bytecode directly. +author: Micah Zoltu (@MicahZoltu) +discussions-to: https://ethereum-magicians.org/t/rich-transactions-via-evm-bytecode-execution-from-externally-owned-accounts/4025 +status: Stagnant +type: Standards Track +category: Core +created: 2020-07-18 +--- + +## Abstract +If a transaction has a `to` of address `x`, then the `data` of the transaction will be treated as EVM bytecode and it will be executed from the context of the `CALLER` of the transaction (aka: the transaction signer). + +## Motivation +Many Ethereum DApps presently require users to approve multiple transactions in order to produce one effect - for example, the common pattern of first approving a contract to spend a token, then calling that contract. This results in a poor user-experience, and complicates the experience of interacting with DApps. + +Making it possible for externally owned accounts to execute EVM bytecode directly allows a single transaction to execute multiple contract calls, allowing DApps to provide a streamlined experience, where every interaction results in at most one transaction. + +While this is in principle possible today using contract wallets, other UX issues, such as the need to fund a sending account with gas money, lack of support for contract wallets in browser integrations, and lack of a consistent API for contract wallets has led to poor adoption of these.This EIP is a way of enhancing the utility of existing EOAs, in the spirit of "don't let the perfect be the enemy of the good". + +## Specification +A new reserved address is specified at `x`, in the range used for precompiles. When a transaction is sent to this address from an externally owned account, the payload of the transaction is treated as EVM bytecode, and executed with the signer of the transaction as the current account. For clarity: + - The `ADDRESS` opcode returns the address of the EOA that signed the transaction. + - The `BALANCE` opcode returns the balance of the EOA that signed the transaction. + - Any `CALL` operations that send value take their value from the EOA that signed the transaction. + - `CALL` will set the `CALLER` to the EOA (not `x`). + - `DELEGATECALL` preserves the EOA as the owning account. + - The `CALLER` and `ORIGIN` opcodes both return the address of the EOA that signed the transaction. + - There is no code associated with the precompile address. `CODE*` and `EXTCODE*` opcodes behave the same as they do for any empty address. + - `CALLDATA*` opcodes operate on the transaction payload as expected. + - `SLOAD` and `SSTORE` operate on the storage of the EOA. As a result, an EOA can have data in storage, that persists between transactions. + - The `SELFDESTRUCT` opcode does nothing. + - All other opcodes behave as expected for a call to a contract address. + - The transaction is invalid if there is any value attached. + - A call to the precompile address from a contract has no special effect and is equivalent to a call to a nonexistent precompile or an empty address. + +## Rationale +The intent of this EIP is for the new precompile to act in all ways possible like a `DELEGATECALL` from an externally owned account. Some changes are required to reflect the fact that the code being executed is not stored on chain, and for special cases such as `SELFDESTRUCT`, to prevent introducing new edge-cases such as the ability to zero-out an EOA's nonce. + +A precompile was used rather than a new EIP-2718 transaction type because a precompile allows us to have a rich transaction with any type of EIP-2718 transaction. + +## Backwards Compatibility +This EIP introduces a new feature that will need to be implemented in a future hard fork. No backwards compatibility issues with existing code are expected. + +Contracts or DApps that assume that an EOA cannot atomically perform multiple operations may be affected by this change, as this now makes it possible for EOAs to execute multiple atomic operations together. The authors do not believe this is a significant use-case, as this 'protection' is already trivially defeated by miners. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2831.md b/EIPS/eip-2831.md new file mode 100644 index 00000000000000..3a07fba8b28848 --- /dev/null +++ b/EIPS/eip-2831.md @@ -0,0 +1,169 @@ +--- +eip: 2831 +title: Transaction Replacement Message Type +author: Gregory Markou (@GregTheGreek) +discussions-to: https://ethereum-magicians.org/t/eip-2831-transaction-replacement-message-type/4448 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-07-26 +requires: 1193 +--- + +## Summary + +An extension to the JavaScript Ethereum Provider API ([EIP-1193](./eip-1193.md)) this creates a new message type in the event a transaction replacement occurs. + +## Abstract + +The current communication between providers and consumers of providers are fundamentally broken in the event that a transaction in the mempool has been superseded by a newer transactions. Providers currently have no way of communicating a transaction replacement, and consumers are required to poll block by block for the resulting transaction. + +## Motivation + +Exert from EIP-1193 +> A common convention in the Ethereum web application ("dapp") ecosystem is for key management software ("wallets") to expose their API via a JavaScript object in the web page. +This object is called "the Provider". + +Many ingenious developments have been made by wallet developers to improve the overall user experience while interacting with the Ethereum blockchain. One specific innovation was transaction replacement, offering users the ability to effectively cancel a previously sent transaction. + +Transaction replacement is not a new concept, but unfortunately causes major user experience problems for dapp developers as the replaced transaction is near impossible to track. + +This EIP formalizes a way for both providers and dapp developers to track transaction replacements seamlessly. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC-2119](https://www.ietf.org/rfc/rfc2119.txt). + +### Definitions + +_This section is non-normative._ + +- Provider + - A JavaScript object made available to a consumer, that provides access to Ethereum by means of a Client. +- Wallet + - An end-user application that manages private keys, performs signing operations, and acts as a middleware between the Provider and the Client. +- Transaction Replacement + - Submitting a transaction with both: the same nonce and a 10% increase in the gas price, of a previous transaction which a user no longer wishes to send. This must occur before the original transaction is included in the blockchain. + +### Events + +These methods **MUST** be implemented per the Node.js [`EventEmitter` API](https://nodejs.org/api/events.html). + +The following three events must be implemented: `tx_replacement`, `tx_speedup` and `tx_cancel`. + +A `tx_speedup` is defined as a transaction replacement in which the user wishes to adjust the `gasPrice`, to potentially receive a fast block inclusion. For a `tx_speedup` to be considered valid, the replacement tx must contain the **same** following properties as the one it supersedes: +- Nonce +- To +- Value +- Data + +```typescript +interface txSpeedupInfo { + readonly oldTx: string; + readonly newTx: string; + readonly nonce: string; + readonly from: string; +} + +Provider.on('tx_speedup', listener: (txSpeedupInfo: txSpeedupInfo) => void): Provider; +``` +This event emits the old transaction hash (`oldTx`), the new transaction hash (`newTx`), the nonce used for both transactions (`nonce`), and the signing address for the transaction (`from`). + +A `tx_cancel` is defined as a transaction replacement in which the user wishes to nullify a previous transaction before its inclusion. For a `tx_cancel` to be considered valid, the replacement tx must contain the following properties: +- The same nonce as the superseded transaction +- The same From and To +- Zero value +- No data + +```typescript +interface txCancelInfo { + readonly oldTx: string; + readonly newTx: string; + readonly nonce: string; + readonly from: string; +} + +Provider.on('tx_cancel', listener: (txCancelInfo: txCancelInfo) => void): Provider; +``` +This event emits the old transaction hash (`oldTx`), the new transaction hash (`newTx`), the nonce used for both transactions (`nonce`), and the signing address for the transaction (`from`). + +A `tx_replacement` is defined as a transaction replacement in which a user has completely replaced a previous transaction with a completely brand new one. The replacement tx must contain the following properties: +- The same nonce as the superseded transaction + +```typescript +interface txReplacementInfo { + readonly oldTx: string; + readonly newTx: string; + readonly nonce: string; + readonly from: string; +} + +Provider.on('tx_replacement', listener: (txReplacementInfo: txReplacementInfo) => void): Provider; +``` +This event emits the old transaction hash (`oldTx`), the new transaction hash (`newTx`), the nonce used for both transactions (`nonce`), and the signing address for the transaction (`from`). + +## Rationale + +The implementation was chosen to help the ease of implementation for both providers and dapp developers. Since `ProviderMessage` is widely used by dapp developers already it means that the implementation path would be as trivial as adding and additional `if` clause to their existing message listener. This also provides a benefit to dapps in the event that a provider has not yet implemented the events, it will not cause the dapp panic with `undefined` should it be implemented natively (eg: `ethereum.txCancel(...)` which would error with `ethereum.txReplacement()` is not a function). + +## Backwards Compatibility + +Many Providers adopted EIP-1193, as this EIP extends the same event logic, there should be no breaking changes. All providers that do not support the new events should either I) Ignore the subscription or II) Provide some error to the user. + +## Implementations + +- [Web3.js](https://github.com/ethereum/web3.js/issues/3723) +- [MetaMask](https://github.com/MetaMask/metamask-extension/issues/9174) + +## Security Considerations + +None at the current time. + +## References + +- [Web3.js issue with metamask tx cancel](https://github.com/ethereum/web3.js/issues/3585) +- [Browser doesn't know when a transaction is replace](https://github.com/MetaMask/metamask-extension/issues/3347) + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + +## Appendix I: Examples + +These examples assume a web browser environment. + +```javascript +// Most Providers are available as window.ethereum on page load. +// This is only a convention, not a standard, and may not be the case in practice. +// Please consult the Provider implementation's documentation. +const ethereum = window.ethereum; + +const transactionParameters = { ... } // Fill in parameters + +ethereum + .request({ + method: 'eth_sendTransaction', + params: [transactionParameters], + }) + .then((txHash) => { + ethereum.on('tx_cancel', (info) => { + const { oldTx, newTx, nonce, from } = message.data; + console.log(`Tx ${oldTx} with nonce ${nonce} from ${from} was cancelled, the new hash is ${newTx}`) + }); + ethereum.on('tx_speedup', (info) => { + const { oldTx, newTx, nonce, from } = message.data; + console.log(`Tx ${oldTx} with nonce ${nonce} from ${from} was sped up, the new hash is ${newTx}`) + }); + ethereum.on('tx_replacement', (info) => { + const { oldTx, newTx, nonce, from } = message.data; + console.log(`Tx ${oldTx} with nonce ${nonce} from ${from} was replaced, the new hash is ${newTx}`) + }); + + + console.log(`Transaction hash ${txHash}`) + }) + .catch((error) => { + console.error(`Error sending transaction: ${error.code}: ${error.message}`); + }); + +``` diff --git a/EIPS/eip-2844.md b/EIPS/eip-2844.md new file mode 100644 index 00000000000000..6546ba3f79bc65 --- /dev/null +++ b/EIPS/eip-2844.md @@ -0,0 +1,132 @@ +--- +eip: 2844 +title: Add DID related methods to the JSON-RPC +author: Joel Thorstensson (@oed) +discussions-to: https://github.com/ethereum/EIPs/issues/2845 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-08-01 +--- + +## Simple Summary +Add new methods to the JSON-RPC for signing and decrypting JOSE objects under a new `did_*` prefix. + +## Abstract +This EIP describes three new methods to add to the JSON-RPC that enables wallets to support *Decentralized Identifiers* (DIDs) as well as *JSON Object Signing and Encryption* (JOSE). These standards enables wallets to support data decryption as well as authenticated data, both in standard formats using JOSE. With these new methods apps can request the DID from a users wallet, from which a DID document can be resolved. The DID document contains public keys that can be used for encryption and signature verification. This enables Alice to discover Bobs public keys by only knowing Bobs DID. This EIP does not enforce the user of any particular DID method or JOSE algorithms, wallets are free to implement these however they wish. + +## Motivation +There has been one main previous effort ([#130](https://github.com/ethereum/EIPs/issues/130), [#1098](https://github.com/ethereum/EIPs/pull/1098)) to add decryption to Ethereum wallets in a standard way. This previous approach used a non standard way to encode and represent data encrypted using `x25519-xsalsa20-poly1305`. While this approach does provide a functional way to add encryption support to wallets, it does not take into account similar work that has gone into standardizing the way encrypted data is represented, namely using [JOSE](https://datatracker.ietf.org/wg/jose/documents/). This is a standard from IETF for representing signed and encrypted objects. Another shortcoming of the previous approach is that it's impossible to retrieve the `x25519` public key from another user if only an Ethereum address is known. Public key discoverability is at the core of the work that is happening with the [W3C DID standard](https://w3c.github.io/did-core), where given a DID a document which contains public keys can always be discovered. Implementations of this standard already exist and are adopted within the Ethereum community, e.g. [`did:ethr`](https://github.com/decentralized-identity/ethr-did-resolver/) and [`did:3`](https://github.com/3box/3id-resolver). Interoperability between JOSE and DIDs [already exists](https://github.com/decentralized-identity/did-jwt), and work is being done to [strengthen it](https://github.com/decentralized-identity/did-jose-extensions). Adding support for JOSE and DIDs will enable Ethereum wallets to support a wide range of new use cases such as more traditional authentication using JWTs, as well as new emerging technologies such as [Secure Data Stores](https://identity.foundation/secure-data-store/) and [encrypted data in IPFS](https://github.com/ipld/specs/pull/269). + +## Specification +Three new JSON-RPC methods are specified under the new `did_*` prefix. + +### Auth + +Authenticate the current rpc connection to the DID methods. + +Prompt the user to give permission to the current connection to access the user DID and the given `paths`. + +##### Method: + +`did_authenticate` + +##### Params: + +* `nonce` - a random string used as a challenge +* `aud` - the intended audience of the authentication response +* `paths` - an array of strings + +##### Returns: + +A JWS with general serialization containing the following properties: + +* `nonce ` - the random string which was given as a challenge + +* `did` - the DID which authentication was given for +* `paths` - the paths which was given permission for +* `exp` - a unix timestamp after which the JWS should be considered invalid +* `aud` - optional audience for the JWS, should match the domain which made the request + +An additional property `kid` with the value which represents the DID, and the `keyFragment` that was used to sign the JWS should be added to the protected header ([details](https://github.com/decentralized-identity/did-jose-extensions/issues/2)). + + +#### CreateJWS + +Creates a JSON Web Signature (JWS). + +An additional property `kid` with the value which represents the DID, and the `keyFragment` that was used to sign the JWS should be added to the protected header ([details](https://github.com/decentralized-identity/did-jose-extensions/issues/2)). When `revocable` is set to false the JWS signature should not be possible to revoke. For some DID methods like. `did:key` this is always the case. For other methods which support key revocation it is necessary to include the `version-id` in the `kid` to refer to a specific version of the DID document. When `revocable` is set to true `version-id` must not be included in the `kid` for DID methods that support key revocation. + +##### Method: + +`did_createJWS` + +##### Params: + +* `payload` - the payload to sign, json object or `base64url` encoded string +* `protected` - the protected header, json object +* `did` - the DID that should sign the message, may include the key fragment, string +* `revocable` - makes the JWS revocable when rotating keys, boolean default to `false` + +##### Returns: + +An object containing a JWS with general serialization on the `jws` property. + +##### Recommendation: + +Use `secp256k1` for signing, alternatively `ed25519`. + + + +#### DecryptJWE + +Decrypt the given JWE. + +If the cleartext object contains a property `paths` that contains an array of strings and one of the paths in there are already authenticated using `did_authenticate` the decryption should happen without user confirmation. + +##### Method: + +`did_decryptJWE` + +##### Params: + +* `jwe` - a JWE with general serialization, string +* `did` - the DID that should try to decrypt the JWE, string + +##### Returns: + +An object containing the cleartext, encoded using [`base64pad`](https://github.com/multiformats/multibase), assigned to the `cleartext` property. + +##### Recommendation: + +Implement decryption using `xchacha20poly1305` and `x25519` for key agreement. + + + +## Rationale +This EIP chooses to rely on DIDs and JOSE since there is already support for these standards in many places, by current systems and new systems. By using DIDs and JOSE wallet implementers can also choose which signing and encryption algorithms that they want to support, since these formats are fairly agnostic to specific crypto implementations. + +### Permission system + +A simple permission system is proposed where clients can request permissions though path prefixes, e.g. `/some/permission`. When decryption of a JWE is requested the wallet should check if the decrypted payload contains a `paths` property. If this property doesn't exist the user may be prompted to confirm that the given rpc connection (app) is allowed to read the decrypted data. If the `paths` property is present in the decrypted data it should contain an array of string paths. If one of the these path prefixes matches with one of the path prefixes the user has already granted permission for then decryption should happen automatically without any user confirmation. + +This simple permission system was inspired by some previous comments ([1](https://github.com/ethereum/EIPs/issues/130#issuecomment-329770999), [2](https://medium.com/@wighawag/3-proposals-for-making-web3-a-better-experience-974f97765700)) but avoids data lock in around origins. + +## Implementation + +[IdentityWallet](https://github.com/3box/identity-wallet-js/): An implementation of the wallet side `did_*` methods using the 3ID DID. + +[key-did-provider-ed25519](https://github.com/ceramicnetwork/key-did-provider-ed25519): An implementation of the wallet side `did_*` methods using the `did:key` method. + +[js-did](https://github.com/ceramicnetwork/js-did): A small library which consumes the `did_*` methods. + +[MinimalCipher](https://github.com/digitalbazaar/minimal-cipher): An implementation of DID related encryption for JWE. + +## Security Considerations + +Both JOSE and DIDs are standards that have gone though a lot of scrutiny. Their security will not be considered in this document. In the specification section, recommendations are given for which algorithms to use. For signatures `secp256k1` is already used by ethereum and for decryption `xchacha20poly1305` is widely available, very performant, and already used in TLS. + +The main security consideration of this EIP is the suggested permission system. Here various threat models could be considered. However, this EIP does not go into details about how it should work other than suggesting an approach. In the end it is up to wallet implementations to choose how to ask their users for consent. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2848.md b/EIPS/eip-2848.md new file mode 100644 index 00000000000000..e1bf77a5c8cf0e --- /dev/null +++ b/EIPS/eip-2848.md @@ -0,0 +1,7 @@ +--- +eip: 2848 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2848.md diff --git a/EIPS/eip-2876.md b/EIPS/eip-2876.md new file mode 100644 index 00000000000000..0edca2a8be05ce --- /dev/null +++ b/EIPS/eip-2876.md @@ -0,0 +1,7 @@ +--- +eip: 2876 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2876.md diff --git a/EIPS/eip-2917.md b/EIPS/eip-2917.md new file mode 100644 index 00000000000000..8ff04516b1ce20 --- /dev/null +++ b/EIPS/eip-2917.md @@ -0,0 +1,7 @@ +--- +eip: 2917 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2917.md diff --git a/EIPS/eip-2926.md b/EIPS/eip-2926.md new file mode 100644 index 00000000000000..2c3c199b3cd72c --- /dev/null +++ b/EIPS/eip-2926.md @@ -0,0 +1,148 @@ +--- +eip: 2926 +title: Chunk-Based Code Merkleization +description: Introduce code-chunking in an MPT context. +author: Sina Mahmoodi (@s1na), Alex Beregszaszi (@axic), Guillaume Ballet (@gballet), Jochem Brouwer (@jochem-brouwer), Ignacio Hagopian (@jsign) +discussions-to: https://ethereum-magicians.org/t/eip-2926-chunk-based-code-merkleization/4555 +status: Draft +type: Standards Track +category: Core +created: 2020-08-25 +requires: 161, 170 +--- + +## Abstract + +Code merkleization, along with binarification of the trie and gas cost bump of state-accessing opcodes, are considered as the main levers for decreasing block witness sizes in stateless or partial-stateless Eth1x roadmaps. Here we specify a fixed-sized chunk approach to code merkleization and outline how the transition of existing contracts to this model would look like. + +## Motivation + +Bytecode is currently the second contributor to block witness size, after the proof hashes. Transitioning the trie from hexary to binary reduces the hash section of the witness by 3x, thereby making code the first contributor. By breaking contract code into chunks and committing to those chunks in a merkle tree, stateless clients would only need the chunks that were touched during a given transaction to execute it. + +## Specification + +What follows is structured to have two sections: + +1. How a given contract code is split into chunks and then merkleized +2. How to merkleize all existing contract codes during a hardfork + +### Constants and Definitions + +#### Constants + +- `CHUNK_SIZE`: 31 (bytes) +- `VERSION_KEY`: `max(u256)` +- `VERSION`: 0 +- `EMPTY_CODE_ROOT`: `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` (==`keccak256('')`) +- `HF_TIMESTAMP`: to be defined +- `ITERATOR_STRIDE`: `TBC` but based on verkle numbers, first devnets should use `50_000` + +#### Definitions + +- `BE(x, N)`: casts `x` to an unsigned integer of `N` bytes and returns its big-endian representation + +### Code merkleization + +For an account record `A` with code `C`, two extra optional fields are added: `A.codeSize` and `A.codeRoot`. `A.codeHash` is retained to serve `EXTCODEHASH`. + +If `C` is empty, i.e. in the case of an EoA, `A.codeRoot` and `A.codeSize` are omitted from the account's RLP. This is intended to limit the size overhead of this change. + +If `C` is not empty: + + - `A.codeSize = len(code)` + - `A.codeRoot` contains the root of `codeTrie`, a trie with the following leaves: + - Key: `VERSION_KEY`, value: `BE(VERSION, 1)` + - A list of code `chunks = [(FIO_0, code_0), ..., (FIO_n, code_n)]` which are derived from `C` as follows: + - `code_0 || ... || code_n == C`. + - `length(code_i) == CHUNK_SIZE` where `0 <= i < n`. + - `length(code_n) <= CHUNK_SIZE`. + - `FIO_i` is the offset of the first instruction within the chunk. It should only be greater than zero if the last instruction in `code_i-1` is a multi-byte instruction (like `PUSHN`) crossing the chunk boundary. It is set to `CHUNK_SIZE` in the case where all bytes of a chunk are data. + +The `i`th element of `chunks` is stored in `codeTrie` with: + +- Key: `BE(i, 4)` +- Value: `BE(FIO_i, 1) || code_i`, where `||` stands for byte-wise concatenation + +#### Contract creation gas cost + +As of now there is a charge of 200 gas per byte of the code stored in state by contract creation operations, be it initiated via `CREATE`, `CREATE2`, or an external transaction. This per byte cost is to be increased from `200` to `500` to account for the chunking and merkleization costs. This number is inherited from [EIP-4762](./eip-4762.md) and is picked for forward-compatibility. + +### Updating existing code (transition process) + +The transition process involves reading all contracts in the state and applying the above procedure to them. A process similar to [EIP-7612](./eip-7612.md) is to be used, as the total code size at the time of this EIP edit is >10GB and can not be processed in a single block. + +Note that: + + - Because multiple accounts can share the same code hash, the whole account tree needs to be iterated over to convert each account. Only iterating over the bytecodes isn't enough. + - Nonetheless, the conversion process should take a few hours, instead of days for a full tree change. + +At `HF_TIMESTAMP` the EIP gets activated: + + - any contract creation and 7702 delegation updates must use the new format. + - for 7702 accounts, the code size is set to `23`, and `CODESIZE`/`CODECOPY` are forwarded to the delegated account. `EXTCODESIZE`/`EXTCODEHASH`/`EXTCODECOPY` behave the same as they did before the activation of this EIP. + - accounts are NOT converted in case of a balance or nonce update: accounts are converted by the iterator sweep or automatically at creation time. + - at the end of block processing, and after all transactions have been executed but before recomputing the tree root hash, the client iterates over `ITERATOR_STRIDE` accounts in the tree, and for each account: + - if the account has empty code, or is a contract using the new format, leave that account untouched, + - if the account is a "legacy" contract, convert it and write it back to the tree + +The value for `ITERATOR_STRIDE` has been chosen to be safe while ensuring the transition process does not last too long. At the current state size and block time, this represents about 10000 blocks, which is about one and a half day. + +Following the transition process described in [EIP-8032](./eip-8032.md), the transition process uses a system contract to store its progress pointers. The transition process has been designed in such a way that if both EIPs are activated at the same time, their transition process can be merged. Refer to that EIP for more details. + +Note that for a bytecode used by multiple contracts, the chunking need happen only once. Such contract only need to update their code size and code root, which MAY be cached during the transition process. + +## Rationale + +### Hexary vs binary trie + +The trie format is chosen to be the same as that of the account trie. If a tree conversion happens at a later stage, the chunk tree will have to be converted as well, e.g. the way it is in [EIP-6800](./eip-6800.md) or [EIP-7864](./eip-7864.md). + +### Chunk size + +The current recommended chunk size of 31 bytes has been selected based on a few observations. Smaller chunks are more efficient (i.e. have higher chunk utilization), but incur a larger hash overhead (i.e. number of hashes as part of the proof) due to a higher trie depth. Larger chunks are less efficient, but incur less hash overhead. We plan to run a larger experiment comparing various chunk sizes to arrive at a final recommendation. + +### First instruction offset + +The `firstInstructionOffset` field allows safe jumpdest analysis when a client doesn't have all the chunks, e.g. a stateless clients receiving block witnesses. + +Note: there could be an edge case when computing FIO for the chunks where the data bytes at the end of a bytecode (last chunk) resemble a multi-byte instruction. This case can be safely ignored. + +### Gas cost of code-accessing opcodes + +Details of how the code is stored, is left to the client implementers. However, to reflect the removal of the max code limit and the fact that larger codes will be more expensive to load, reading a non-accessed chunk will incur a 200 warming cost, and chunks written beyond the 24kb limit will cost 500 gas instead of 200. + +### Different chunking logic + +We have considered an alternative option to package chunks, where each chunk is prepended with its `chunkLength` and would only contain complete opcodes (i.e. any multi-byte opcode not fitting the `CHUNK_SIZE` would be deferred to the next chunk). + +This approach has downsides compared to the one specified: + +1) Requires a larger `CHUNK_SIZE` -- at least 33 bytes to accommodate the `PUSH32` instruction. +2) It is more wasteful. For example, `DUP1 PUSH32 <32-byte payload>` would be encoded as two chunks, the first chunk contains only `DUP1`, and the second contains only the `PUSH32` instruction with its payload. +3) Calculating the number of chunks is not trivial and would have to be stored explicitly in the metadata. + +Additionally we have reviewed many other options (basic block based, Solidity subroutines (requires determining the control flow), EIP-2315 subroutines). This EIP however only focuses on the chunk-based option. + +## Backwards Compatibility + +From the perspective of contracts, the design aims to be transparent, with the exception of changes in gas costs. + +Outside of the interface presented for contracts, this proposal introduces major changes to the way contract code is stored, and needs a substantial modification of the Ethereum state. Therefore it can only be introduced via a hard fork. + +## Test Cases + +TBD + +Show the `codeRoot` for the following cases: + +1. `code=''` +2. `code='PUSH1(0) DUP1 REVERT'` +3. `code='PUSH32(-1)'` (data passing through a chunk boundary) + +## Security Considerations + +TBA + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2929.md b/EIPS/eip-2929.md new file mode 100644 index 00000000000000..0e11417265a623 --- /dev/null +++ b/EIPS/eip-2929.md @@ -0,0 +1,172 @@ +--- +eip: 2929 +title: Gas cost increases for state access opcodes +author: Vitalik Buterin (@vbuterin), Martin Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/eip-2929-gas-cost-increases-for-state-access-opcodes/4558 +status: Final +type: Standards Track +category: Core +created: 2020-09-01 +--- + +## Simple Summary + +Increases gas cost for `SLOAD`, `*CALL`, `BALANCE`, `EXT*` and `SELFDESTRUCT` when used for the first time in a transaction. + +## Abstract + +Increase the gas cost of `SLOAD` (`0x54`) to 2100, and the `*CALL` opcode family (`0xf1`, `f2`, `f4`, `fA`), `BALANCE` `0x31` and the `EXT*` opcode family (`0x3b`, `0x3c`, `0x3f`) to 2600. Exempts (i) precompiles, and (ii) addresses and storage slots that have already been accessed in the same transaction, which get a decreased gas cost. Additionally reforms `SSTORE` metering and `SELFDESTRUCT` to ensure "de-facto storage loads" inherent in those opcodes are priced correctly. + +## Motivation + +Generally, the main function of gas costs of opcodes is to be an estimate of the time needed to process that opcode, the goal being for the gas limit to correspond to a limit on the time needed to process a block. However, storage-accessing opcodes (`SLOAD`, as well as the `*CALL`, `BALANCE` and `EXT*` opcodes) have historically been underpriced. In the 2016 Shanghai DoS attacks, once the most serious client bugs were fixed, one of the more durably successful strategies used by the attacker was to simply send transactions that access or call a large number of accounts. + +Gas costs were increased to mitigate this, but recent numbers suggest they were not increased enough. Quoting [https://arxiv.org/pdf/1909.07220.pdf](https://arxiv.org/pdf/1909.07220.pdf): + +> Although by itself, this issue might seem benign, `EXTCODESIZE` forces the client to search the contract ondisk, resulting in IO heavy transactions. While replaying the Ethereum history on our hardware, the malicious transactions took around 20 to 80 seconds to execute, compared to a few milliseconds for the average transactions + +This proposed EIP increases the costs of these opcodes by a factor of ~3, reducing the worst-case processing time to ~7-27 seconds. Improvements in database layout that involve redesigning the client to read storage directly instead of hopping through the Merkle tree would decrease this further, though these technologies may take a long time to fully roll out, and even with such technologies the IO overhead of accessing storage would remain substantial. + +A secondary benefit of this EIP is that it also performs most of the work needed to make [stateless witness sizes](https://ethereum-magicians.org/t/protocol-changes-to-bound-witness-size/3885) in Ethereum acceptable. Assuming [a switch to binary tries](https://ethresear.ch/t/binary-trie-format/7621), the theoretical maximum witness size not including code size (hence "most of the work" and not "all") would decrease from `(12500000 gas limit) / (700 gas per BALANCE) * (800 witness bytes per BALANCE) ~= 14.3M bytes` to `12500000 / 2600 * 800 ~= 3.85M bytes`. Pricing for code access could be changed when code merklization is implemented. + +In the further future, there are similar benefits in the case of SNARK/STARK witnesses. Recent numbers from Starkware suggest that they are able to prove 10000 Rescue hashes per second on a consumer desktop; assuming 25 hashes per Merkle branch, and a block full of state accesses, at present this would imply a witness would take `12500000 / 700 * 25 / 10000 ~= 44.64` seconds to generate, but after this EIP that would reduce to `12500000 / 2500 * 25 / 10000 ~= 12.5` seconds, meaning that a single desktop computer would be able to generate witnesses on time under any conditions. Future gains in STARK proving could be spent on either (i) using a more expensive but robust hash function or (ii) reducing proving times further, reducing the delay and hence improving user experience of stateless clients that rely on such witnesses. + +## Specification + +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | 12244000 | +| `COLD_SLOAD_COST` | 2100 | +| `COLD_ACCOUNT_ACCESS_COST` | 2600 | +| `WARM_STORAGE_READ_COST` | 100 | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +When executing a transaction, maintain a set `accessed_addresses: Set[Address]` and `accessed_storage_keys: Set[Tuple[Address, Bytes32]]` . + +The sets are transaction-context-wide, implemented identically to other transaction-scoped constructs such as the self-destruct-list and global `refund` counter. In particular, if a scope reverts, the access lists should be in the state they were in before that scope was entered. + +When a transaction execution begins, + - `accessed_storage_keys` is initialized to empty, and + - `accessed_addresses` is initialized to include + - the `tx.sender`, `tx.to` (or the address being created if it is a contract creation transaction) + - and the set of all precompiles. + + +### Storage read changes + +When an address is either the target of a (`EXTCODESIZE` (`0x3B`), `EXTCODECOPY` (`0x3C`), `EXTCODEHASH` (`0x3F`) or `BALANCE` (`0x31`)) opcode or the target of a (`CALL` (`0xF1`), `CALLCODE` (`0xF2`), `DELEGATECALL` (`0xF4`), `STATICCALL` (`0xFA`)) opcode, the gas costs are computed as follows: + +* If the target is not in `accessed_addresses`, charge `COLD_ACCOUNT_ACCESS_COST` gas, and add the address to `accessed_addresses`. +* Otherwise, charge `WARM_STORAGE_READ_COST` gas. + +In all cases, the gas cost is charged and the map is updated at the time that the opcode is being called. +When a `CREATE` or `CREATE2` opcode is called, immediately (ie. before checks are done to determine whether or not the address is unclaimed) add the address being created to `accessed_addresses`, but gas costs of `CREATE` and `CREATE2` are unchanged. +Clarification: If a `CREATE`/`CREATE2` operation fails later on, e.g during the execution of `initcode` or has insufficient gas to store the code in the state, the `address` of the contract itself remains in `access_addresses` (but any additions made within the inner scope are reverted). + +For `SLOAD`, if the `(address, storage_key)` pair (where `address` is the address of the contract whose storage is being read) is not yet in `accessed_storage_keys`, charge `COLD_SLOAD_COST` gas and add the pair to `accessed_storage_keys`. If the pair is already in `accessed_storage_keys`, charge `WARM_STORAGE_READ_COST` gas. + +Note: For call-variants, the `100`/`2600` cost is applied immediately (exactly like how `700` was charged before this EIP), i.e: before calculating the `63/64ths` available for entering the call. + +Note 2: There is currently no way to perform a 'cold sload read/write' on a 'cold account', simply because in order to read/write a `slot`, the execution must already be inside the `account`. Therefore, the behaviour of cold storage reads/writes on cold accounts is undefined as of this EIP. Any future EIP which +proposes to add 'remote read/write' would need to define the pricing behaviour of that change. + +### SSTORE changes + +When calling `SSTORE`, check if the `(address, storage_key)` pair is in `accessed_storage_keys`. If it is not, charge an additional `COLD_SLOAD_COST` gas, and add the pair to `accessed_storage_keys`. Additionally, modify the parameters defined in [EIP-2200](./eip-2200.md) as follows: + +| Parameter | Old value | New value | +| - | - | - | +| `SLOAD_GAS` | 800 | `= WARM_STORAGE_READ_COST` | +| `SSTORE_RESET_GAS` | 5000 | `5000 - COLD_SLOAD_COST` | + +The other parameters defined in EIP 2200 are unchanged. +Note: The constant `SLOAD_GAS` is used in several places in EIP 2200, e.g `SSTORE_SET_GAS - SLOAD_GAS`. Implementations that are using composite definitions have to ensure to update those definitions too. + +### SELFDESTRUCT changes + +If the ETH recipient of a `SELFDESTRUCT` is not in `accessed_addresses` (regardless of whether or not the amount sent is nonzero), charge an additional `COLD_ACCOUNT_ACCESS_COST` on top of the existing gas costs, and add the ETH recipient to the set. + +Note: `SELFDESTRUCT` does not charge a `WARM_STORAGE_READ_COST` in case the recipient is already warm, which differs from how the other call-variants work. The reasoning behind this is to keep the changes small, a `SELFDESTRUCT` already costs `5K` and is a no-op if invoked more than once. + +## Rationale + +### Opcode costs vs charging per byte of witness data + +The natural alternative path to changing gas costs to reflect witness sizes is to charge per byte of witness data. However, that would take a longer time to implement, hampering the goal of providing short-term security relief. Furthermore, following that path faithfully would lead to extremely high gas costs to transactions that touch contract code, as one would need to charge for all 24576 contract code bytes; this would be an unacceptably high burden on developers. It is better to wait for [code merklization](https://medium.com/ewasm/evm-bytecode-merklization-2a8366ab0c90) to start trying to properly account for gas costs of accessing individual chunks of code; from a short-term DoS prevention standpoint, accessing 24 kB from disk is not much more expensive than accessing 32 bytes from disk, so worrying about code size is not necessary. + +### Adding the accessed_addresses / accessed_storage_keys sets + +The sets of already-accessed accounts and storage slots are added to avoid needlessly charging for things that can be cached (and in all performant implementations already are cached). Additionally, it removes the current undesirable status quo where it is needlessly unaffordable to do self-calls or call precompiles, and enables contract breakage mitigations that involve pre-fetching some storage key allowing a future execution to still take the expected amount of gas. + +### SSTORE gas cost change + +The change to SSTORE is needed to avoid the possibility of a DoS attack that "pokes" a randomly chosen zero storage slot, changing it from 0 to 0 at a cost of 800 gas but requiring a de-facto storage load. The `SSTORE_RESET_GAS` reduction ensures that the total cost of SSTORE (which now requires paying the `COLD_SLOAD_COST`) remains unchanged. Additionally, note that applications that do `SLOAD` followed by `SSTORE` (eg. `storage_variable += x`) _would actually get cheaper_! + +### Change SSTORE accounting only minimally + +The SSTORE gas costs continue to use Wei Tang's original/current/new approach, instead of being redesigned to use a dirty map, because Wei Tang's approach correctly accounts for the actual costs of changing storage, which only care about current vs final value and not intermediate values. + +### How would gas consumption of average applications increase under this proposal? + +#### Rough analysis from witness sizes + +We can look at [Alexey Akhunov's earlier work](https://medium.com/@akhounov/data-from-the-ethereum-stateless-prototype-8c69479c8abc) for data on average-case blocks. In summary, average blocks have witness sizes of ~1000 kB, of which ~750 kB is Merkle proofs and not code. Assuming a conservative 2000 bytes per Merkle branch this implies ~375 accesses per block (SLOADs have a similar gas-increase-to-bytes ratio so there's no need to analyze them separately). + +Data on [txs per day](https://etherscan.io/chart/tx) and [blocks per day](https://etherscan.io/chart/blocks) from Etherscan gives ~160 transactions per block (reference date: Jul 1), implying a large portion of those accesses are just the `tx.sender` and `tx.to` which are excluded from gas cost increases, though likely less than 320 due to duplicate addresses. + +Hence, this implies ~50-375 chargeable accesses per block, and each access suffers a gas cost increase of 1900; `50 * 1900 = 95000` and `375 * 1900 = 712500`, implying the gas limit would need to be raised by ~1-6% to compensate. However, this analysis may be complicated further in either direction by (i) accounts / storage keys being accessed in multiple transactions, which would appear once in the witness but twice in gas cost increases, and (ii) accounts / storage keys being accessed multiple times in the same transaction, which lead to gas cost _decreases_. + +#### Goerli analysis + +A more precise analysis can be found by scanning Goerli transactions, as done by Martin Swende here: https://github.com/holiman/gasreprice + +The conclusion is that on average gas costs increase by ~2.36%. One major contributing factor to reducing gas costs is that a large number of contracts inefficiently read the same storage slot multiple times, which leads to this EIP giving a few transactions gas cost _savings_ of over 10%. + +## Backwards Compatibility + +These gas cost increases may potentially break contracts that depend on fixed gas costs; see the security considerations section for details and arguments for why we expect the total risks to be low and how if desired they can be reduced further. + +## Test Cases + +Some test cases can be found here: https://gist.github.com/holiman/174548cad102096858583c6fbbb0649a + +Ideally we would test the following: + +* SLOAD the same storage slot {1, 2, 3} times +* CALL the same address {1, 2, 3} times +* (SLOAD | CALL) in a sub-call, then revert, then (SLOAD | CALL) the same (storage slot | address) again +* Sub-call, SLOAD, sub-call again, revert the inner sub-call, SLOAD the same storage slot +* SSTORE the same storage slot {1, 2, 3} times, using all combinations of zero/nonzero for original value and the value being set +* SSTORE then SLOAD the same storage slot +* `OP_1` then `OP_2` to the same address where `OP_1` and `OP_2` are all combinations of (`*CALL`, `EXT*`, `SELFDESTRUCT`) +* Try to `CALL` an address but with all possible failure modes (not enough gas, not enough ETH...), then (`CALL` | `EXT*`) that address again successfully + +## Implementation + +A WIP early-draft implementation for Geth can be found here: https://github.com/holiman/go-ethereum/tree/access_lists + +## Security Considerations + +As with any gas cost increasing EIP, there are three possible cases where it could cause applications to break: + +1. Fixed gas limits to sub-calls in contracts +2. Applications relying on contract calls that consume close to the full gas limit +3. The 2300 base limit given to the callee by ETH-transferring calls + +These risks have been studied before in the context of an earlier gas cost increase, EIP-1884. See [Martin Swende's earlier report](https://github.com/holiman/eip-1884-security) and [Hubert Ritzdorf's analysis](https://gist.github.com/ritzdorf/1c6bd72955391e831f8a397d3152b4e0/) focusing on (1) and (3). (2) has received less analysis, though one can argue that it is very unlikely both because applications tend to very rarely use close to the entire gas limit in a transaction, and because gas limits were very recently raised from 10 million to 12.5 million. EIP-1884 in practice [did lead to a small number of contracts breaking](https://www.coindesk.com/ethereums-istanbul-upgrade-will-break-680-smart-contracts-on-aragon) for this reason. + +There are two ways to look at these risks. First, we can note that as of today developers have had years of warning; gas cost increases on storage-accessing opcodes have been [discussed for a long time](https://ethereum-magicians.org/t/protocol-changes-to-bound-witness-size/3885), with multiple statements made including to major dapp developers around the likelihood of such changes. EIP-1884 itself provided an important wake-up call. Hence, we can argue that risks this time will be significantly lower than EIP-1884. + +### Contract breakage mitigations + +A second way to look at the risks is to explore mitigations. First of all, the existence of an `accessed_addresses` and `accessed_storage_keys` map (present in this EIP, absent in EIP-1884) already makes some cases recoverable: in any case where a contract A needs to send funds to some address B, where that address accepts funds from any source but leaves a storage-dependent log, one can recover by first sending a separate call to B to pull it into the cache, and then call A, knowing that the execution of B triggered by A will only charge 100 gas per SLOAD. This fact does not fix all situations, but it does reduce risks significantly. + +But there are ways to further expand the usability of this pattern. One possibility is to add a `POKE` precompile, which would take an address and a storage key as input and allow transactions that attempt to "rescue" stuck contracts by pre-poking all of the storage slots that they will access. This works even if the address only accepts transactions from the contract, and works in many other contexts with present gas limits. The only case where this will not work would be the case where a transaction call _must_ go from an EOA straight into a specific contract that then sub-calls another contract. + +Another option is [EIP-2930](./eip-2930.md), which would have a similar effect to `POKE` but is more general: it also works for the EOA -> contract -> contract case, and generally should work for all known cases of breakage due to gas cost increases. This option is more complex, though it is arguably a stepping stone toward access lists being used for other use cases (regenesis, account abstraction, SSA all demand access lists). + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2930.md b/EIPS/eip-2930.md new file mode 100644 index 00000000000000..c9db53a936c5c9 --- /dev/null +++ b/EIPS/eip-2930.md @@ -0,0 +1,140 @@ +--- +eip: 2930 +title: Optional access lists +author: Vitalik Buterin (@vbuterin), Martin Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/eip-2930-optional-access-lists/4561 +status: Final +type: Standards Track +category: Core +created: 2020-08-29 +requires: 2718, 2929 +--- + +## Simple Summary + +Adds a transaction type which contains an access list, a list of addresses and storage keys that the transaction plans to access. Accesses outside the list are possible, but become more expensive. + +## Abstract + +We introduce a new [EIP-2718](./eip-2718.md) transaction type, with the format `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, signatureYParity, signatureR, signatureS])`. + +The `accessList` specifies a list of addresses and storage keys; these addresses and storage keys are added into the `accessed_addresses` and `accessed_storage_keys` global sets (introduced in [EIP-2929](./eip-2929.md)). A gas cost is charged, though at a discount relative to the cost of accessing outside the list. + +## Motivation + +This EIP serves two functions: + +1. Mitigates contract breakage risks introduced by [EIP-2929](./eip-2929.md), as transactions could pre-specify and pre-pay for the accounts and storage slots that the transaction plans to access; as a result, in the actual execution, the SLOAD and EXT* opcodes would only cost 100 gas: low enough that it would not only prevent breakage due to that EIP but also "unstuck" any contracts that became stuck due to EIP 1884. +2. Introduces the access list format and the logic for handling the format. This logic can later be repurposed for many other purposes, including block-wide witnesses, use in ReGenesis, moving toward static state access over time, and more. + +## Specification + +### Definitions + +**`TransactionType`** `1`. See [EIP-2718](./eip-2718.md) + +**`ChainId`** The transaction only valid on networks with this `chainID`. + +**`YParity`** The parity (0 for even, 1 for odd) of the y-value of a secp256k1 signature. + + +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | 12244000 | +| `ACCESS_LIST_STORAGE_KEY_COST` | 1900 | +| `ACCESS_LIST_ADDRESS_COST` | 2400 | + +As of `FORK_BLOCK_NUMBER`, a new [EIP-2718](./eip-2718.md) transaction is introduced with `TransactionType` `1`. + +The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is `rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, signatureYParity, signatureR, signatureS])`. + +The `signatureYParity, signatureR, signatureS` elements of this transaction represent a secp256k1 signature over `keccak256(0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList]))`. + +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulativeGasUsed, logsBloom, logs])`. + +For the transaction to be valid, `accessList` must be of type `[[{20 bytes}, [{32 bytes}...]]...]`, where `...` means "zero or more of the thing to the left". For example, the following is a valid access list (all hex strings would in reality be in byte representation): + +``` +[ + [ + "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae", + [ + "0x0000000000000000000000000000000000000000000000000000000000000003", + "0x0000000000000000000000000000000000000000000000000000000000000007" + ] + ], + [ + "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", + [] + ] +] +``` + +At the beginning of execution (ie. at the same time as the `21000 + 4 * zeroes + 16 * nonzeroes` start gas is charged according to [EIP-2028](./eip-2028.md) rules), we charge additional gas for the access list: `ACCESS_LIST_ADDRESS_COST` gas per address and `ACCESS_LIST_STORAGE_KEY_COST` gas per storage key. For example, the above example would be charged `ACCESS_LIST_ADDRESS_COST * 2 + ACCESS_LIST_STORAGE_KEY_COST * 2` gas. + +Note that non-unique addresses and storage keys are not disallowed, though they will be charged for multiple times, and aside from the higher gas cost there is no other difference in execution flow or outcome from multiple-inclusion of a value as opposed to the recommended single-inclusion. + +The address and storage keys would be immediately loaded into the `accessed_addresses` and `accessed_storage_keys` global sets; this can be done using the following logic (which doubles as a specification-in-code of validation of the RLP-decoded access list) + +```python +def process_access_list(access_list) -> Tuple[List[Set[Address], Set[Pair[Address, Bytes32]]], int]: + accessed_addresses = set() + accessed_storage_keys = set() + gas_cost = 0 + assert isinstance(access_list, list) + for item in access_list: + assert isinstance(item, list) and len(item) == 2 + # Validate and add the address + address = item[0] + assert isinstance(address, bytes) and len(address) == 20 + accessed_addresses.add(address) + gas_cost += ACCESS_LIST_ADDRESS_COST + # Validate and add the storage keys + assert isinstance(item[1], list) + for key in item[1]: + assert isinstance(key, bytes) and len(key) == 32 + accessed_storage_keys.add((address, key)) + gas_cost += ACCESS_LIST_STORAGE_KEY_COST + return ( + accessed_addresses, + accessed_storage_keys, + gas_cost + ) +``` + +The access list is NOT charged per-byte fees like tx data is; the per-item costs described above are meant to cover the bandwidth costs of the access list data in addition to the costs of accessing those accounts and storage keys when evaluating the transaction. + +## Rationale + +### Charging less for accesses in the access list + +This is done to encourage transactions to use the access list as much as possible, and because processing transactions is easier when their storage reads are predictable (because clients can pre-load the data from databases and/or ask for witnesses at the time the transaction is received, or at least load the data in parallel). + +### Allowing duplicates + +This is done because it maximizes simplicity, avoiding questions of what to prevent duplication against: just between two addresses/keys in the access list, between the access list and the tx sender/recipient/newly created contract, other restrictions? Because gas is charged per item, there is no gain and only cost in including a value in the access list twice, so this should not lead to extra chain bloat in practice. + +### Signature signs over the transaction type as well as the transaction data + +This is done to ensure that the transaction cannot be "re-interpreted" as a transaction of a different type. + +## Backwards Compatibility + +This EIP does make it more gas-expensive to perform "unexpected" SLOADs and account accesses. Because gas is prepaid and so does not affect fixed-gas local calls, it does not break contracts in the way that previous gas cost increases would risk. However, it does make applications that heavily rely on storage access much less economically viable. + +## Security Considerations + +### Access list generation + +Access lists are difficult to construct in real-time in many situations, and this is exacerbated in environments where there is a high time lag between transaction generation and signing or simplicity of the transaction generator is highly valued (eg. either or both may apply in hardware wallets). + +However, this EIP proposes only a 10% initial discount to access lists, so there is almost no cost to not bothering with access list generation and only making a simple transaction. The cost of accessing state outside the access list is expected to be ramped up in future hard forks over time as tools are developed and access list generation becomes more mature. + +### Transaction size bloating + +Average block size will increase as a result of access lists being used. However, the per-byte cost of access lists is `1900 / 32 = 59.375` for storage keys and `2400 / 20 = 120` for addresses, making it much more expensive than calldata; hence, worst-case block size will not increase. Additionally, increases in average block size will be partially compensated for by the ability to pre-fetch storage at time of receiving a transaction and/or load storage in parallel upon receiving a block. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2935.md b/EIPS/eip-2935.md new file mode 100644 index 00000000000000..b2cc9732192c87 --- /dev/null +++ b/EIPS/eip-2935.md @@ -0,0 +1,225 @@ +--- +eip: 2935 +title: Serve historical block hashes from state +description: Store and serve last 8191 block hashes as storage slots of a system contract to allow for stateless execution +author: Vitalik Buterin (@vbuterin), Tomasz Stanczak (@tkstanczak), Guillaume Ballet (@gballet), Gajinder Singh (@g11tech), Tanishq Jasoria (@tanishqjasoria), Ignacio Hagopian (@jsign), Jochem Brouwer (@jochem-brouwer), Sina Mahmoodi (@s1na) +discussions-to: https://ethereum-magicians.org/t/eip-2935-save-historical-block-hashes-in-state/4565 +status: Final +type: Standards Track +category: Core +created: 2020-09-03 +--- + +## Abstract + +Store last `HISTORY_SERVE_WINDOW` historical block hashes in the storage of a system contract as part of the block processing logic. Furthermore this EIP has no impact on `BLOCKHASH` resolution mechanism (and hence its range/costs etc). + +## Motivation + +EVM implicitly assumes the client has the recent block (hashes) at hand. This assumption is not future-proof given the prospect of stateless clients. Including the block hashes in the state will allow bundling these hashes in the witness provided to a stateless client. This is already possible in the MPT and will become more efficient post-Verkle. + +Extending the range of blocks which `BLOCKHASH` can serve (`BLOCKHASH_SERVE_WINDOW`) would have been a semantics change. Using extending that via this contract storage would allow a soft-transition. Rollups can benefit from the longer history window through directly querying this contract. + +A side benefit of this approach could be that it allows building/validating proofs related to last `HISTORY_SERVE_WINDOW` ancestors directly against the current state. + +## Specification + +| Parameter | Value | +| - | - | +| `BLOCKHASH_SERVE_WINDOW` | `256` | +| `HISTORY_SERVE_WINDOW` | `8191` | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | +| `HISTORY_STORAGE_ADDRESS` | `0x0000F90827F1C53a10cb7A02335B175320002935` | + +This EIP specifies for storing last `HISTORY_SERVE_WINDOW` block hashes in a ring buffer storage of `HISTORY_SERVE_WINDOW` length. Note that `HISTORY_SERVE_WINDOW` > `BLOCKHASH_SERVE_WINDOW` (which remains unchanged). + +### Block processing + +At the start of processing any block where this EIP is active (ie. before processing any transactions), call to `HISTORY_STORAGE_ADDRESS` as `SYSTEM_ADDRESS` with the 32-byte input of `block.parent.hash`, a gas limit of `30_000_000`, and `0` value. This will trigger the `set()` routine of the history contract. This is a system operation following the same convention as [EIP-4788](./eip-4788.md) and therefore: + +* the call must execute to completion +* the call does not count against the block's gas limit +* the call does not follow the [EIP-1559](./eip-1559.md) burn semantics - no value should be transferred as part of the call +* if no code exists at `HISTORY_STORAGE_ADDRESS`, the call must fail silently + +Note: Alternatively clients can choose to directly write to the storage of the contract but EVM calling the contract remains preferred. Refer to the rationale for more info. + +Note that, it will take `HISTORY_SERVE_WINDOW` blocks after the EIP's activation to completely fill up the ring buffer. The contract will only contain the parent hash of the fork block and no hashes prior to that. + + +### EVM Changes + +The `BLOCKHASH` opcode semantics remains the same as before. + +### Block hash history contract + +The history contract has two operations: `get` and `set`. The `set` operation is invoked only when the `caller` is equal to the `SYSTEM_ADDRESS` as per [EIP-4788](./eip-4788.md). Otherwise the `get` operation is performed. + +#### `get` + +It is used from the EVM for looking up block hashes. + +* Callers provide the block number they are querying in a big-endian encoding. +* If calldata is not 32 bytes, revert. +* For any request outside the range of [block.number-`HISTORY_SERVE_WINDOW`, block.number-1], revert. + +#### `set` + +* Caller provides `block.parent.hash` as calldata to the contract. +* Set the storage value at `block.number-1 % HISTORY_SERVE_WINDOW` to be `calldata[0:32]`. + +#### Bytecode + +Exact evm assembly that can be used for the history contract: + +``` +// https://github.com/lightclient/sys-asm/blob/f1c13e285b6aeef2b19793995e00861bf0f32c9a/src/execution_hash/main.eas +caller +push20 0xfffffffffffffffffffffffffffffffffffffffe +eq +push1 0x46 +jumpi +push1 0x20 +calldatasize +sub +push1 0x42 +jumpi +push0 +calldataload +push1 0x01 +number +sub +dup2 +gt +push1 0x42 +jumpi +push2 0x1fff +dup2 +number +sub +gt +push1 0x42 +jumpi +push2 0x1fff +swap1 +mod +sload +push0 +mstore +push1 0x20 +push0 +return +jumpdest +push0 +push0 +revert +jumpdest +push0 +calldataload +push2 0x1fff +push1 0x01 +number +sub +mod +sstore +stop +``` + +#### Deployment + +A special synthetic address is generated by working backwards from the desired deployment transaction: + +```json +{ + "type": "0x0", + "nonce": "0x0", + "to": null, + "gas": "0x3d090", + "gasPrice": "0xe8d4a51000", + "maxPriorityFeePerGas": null, + "maxFeePerGas": null, + "value": "0x0", + "input": "0x60538060095f395ff33373fffffffffffffffffffffffffffffffffffffffe14604657602036036042575f35600143038111604257611fff81430311604257611fff9006545f5260205ff35b5f5ffd5b5f35611fff60014303065500", + "v": "0x1b", + "r": "0x539", + "s": "0xaa12693182426612186309f02cfe8a80a0000", + "hash": "0x67139a552b0d3fffc30c0fa7d0c20d42144138c8fe07fc5691f09c1cce632e15" +} +``` + +Note, the input in the transaction has a simple constructor prefixing the desired runtime code. + +The sender of the transaction can be calculated as `0x3462413Af4609098e1E27A490f554f260213D685`. The address of the first contract deployed from the account is `rlp([sender, 0])` which equals `0x0000F90827F1C53a10cb7A02335B175320002935`. This is how `HISTORY_STORAGE_ADDRESS` is determined. Although this style of contract creation is not tied to any specific initcode like create2 is, the synthetic address is cryptographically bound to the input data of the transaction (e.g. the initcode). + + +Some activation scenarios: + + * For the fork to be activated at genesis, no history is written to the genesis state, and at the start of block `1`, genesis hash will be written as a normal operation to slot `0`. + * for activation at block `1`, only genesis hash will be written at slot `0`. + * for activation at block `32`, block `31`'s hash will be written to slot `31`. Every other slot will be `0`. + +### [EIP-161](./eip-161.md) handling + +The bytecode above will be deployed à la [EIP-4788](./eip-4788.md). As such the account at `HISTORY_STORAGE_ADDRESS` will have code and a nonce of 1, and will be exempt from EIP-161 cleanup. + +### Gas costs + +The system update at the beginning of the block, i.e. `process_block_hash_history` (or via system call to the contract with `SYSTEM_ADDRESS` caller), will not warm the `HISTORY_STORAGE_ADDRESS` account or its storage slots as per [EIP-2929](./eip-2929.md) rules. As such the first call to the contract will pay for warming up the account and storage slots it accesses.To clarify further any contract call to the `HISTORY_STORAGE_ADDRESS` will follow normal EVM execution semantics. + +Since `BLOCKHASH` semantics doesn't change, this EIP has no impact on `BLOCKHASH` mechanism and costs. + +## Rationale + +Very similar ideas were proposed before. This EIP is a simplification, removing two sources of needless complexity: + +1. Having a tree-like structure with multiple layers as opposed to a single list +2. Writing the EIP in EVM code +3. Serial unbounded storage of hashes for a deep access to the history + +However after weighing pros and cons, we decided to go with just a limited ring buffer to only serve the requisite `HISTORY_SERVE_WINDOW` as [EIP-4788](./eip-4788.md) and beacon state accumulators allow (albeit a bit more complex) proof against any ancestor since merge. + +Second concern was how to best transition the BLOCKHASH resolution logic post fork by: + +1. Either waiting for `HISTORY_SERVE_WINDOW` blocks for the entire relevant history to persist +2. Storing of all last `HISTORY_SERVE_WINDOW` block hashes on the fork block. + +We choose to go with the former. It simplifies the logic greatly. It will take roughly a day to bootstrap the contract. Given that this is a new way of accessing history and no contract depends on it, it is deemed a favorable tradeoff. + +### Inserting the parent block hash + +Clients have generally two options for inserting the parent block hash into state: + +1. Performing a system call to `HISTORY_STORAGE_ADDRESS` and letting that handle the storing in state. +2. Avoid EVM processing and directly write to the state trie. + +The latter option is as follows: + +```python +def process_block_hash_history(block: Block, state: State): + if block.timestamp >= FORK_TIMESTAMP: // FORK_TIMESTAMP should be defined outside of the EIP + state.insert_slot(HISTORY_STORAGE_ADDRESS, (block.number-1) % HISTORY_SERVE_WINDOW , block.parent.hash) +``` + +The first option is recommended until the Verkle fork, to stay consistent with [EIP-4788](./eip-4788.md) and to issues for misconfigured networks where this EIP is activated but history contract hasn't been deployed. The recommendation may be reconsidered at the Verkle fork if filtering the system contract code chunks is deemed too complex. + +### Size of ring buffers + +The ring buffer data structure is sized to hold 8191 hashes. In other system contracts a prime ring buffer size is chosen in because using a prime as the modulus ensures that no value is overwritten until the entire ring buffer has been saturated and thereafter, each value will be updated once per iteration, regardless of if some slot are missing or the slot time changes. However, in this EIP the block number is the value in the modulo operation and it only ever increases by 1 each iteration. Which means we can be confident that the ring buffer will always remain saturated. + +For consistency with other system contracts, we have decided to retain the buffer size of 8191. Given the current mainnet values, 8191 roots provides about a day of coverage. This also gives users plenty of time to make a transaction with a verification against a specific hash and get the transaction included on-chain. + +## Backwards Compatibility + +This EIP introduces backwards incompatible changes to the block validation rule set. But neither of these changes break anything related to current user activity and experience. + +## Test Cases + +[EIP-2935 Execution Spec Tests](https://github.com/ethereum/execution-spec-tests/tree/3810d22f84f206866f66f4f6bf856187c2893ab1/tests/prague/eip2935_historical_block_hashes_from_state) + +## Security Considerations + +Having contracts (system or otherwise) with hot update paths (branches) poses a risk of "branch" poisoning attacks where attacker could sprinkle trivial amounts of eth around these hot paths (branches). But it has been deemed that cost of attack would escalate significantly to cause any meaningful slow down of state root updates. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2936.md b/EIPS/eip-2936.md new file mode 100644 index 00000000000000..daad2d0bf28d4b --- /dev/null +++ b/EIPS/eip-2936.md @@ -0,0 +1,60 @@ +--- +eip: 2936 +title: EXTCLEAR Opcode For SELFDESTRUCTed contracts +author: William Morriss (@wjmelements) +discussions-to: https://ethereum-magicians.org/t/eip-2936-extclear-for-selfdestruct/4569 +status: Stagnant +type: Standards Track +category: Core +created: 2020-09-03 +--- + +## Simple Summary +Enable new opcode to clear storage for `SELFDESTRUCTED`ed contracts. + +## Abstract +Changes `SELFDESTRUCT` (`0xff`) to not clear any storage and adds a new `EXTCLEAR` (`0x5c`) opcode that will clear a specific storage slot for a contract that has previously been self destructed. + +## Motivation +`SELFDESTRUCT` (`0xFF`) is unnecessarily complex because it clears an unbounded amount of contract storage. +It is computationally expensive for nodes to track all of the storage used in every contract in case the contract `SELFDESTRUCT`s. +Further, contracts can be re-initialized using `CREATE2` (`0xF5`), and then `SLOAD` (`0x54`) prior storage. +Therefore, several ethereum clients do not clear storage at all, and just check if the contract was initiated since `SSTORE` (`0x55`) during `SLOAD`. +`CREATE2` was not intended to complicate `SLOAD`, and this change reverts that complexity. +Also, bugs in this implementation could split the network. + +Instead this defers the time of storage cleanup, and leaves the storage in-place, which reduces the complexity of `SLOAD` and `SELFDESTRUCT`. + +This empowers the `CREATE2` reincarnation proxy pattern by retaining storage during upgrade, which would otherwise have to be reset again. +An atomic reincarnation upgrade could clear a subset of storage during the upgrade, while the contract is destroyed, before reinstating it. + +## Specification + +After `FORK_BLOCK_NUM`, a new opcode, `EXTCLEAR`, is enabled at `0x5C` to clear storage for `SELFDESTRUCT`ed contracts. +`EXTCLEAR`: +* does not push any words onto the stack +* pops two words off the stack: the destroyed contract address and a storage address +* if the contract exists, charge the same gas cost as `EXTCODEHASH` (`0x3F`) +* otherwise, if the storage is zero, charge the same gas as `EXTCODEHASH` plus `SLOAD` +* otherwise, the destroyed contract's slot is reset to 0, charging the same gas as `EXTCODEHASH` and `SSTORE` when resetting storage, while also refunding the amount specified in `SSTORE`. + +`SELFDESTRUCT` is modified to not clear contract storage. +This change also works retroactively: all prior destroyed contracts can be cleaned up. + +## Rationale +`0x5C` is available in the same range as `SSTORE` and `SLOAD`. + +## Backwards Compatibility +A reincarnation upgrade mechanism that expects all internal storage to be cleared might break, but such an upgrade mechanism would allow adaptation to this new behavior. + +## Test Cases +TODO + +## Implementation +Implementation is required on all major clients to add the opcode. + +## Security Considerations +A reincarnated contract that does not expect its state to be cleared by malicious actors SHOULD reinitialize itself to avoid antagonistic `EXTCLEAR`. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2937.md b/EIPS/eip-2937.md new file mode 100644 index 00000000000000..4122d7c7d02fc7 --- /dev/null +++ b/EIPS/eip-2937.md @@ -0,0 +1,48 @@ +--- +eip: 2937 +title: SET_INDESTRUCTIBLE opcode +author: Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-2937-set-indestructible/4571 +status: Stagnant +type: Standards Track +category: Core +created: 2020-09-04 +--- + +## Simple Summary + +Add a `SET_INDESTRUCTIBLE (0xA8)` opcode that prevents the contract from calling `SELFDESTRUCT (0xFF)`. + +## Abstract + +## Motivation + +The intended use case would be for contracts to make their first byte of code be the `SET_INDESTRUCTIBLE` opcode if they wish to serve as libraries that guarantee to users that their code will exist unmodified forever. This is useful in account abstraction as well as other contexts. + +Unlike EIPs that disable the `SELFDESTRUCT` opcode entirely, this EIP does not modify behavior of any existing contracts. + +## Specification + +Add a transaction-wide global variable `globals.indestructible: Set[Address]` (i.e. a variable that operates the same way as the selfdestructs set), initialized to the empty set. + +Add a `SET_INDESTRUCTIBLE` opcode at `0xA8`, with gas cost `G_base`, that adds the current `callee` to the `globals.indestructible` set. If in the current execution context the `callee` is in `globals.indestructible`, the `SELFDESTRUCT` opcode throws an exception. + +## Rationale + +Alternative proposals to this include: + +* Simply banning `SELFDESTRUCT` outright. This would be ideal, but has larger backwards compatibility issues. +* Using a local variable instead of a global variable. This is problematic because it would be broken by `DELEGATECALL`. + +## Backwards Compatibility + +TBD + +## Security Considerations + +This breaks forward compatibility with _some_ forms of state rent, which would simply delete contracts that get too old without paying some maintenance fee. However, this is not the case with all state size control schemes; for example this is not an issue if we use [ReGenesis](https://ledgerwatch.github.io/regenesis_plan.html). + +If `SELFDESTRUCT` is ever removed in the future, this EIP would simply become a no-op. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2938.md b/EIPS/eip-2938.md new file mode 100644 index 00000000000000..ce55b6e9f747a9 --- /dev/null +++ b/EIPS/eip-2938.md @@ -0,0 +1,288 @@ +--- +eip: 2938 +title: Account Abstraction +author: Vitalik Buterin (@vbuterin), Ansgar Dietrichs (@adietrichs), Matt Garnett (@lightclient), Will Villanueva (@villanuevawill), Sam Wilson (@SamWilsn) +discussions-to: https://ethereum-magicians.org/t/eip-2938-account-abstraction/4630 +status: Withdrawn +type: Standards Track +category: Core +created: 2020-09-04 +requires: 2718 +withdrawal-reason: Very out of date; needs rewrite. +--- + +## Simple Summary + +Account abstraction (AA) allows a contract to be the top-level account that pays fees and starts transaction execution. + +## Abstract + +**See also: [https://ethereum-magicians.org/t/implementing-account-abstraction-as-part-of-eth1-x/4020](https://ethereum-magicians.org/t/implementing-account-abstraction-as-part-of-eth1-x/4020) and the links therein for historical work and motivation.** + +Transaction validity, as of Muir Glacier, is defined rigidly by the protocol: ECDSA signature, a simple nonce, and account balance. Account abstraction extends the validity conditions of transactions with the execution of arbitrary EVM bytecode (with some limits on what state may be accessed.) To signal validity, we propose a new EVM opcode `PAYGAS`, which also sets the gas price and gas limit the contract is willing to pay. + +We split account abstraction into two tiers: **single-tenant AA**, which is intended to support wallets or other use cases with few participants, and **multi-tenant AA**, which is intended to support applications with many participants (eg. tornado.cash, Uniswap). + +## Motivation + +The existing limitations preclude innovation in a number of important areas, particularly: + +1. Smart contract wallets that use signature verification other than ECDSA (eg. Schnorr, BLS, post-quantum...) +2. Smart contract wallets that include features such as multisig verification or social recovery, reducing the highly prevalent risk of funds being lost or stolen +3. Privacy-preserving systems like [tornado.cash](http://tornado.cash) +4. Attempts to improve gas efficiency of DeFi protocols by preventing transactions that don't satisfy high-level conditions (eg. existence of a matching order) from being included on chain +5. Users being able to pay for transaction fees in a token other than ETH (eg. by converting that token into the ETH needed for fees inside the transaction in real-time) + +Most of the above use cases are currently possible using intermediaries, most notably the [Gas Station Network](https://www.opengsn.org/) and application-specific alternatives. These implementations are (i) technically inefficient, due to the extra 21000 gas to pay for the relayer, (ii) economically inefficient, as relayers need to make a profit on top of the gas fees that they pay. Additionally, use of intermediary protocols means that these applications cannot simply rely on base Ethereum infrastructure and need to rely on extra protocols that have smaller userbases and higher risk of no longer being available at some future date. + +Out of the five use cases above, single-tenant AA approximately supports (1) and (2), and multi-tenant AA approximately supports (3) and (4). We discuss the differences between the two tiers in the specification and rationale sections below. + +## Specification + +### Single Tenant + +After `FORK_BLOCK`, the following changes will be recognized by the protocol. + +#### Constants + +| Constant | Value | +| - | - | +| **`AA_ENTRY_POINT`** | `0xffffffffffffffffffffffffffffffffffffffff` | +| **`AA_TX_TYPE`** | `2` | +| **`FORK_BLOCK`** | TBD | +| **`AA_BASE_GAS_COST`** | 15000 | + +#### New Transaction Type + +A new [EIP-2718](./eip-2718.md) transaction with type `AA_TX_TYPE` is introduced. Transactions of this type are referred to as "AA transactions". Their payload should be interpreted as `rlp([nonce, target, data])`. + +The base gas cost of this transaction is set to `AA_BASE_GAS_COST` instead of 21000 to reflect the lack of "intrinsic" ECDSA and signature. + +Nonces are processed analogously to existing transactions (check `tx.nonce == tx.target.nonce`, transaction is invalid if this fails, otherwise proceed and immediately set `tx.nonce += 1`). + +Note that this transaction type has no intrinsic gas limit; when beginning execution, the gas limit is simply set to the remaining gas in the block (ie. `block.gas_limit` minus gas spent on previous transactions), and the `PAYGAS` opcode (see below) can adjust the gas limit downwards. + +#### Transaction-wide global variables + +Introduce some new transaction-wide global variables. These variables work similarly (in particular, have similar reversion logic) to the SSTORE refunds counter. + +| Variable | Type | Initial value | +| - | - | - | +| `globals.transaction_fee_paid` | `bool` | `False if type(tx) == AA_TX_TYPE else True` | +| `globals.gas_price` | `int` | `0 if type(tx) == AA_TX_TYPE else tx.gas_price` | +| `globals.gas_limit` | `int` | `0 if type(tx) == AA_TX_TYPE else tx.gas_limit` | + +#### `NONCE (0x48)` Opcode + +A new opcode `NONCE (0x48)` is introduced, with gas cost `G_base`, which pushes the `nonce` of the callee onto the stack. + +#### `PAYGAS (0x49)` Opcode + +A new opcode `PAYGAS (0x49)` is introduced, with gas cost `G_base`. It takes two arguments off the stack: (top) `version_number`, (second from top) `memory_start`. In the initial implementation, it will `assert version_number == 0` and read: + +* `gas_price = bytes_to_int(vm.memory[memory_start: memory_start + 32])` +* `gas_limit = bytes_to_int(vm.memory[memory_start + 32: memory_start + 64])` + +Both reads use similar mechanics to MLOAD and CALL, so memory expands if needed. + +Future hard forks may add support for different version numbers, in which case the opcode may take different-sized memory slices and interpret them differently. Two particular potential use cases are [EIP 1559](https://notes.ethereum.org/@vbuterin/BkSQmQTS8) and [the escalator mechanism](https://ethresear.ch/t/another-simple-gas-fee-model-the-escalator-algorithm-from-the-agoric-papers/6399). + +The opcode works as follows. If all three of the following conditions (in addition to the version number check above) are satisfied: + +1. The account's balance is `>= gas_price * gas_limit` +2. `globals.transaction_fee_paid == False` +3. We are in a top-level AA execution frame (ie. if the currently running EVM execution exits or reverts, the EVM execution of the entire transaction is finished) + +Then do the following: + +* Subtract `gas_price * gas_limit` from the contract's balance +* Set `globals.transaction_fee_paid` to `True` +* Set `globals.gas_price` to `gas_price`, and `globals.gas_limit` to `gas_limit` +* Set the remaining gas in the current execution context to equal `gas_limit` minus the gas that was already consumed + +If any of the above three conditions are not satisfied, throw an exception. + +At the end of execution of an AA transaction, it is mandatory that `globals.transaction_fee_paid == True`; if it is not, then the transaction is invalid. At the end of execution, the contract is refunded `globals.gas_price * remaining_gas` for any remaining gas, and `(globals.gas_limit - remaining_gas) * globals.gas_price` is transferred to the miner. + +`PAYGAS` also serves as an EVM execution _checkpoint_: if the top-level execution frame reverts after `PAYGAS` has been called, then the execution only reverts up to the point right after `PAYGAS` was called, and exits there. In that case, the contract receives no refund, and `globals.gas_limit * globals.gas_price` is transferred to the miner. + +#### Replay Protection + +One of the two following approaches must be implemented to safeguard against replay attacks. + +##### Require `SET_INDESTRUCTIBLE` + +Require that contracts targeted by AA transactions begin with [EIP-2937]'s `SET_INDESTRUCTIBLE` opcode. AA transactions targeting contracts that do not begin with `SET_INDESTRUCTIBLE` are invalid, and cannot be included in blocks. + +`AA_PREFIX` would need to be modified to include this opcode. + +[EIP-2937]: ./eip-2937.md + +##### Preserve Nonce on `SELFDESTRUCT` + +The other option is to preserve contract nonces across `SELFDESTRUCT` invocations, instead of setting the nonce to zero. + +#### Miscellaneous + +* If `CALLER (0x33)` is invoked in the first frame of + execution of a call initiated by an AA transaction, then it must return `AA_ENTRY_POINT`. +* If `ORIGIN (0x32)` is invoked in any frame of execution of an AA + transaction it must return `AA_ENTRY_POINT`. +* The `GASPRICE (0x3A)` opcode now pushes the value `globals.gas_price` + +Note that the new definition of `GASPRICE` does not lead to any changes in behavior in non-AA transactions, because `globals.gas_price` is initialized to `tx.gas_price` and cannot be changed as `PAYGAS` cannot be called. + +#### Mining and Rebroadcasting Strategies + +Much of the complexity in account abstraction originates from the strategies used by miners and validating nodes to determine whether or not to accept and rebroadcast transactions. Miners need to determine if a transaction will actually pay the fee if they include it after only a small amount of processing to avoid [DoS attacks](https://hackingdistributed.com/2016/06/28/ethereum-soft-fork-dos-vector/). Validating nodes need to perform an essentially identical verification to determine whether or not to rebroadcast the transaction. + +By keeping the consensus changes minimal, this EIP allows for gradual introduction of AA mempool support by miners and validating nodes. Initial support would be focused on enabling simple, single-tenant use cases, while later steps would additionally allow for more complex, multi-tenant use cases. Earlier stages are deliberately more fully fleshed-out than later stages, as there is still more time before later stages need to be implemented. + +##### Transactions with Fixed Nonces + +| Constant | Value | +| - | - | +| `VERIFICATION_GAS_MULTIPLIER` | `6` | +| `VERIFICATION_GAS_CAP` | `= VERIFICATION_GAS_MULTIPLIER * AA_BASE_GAS_COST = 90000` | +| `AA_PREFIX` | `if(msg.sender != shr(-1, 12)) { LOG1(msg.sender, msg.value); return }`; compilation to EVM TBD | + +When a node receives an AA transaction, they process it (i.e. attempt to execute it against the current chain head's post-state) to determine its validity, continuing to execute until one of several events happens: + +* If the code of the `target` is NOT prefixed with `AA_PREFIX`, exit with failure +* If the execution hits any of the following, exit with failure: + * An environment opcode (`BLOCKHASH`, `COINBASE`, `TIMESTAMP`, `NUMBER`, `DIFFICULTY`, `GASLIMIT`) + * `BALANCE` (of any account, including the `target` itself) + * An external call/create that changes the `callee` to anything but the `target` or a precompile (`CALL`, `CALLCODE`, `STATICCALL`, `CREATE`, `CREATE2`). + * An external state access that reads code (`EXTCODESIZE`, `EXTCODEHASH`, `EXTCODECOPY`, but also `CALLCODE` and `DELEGATECALL`), unless the address of the code that is read is the `target`. +* If the execution consumes more gas than `VERIFICATION_GAS_CAP` (specified above), or more gas than is available in the block, exit with failure +* If the execution reaches `PAYGAS`, then exit with success or failure depending on whether or not the balance is sufficient (e.g. `balance >= gas_price * gas_limit`). + +Nodes do not keep transactions with nonces higher than the current valid nonce in the mempool. If the mempool already contains a transaction with a currently valid nonce, another incoming transaction to the same contract and with the same nonce either replaces the existing one (if its gas price is sufficiently higher) or is dropped. Thus, the mempool keeps only at most one pending transaction per account. + +While processing a new block, take note of which accounts were the `target` of an AA transaction (each block currently has `12500000` gas and an AA transaction costs `>= 15000` so there would be at most `12500000 // 15000 = 833` targeted accounts). Drop all pending transactions targeting those accounts. All other transactions remain in the mempool. + +### Single Tenant+ + +If the [indestructible contracts EIP](http://github.com/ethereum/EIPs/pull/2937) is added, Single Tenant AA can be adapted to allow for `DELEGATECALL` during transaction verification: during execution of a new AA transaction, external state access that reads code (`EXTCODESIZE`, `EXTCODEHASH`, `EXTCODECOPY`, `CALLCODE`, `DELEGATECALL`) of any contract whose first byte is the `SET_INDESTRUCTIBLE` opcode is no longer banned. However, calls to anything but the `target` or a precompile that change the `callee` (i.e., calls other than `CALLCODE` and `DELEGATECALL`) are still not permitted. + +If the [IS_STATIC EIP](http://github.com/ethereum/EIPs/pull/2975) is added, the list of allowed prefixes can be extended to allow a prefix that enables incoming static calls but not state-changing calls. + +The list of allowed prefixes can also be extended to enable other benign use cases (eg. logging incoming payments). + +External calls _into_ AA accounts can be allowed as follows. We can add an opcode `RESERVE_GAS`, which takes as argument a value `N` and has simple behavior: immediately burn `N` gas and add `N` gas to the refund. We then add an allowed `AA_PREFIX` that reserves `>= AA_BASE_GAS_COST * 2` gas. This ensures that at least `AA_BASE_GAS_COST` gas must be spent (as refunds can refund max 50% of total consumption) in order to call into an account and invalidate transactions targeting that account in the mempool, preserving that invariant. + +Note that accounts may also opt to set a higher `RESERVE_GAS` value in order to safely have a higher `VERIFICATION_GAS_CAP`; the goal would be to preserve a `VERIFICATION_GAS_MULTIPLIER`-to-1 ratio between the minimum gas cost to edit an account (ie. half its `RESERVE_GAS`) and the `VERIFICATION_GAS_CAP` that is permitted that account. This would also preserve invariants around maximum reverification gas consumption that are implied by the previous section. + +### Multi-Tenant & Beyond + +In a later stage, we can add support for multiple pending transactions per account in the mempool. The main challenge here is that a single transaction can potentially cause state changes that invalidate all other transactions to that same account. Additionally, if we naively prioritize transactions by gasprice, there is an attack vector where the user willing to pay the highest gasprice publishes many (mutually exclusive) versions of their transaction with small alterations, thereby pushing everyone else's transactions out of the mempool. + +Here is a sketch of a strategy for mitigating this problem. We would require incoming transactions to contain an [EIP-2930](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2930.md)-style access list detailing the storage slots that the transaction reads or modifies, and make it binding; that is, accesses outside the access list would be invalid. A transaction would only be included in the mempool if its access list is disjoint from the access lists of other transactions in the mempool (or if its gasprice is higher). An alternative way to think about this is to have per-storage-slot mempools instead of just per-account mempools, except a transaction could be part of multiple per-storage-slot mempools (if desired it could be capped to eg. 5 storage slots). + +Note also that multi-tenant AA will almost certainly require allowing miners to edit the nonces of incoming transactions to put them into sequence, with the result that the final hash of a transaction is unpredictable at publication time. Clients will need to explicitly work around this. + +More research is required to refine these ideas, and this is left for later work. + +## Rationale + +The core problem in an account abstraction setup is always that miners and network nodes need to be able to verify that a transaction that they attempt to include, or rebroadcast, will actually pay a fee. Currently, this is fairly simple, because a transaction is guaranteed to be includable and pay a fee as long as the signature and nonce are valid and the balance and gasprice are sufficient. These checks can be done quickly. + +In an account abstraction setup, the goal is to allow accounts to specify EVM code that can establish more flexible conditions for a transaction's validity, but with the requirement that this EVM code can be quickly verified, with the same safety properties as the existing setup. + +In a normal transaction, the top-level call goes from the `tx.sender` to `tx.to` and carries with it `tx.value`. In an AA transaction, the top-level call goes from the _entry point address_ (`0xFFFF...FF`) to the `tx.target`. + +The top-level code execution is expected to be split into two phases: the shorter **verification phase** (before `PAYGAS`) and the longer **execution phase** (after `PAYGAS`). If execution throws an exception during the verification phase, the transaction is invalid, much like a transaction with an invalid signature in the current system. If execution throws an exception after the verification phase, the transaction pays fees, and so the miner can still include it. + +The transition between different stages of AA is entirely done through changes in miner strategy. The first stage supports **single-tenant AA**, where the only use cases that can be easily implemented are where the `tx.target` is a contract representing a user account (that is, a smart contract wallet, eg. multisig). Later stages improve support for eg. logs and libraries, and also move toward supporting **multi-tenant AA**, where the goal is to try to support cases where the `tx.target` represents an _application_ that processes incoming activity from multiple users. + +### Nonces still enshrined in single-tenant AA + +Nonces are still enforced in single-tenant AA to ensure that single-target AA does not break the invariant that each transaction (and hence each transaction hash) can only be included in the chain once. While there is some limited value in allowing arbitrary-order transaction inclusion in single-tenant AA, there is not enough value to justify breaking that invariant. + +Note that nonces in AA accounts do end up having a dual-purpose: they are both there for replay protection and for contract address generation when using the `CREATE` opcode. This does mean that a single transaction could increment the nonce by more than 1. This is deemed acceptable, as the other mechanics introduced by AA already break the ability to easily verify that a chain longer than one transaction can be processed. However, we strongly recommend that AA contracts use `CREATE2` instead of `CREATE`. + +In multi-tenant AA, as mentioned above, nonces are expected to become malleable and applications that use multi-tenant AA systems would need to manage this. + +### Nonces are exposed to the EVM + +This is done to allow signature checking done in validation code to validate the nonce. + +### Replay Protection + +One of the above two approaches (requiring `SET_INDESTRUCTIBLE` or modifying `SELFDESTRUCT` behavior) must be implemented so that nonces cannot be reused. It must be a consensus change, and not simply part of `AA_PREFIX`, so that transaction hash uniqueness is maintained. + +### Miners refuse transactions that access external data or the target's own balance, before PAYGAS + +An important property of traditional transactions is that activity happening as part of transactions that originate outside of some given account X cannot make transactions whose sender is X invalid. The only state change that an outside transaction can impose on X is increasing its balance, which cannot invalidate a transaction. + +Allowing AA contracts to access external data (both other accounts and environment variables such as GASPRICE, DIFFICULTY, etc.) before they call `PAYGAS` (ie. during the verification phase) breaks this invariant. For example, imagine someone sends many thousands of AA transactions that perform an external call `if FOO.get_number() != 5: throw()`. `FOO.number` might be set to `5` when those transactions are all sent, but a single transaction to `FOO` could set the `number` to something else, invalidating _all of the thousands of AA transactions_ that depend on it. This would be a serious DoS vector. + +The one allowed exception is contracts that are indestructible (that is, whose first byte is the `SET_INDESTRUCTIBLE` opcode defined in [this EIP](https://hackmd.io/@HWeNw8hNRimMm2m2GH56Cw/SyNT3Cdmw)). This is a safe exception, because the data that is being read cannot be changed. + +Disallowing reading `BALANCE` blocks a milder attack vector: an attacker could force a transaction to be reprocessed at a mere cost of 6700 gas (not 15000 or 21000), in the worst case more than doubling the number of transactions that would need to be reprocessed. + +In the long term, AA could be expanded to allow reading external data, though protections such as mandatory access lists would be required. + +### AA transactions must call contracts with prefix + +The prelude is used to ensure that *only* AA transactions can call the contract. This is another measure taken to ensure the invariant described above. If this check did not occur, it would be possible for a transaction originating outside some AA account X to call into X and make a storage change, forcing transactions targeting that account to be reprocessed at the cost of a mere 5000 gas. + +### Multi-tenant AA + +Multi-tenant AA extends single-tenant AA by **better handling cases where distinct and uncoordinated users attempt to send transactions for/to the same account and those transactions may interfere with each other**. + +We can understand the value of multi-tenant AA by examining two example use cases: (i) [tornado.cash](http://tornado.cash) and (ii) [Uniswap](http://uniswap.exchange). In both of these cases, there is a single central contract that represents the application, and not any specific user. Nevertheless, there is important value in using abstraction to do application-specific validation of transactions. + +#### Tornado Cash + +The tornado.cash workflow is as follows: + +1. A user sends a transaction to the TC contract, depositing some standard quantity of coins (eg. 1 ETH). A record of their deposit, containing the hash of a secret known by the user, is added to a Merkle tree whose root is stored in the TC contract. +2. When that user later wants to withdraw, they generate and send a ZK-SNARK proving that they know a secret whose hash is in a leaf somewhere in the deposit tree (without revealing where). The TC contract verifies the ZK-SNARK, and also verifies that a nullifier value (also derivable from the secret) has not yet been spent. The contract sends 1 ETH to the user's desired address, and saves a record that the user's nullifier has been spent. + +The privacy provided by TC arises because when a user makes a withdrawal, they can prove that it came from _some_ unique deposit, but no one other than the user knows which deposit it came from. However, implementing TC naively has a fatal flaw: the user usually does not yet have ETH in their withdrawal address, and if the user uses their deposit address to pay for gas, that creates an on-chain link between their deposit address and their withdrawal address. + +Currently, this is solved via relayers; a third-party relayer verifies the ZK-SNARK and unspent status of the nullifier, publishes the transaction using their own ETH to pay for gas, and collects the fee back from the user from the TC contract. + +AA allows this without relayers: the user could simply send an AA transaction targeting the TC contract, the ZK-SNARK verification and the nullifier checking can be done in the verification step, and PAYGAS can be called directly after that. This allows the withdrawer to pay for gas directly out of the coins going to their withdrawal address, avoiding the need for relayers or for an on-chain link to their deposit address. + +Note that fully implementing this functionality requires AA to be structured in a way that supports multiple users sending withdrawals at the same time (requiring nonces would make this difficult), and that allows a single account to support both AA transactions (the withdrawals) and externally-initiated calls (the deposits). + +#### Uniswap + +A new version of Uniswap could be built that allows transactions to be sent that directly target the Uniswap contract. Users could deposit tokens into Uniswap ahead of time, and Uniswap would store their balances as well as a public key that transactions spending those balances could be verified against. An AA-initiated Uniswap trade would only be able to spend these internal balances. + +This would be useless for normal traders, as normal traders have their coins outside the Uniswap contract, but it would be a powerful boon to arbitrageurs. Arbitrageurs would deposit their coins into Uniswap, and they would be able to send transactions that perform arbitrage every time external market conditions change, and logic such as price limits could be enforced during the verification step. Hence, transactions that do not get in (eg. because some other arbitrageur made the trade first) would not be included on-chain, allowing arbitrageurs to not pay gas, and reducing the number of "junk" transactions that get included on-chain. This could significantly increase both de-facto blockchain scalability as well as market efficiency, as arbitrageurs would be able to much more finely correct for cross-exchange discrepancies between prices. + +Note that here also, Uniswap would need to support both AA transactions and externally-initiated calls. + +## Backwards Compatibility + +This AA implementation preserves the existing transaction type. The use of `assert origin == caller` to verify that an account is an EOA remains sound, but is not extensible to AA accounts; AA transactions will always have `origin == AA_ENTRY_POINT`. + +Badly-designed single-tenant AA contracts will break the transaction non-malleability invariant. That is, it is possible to take an AA transaction in-flight, modify it, and have the modified version still be valid; AA account contracts can be designed in such a way as to make that not possible, but it is their responsibility. Multi-tenant AA will break the transaction non-malleability invariant much more thoroughly, making the transaction hash unpredictable even for legitimate applications that use the multi-tenant AA features (though the invariant will not further break for applications that existed before then). + +AA contracts may not have replay protection unless they build it in explicitly; this can be done with the `CHAINID (0x46)` opcode introduced in [EIP 1344](./eip-1344.md). + +## Test Cases +See: [https://github.com/quilt/tests/tree/account-abstraction](https://github.com/quilt/tests/tree/account-abstraction) + +## Implementation +See: [https://github.com/quilt/go-ethereum/tree/account-abstraction](https://github.com/quilt/go-ethereum/tree/account-abstraction) + +## Security Considerations + +See [https://ethresear.ch/t/dos-vectors-in-account-abstraction-aa-or-validation-generalization-a-case-study-in-geth/7937](https://ethresear.ch/t/dos-vectors-in-account-abstraction-aa-or-validation-generalization-a-case-study-in-geth/7937) for an analysis of DoS issues. + +### Re-validation + +When a transaction enters the mempool, the client is able to quickly ascertain whether the transaction is valid. Once it determines this, it can be confident that the transaction will continue to be valid unless a transaction from the same account invalidates it. + +There are, however, cases where an attacker can publish a transaction that invalidates existing transactions and requires the network to perform more recomputation than the computation in the transaction itself. The EIP maintains the invariant that recomputation is bounded to a theoretical maximum of six times the block gas limit in a single block; this is somewhat more expensive than before, but not that much more expensive. + +#### Peer denial-of-service + +Denial-of-Service attacks are difficult to defend against, due to the difficulty in identifying sybils within a peer list. At any moment, one may decide (or be bribed) to initiate an attack. This is not a problem that Account Abstraction introduces. It can be accomplished against existing clients today by inundating a target with transactions whose signatures are invalid. However, due to the increased allotment of validation work allowed by AA, it's important to bound the amount of computation an adversary can force a client to expend with invalid transactions. For this reason, it's best for the miner to follow the recommended mining strategies. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2942.md b/EIPS/eip-2942.md new file mode 100644 index 00000000000000..265660ceaee3b1 --- /dev/null +++ b/EIPS/eip-2942.md @@ -0,0 +1,7 @@ +--- +eip: 2942 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2942.md diff --git a/EIPS/eip-2970.md b/EIPS/eip-2970.md new file mode 100644 index 00000000000000..0d58fe4d4ffe9a --- /dev/null +++ b/EIPS/eip-2970.md @@ -0,0 +1,39 @@ +--- +eip: 2970 +title: IS_STATIC opcode +author: Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/is-static-opcode-useful-for-aa/4609 +status: Stagnant +type: Standards Track +category: Core +created: 2020-09-13 +--- + +## Simple Summary + +Add a `IS_STATIC (0x4A)` opcode that pushes `1` if the current context is static (ie. the execution is in a `STATICCALL` or a descendant thereof, so state-changing operations are not possible), and `0` if it is not. + +## Abstract + +## Motivation + +The main intended use case is to allow account abstraction (EIP 2938) to be extended so that accounts can allow static calls from the outside (which are harmless to AA's security model) but not state-changing calls. + +## Specification + +Add a `IS_STATIC (0x4A)` opcode that pushes `1` if the current context is static (ie. the execution is in a `STATICCALL` or a descendant thereof, so state-changing operations are not possible), and `0` if it is not. + +## Rationale + +Determining staticness is already possibly using the following hacky technique: make a `CALL` with limited gas, and inside that `CALL` issue one `LOG` and exit. If the context is static, the `CALL` would fail and leave a 0 on the stack; if the context is non-static, the `CALL` would succeed. However, this technique is fragile against changes to gas costs, and is needlessly wasteful. Hence, the status quo neither allows a reasonably effective way of determining whether or not the context is static, nor provides any kind of invariant that executions that do not fail outright will execute the same way in a static and non-static context. This EIP provides a cleaner way of determining staticness. + +## Backwards Compatibility + +TBD + +## Security Considerations + +TBD + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2972.md b/EIPS/eip-2972.md new file mode 100644 index 00000000000000..0db0c868d1bac8 --- /dev/null +++ b/EIPS/eip-2972.md @@ -0,0 +1,127 @@ +--- +eip: 2972 +title: Wrapped Legacy Transactions +author: Micah Zoltu (@MicahZoltu) +discussions-to: https://ethereum-magicians.org/t/eip-2972-wrapped-legacy-transactions/4604 +status: Withdrawn +type: Standards Track +category: Core +created: 2020-09-12 +requires: 155, 2718 +--- + +## Simple Summary +Two new transaction types for wrapping legacy transactions with and without a chain ID. + +## Abstract +Introduces two new [EIP-2718](./eip-2718.md) transactions that are signature compatible with legacy transactions and can be automatically upgraded by any client. + +* `0x00 || ssz.serialize(yParity, r, s, rlp([nonce, gasPrice, gasLimit, to, value, data]))` +* `0x01 || ssz.serialize(yParity, r, s, rlp([nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0]))` + +## Motivation +We would like to eventually deprecate legacy transactions so we no longer have to retain code in the networking and signer layer that deals with them. +However, we also want to ensure that signatures for transactions that were generated prior to that deprecation are still valid and funds don't end up stuck because of an inability to sign a new style transaction. +This EIP provides a mechanism for transmitting/including transactions in a way that is [EIP-2718](./eip-2718.md) compatible while still being signature compatible with legacy transactions. + +## Specification +### Definitions +* `||` is the byte/byte-array concatenation operator. +* `yParity` is the parity (0 for even, 1 for odd) of the `y` value of the curve point for which `r` is the `x` value in the secp256k1 signing process. + +### Transactions +As of `FORK_BLOCK_NUMBER`, `0x00 || ssz.serialize(yParity, r, s, rlp([nonce, gasPrice, gasLimit, to, value, data]))` will be a valid transaction where: +* the RLP encoded transaction portion is signed/processed/handled exactly the same as legacy transactions were signed/processed/handled, with the exception of the final encoding +* TODO: Hashing or Merkleizing for block transaction root + +As of `FORK_BLOCK_NUMBER`, `0x01 || ssz.serialize(yParity, r, s, rlp([nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0]))` will be a valid transaction where: +* the RLP encoded transaction portion is signed/processed/handled exactly the same as legacy transactions were signed/processed/handled, with the exception of the final encoding +* TODO: Hashing or Merkleizing for block transaction root + +The SSZ schema for both transaction types is: + ``` + Transaction[ + yParity: boolean, + r: bytes32, + s: bytes32, + signedData: bytes, + ] + ``` + +Note: `sszencode(yParity, r, s, rlp(...))` is the same as `yParity || r || s || 0x45000000 || rlp(...)` + +As of `FORK_BLOCK_NUMBER`, `rlp(nonce, gasPrice, gasLimit, to, value, data, v, r, s)` will no longer be a valid transaction in a block. + +### Receipts +As of `FORK_BLOCK_NUMBER`, `0 || ssz.serialize(status, cumulativeGasUsed, logsBloom, logs)` will be a valid receipt where: +* the `ReceiptPayload` will be generated/processed/handled exactly the same as legacy receipts were processed/handled with the exception of its encoding +* TODO: Hashing or Merkleizing for block receipt root + +As of `FORK_BLOCK_NUMBER`, `1 || ssz.serialize(status, cumulativeGasUsed, logsBloom, logs)` will be a valid receipt where: +* the `ReceiptPayload` will be generated/processed/handled exactly the same as legacy receipts were processed/handled with the exception of its encoding +* TODO: Hashing or Merkleizing for block receipt root + +The SSZ schema for both receipt types is: +``` +Log[ + address: bytes20, + topics: List[bytes32, 4], + data: List[uint8, 0xffffff], +] +Receipt[ + status: uint8, + cumulativeGasUsed: uint64, + logsBloom: BitVector[2048], + logs: List[Log, 0xffffff], +] +``` + +As of `FORK_BLOCK_NUMBER`, `rlp(status, cumulativeGasUsed, logsBloom, logs)` will no longer be a valid receipt in a block. + +## Rationale +### Signature doesn't include transaction type as first signature byte +These transaction types are explicitly designed to be signature compatible with legacy transactions, which means we cannot change the data being signed. +See Security Considerations section for more details. +### Two transaction types instead of one +With the introduction of typed transactions, we no longer need to do bit packing to avoid changing the shape of the signature. +Legacy transactions introduced chain ID in [EIP-155](./eip-155.md) and wanted to avoid changing the transaction array length, so it bitpacked the chainID into the signature's `v` value. +Since we no longer need to guarantee consistent payload lengths between transaction types, we have opted to have two transaction types with clear fields. +### Signature separate from signed data +When validating a signature, one must first separate out the signed data from the signature and then validate the signature against the signed data. +In the case of legacy transactions, this was a bit of a burden since you had to first RLP decode the transaction, then extract out the signature, then RLP encode a subset of the transaction. +EIP-155 made this process even worse by requiring the validator to further decode the `v` signature value to extract the chain ID (if present) and include that in the signed data payload. +By having the signed data encoded exactly as it is signed, we make it so one can verify the transaction's signature without having to do any decoding before hand. +By having the signature SSZ encoded up front, we can easily extract the signature without even having to use a decoder. +### SSZ for serialization +There is a weak consensus that RLP is not a particularly good encoding scheme for hashed data partially due to its inability to be streamed. +SSZ is almost certainly going to be included in Ethereum at some point in the future, so clients likely have access to an SSZ decoder. +For this particular case, manual decoding without a full SSZ decoder isn't too complicated, though it does require doing a bit of "pointer math" since `logs` is an array of variable length items. +### Deprecating legacy transactions +By deprecating legacy transactions, we make it easier for clients as they can always deal with typed transactions in blocks. +### Max length of logs and logs data +[EIP-706](./eip-706.md) limits devp2p messages to 24 bit length, which gives us a pragmatic cap at that for any single transaction at the moment. +This number seems to far exceed what is reasonable anytime in the near future, so feels like as reasonable of a cap as any. + +## Backwards Compatibility +The new transactions are signature compatible with legacy transactions. +Legacy transactions can be decoded and then encoded as type 0 or type 1 transactions. +This EIP does not introduce any deprecation process for legacy encoded transactions, though the authors do encourage client developers to upgrade legacy encoded transactions to typed transactions as soon as it is reasonable. + +The signature compatibility means that a client may see the same transaction encoded both ways. +In such a case the client can choose which to retain, but it is encouraged to retain the typed transaction rather than the legacy encoded transaction. +Since the two transactions would share a nonce, only one will ever be valid in a chain at a time. + +## Test Cases +TBD + +## Implementation +TBD + +## Security Considerations +While [EIP-2718](./eip-2718.md) strongly recommends including the transaction type as the first byte of the signed data, we cannot accomplish that in this case because we need to remain signature compatible with legacy transactions. +Luckily, [EIP-2718](./eip-2718.md) also excludes transaction types `0xc0` to `0xfe` from valid transaction types, and the first byte of the signature in this case is in that range so we can be sure this will not conflict with any future transaction types. + +A signature for these transaction types **does** collide with legacy transactions, but the transactions will be processed the same so it doesn't matter if the transaction ends up included as a legacy transaction or a typed transaction. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2976.md b/EIPS/eip-2976.md new file mode 100644 index 00000000000000..36bd2d463a7f48 --- /dev/null +++ b/EIPS/eip-2976.md @@ -0,0 +1,97 @@ +--- +eip: 2976 +title: Typed Transactions over Gossip +description: Adds support for transmission of typed transactions over devp2p. +author: Micah Zoltu (@MicahZoltu) +discussions-to: https://ethereum-magicians.org/t/eip-2976-eth-typed-transactions-over-gossip/4610 +status: Final +type: Standards Track +category: Networking +created: 2020-09-13 +requires: 2718 +--- + +## Abstract +[Typed Transactions](./eip-2718.md) can be sent over devp2p as `TransactionType || TransactionPayload`. +The exact contents of the `TransactionPayload` are defined by the `TransactionType` in future EIPs, and clients may start supporting their gossip without incrementing the devp2p version. +If a client receives a `TransactionType` that it doesn't recognize, it **SHOULD** disconnect from the peer who sent it. +Clients **MUST NOT** send new transaction types before they believe the fork block is reached. + +## Motivation +[EIP-2718](./eip-2718.md) introduced new transaction types for blocks (which presents itself in the makeup of a block header's transaction root and receipts root). +However, without a mechanism for gossiping these transactions, no one can actually include them in a block. +By updating devp2p to support the gossip of Typed Transactions, we can benefit from these new transaction types. + +*Note: See [EIP-2718](./eip-2718.md) for additional motivations of Typed Transactions.* + +## Specification +All changes specified below apply to all protocol/versions retroactively. + +### Definitions +* `||` is the byte/byte-array concatenation operator. +* `|` is the type union operator. +* `DEVP2P_VERSION = TBD` +* `Transaction` is either `TypedTransaction` or `LegacyTransaction` +* `TypedTransaction` is a byte array containing `TransactionType || TransactionPayload` +* `TypedTransactionHash` is `keccak256(TypedTransaction)` +* `TransactionType` is a positive unsigned 8-bit number between `0` and `0x7f` that represents the type of the transaction +* `TransactionPayload` is an opaque byte array whose interpretation is dependent on the `TransactionType` and defined in future EIPs +* `LegacyTransaction` is an array of the form `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` +* `LegacyTransactionHash` is `keccak256(rlp(LegacyTransaction))` +* `TransactionId` is `keccak256(TypedTransactionHash | LegacyTransactionHash)` +* `Receipt` is either `TypedReceipt` or `LegacyReceipt` +* `TypedReceipt` is a byte array containing `TransactionType || ReceiptPayload` +* `ReceiptPayload` is an opaque byte array whose interpretation is dependent on the `TransactionType` and defined in future EIPs +* `LegacyReceipt` is an array of the form `[status, cumulativeGasUsed, logsBloom, logs]` +* `LegacyReceiptHash` is `keccak256(rlp(LegacyReceipt))` + +### Protocol Behavior +If a client receives a `TransactionType` it doesn't recognize via any message, it **SHOULD** disconnect the peer that sent it. + +If a client receives a `TransactionPayload` that isn't valid for the `TransactionType`, it **SHOULD** disconnect the peer that sent it. + +Clients **MUST NOT** send transactions of a new `TransactionType` until that transaction type's introductory fork block. + +Clients **MAY** disconnect peers who send transactions of a new `TransactionType` significantly before that transaction type's introductory fork block. + +### Protocol Messages +`Transactions (0x02)`: `[Transaction_0, Transaction_1, ..., Transaction_n]` + +`BlockBodies (0x06)`: `[BlockBody_0, BlockBody_1, ..., BlockBody_n]` where: +* `BlockBody` is `[TransactionList, UncleList]` +* `TransactionList` is `[Transaction_0, Transaction_1, ..., Transaction_n]` +* `UnclesList` is defined in previous versions of the devp2p specification + +`NewBlock (0x07)`: `[[BlockHeader, TransactionList, UncleList], TotalDifficulty]` where: +* `BlockHeader` is defined in previous versions of the devp2 specification +* `TransactionList` is `[Transaction_0, Transaction_1, ..., Transaction_n]` +* `UnclesList` is defined in previous versions of the devp2p specification +* `TotalDifficulty` is defined in previous versions of the devp2p specification + +`NewPooledTransactionIds (0x08)`: `[TransactionId_0, TransactionId_1, ..., TransactionId_n]` + +`GetPooledTransactions (0x09)`: `[TransactionId_0, TransactionId_1, ..., TransactionId_n]` + +`PooledTransactions (0x0a)`: `[Transaction_0, Transaction_1, ..., Transaction_n]` + +`Receipts (0x10)`: `[ReceiptList_0, ReceiptList_1, ..., ReceiptList_n]` where: +* `ReceiptList` is `[Receipt_0, Receipt_1, ..., Receipt_n]` + +## Rationale +### Why not specify each transaction type at the protocol layer? +We could have chosen to make the protocol aware of the shape of the transaction payloads. +The authors felt that it would be too much maintenance burden long term to have every new transaction type require an update to devp2p, so instead we merely define that typed transactions are supported. +### Why have peers disconnect if they receive an unknown transaction type? +We could encourage peers to remain connected to peers that submit an unknown transaction type, in case the transaction is some new transaction type that the receiver isn't aware of it. +However, doing so may open clients up to DoS attacks where someone would send them transactions of an undefined `TransactionType` in order to avoid being disconnected for spamming. +Also, in most cases we expect that by the time new transaction types are being sent over devp2p, a hard fork that requires all connected clients to be aware of the new transaction type is almost certainly imminent. + +## Backwards Compatibility +Legacy transactions are still supported. + +## Security Considerations +If a client chooses to ignore the **SHOULD** recommendation for disconnecting peers that send unknown transaction types they may be susceptible to DoS attacks. +Ignoring this recommendation should be limited to trusted peers only, or other situations where the risk of DoS is extremely low. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2980.md b/EIPS/eip-2980.md new file mode 100644 index 00000000000000..84cdaf8aa83904 --- /dev/null +++ b/EIPS/eip-2980.md @@ -0,0 +1,7 @@ +--- +eip: 2980 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2980.md diff --git a/EIPS/eip-2981.md b/EIPS/eip-2981.md new file mode 100644 index 00000000000000..9b6e89e7e50d44 --- /dev/null +++ b/EIPS/eip-2981.md @@ -0,0 +1,7 @@ +--- +eip: 2981 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2981.md diff --git a/EIPS/eip-2982.md b/EIPS/eip-2982.md new file mode 100644 index 00000000000000..379dfb5cdbe993 --- /dev/null +++ b/EIPS/eip-2982.md @@ -0,0 +1,443 @@ +--- +eip: 2982 +title: Serenity Phase 0 +description: Phase 0 of the release schedule of Serenity, a series of updates to Ethereum a scalable, proof-of-stake consensus +author: Danny Ryan (@djrtwo), Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/serenity-phase-0-eip/4621 +status: Final +type: Informational +created: 2020-09-15 +--- + +## Abstract + +This EIP specifies Phase 0 of Serenity (eth2), a multi-phased upgrade to the consensus mechanism for Ethereum mainnet. In Phase 0, the existing PoW chain and mechanics are entirely unaffected, while a PoS chain -- the beacon chain -- is built in parallel to serve as the core of the upgraded consensus. In subsequent phases, the beacon chain is enhanced to support and secure the consensus of a number of parallel shard chains, ultimately incorporating current Ethereum mainnet as one of those shards. + +At the core of the beacon chain is a proof of stake consensus mechanism called Casper the Friendly Finality Gadget (FFG) and a fork-choice rule called Latest Message Driven Greedy Heaviest Observed Sub-Tree (LMD-GHOST). Phase 0 is centered primarily around the mechanics and incentives of validators executing these algorithms. The detailed specifications for eth2 are contained in an independent repository from this EIP, and safety and liveness proofs can be found in the [Combining GHOST and Casper](../assets/eip-2982/arxiv-2003.03052-Combining-GHOST-and-Casper.pdf) paper. To avoid duplication, this EIP just references relevant spec files and releases. + +Early phases of eth2 are executed without any breaking consensus changes on current Ethereum mainnet. This EIP serves to document the bootstrapping of this consensus mechanism and note the path for eth2 to supplant Ethereum's current proof-of-work (PoW) consensus. + +## Motivation + +Eth2 aims to fulfill the original vision of Ethereum to support an efficient, global-scale, general-purpose transactional platform while retaining high cryptoeconomic security and decentralization. + +Today, Ethereum blocks are consistently full due to increasingly high demand for decentralized applications. Ever since the first serious spikes in adoption in 2017 (cryptokitties), the Ethereum community has consistently and vocally demanded scaling solutions. + +Since day 0 of Ethereum, the investigation and expectation in scaling solutions has been two-pronged -- scale from both Layer 1 upgrades and Layer 2 adoption. This EIP represents the start to a multi-phased rollout of the former. + +### Scaling through sharding + +As the Ethereum network and the applications built upon it have seen increasing usage over the past 5 years, blocks have become regularly full and the gas price market continues to climb. Simple increases to the block gas-limit of the current Ethereum chain are unable to account for the increase in demand of the system without inducing an unsustainably high resource burden (in the form of bandwidth, computational, and disk resources) on consumer nodes. To retain decentralization while scaling up the Ethereum network, another path must be taken. + +To provide more scale to Ethereum, while not inducing a restrictively high burden on both consumer and consensus nodes, eth2 introduces a "sharded" solution in which a number of blockchain shards -- each of similar capacity to Ethereum mainnet today -- run in parallel under a unified consensus mechanism. The core consensus (the beacon chain) and a small number of these shards can be processed via a single consumer machine, while the aggregate of the system provides much higher capacity. + +### Decentralization and economic finality through proof-of-stake + +Since the early days of Ethereum, proof-of-stake has been a long-awaited desideratum for the following: +* Increased decentralization of the core consensus by lowering the barrier to entry and technical requirements of participation +* Increased cryptoeconomic security via in-protocol penalties for misbehaviour and the addition of economic finality +* Elimination of the energy hungry mining of the current PoW consensus mechanism + +In addition to the above, PoS has synergies with the sharding scaling solution. Due to the random sampling requirement of sharding, PoS provides a more simple and direct access to the "active validator set" than PoW and thus allows for a more direct sharded protocol construction. + + +## Specification + +Phase 0 is designed to require _no breaking consensus changes_ to existing Ethereum mainnet. Instead, this is the bootstrapping a new PoS consensus that can, once stable, supplant the current PoW consensus. + +Phase 0 specifications are maintained in a repository independent of this EIP. `SPEC_RELEASE_VERSION` release of the specs at `SPEC_RELEASE_COMMIT` are considered the canonical Phase 0 specs for this EIP. + +This EIP provides a high level view on the Phase 0 mechanisms, especially those that are relevant to Ethereum mainnet (e.g. the deposit contract) and users (e.g. validator mechanics and eth2 issuance). The extended and low level details remain in the `consensus-specs` repository + +### Parameters + +| Parameter | Value | +| - | - | +| `SPEC_RELEASE_VERSION` | `v1.0.0` | +| `SPEC_RELEASE_COMMIT` | `579da6d2dc734b269dbf67aa1004b54bb9449784` | +| `DEPOSIT_CONTRACT_ADDRESS` | `0x00000000219ab540356cBB839Cbe05303d7705Fa` | +| `MIN_GENESIS_TIME` | `1606824000` | +| `BASE_REWARD_FACTOR` | `2**6` (64) | +| `INACTIVITY_PENALTY_QUOTIENT` | `2**26` (67,108,864) | +| `PROPORTIONAL_SLASHING_MULTIPLIER` | `1` | +| `MIN_SLASHING_PENALTY_QUOTIENT` | `2**7` (128) | + +_Note:_ Eth2 has many more Phase 0 configuration parameters but the majority are left out of this EIP for brevity. + +### Validator deposit contract + +In Phase 0, eth2 uses a contract deployed on Ethereum mainnet -- the Deposit Contract -- at `DEPOSIT_CONTRACT_ADDRESS` to onboard validators into the PoS consensus of the beacon chain. + +To participate in the PoS consensus, users submit validator deposits to the deposit contract. The beacon chain comes to consensus on the state of this contract and processes new validator deposits. This uni-directional deposit mechanism is the only technical link between the two components of the system (Ethereum mainnet and beacon chain) in Phase 0. + +### Beacon chain and validator mechanics + +Users who choose to participate in eth2 consensus deposit ETH collateral into the deposit contract in order to be inducted into the beacon chain validator set. From there, these validators are responsible for constructing the **beacon chain** (note that these consensus participants in PoS are akin to miners in PoW). + +The beacon chain is a pure PoS chain that in Phase 0 is primarily concerned with maintaining its own consensus and managing the registry of validators. The consensus rules define _roles_ (e.g. block proposal, block attesting) that validators are expected to participate in; validators who perform their roles well are rewarded, and validators who perform their roles poorly or are offline are penalized. Phase 0 does not yet include any ETH transfer, sharding or smart contract / VM execution capabilities. + +In subsequent phases, additional mechanisms and validator responsibilities will be added to the beacon chain to manage the consensus of a number of parallel shard chains ("Phase 1"), to integrate the existing Ethereum system ("Phase 1.5") and to add full support for sharded smart contract execution ("Phase 2"). + +### Issuance + +To incentivize validators to deposit ether collateral and participate in the eth2 consensus, we propose that rewards (in the form of Ethereum's native asset, ether) be regularly issued to consensus participants. Due to the beacon chain operating in parallel to the existing PoW chain in early phases of eth2, this issuance is _in addition to_ any PoW rewards until the existing chain is merged into eth2 as a shard. + +The amount of ether issued to validators on the beacon chain is proportional to the square root of the total ether deposited. This issuance curve was chosen as a more stable and sustainable curve to the two obvious alternatives -- fixed total issuance and fixed issuance per ether staked. For a more technical discussion on this choice see [here](../assets/eip-2982/ef-Discouragement-Attacks.pdf). + +In eth2, this curve is parameterized by `BASE_REWARD_FACTOR` in the context of slot time and epoch length. Below is the issuance curve as a function of ether staked, along with a table of examples for illustration. Note, all figures shown are annualized. + +![](../assets/eip-2982/2982-issuance.png) + +| Active Deposits | Max Annual Validator Reward\* | Max Annual ETH Issued\* | +| -------- | -------: | --------: | +| 0.5M ETH | 23.50% | 117,527 | +| 1M ETH | 16.60% | 166,208 | +| 2M ETH | 11.75% | 235,052 | +| 4M ETH | 8.31% | 332,411 | +| 8M ETH | 5.88% | 470,104 | +| 16M ETH | 4.16% | 664,801 | +| 32M ETH | 2.94% | 940,167 | +| 64M ETH | 2.08% | 1,329,603 | +| 128M ETH | 1.47% | 1,880,334 | + +_\*Assuming validators are online 100% of the time and behaving optimally. Suboptimal validator behavior will lead to reduced rewards and/or penalties that reduce total issuance._ + +### Initial punitive parameters + +For PoS protocols to be crypto-economically secure, in-protocol penalties are required. Small offline penalties incentivize validator liveness, whereas (potentially) much larger penalties provide protocol security in the event of tail-risk scenarios. + +Specifically, the following significant penalties exist: +* **Inactivity Leak**: an offline penalty that increases each epoch is applied to validators during extended times of no finality (e.g. if one-third or more are offline or not on the canonical chain). This ensures the chain can eventually regain finality even under catastrophic conditions. +* **Slashing**: a penalty applied to validators that sign _explicitly malicious_ messages that could lead to the construction and finalization of two conflicting chains (e.g. two blocks or attestations in the same slot). This penalty is designed to scale up in proportion to the number of slashable validators in the same time period such that if a critical number (wrt chain safety) of slashings have occurred, validators are _maximally_ punished. + +For the initial launch of Phase 0, the parameters defining the magnitude of these penalties -- `INACTIVITY_PENALTY_QUOTIENT`, `PROPORTIONAL_SLASHING_MULTIPLIER`, and `MIN_SLASHING_PENALTY_QUOTIENT` -- have been tuned to be less punitive than their final intended values. This provides a more forgiving environment for early validators and client software in an effort to encourage validation in this early, higher technical-risk stage. + +_`INACTIVITY_PENALTY_QUOTIENT` is configured initially to four times its final value_. This results in a slower inactivity leak during times of non-finality, which means the chain is less responsive to such an event. If there is an extended time of non-finality during the early months of eth2, it is far more likely to be due to technical issues with client software rather than some sort of global catastrophic event. + +_`PROPORTIONAL_SLASHING_MULTIPLIER` is configured initially to one-third of its final value_. This results in a lower accountable safety margin in the event of an attack. If any validators are slashed in the early months of eth2, it is far more likely to be the result of user mismanagement of keys and/or issues with client software than an organized attack. + +_`MIN_SLASHING_PENALTY_QUOTIENT` configured initially to four times its final value_. This results in a lower guaranteed minimum penalty for a slashable offense and thus reduces the baseline punitive incentive to keep an individual validator's system secure. As with `PROPORTIONAL_SLASHING_MULTIPLIER`, slashings during the early months of eth2 are far more likely to be due to user mismanagement, or issues with client software, than an organized attack. + +## Rationale + +### Principles + +* **Simplicity**: especially since cryptoeconomic proof of stake and quadratic sharding are inherently complex, the protocol should strive for maximum simplicity in its decisions as much as possible. This is important because it (i) minimizes development costs, (ii) reduces risk of unforeseen security issues, and (iii) allows protocol designers to more easily convince users that parameter choices are legitimate. When complexity is unavoidable to achieve a given level of functionality, the preference order for where the complexity goes is: layer 2 protocols > client implementations > protocol spec. +* **Long-term stability**: the low levels of the protocol should ideally be built so that there is no need to change them for a decade or longer, and any needed innovation can happen on higher levels (client implementations or layer 2 protocols). +* **Sufficiency**: it should be fundamentally possible to build as many classes of applications as possible on top of the protocol. +* **Defense in depth**: the protocol should continue to work as well as possible under a variety of possible security assumptions (eg. regarding network latency, fault count, the motivations of users) +* **Full light-client verifiability**: given some assumptions (eg. network latency, bounds on attacker budget, 1-of-N or few-of-N honest minority), a client verifying a small fixed amount of data (ideally just the beacon chain) should be able to gain indirect assurance that all of the data in the full system is available and valid, even under a 51% attack (note: this is a form of defense-in-depth but it's important enough to be separate) + +### The Layer 1 vs Layer 2 Tradeoff + +The Ethereum roadmap uses a mixed layer 1 / layer 2 approach. We focus on serving a particular type of layer 2 (rollups) because it's the only kind of layer 2 that both inherits the security of layer 1 and provides scaling of general-purpose applications. However, rollups come at a cost: they require some on-chain data _per transaction_, and so a blockchain with really high capacity rollups must be able to handle a still quite high amount of data bandwidth. So make this more feasible, we are implementing on scalable data layer technologies, particularly data availability sampling. + +The reason to not take a pure layer 2 approach is that pure layer 2 scaling can only be done either with trust-based solutions (not desirable), or with channels or plasma (which have inherent limitations and cannot support the full EVM. + +The reason to not take a pure layer 1 approach is to enable more room for experimentation in execution layers, and allow the base protocol to be simpler and have less intensive governance. + +### Why proof of stake + +In short: + +* **No need to consume large quantities of electricity** in order to secure a blockchain (e.g. it's estimated that both Bitcoin and Ethereum burn over $1 million worth of electricity and hardware costs per day as part of their consensus mechanism). +* Because of the lack of high electricity consumption, there is **not as much need to issue as many new coins** in order to motivate participants to keep participating in the network. It may theoretically even be possible to have negative net issuance, where a portion of transaction fees is "burned" and so the supply goes down over time. +* Proof of stake opens the door to a wider array of techniques that use game-theoretic mechanism design in order to better **discourage centralized cartels** from forming and, if they do form, from acting in ways that are harmful to the network (e.g. like selfish mining in proof of work). +* **Reduced centralization risks**, as economies of scale are much less of an issue. $10 million of coins will get you exactly 10 times higher returns than $1 million of coins, without any additional disproportionate gains because at the higher level you can afford better mass-production equipment, which is an advantage for Proof-of-Work. +* Ability to use economic penalties to **make various forms of 51% attacks vastly more expensive** to carry out than proof of work - to paraphrase Vlad Zamfir, "it's as though your ASIC farm burned down if you participated in a 51% attack". + +### Why Casper + +There are currently three major schools of proof of stake consensus algorithm: + +* **Nakamoto-inspired** (Peercoin, NXT, Ouroboros...) +* **PBFT-inspired** (Tendermint, Casper FFG, Hotstuff...) +* **CBC Casper** + +Within the latter two camps, there is also the question of whether and how to use security deposits and slashing (Nakamoto-inspired algorithms are incompatible with non-trivial slashing). All three are superior to proof of work, but we want to defend our own approach. + +#### Slashing + +Ethereum 2.0 uses a **slashing** mechanism where a validator that is detected to have misbehaved can be penalized, in the best case ~1% but in the worst case up to its entire deposit. + +We defend our use of slashing as follows: + +1. **Raising the cost of attack**: We want to be able to make a hard claim that a 51% attack on a proof of stake blockchain forces the attacker to incur a very large amount of expense (think: hundreds of millions of dollars worth of coins) that get burned, and any attack can be recovered from quickly. This makes the attack/defense calculus very unfavorable for attackers, and in fact makes attacks potentially _counterproductive_, because the disruption to service is outweighed by price gains to legitimate coin holders. +2. **Overcoming the validator's dilemma**: the most realistic immediate way for nodes to start to deviate from "honest" behavior is _laziness_ (ie. not validating things that one should be validating, signing everything just in case, etc). See [the validator's dilemma paper](../assets/eip-2982/iacr-2015-702-Demystifying-Incentives-in-the-Consensus-Computer.pdf) (Luu et al., CC BY) for theoretical reasoning and the Bitcoin SPV mining fork for examples of this happening and leading to very harmful consequences in the wild. Having very large penalties for self-contradicting or for signing incorrect things helps to alleviate this. + +A more subtle instance of (2) can be seen as follows. In July 2019 a validator on Cosmos was slashed for signing two conflicting blocks. An investigation revealed that this happened because that validator was running a primary and a backup node (to ensure that one of the two going offline would not prevent them from getting rewards) and the two were accidentally turned on at the same time, leading to them contradicting each other. + +If it became standard practice to have a primary and backup node, then an attacker could partition the network and get the primaries and the backups of all the validators to commit to different blocks, and thereby lead to two conflicting blocks being finalized. Slashing penalties help to heavily disincentivize this practice, reducing the risk of such a scenario taking place. + +#### Choice of consensus algorithm + +Only the BFT-inspired and CBC schools of consensus algorithm have a notion of finality, where a block is confirmed in such a way that a large portion (1/3 in BFT-inspired, 1/4 in CBC) of validators would need to misbehave and get slashed for that block to get reverted in favor of some conflicting block; Nakamoto-inspired (ie. longest-chain-rule) consensus algorithms have no way of achieving finality in this sense. + +Note that finality requires a (super)majority of validators being online, but this is a requirement of the sharding mechanism already, as it requires 2/3 of a randomly sampled committee of validators to sign off on a crosslink for that crosslink to be accepted. + +Our choice of [Casper FFG](../assets/eip-2982/arxiv-1710.09437-Casper-the-Friendly-Finality-Gadget.pdf) was simply a matter of it being the simplest algorithm available at the time that part of the protocol was being finalized. Details are still subject to long-term change; in particular, we are actively exploring solutions to achieve single slot finality. + +### Sharding - or, why do we hate supernodes? + +The main alternative to sharding for layer-1 scaling is the use of supernodes - simply requiring every consensus node to have a powerful server so that it can individually process every transaction. Supernode-based scaling is convenient because it is simple to implement: it works just the same way blockchains do now, except that more software-engineering work is required to build things in a way that is more parallelizable. + +Our main objections to this approach are as follows: + +* **Pool centralization risk**: in a supernode-based system, running a node has a high fixed cost, so far fewer users can participate. This is usually rebutted with "well consensus in most PoW and PoS coins is dominated by 5-20 pools anyway, and the pools will be able to run nodes just fine". However, this response ignores the risk of centralization pressure even between pools that can afford it. If the fixed cost of running a validator is significant relative to the returns, then larger pools will be able to offer smaller fees than smaller ones and this could lead to smaller pools being pushed out or feeling pressure to merge. In a sharded system, on the other hand, validators with more ETH need to verify more transactions, so costs are not fixed. +* **AWS centralization risk**: in a supernode-based system, home staking is infeasible and so it's more likely that most staking will happen inside cloud computing environments, of which there are only a few options to choose from. This creates a single point of failure. +* **Reduced censorship resistance**: making it impossible to participate in consensus without high computation+bandwidth requirements makes detection and censorship of validators easier. +* **Scalability**: as transaction throughput increases, in a supernode-based system the above risks increase, whereas sharded systems can more easily handle the increased load. + +These centralization risks are also why we are NOT attempting to achieve super-low-latency (<1s) of the blockchain, instead opting for (relatively!) conservative numbers. + +Instead, Ethereum is taking an approach where each validator is only assigned to process a small portion of all data. Only validators staking large amounts of ETH (think: tens of thousands or more) are required to process the entire data in the chain. + +Note that there is a possible middle-ground in sharding design where block _production_ is centralized but (i) block _verification_ is decentralized and (ii) there exist "bypass channels" where users can send transactions and block producers are forced to include them, so even a monopoly producer cannot censor. We are actively considering sharding designs that lean somewhat in this direction to increase simplicity so that scaling can be deployed faster, though if desired even within this spec it's possible to run distributed builders and avoid centralization even there. + + +### Security models + +It's commonly assumed that blockchains depend on an "honest majority" assumption for their security: that >=50% of participants will faithfully follow a prescribed protocol, even forgoing opportunities to defect for their own personal interest. In reality, (i) an honest majority model is unrealistic, with participants being "lazy" and signing off on blocks without validating them (see [the validator's dilemma paper](../assets/eip-2982/iacr-2015-702-Demystifying-Incentives-in-the-Consensus-Computer.pdf) and the Bitcoin SPV mining fork) being a very common form of defection, but fortunately (ii) blockchains maintain many or all of their security properties under much harsher models, and it's really important to preserve those extra guarantees. + +A common harsher model is the _uncoordinated rational majority_ model, which states that participants act in their own self-interest, but no more than some percentage (eg. 23.21% in simple PoW chains) are cooperating with each other. An even harsher model is the worst-case model where there is a single actor that controls more than 50% of hashpower or stake, and the question becomes: + +* Can we, even under that scenario, force the attacker to have to pay a very high cost to break the chain's guarantees? +* What guarantees can we unconditionally preserve? + +Slashing in proof of stake chains accomplishes the first objective. In non-sharded chains, every node verifying every block accomplishes the second objective for two specific guarantees: (i) that the longest chain is valid, and (ii) that the longest chain is _available_. + +A major challenge in sharding is getting the same two properties without requiring each node to verify the full chain. Our defense-in-depth approach with sharding accomplishes just that. The core idea is to combine together random committee sampling, proof of custody, fraud proofs, [data availability sampling (DAS)](../assets/eip-2982/arxiv-1809.09044-Fraud-and-Data-Availability-Proofs--Maximising-Light-Client-Security-and-Scaling-Blockchains-with-Dishonest-Majorities.pdf) and eventually ZK-SNARKs, to allow clients to detect and reject invalid or unavailable chains without downloading and verifying all of the data, even if the invalid chains are supported by a majority of all proof of stake validators. + +Censorship of transactions can potentially be detected by clients in a consensus-preserving way, but this research has not yet been incorporated into the ethereum roadmap. + +Here is the current expected security properties expressed in a table: + +| | Network delay <3s |Network delay 3s - 6 min|Network delay > 6 min| +|---|---|---|---| +|>2/3 validators honest|Perfect operation|Imperfect but acceptable operation. No rigorous proof of liveness, but liveness expected in practice.|Likely intermittent liveness failures, no safety failures| +|>2/3 validators rational, <1/3 coordinated|Perfect operation|Imperfect but acceptable operation, heightened centralization risk|Likely intermittent liveness failures, no safety failures, very high centralization risk| +|51% attacker|Can revert finality or censor, but at high cost; cannot force through invalid or unavailable chains|Can revert finality or censor, but at high cost; cannot force through invalid or unavailable chains|Can revert finality or censor; cannot force through invalid or unavailable chains| + +### Why are the Casper incentives set the way they are? + +#### Base rewards + +During each epoch, every validator is expected to make an "attestation", a signature that expresses that validator's opinion on what the head of the chain is. There is a reward for having one's attestation included, with four components (called "duties"): + +1. Reward for the attestation getting included at all +2. Reward for the attestation specifying the correct epoch checkpoint +3. Reward for the attestation specifying the correct chain head +4. Reward for correctly participating in sync committee signatures + +Note also that mixed into these duties is a timeliness requirement: your attestation has to be included within a certain time to be eligible for the rewards, and for the "correct head" duty that time limit is 1 slot. + +For each duty, the actual reward is computed as follows. If: + +* $R = B * \frac{nom}{den}$ equals the base reward multiplied by the fraction $\frac{nom}{den}$ that corresponds to that particular duty +* $P$ is the portion of validators that did the desired action + +Then: + +* Any validator that fulfilled the duty gets a reward of $R * P$ +* Any validator that did not fulfill the duty gets a penalty $-R$ + +The purpose of this "collective reward" scheme where "if anyone performs better, everyone performs better" is to bound griefing factors (see [this paper](../assets/eip-2982/ef-Discouragement-Attacks.pdf) for one description of griefing factors and why they are important). + +The base reward $B$ is itself calculated as $k * \frac{D_i}{\sqrt{\sum_{j=1}^{n} D_j}}$ where $D_1 ... D_n$ are deposit sizes and $k$ is a constant; this is a halfway compromise between two common models, (i) fixed reward rate, ie. $k * D_i$, and (ii) fixed total reward, ie. $k * \frac{D_i}{\sum_{j=1}^{n} D_j}$. + +The main argument against (i) is that it imposes too much uncertainty on the network of two kinds: uncertainty of the total level of issuance, and uncertainty of the total level of deposits (as if a fixed reward rate is set too low then almost no one will participate, threatening the network, and if a rate is set too high then very many validators will participate, leading to unexpectedly high issuance). The main argument against (ii) is greater vulnerability to discouragement attacks (again see the [discouragement attacks paper](../assets/eip-2982/ef-Discouragement-Attacks.pdf)). The inverse-square-root approach compromises between the two and avoids the worst consequences of each one. + +When an attestation gets a reward, the proposer gets a fraction of that reward. This is to encourage proposers to listen well for messages and accept as many as possible. + +Note also that the rewards are designed to be forgiving to validators who are offline often: being offline 1% of the time only sacrifices about 1.6% of your reward. This is also to promote decentralization: the goal of a decentralized system is to create a reliable whole out of unreliable parts, so we should not be trying to force each individual node to be extremely reliable. + +#### Inactivity leak + +If the chain fails to finalize for $tsf > 4$ epochs ($tsf$ = "time since finality"), then a penalty is added so that the maximum possible reward is zero (validators performing imperfectly get penalized), and a second penalty component is added, proportional to $tsf$ (that is, the longer the chain has not finalized, the higher the _per-epoch_ penalty for being offline). This ensures that if more than 1/3 of validators drop off, validators that are not online get penalized much more heavily, and the total penalty goes up quadratically over time. + +This has three consequences: + +* Penalizes being offline much more heavily in the case where you being offline is actually preventing blocks from being finalized +* Serves the goals of being an anti-correlation penalty (see section below) +* Ensures that if more than 1/3 do go offline, eventually the portion online goes back up to 2/3 because of the declining deposits of the offline validators + +With the current parametrization, if blocks stop being finalized, validators lose 1% of their deposits after 2.6 days, 10% after 8.4 days, and 50% after 21 days. This means for example that if 50% of validators drop offline, blocks will start finalizing again after 21 days. + +#### Slashing and anti-correlation penalties + +If a validator is caught violating the Casper FFG slashing condition, they get penalized a portion of their deposit equal to three times the portion of validators that were penalized around the same time as them (specifically, between 18 days before they were penalized and roughly the time they withdrew). This is motivated by several goals: + +* A validator misbehaving is only really bad for the network if they misbehave at the same time as many other validators, so it makes sense to punish them more in that case +* It heavily penalizes actual attacks, but applies very light penalties to single isolated failures that are likely to be honest mistakes +* It ensures that smaller validators take on less risk than larger validators (as in the normal case, a large validator would be the only one failing at the same time as themselves) +* It creates a disincentive against everyone joining the largest pool + +### BLS Signatures + +BLS signatures are used because of their aggregation-friendliness: any two signatures $S_1$ and $S_2$ of a message $M$ signed by keys $k_1$ and $k_2$ (corresponding pubkeys $K_1 = G * k_1$ and $K_2 = G * k_2$ where $G$ is the generator of the elliptic curve) can simply be aggregated by elliptic curve point addition: $S_1 + S_2$, which verifies against the public key $K_1 + K_2$. This allows many thousands of signatures to be aggregated, with the marginal cost of one signature being one bit of data (to express that a particular public key is present in the aggregate signature) and one elliptic curve addition for computation. + +Note that BLS signatures of this form are vulnerable to _rogue key attacks_: if you see that other validators have already published public keys $K_1 ... K_n$, then you can generate a private key $r$ and publish a public key $G * r - K_1 - ... - K_n$. The aggregate public key would simply be $G * r$, so you would be able to make a signature that verifies against the combined public key by yourself. The standard way to get around this is to require a _proof of possession_: basically, a signature of a message (that depends on the public key, and that would normally not be signed) that verifies against the public key by itself (ie. $sign(message=H'(K), key=k)$ for privkey $k$ and pubkey $K$, where $H'$ is a hash function). This ensures that you personally control the private key connected to the public key that you publish. + +We use the signature of a deposit message (which specifies the signing key but also other important data such as the withdrawal key) as a proof of possession. + +### Why 32 ETH validator sizes? + +Any BFT consensus algorithm with accountable fault tolerance (ie. if two conflicting blocks get finalized you can identify which 1/3 of nodes were responsible) must have all validators participate, and furthermore for technical reasons you need two rounds of every validator participating to finalize a message. + +This leads to the decentralization / finality time / overhead tradeoff: if $n$ is the number of validators in a network, $f$ is the time to finalize a block, and $\omega$ is the overhead in messages per second, then we have: + +$$\omega \ge \frac{2 * n}{f}$$ + +For example, if we are ok with an overhead of 10 messages per second, then a 10000-node network could only have a finality time of at least 2000 seconds (~33 minutes). + +In Ethereum's case, if we assume a total ETH supply of $\approx 2^{27}$ ETH, then with 32 ETH deposit sizes, there are at most $2^{22}$ validators (and that's if everyone validates; in general we expect ~10x less ETH validating). With a finality time of 2 epochs (2 * 32 * 12 = 768 seconds), that implies a max overhead of $\frac{2^{22}}{768} \approx 5461$ messages per second. We can tolerate such high overhead due to BLS aggregation reducing the marginal size of each signature to 1 bit and the marginal verification complexity to one elliptic curve addition. + +32 slots is a safe minimum for another reason: if an attacker manipulates the randomness used for proposer selection, this number still provides enough space to ensure that there will be at least one honest proposer in each epoch, which is sufficient to ensure blocks keep finalizing. Our calculations suggest that current levels of overhead are acceptable, but higher levels would make running a node too difficult. Finally, the validator deposit size is ideal for shard crosslinking (see below). + +### Random sampling + +#### Seed selection + +The seed used for randomness is updated every block by "mixing in" (ie. `seed <- xor(seed, new_data)`) a value that must be revealed by the proposer of the block. Just like proof of custody subkeys, a validator's values are all pre-determined once the validator has deposited, third parties cannot compute subkeys but can verify subkeys that are revealed voluntarily (this mechanism is sometimes called RANDAO). + +This ensures that each proposer has one "bit of manipulation" over the seed: they can either make a block or not make a block. Not making a block is expensive in that the proposer misses out on many rewards. Furthermore, because the persistent and beacon committee sizes (see below) are large, manipulation of the randomness almost certainly cannot allow minority attackers to get 2/3 of any committee. + +In the future we plan to use verifiable delay functions (VDFs) to further increase the random seeds' robustness against manipulation. + +#### Shuffling + +We use the swap-or-not shuffle described by Viet Tung Hoang, Ben Morris, and Phillip Rogaway to shuffle the validator set and assign responsibilities every epoch. This algorithm ensures that: + +* As the shuffle is a permutation, each validator is assigned to be a member of exactly one committee during each epoch (keeping their load stable and reducing the chance manipulation of randomness can be profitable) +* As the shuffle is pointwise-evaluable in the forward direction, a validator can determine their own responsibilities in O(1) time +* As the shuffle is pointwise-evaluable in the reverse direction, the members of any specific committee or the proposer of any specific block can be computed in O(1) time + +#### Shuffling by slot + +There are 32 slots in an epoch, and the validators responsible for attesting to each slot are chosen by shuffling. This ensures that attackers with a significant but still small portion of total stake cannot take over specific slots and cause short-range reorgs. + +#### Beacon committees + +The committee for each slot is in turn split up into some number of _beacon committees_. Today (2022 Jan), this design does serve one useful function, allowing different subsets of attestations to get aggregated in separate subnets and thus making the p2p network more efficient. However, it does not serve any other useful consensus-related role. + +In the original sharding design, the intention was that each beacon committee would be responsible for verifying a specific shard. However, this approach is likely deprecated if we switch to a single-proposer model. Hence, the more fine-grained beacon committees may well only be there vestigially and could eventually be removed or re-structured in a different way to focus on facilitating attestation aggregation. + +#### Sync committee + +A sync committee of 512 validators is selected once every ~27 hours to sign a block; this committee's pubkeys are saved in an easily accessible list, allowing signatures to be easily verified by ultra-light clients. + +### LMD GHOST fork choice rule + +The beacon chain uses an LMD GHOST fork choice rule. + +The LMD GHOST fork choice rule incorporates information from all validators, hundreds in each slot, making it extremely unlikely in the normal case that even a single block will be reverted. Because the fork choice is dependent on all validators, this also ensures that blocks cannot be reverted unless an attacker really does control close to 50% of the entire validator set; one cannot achieve a large advantage by manipulating the randomness. + +### The proof of custody game + +For each 9-day period, each validator has the ability to privately generate a "period subkey". The validator's public key uniquely determines their period subkey for every period, so once a validator has deposited they have no further freedom to choose what their subkeys are. No one can compute any given validator's subkey except the validator themselves, but once a validator reveals a subkey voluntarily, anyone can verify its correctness (this is all done via BLS magic, and if quantum-safety is required in the future it can be done with hash-based commitments). + +When signing a block with data $D$ with root $R$ during period $j$, letting $s$ being the period-$j$ secret of that validator, a validator is required to compute a bitfield $M$ as follows: + +* Split $D$ into 512-byte chunks $D[0] ... D[n-1]$ +* Set $M$ to be the bitfield where the i'th bit is $M[i] = mix(s, D[i])$ + +They include `get_chunk_bits_root(M)` (this is called the **custody bit**) as part of what they are signing. `mix` and `get_chunk_bits_root` can both be viewed as hash-like functions that output a single bit (but are designed for multi-party-computation friendliness). + +If a crosslink includes multiple blocks $B_1 ... B_n$ and the validator computes custody bits $c_1 ... c_n$ for these blocks, then the validator signs all $(B_i, c_i, i)$ tuples and aggregates them. This unconventional self-aggregation is used to ensure that there are only $2n$ different messages (n different block/index pairs * 2 different bit values) being signed by different validators, reducing the number of pairings needed to verify the signatures. + +If a validator publishes their period $j$ subkey during or before period $j$, any other validator can publish a proof-of-knowledge of the subkey to the chain, which then penalizes the validator whose subkey was revealed. The proof of knowledge also proves which validator created it; this prevents block proposers from "stealing" the whistleblowing reward (once again all done via BLS magic, if quantum-safety is required in the future this can be done with STARKs). The goal of this is to make it dangerous to outsource computation of $M$. + +After a validator publishes their period $j$ subkey, anyone else can check their work for any block that they signed. If they discover that a validator provided an incorrect custody bit, they can challenge this on-chain, and slash that validator. In general, random guessing (or any procedure that does not involve all of $D$) will only give a correct answer half the time, leading to a 50% risk of slashing per block signed. + +The purpose of this mechanism is to mitigate the [validator's dilemma](../assets/eip-2982/iacr-2015-702-Demystifying-Incentives-in-the-Consensus-Computer.pdf) problem, where validators have an incentive to avoid verifying data out of laziness and piggyback on the assumption that all _other_ validators are honest; if too many validators think in this way, it could lead to a tragedy of the commons leading to the chain accepting invalid blocks. With this scheme, if a validator attempts to commit to data that they did not personally process, then they would not be able to compute $M$, and so would lose the interactive challenge game. + +### SSZ + +The SimpleSerialize suite contains the following algorithms: + +* A serialization algorithm +* A hashing algorithm (called `SSZTreeHash` or `hash_tree_root`) +* A generalized Merkle proof algorithm (called "SSZ partials") that can handle proofs for multiple values and optimally deduplicates Merkle tree sister nodes in such cases. + +The serialization algorithm has the following design goals: + +* Simplicity (eg. no three clauses like RLP has for long / list encoding depending on item length) +* Being equivalent to simple concatenation in the case of entirely fixed-size objects +* Being usable as both a consensus-layer serialization algorithm and an application-layer ABI + +Note that the resulting SSZ serialization spec is very similar to the ethereum 1.0 ABI, with the major differences being (i) different basic data types and (ii) replacing the 32 byte length/position record size with a 4 byte size. + +The hashing algorithm has the following design goals: + +* Efficiency of computing the hash of an updated object, especially in the case where the object is very large and/or complex and the change is relatively small +* Efficiency (in terms of verification complexity _and_ witness size) of proving the value of a specific field even in a large or complex object with a given hash + +These requirements together make a Merkle tree structure the obvious choice. + +#### Generalized indices + +See https://github.com/ethereum/eth2.0-specs/blob/dev/ssz/merkle-proofs.md for a description of generalized indices, and how they allow for very easy verification of Merkle proofs "poking into" arbitrary positions in an object by representing paths as an integer or bitfield. + +### The validator lifecycle + +#### Depositing + +A validator deposits by sending a transaction that calls a function on the deposit contract on the eth1 chain (eventually, a way to deposit from inside eth2 will also be added). A deposit specifies: + +* The public key corresponding to the private key that will be used to sign messages +* The withdrawal credentials (hash of the public key that will be used to withdraw funds once the validator is done validating) +* The deposit amount + +These values are all signed by the signing key. The goal of having separate signing and withdrawal keys is to allow the more dangerous withdrawal key to be kept more securely (offline, not shared with any staking pools, etc) while the signing key is used to actively sign a message every epoch. + +The deposit contract maintains a Merkle root of all deposits made so far. Once a merkle root containing the deposit gets included into the eth2 chains (via the Eth1Data voting mechanism), an eth2 block proposer can submit a Merkle proof of the deposit and start the deposit process. + +#### Activation + +The validator immediately joins the validator registry, but is at first inactive. The validator becomes active after $N \ge 4$ epochs; the minimum of 4 is there to ensure the RANDAO is not manipulable, and $N$ may exceed 4 if too many validators try to join at the same time. If the active validator set has size $|V|$, a maximum of $max(4, \frac{|V|}{65536})$ validators can join per epoch; if more validators try to join, they are put in a queue and processed as quickly as possible. + +#### Exiting + +When a validator exits (whether by publishing a voluntary exit message or being slashed), they are similarly put into an exit queue with the same maximum throughput. + +The reason for the entrance/exit queue limits is to ensure that the validator set cannot change too quickly between any two points in time, which ensures that finality guarantees still remain between two chains as long as a validator logs on often enough (once every ~1-2 months if $|V| \ge 262144$). See here https://ethresear.ch/t/rate-limiting-entry-exits-not-withdrawals/4942 for rationale (and specifically why to use a rate limit instead of a fixed waiting time) and https://ethresear.ch/t/weak-subjectivity-under-the-exit-queue-model/5187 for how to calculate safety margin for a client that has been offline for some amount of time. + +#### Withdrawal + +Once a validator leaves the exit queue, there is a ~27 hour period until they can withdraw. This period has several functions: + +* It ensures that if a validator misbehaved there is a period of time within which the error can be caught and the validator can be slashed even if the exit queue is nearly empty. +* It provides time for the last period of shard rewards to be included. +* It provides time for proof of custody challenges to be made. + +If a validator is slashed, a further delay of ~36 days is imposed. This further penalizes them (and forces them to hold the ETH; this makes the penalty somewhat larger for malicious validators that are trying to destroy the ethereum blockchain than those validators that want to support the platform but just made a mistake, as the former category would have to risk the exposure or pay for derivatives to cancel it out), but also allows for a period during which the number of other validators that got slashed can be calculated. + +In phase 0, a "withdrawn" validator cannot actually withdraw to anywhere yet; the only distinction is that it is protected from validator penalties and does not have any responsibilities. In later phases, the ability to move funds from a withdrawn validator slot to an execution environment will be made available. + +#### Effective balances + +Most calculations based on a validator's balance use the validator's "effective balance"; the only exception is calculations that increase or decrease the validator's balance. Only when the validators's balance $B$ falls below $EB$ or goes above $EB + 1.5$ is $EB$ adjusted to equal $floor(B)$. This is done to ensure that effective balance changes infrequently, reducing the amount of hashing needed to recompute the state every epoch; on average, only the balances need to all be updated, and the effective balances only get updated relatively rarely per validator. Balances are all stored in a dedicated vector, so $2 * \frac{N * 8}{32} = \frac{N}{2}$ hashes are needed to recompute a balance array, whereas effective balances are stored in validator record objects, where at least $5N$ hashes would be needed per validator to adjust the SSZ hash roots. Additionally, $EB$ can be compressed more easily into a CompactValidator object, as it's only one byte. + +### Fork mechanism + +The `Fork` data structure contains (i) the current "fork ID", (ii) the previous fork ID and (iii) the switchover slot. The fork ID at the current height influences the valid signatures of all messages; hence, a message signed with one fork ID is invalid to a verification function using any other fork ID. + +A fork is done by adding a state transition at some "fork slot" $n$ which sets the previous fork ID to the current fork ID, the current fork ID to a new value, and the switchover slot to $n$. Signature verification functions will verify messages using the fork ID at the slot the message is for, which could be the previous fork ID or the current one (eg. consider the case of attestations included after a delay; an attestation from before the fork slot could be included after the fork slot). + +If any users do not want to join the fork, they can simply continue the chain that does not change the fork ID at the fork slot. The two chains would be able to proceed and validators would be free to validate on both without getting slashed. + +## Backwards Compatibility + +Although this EIP does not introduce any immediate changes to the current Ethereum mainnet, this EIP lays the groundwork for future backwards incompatibilities through the introduction of the new eth2 consensus mechanism in which Ethereum will be integrated in subsequent phases. To secure this mechanism, users move ether into the beacon chain and additional ether is issued. This EIP is a commitment to this path being canonical, as well as directly informing the future and roadmap of Ethereum mainnet. + +## Security Considerations + +Eth2 is a major overhaul of the Ethereum's core consensus from PoW to a sharded PoS. There are inherent risks in this migration but there is extensive research literature analyzing security and trade-offs. _The following only represents a high level selection of the resources available:_ + +* [Casper FFG](../assets/eip-2982/arxiv-1710.09437-Casper-the-Friendly-Finality-Gadget.pdf) +* [Combining GHOST and Casper](../assets/eip-2982/arxiv-2003.03052-Combining-GHOST-and-Casper.pdf) + +In addition to the research supporting this path, a number of audits and formal verification of specs, cryptography, and client implementations have been performed. _Many client and utility library audits are currently in progress and will be appended here upon completion._ + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2997.md b/EIPS/eip-2997.md new file mode 100644 index 00000000000000..ee1152b5406c89 --- /dev/null +++ b/EIPS/eip-2997.md @@ -0,0 +1,103 @@ +--- +eip: 2997 +title: IMPERSONATECALL Opcode +author: Sergio Demian Lerner (@SergioDemianLerner) +discussions-to: https://ethresear.ch/t/impersonatecall-opcode/8020 +category: Core +type: Standards Track +status: Stagnant +created: 2020-09-24 +--- + +## Abstract + +Add a new opcode, `IMPERSONATECALL` at `0xf6`, which is similar in idea to `CALL (0xF1)`, except that it impersonates a sender, i.e. the callee sees a sender different from the real caller. The impersonated sender address is derived from the real caller address and a salt. + +## Motivation + +This proposal enables native multi-user wallets (wallets that serve multiple users) that can be commanded by EIP-712 based messages and therefore enable meta-transactions. Multi-user wallets also enable the aggregation of transfer operations in batches similar to rollups, but maintaining the same address space as normal onchain transactions, so the sender's wallet does not need to be upgraded to support sinding ether or tokens to a user of a multi-user wallet. +Additionally, many times a sponsor company wants to deploy non-custodial smart wallets for all its users. The sponsor does not want to pay the deployment cost of each user contract in advance. Counterfactual contract creation enables this, yet it forces the sponsor to create the smart wallet (or a proxy contract to it) when the user wants to transfer ether or tokens out of his/her account for the first time. This proposal avoids this extra cost, which is at least 42000 gas per user. + + +## Specification + +`IMPERSONATECALL`: `0xf6`, takes 7 operands: + +- `gas`: the amount of gas the code may use in order to execute; +- `to`: the destination address whose code is to be executed; +- `in_offset`: the offset into memory of the input; +- `in_size`: the size of the input in bytes; +- `ret_offset`: the offset into memory of the output; +- `ret_size`: the size of the scratch pad for the output. +- `salt` is a `32` bytes value (a stack item). + +### Computation of impersonated sender + +The impersonated sender address is computed as `keccak256( 0xff ++ address ++ salt ++ zeros32)[12:]`. + +- `0xff` is a single byte, +- `address` is always `20` bytes, and represents the address of the real caller contract. +- `salt` is always `32` bytes. + +- The field zeros32 corresponds to 32 zero bytes. + +This scheme emulates `CREATE2` address derivation, but it cannot practically collude with the `CREATE2` address space. + +### Notes +- The opcode behaves exactly as `CALL` in terms of gas consumption. +- In the called context `CALLER (0x33)` returns the impersonated address. +- If value transfer is non-zero in the call, the value is transferred from the impersonated account, and not from the real caller. This can be used to transfer ether out of an impersonated account. + +## Rationale + +Even if `IMPERSONATECALL` requires hashing 3 words, implying an additional cost of 180 gas, we think the benefit of accounting for hashing doesn't not compensate increasing the complexity of the implementation. + +We use the zeros32 field to base address derivation in a pre-image of similar size than CREATE2 and reuse the existing address derivation functions. We also avoid worrying about address collisions between EOA derivation (65 bytes pre-image), CREATE derivation (from 23 to 27 bytes pre-image, for a 32bit nonce) and CREATE2 derivation (85 bytes pre-image). + +An option is to omit the zeros32 field: the resulting length of the Keccak pre-image for IMPERSONATECALL address is 53 bytes , which does not generate address collision. + +While the same functionality could be provided in a pre-compiled contract, we believe using a new opcode is a cleaner solution. + + +## Clarifications + +- This EIP makes address collisions possible, yet practically impossible. + +- If a contract already exists with an impersonated address, the `IMPERSONATECALL` is executed in the same way, and the existing code will not be executed. It should be noted that `SELFDESTRUCT` (`0xff`) cannot be executed directly with `IMPERSONATECALL` as no opcode is executed in the context of the impersonated account. + +## Backward Compatibility + +The opcode number `0xf6` is currently unused and results in an out-of-gas (OOG) exception. Solidity uses the `INVALID (0xfe)` opcode (called `ABORT` by EIP-1803) to raise OOG exceptions, so the `0xf6` opcode does not appear in normal Solidity programs. Programmers are already advised not to include this opcode in contracts written in EVM assembly. Therefore is does not pose any backward compatibility risk. + +## Test Cases + +We present 4 examples of impersonated address derivation: + +Example 0 + +* address `0x0000000000000000000000000000000000000000` +* salt `0x0000000000000000000000000000000000000000000000000000000000000000` +* result: `0xFFC4F52F884A02BCD5716744CD622127366F2EDF` + +Example 1 +* address `0xdeadbeef00000000000000000000000000000000` +* salt `0x0000000000000000000000000000000000000000000000000000000000000000` +* result: `0x85F15E045E1244AC03289B48448249DC0A34AA30` + +Example 2 +* address `0xdeadbeef00000000000000000000000000000000` +* salt `0x000000000000000000000000feed000000000000000000000000000000000000` +* result: `0x2DB27D1D6BE32C9ABFA484BA3D591101881D4B9F` + +Example 3 +* address `0x00000000000000000000000000000000deadbeef` +* salt `0x00000000000000000000000000000000000000000000000000000000cafebabe` +* result: `0x5004E448F43EFE3C7BF32F94B83B843D03901457` + +## Security Considerations + +The address derivation scheme prevents address collision with another deployed contract or an externally owned account, as the impersonated sender address is derived from the real caller address and a salt. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3.md b/EIPS/eip-3.md index 621b143554d6b0..3d7c9699847ea7 100644 --- a/EIPS/eip-3.md +++ b/EIPS/eip-3.md @@ -2,7 +2,7 @@ eip: 3 title: Addition of CALLDEPTH opcode author: Martin Holst Swende -status: Deferred +status: Withdrawn type: Standards Track category: Core created: 2015-11-19 diff --git a/EIPS/eip-3000.md b/EIPS/eip-3000.md new file mode 100644 index 00000000000000..fd185a40d8b10d --- /dev/null +++ b/EIPS/eip-3000.md @@ -0,0 +1,7 @@ +--- +eip: 3000 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3000.md diff --git a/EIPS/eip-3005.md b/EIPS/eip-3005.md new file mode 100644 index 00000000000000..1b8dc33c0f8ba9 --- /dev/null +++ b/EIPS/eip-3005.md @@ -0,0 +1,7 @@ +--- +eip: 3005 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3005.md diff --git a/EIPS/eip-3009.md b/EIPS/eip-3009.md new file mode 100644 index 00000000000000..66ff691c786e23 --- /dev/null +++ b/EIPS/eip-3009.md @@ -0,0 +1,7 @@ +--- +eip: 3009 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3009.md diff --git a/EIPS/eip-3014.md b/EIPS/eip-3014.md new file mode 100644 index 00000000000000..408d992c0f5c74 --- /dev/null +++ b/EIPS/eip-3014.md @@ -0,0 +1,48 @@ +--- +eip: 3014 +title: eth_symbol JSON-RPC method +author: Peter Grassberger (@PeterTheOne) +discussions-to: https://github.com/ethereum/EIPs/issues/3012 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-09-30 +--- + +## Simple Summary +Add `eth_symbol` method to the JSON-RPC that returns the symbol of the native coin of the network. + +## Abstract +The new method `eth_symbol` (`eth_`-namespaced) has no parameters and returns a string of the native coin of the network. For the Ethereum mainnet this will be `ETH`, other networks will have other symbols. + +## Motivation +Wallets that deal with multiple networks need some basic information for every blockchain that they connect to. One of those things is the symbol of the native coin of the network. Instead of requiring the user to research and manually add the symbol it could be provided to the wallet via this proposed JSON-RPC endpoint and used automatically. There are lists of networks with symbols like https://github.com/ethereum-lists/chains where a user can manually look up the correct values. But this information could easily come from the network itself. + +## Specification +Method: `eth_symbol`. + +Params: none. + +Returns: `result` - the native coin symbol, string + +Example: + +```js +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_symbol","params":[],"id":1}' + +// Result +{ + "id": 1, + "jsonrpc": "2.0", + "result": "ETH" +} +``` + +## Rationale +This endpoint is similar to [EIP-695](./eip-695.md) but it provides the symbol instead of `chainId`. It provides functionality that is already there for [ERC-20](./eip-20.md) tokens, but not yet for the native coin of the network. Alternative naming of `eth_nativeCurrencySymbol` was considered, but the context and the fact that it just returns one value makes it clear that that it returns the symbol for the native coin of the network. + +## Security Considerations +It is a read only endpoint. The information is only as trusted as the JSON-RPC node itself, it could supply wrong information and thereby trick the user in believing he/she is dealing with another native coin. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3026.md b/EIPS/eip-3026.md new file mode 100644 index 00000000000000..4b762acdd2553f --- /dev/null +++ b/EIPS/eip-3026.md @@ -0,0 +1,304 @@ +--- +eip: 3026 +title: BW6-761 curve operations +description: Precompiles for BW6-761 curve operations +author: Youssef El Housni (@yelhousni), Michael Connor (@iAmMichaelConnor), Aurore Guillevic , hujw77 (@hujw77) +discussions-to: https://ethereum-magicians.org/t/eip-3026-bw6-761-curve-operations/4790 +status: Stagnant +type: Standards Track +category: Core +created: 2020-10-05 +requires: 2539 +--- + +## Abstract + +This precompile adds operations for the BW6-761 curve (from the EY/Inria **Optimized and secure pairing-friendly elliptic curves suitable for one layer proof composition** research paper) as a precompile in a set necessary to *efficiently* perform verification of one-layer composed zkSNARKs proofs. +If `block.number >= X` we introduce *seven* separate precompiles to perform the following operations (addresses to be determined): + +- BW6_G1_ADD - to perform point addition on a curve defined over a prime field +- BW6_G1_MUL - to perform point multiplication on a curve defined over a prime field +- BW6_G1_MULTIEXP - to perform multiexponentiation on a curve defined over a prime field +- BW6_G2_ADD - to perform point addition on a curve twist defined the base a prime field +- BW6_G2_MUL - to perform point multiplication on a curve twist defined over a prime field +- BW6_G2_MULTIEXP - to perform multiexponentiation on a curve twist defined over a prime field +- BW6_PAIRING - to perform a pairing operations between a set of *pairs* of (G1, G2) points + +The multiexponentiation operations are a generalization of point multiplication, but separate precompiles are prosposed because running a single MUL through MULTIEXP seems to be 20% more expensive. + +## Motivation + +This EIP is based on and tends to replace matter-labs' proposal for significant performance reasons. In most applications, BW6-761 is used as an outer curve to BLS12-377 considered in [EIP-2539](./eip-2539.md). +The motivation of this precompile is to allow efficient one-layer composition of SNARK proofs. Currently this is done by Zexe using the BLS12-377/CP6-782 pair of curves. This precompile proposes a replacement of CP6-782 by BW6-761, which allows much faster operations. For example, it was shown that verifying a Groth16 proof with BW6-761 is 30 times faster than with CP6-782. + +### Proposed addresses table + +| Precompile | Address | +| --------------- | ------- | +| BW6_G1_ADD | 0x1e | +| BW6_G1_MUL | 0x1f | +| BW6_G1_MULTIEXP | 0x20 | +| BW6_G2_ADD | 0x21 | +| BW6_G2_MUL | 0x22 | +| BW6_G2_MULTIEXP | 0x23 | +| BW6_PAIRING | 0x24 | + +## Specification + +Curve parameters: + +The BW6-761 `y^2=x^3-1` curve is fully defined by the following set of parameters: + +``` +Base field modulus = 0x122e824fb83ce0ad187c94004faff3eb926186a81d14688528275ef8087be41707ba638e584e91903cebaff25b423048689c8ed12f9fd9071dcd3dc73ebff2e98a116c25667a8f8160cf8aeeaf0a437e6913e6870000082f49d00000000008b +A coefficient = 0x0 +B coefficient = 0x122e824fb83ce0ad187c94004faff3eb926186a81d14688528275ef8087be41707ba638e584e91903cebaff25b423048689c8ed12f9fd9071dcd3dc73ebff2e98a116c25667a8f8160cf8aeeaf0a437e6913e6870000082f49d00000000008a +Main subgroup order = 0x1ae3a4617c510eac63b05c06ca1493b1a22d9f300f5138f1ef3622fba094800170b5d44300000008508c00000000001 +Extension tower: +Fp3 construction: (Fp3 = Fp[u]/u^3+4) +Fp cubic non-residue = 0x122e824fb83ce0ad187c94004faff3eb926186a81d14688528275ef8087be41707ba638e584e91903cebaff25b423048689c8ed12f9fd9071dcd3dc73ebff2e98a116c25667a8f8160cf8aeeaf0a437e6913e6870000082f49d000000000087 +Twist parameters: +Twist type: M +twist curve A coefficient c0 = 0x0 + c1 = 0x0 +twist curve B coefficient c0 = 0x4 + c1 = 0x0 +Generators: +G1: +X = 0x1075b020ea190c8b277ce98a477beaee6a0cfb7551b27f0ee05c54b85f56fc779017ffac15520ac11dbfcd294c2e746a17a54ce47729b905bd71fa0c9ea097103758f9a280ca27f6750dd0356133e82055928aca6af603f4088f3af66e5b43d +Y = 0x58b84e0a6fc574e6fd637b45cc2a420f952589884c9ec61a7348d2a2e573a3265909f1af7e0dbac5b8fa1771b5b806cc685d31717a4c55be3fb90b6fc2cdd49f9df141b3053253b2b08119cad0fb93ad1cb2be0b20d2a1bafc8f2db4e95363 +G2: +X = 0x110133241d9b816c852a82e69d660f9d61053aac5a7115f4c06201013890f6d26b41c5dab3da268734ec3f1f09feb58c5bbcae9ac70e7c7963317a300e1b6bace6948cb3cd208d700e96efbc2ad54b06410cf4fe1bf995ba830c194cd025f1c +Y = 0x17c3357761369f8179eb10e4b6d2dc26b7cf9acec2181c81a78e2753ffe3160a1d86c80b95a59c94c97eb733293fef64f293dbd2c712b88906c170ffa823003ea96fcd504affc758aa2d3a3c5a02a591ec0594f9eac689eb70a16728c73b61 +Pairing parameters: +e(P,Q)=(ML1(P,Q)*ML2(P,Q)^q)^FE +|loop_count_1| (first miller loop ML1 count) = 0x8508c00000000002 +|loop_count_2| (second miller loop ML2 count) = 0x23ed1347970dec008a442f991fffffffffffffffffffffff +loop_count_1 is negative = false +loop_count_2 is negative = false +``` + +### Encoding + +#### Field elements encoding: + +To encode points involved in the operation one has to encode elements of only the base field. + +The base field element (Fp) is encoded as `96` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. The corresponding integer **MUST** be less than the base field modulus. + +If encodings do not follow this spec anywhere during parsing in the precompile, the precompile **MUST** revert with "endoding error". + +#### Encoding of uncompressed points: + +Points in both G1 and G2 can be expressed as `(x, y)` affine coordinates, where `x` and `y` are elements of the base field. +Therefore, points in both G1 and G2 are encoded as the byte concatenation of the field element encodings of the `x` and `y` affine coordinates. The total encoding length for a G1/G2 point is thus `192` bytes. + +#### Point at infinity encoding: + +Also referred as the "zero point". For BW6-761 (`y^2=x^3-1`) and its M-twisted curves (`y^3=x^3+4`), the point with coordinates `(0, 0)` (formal zeros in Fp) is *not* on the curve, and so the encoding of `(0, 0)` is used as a convention to encode the point at infinity. + +#### Encoding of scalars for multiplication and multiexponentiation operations: + +For multiplication and multiexponentiation operations, a scalar is encoded as `64` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. + +Note that the main subgroup order for BW6-761 is actually only `377` bits (`48` bytes), but an encoding of `64` bytes has been chosen to have a `32`-byte-aligned ABI (representable as e.g. `bytes32[2]` or `uint256[2]`). + +The corresponding integer **MAY** be greater than the main subgroup order. + +### ABI for operations + +#### ABI for G1 addition + +G1 addition call expects `384` bytes as an input that is interpreted as the byte concatenation of two G1 points (point-encoded as `192` bytes each). Output is a point-encoding of the addition operation result. + +Error cases: + +- Either of the points being not on the curve +- Input has invalid length +- Field element encoding rules apply (obviously) + +#### ABI for G1 multiplication + +G1 multiplication call expects `256` bytes as an input that is interpreted as the byte concatenation of the point-encoding of a G1 point (`192` bytes) and the encoding of a scalar value (`64` bytes). Output is a point-encoding of the multiplication operation result. + +Error cases: + +- Point being not on the curve +- Input has invalid length +- Field element encoding rules apply (obviously) +- Scalar encoding rules apply (obviously) + +#### ABI for G1 multiexponentiation + +G1 multiplication call expects `256*k` bytes as an input that is interpreted as the byte concatenation of `k` slices, each of them being a byte concatenation of the point-encoding of a G1 point (`192` bytes) and the encoding of a scalar value (`64` bytes). Output is an encoding of the multiexponentiation operation result. + +Error cases: + +- Any of the G1 points being not on the curve +- Input has invalid length +- Field element encoding rules apply (obviously) +- Scalar encoding rules apply (obviously) + +#### ABI for G2 addition + +G2 addition call expects `384` bytes as an input that is interpreted as the byte concatenation of two G2 points (point-encoded as `192` bytes each). Output is a point-encoding of the addition operation result. + +Error cases: + +- Either of points being not on the curve +- Input has invalid length +- Field elements encoding rules apply (obviously) + +#### ABI for G2 multiplication + +G2 multiplication call expects `256` bytes as an input that is interpreted as the byte concatenation of the point-encoding of a G2 point (`192` bytes) and the encoding of a scalar value (`64` bytes). Output is an encoding of multiplication operation result. + +Error cases: + +- Point being not on the curve must result in error +- Field elements encoding rules apply (obviously) +- Input has invalid length + +#### ABI for G2 multiexponentiation + +G2 multiplication call expects `240*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`192` bytes) and encoding of a scalar value (`48` bytes). Output is an encoding of multiexponentiation operation result. + +Error cases: + +- Any of G2 points being not on the curve must result in error +- Field elements encoding rules apply (obviously) +- Input has invalid length + +#### ABI for pairing + +Pairing call expects `384*k` bytes as an input, that is interpreted as the byte concatenation of `k` slices. Each slice has the following structure: + +- `192` bytes G1 point encoding +- `192` bytes G2 point encoding + +Output is `32` bytes representing a boolean: + +- `0x0000000000000000000000000000000000000000000000000000000000000001` if the pairing result is equal the to multiplicative identity in the pairing target field; and +- `0x0000000000000000000000000000000000000000000000000000000000000000` otherwise. + +Error cases: + +- Any of the G1 or G2 points being not on the curve +- Any of the G1 or G2 points being not in the correct subgroup +- Input has invalid length +- Field elements encoding rules apply (obviously) + +### Prevention of DDoS on error handling + +This precompile performs extensive computations and in case of any errors during execution it **MUST** consume all gas from the gas schedule for the corresponding operation. + +### Gas schedule + +#### G1 addition + +`180` gas + +#### G1 multiplication + +`64000` gas + +#### G2 addition + +`180` gas + +#### G2 multiplication + +`64000` gas + +#### G1/G2 Multiexponentiation + +Discounts table as a vector of pairs `[k, discount]`: + +``` +[[1, 1266], [2, 733], [3, 561], [4, 474], [5, 422], [6, 387], [7, 362], [8, 344], [9, 329], [10, 318], [11, 308], [12, 300], [13, 296], [14, 289], [15, 283], [16, 279], [17, 275], [18, 272], [19, 269], [20, 266], [21, 265], [22, 260], [23, 259], [24, 256], [25, 255], [26, 254], [27, 252], [28, 251], [29, 250], [30, 249], [31, 249], [32, 220], [33, 228], [34, 225], [35, 223], [36, 219], [37, 216], [38, 214], [39, 212], [40, 209], [41, 209], [42, 205], [43, 203], [44, 202], [45, 200], [46, 198], [47, 196], [48, 199], [49, 195], [50, 192], [51, 192], [52, 191], [53, 190], [54, 187], [55, 186], [56, 185], [57, 184], [58, 184], [59, 181], [60, 181], [61, 181], [62, 180], [63, 178], [64, 179], [65, 176], [66, 177], [67, 176], [68, 175], [69, 174], [70, 173], [71, 171], [72, 171], [73, 170], [74, 170], [75, 169], [76, 168], [77, 168], [78, 167], [79, 167], [80, 166], [81, 165], [82, 167], [83, 166], [84, 166], [85, 165], [86, 165], [87, 164], [88, 164], [89, 163], [90, 163], [91, 162], [92, 162], [93, 160], [94, 163], [95, 159], [96, 162], [97, 159], [98, 160], [99, 159], [100, 159], [101, 158], [102, 158], [103, 158], [104, 158], [105, 157], [106, 157], [107, 156], [108, 155], [109, 155], [110, 156], [111, 155], [112, 155], [113, 154], [114, 155], [115, 154], [116, 153], [117, 153], [118, 153], [119, 152], [120, 152], [121, 152], [122, 152], [123, 151], [124, 151], [125, 151], [126, 151], [127, 151], [128, 150]] +``` + +`max_discount = 150` + +#### Pairing operation + +Base cost of the pairing operation is `120000*k + 320000` where `k` is a number of pairs. + +## Rationale + +Gas costs are based on [EIP-1962](./eip-1962.md) estimation strategy (but do not fully include yet parsing of ABI, decoding and encoding of the result as a byte array). + +### Gas estimation strategy + +Gas cost is derived by taking the average timing of the same operations over different implementations and assuming a constant `30 MGas/second`. Since the execution time is machine-specific, this constant is determined based on execution times of *ECRECOVER* and *BNPAIR* precompiles on my machine and their proposed gas price (`43.5 MGas/s` for ECRECOVER and `16.5 MGas/s` for BNPAIR). Following are the proposed methods to time the precompile operations: + +- G1 addition: Average timing of 1000 random samples. +- G1 multiplication: Average timing of 1000 samples of random worst-case of double-and-add algorithm (scalar of max bit length and max hamming weight and random base points in G1) +- G2 addition: Average timing of 1000 random samples +- G2 multiplication: Average timing of 1000 samples of random worst-case of double-and-add algorithm (scalar of max bit length and max hamming weight and random base points in G2) +- G1 and G2 multiexponentiations: Expected to be performed by the Peppinger algorithm, with a table prepared for discount in case of `k <= 128` points in the multiexponentiation with a discount cup `max_discount` for `k > 128`. To avoid non-integer arithmetic call cost is calculated as `k * multiplication_cost * discount / multiplier` where `multiplier = 1000`, `k` is a number of (scalar, point) pairs for the call, `multiplication_cost` is a corresponding single multiplication call cost for G1/G2. +- Pairing: Average timing of 1000 random samples (random points in G1 and G2) for different number of pairs with linear lifting. + +### Multiexponentiation as a separate call + +Explicit separate multiexponentiation operation that allows one to save execution time (so gas) by both the algorithm used (namely Peppinger algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negigible overhead if e.g. for multiexponentiation of `100` points would have to call the multiplication precompile `100` times and addition for `99` times (roughly `138600` would be saved). + +### Explicit subgroup checks + +G2 subgroup check has the same cost as G1 subgroup check. Endomorphisms can be leverages to optimize this operation. + +## Backwards Compatibility + +There are no backward compatibility questions. + +## Test Cases + +Due to the large test parameters space we first provide properties that various operations must satisfy. We use additive notation for point operations, capital letters (`P`, `Q`) for points, small letters (`a`, `b`) for scalars. Generator for G1 is labeled as `G`, generator for G2 is labeled as `H`, otherwise we assume random point on a curve in a correct subgroup. `0` means either scalar zero or point of infinity. `1` means either scalar one or multiplicative identity. `group_order` is a main subgroup order. `e(P, Q)` means pairing operation where `P` is in G1, `Q` is in G2. + +Requeired properties for basic ops (add/multiply): + +- Commutativity: `P + Q = Q + P` +- Additive negation: `P + (-P) = 0` +- Doubling `P + P = 2*P` +- Subgroup check: `group_order * P = 0` +- Trivial multiplication check: `1 * P = P` +- Multiplication by zero: `0 * P = 0` +- Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` + +Required properties for pairing operation: + +- Degeneracy `e(P, 0*Q) = e(0*P, Q) = 1` +- Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` (internal test, not visible through ABI) + +## Reference Implementation + +There is a various choice of existing implementations: + +**Libraries:** + +- Rust implementation (EY/Zexe): github.com/yelhousni/zexe/tree/youssef/BW6-761-Fq-ABLR-2ML-M +- C++ implementation (EY/libff): github.com/EYBlockchain/zk-swap-libff +- Golang implementation (Consensys/gurvy): github.com/ConsenSys/gurvy + +**Stand-alone implementation:** + +- Golang implementation with Intel assembly (Onur Kilic): github.com/kilic/bw6 + +**Precompiles:** + +- OpenEthereum (EY/Parity): github.com/EYBlockchain/solidity-elliptic-curves +- Frontier (Parity): github.com/paritytech/frontier/pull/1049/files + +**Scripts:** + +- SageMath and Magma scripts: gitlab.inria.fr/zk-curves/bw6-761/ + +## Security Considerations + +Strictly following the spec will eliminate security implications or consensus implications in a contrast to the previous BN254 precompile. + +Important topic is a "constant time" property for performed operations. We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3030.md b/EIPS/eip-3030.md new file mode 100644 index 00000000000000..7d3ecba3d8de80 --- /dev/null +++ b/EIPS/eip-3030.md @@ -0,0 +1,361 @@ +--- +eip: 3030 +title: BLS Remote Signer HTTP API +author: Herman Junge (@hermanjunge) +discussions-to: https://ethereum-magicians.org/t/eip-3030-bls-remote-signer-http-api-standard/4810 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-09-30 +--- + +## Simple Summary +This EIP defines a HTTP API standard for a BLS remote signer, consumed by validator clients to sign block proposals and attestations in the context of Ethereum 2.0 (eth2). + +## Abstract +A [validator](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/validator.md) client contributes to the consensus of the Eth2 blockchain by signing proposals and attestations of blocks, using a BLS private key which must be available to this client at all times. + +The BLS remote signer API is designed to be consumed by validator clients, looking for a more secure avenue to store their BLS12-381 private key(s), enabling them to run in more permissive and scalable environments. + +## Motivation +Eth2 utilizes [BLS12-381](https://github.com/cfrg/draft-irtf-cfrg-bls-signature/) signatures. + +Consensus on the eth2 Blockchain is achieved via the proposal and attestation of blocks from validator clients, using a BLS private key (_signing_ key) which must be available each time a message is signed: that is, at least once every epoch (6.4 minutes), during a small window of time within this epoch (a _slot_, i.e. 12 seconds), as each validator is expected to attest exactly once per epoch. + +The [eth2 specification](https://github.com/ethereum/eth2.0-specs) does not explicitly provide a directive on where this BLS private key must/should be stored, leaving this implementation detail to the client teams, who assume that this cryptographic secret is stored on the same host as the validator client. + +This assumption is sufficient in the use case where the validator client is running in a physically secure network (i.e. nobody, but the operator, has a chance to log-in into the machine hosting the validator client), as such configuration would only allow _outbound_ calls from the validator client. In this situation, only a physical security breach, or a Remote Code Execution (RCE) vulnerability can allow an attacker to either have arbitrary access to the storage or to the memory of the device. + +There are, however, use cases where it is required by the operator to run a validator client node in less constrained security environments, as the ones given by a cloud provider. Notwithstanding any security expectation, nothing prevents a rogue operator from gaining arbitrary access to the assets running inside a node. + +The situation is not better when the requirement is to execute the validators by leveraging a container orchestration solution (e.g. Kubernetes). The handling of secret keys across nodes can become a burden both from an operational as well as a security perspective. + +The proposed solution comprises running a specialized node with exclusive access to the secret keys, listening to a simple API (defined in the [Specification](#specification) section), and returning the requested signatures. Operators working under this schema must utilize clients with the adequate feature supporting the consumption of this API. + +The focus of this specification is the supply of BLS signatures _on demand_. The aspects of authentication, key management (creation, update, and deletion), and transport encryption are discussed in the [Rationale](#rationale) section of this document. Moreover, the [Threat Model](#threat-model) section of this document provides a (non-exhaustive) list of threats and attack vectors, along with the suggested related mitigation strategy. + +## Specification + +### `GET /upcheck` + +_**Responses**_ + +Success |
+--- | --- +Code | `200` +Content | `{"status": "OK"}` + +--- + +### `GET /keys` + +Returns the identifiers of the keys available to the signer. + +_**Responses**_ + +Success |
+--- | --- +Code | `200` +Content | `{"keys": "[identifier]"}` + +--- + +### `POST /sign/:identifier` + +URL Parameter |
+--- | --- +`:identifier` | `public_key_hex_string_without_0x` + +_**Request**_ + +JSON Body |
|
+--- | --- | --- +`bls_domain` | **Required** | The BLS Signature domain.
As defined in the [specification](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/beacon-chain.md#domain-types), in lowercase, omitting the `domain` prefix.
Supporting `beacon_proposer`, `beacon_attester`, and `randao`. +`data` | **Required** | The data to be signed.
As defined in the specifications for [block](https://github.com/ethereum/eth2.0-APIs/blob/master/types/block.yaml), [attestation](https://github.com/ethereum/eth2.0-APIs/blob/master/types/attestation.yaml), and [epoch](https://github.com/ethereum/eth2.0-APIs/blob/master/types/misc.yaml). +`fork` | **Required** | A `Fork` object containing previous and current versions.
As defined in the [specification](https://github.com/ethereum/eth2.0-APIs/blob/master/types/misc.yaml) +`genesis_validators_root` | **Required** | A `Hash256` for domain separation and chain versioning. +
| Optional | Any other field will be ignored by the signer + +_**Responses**_ + +Success |
+--- | --- +Code | `200` +Content | `{"signature": ""}` + +Where signature is a [BLS signature](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/beacon-chain.md#bls-signatures) byte array encoded as a hexadecimal string. + +_or_ + +Error |
+--- | --- +Code | `400` +Content | `{"error": ""}` + +_or_ + +Error |
+--- | --- +Code | `404` +Content | `{"error": "Key not found: "}` + +--- + +## Rationale + +### UNIX philosophy: Simple API + +This API specification contains only three methods: one for **status**, one for **listing the available keys**, and one to **produce a signature**. There are no methods for authentication, key management, nor transport encryption. + +The following subsections discuss aspects to be considered by the client implementers relative to these subjects. + +#### Implementation of additional features + +From an API pipeline view, we have two nodes: The validator client (1) that makes requests to the remote signer (2). A more sophisticated chain can be built by introducing elements between these two nodes. Either by setting up reverse proxy services, or by adding plugins to the remote signer implementation. + +#### Authentication + +Can be accomplished through the use of an HTTP Request Header. There are several ways to negotiate and issue a valid token to authenticate the communication between the validator client and the remote signer, each of them with potential drawbacks (e.g replay attacks, challenges in distributing the token to the validator client, etc.). In general, any method of authentication must be combined with transport encryption to be effective. + +The operator can also implement network Access Control Lists (ACLs) between the validator client's network and the remote signer's network, reducing the attack surface by requiring a potential attacker to be positioned in the same network as the validator client. + +#### Key management + +There are several ways to store secret keys, namely Hardware Security Modules (HSM), Secrets management applications (e.g. Hashicorp Vault), cloud storage with tight private network ACL rules, or even raw files in a directory. In general the remote signer implementers will abstract the storage medium from the HTTP API. + +It is in this perspective, that any procedure to create, update, or delete keys should be built separate from the client implementation. + +#### Transport Encryption + +If the operator is working with self-signed certificates, it is required that the client enhancement consuming the remote signer allows this option. + +## Test Cases + +### Test Data + +* BLS Pair + * Public key: `0xb7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a`. + * Secret key: `0x68081afeb7ad3e8d469f87010804c3e8d53ef77d393059a55132637206cc59ec`. +* Signing root: `0xb6bb8f3765f93f4f1e7c7348479289c9261399a3c6906685e320071a1a13955c`. +* Expected signature: `0xb5d0c01cef3b028e2c5f357c2d4b886f8e374d09dd660cd7dd14680d4f956778808b4d3b2ab743e890fc1a77ae62c3c90d613561b23c6adaeb5b0e288832304fddc08c7415080be73e556e8862a1b4d0f6aa8084e34a901544d5bb6aeed3a612`. + +### `GET /upcheck` + +```bash +# Success + +## Request +curl -v localhost:9000/upcheck + +## Response +* Trying 127.0.0.1:9000... +* TCP_NODELAY set +* Connected to localhost (127.0.0.1) port 9000 (#0) +> GET /upcheck HTTP/1.1 +> Host: localhost:9000 +> User-Agent: curl/7.68.0 +> Accept: */* +> +* Mark bundle as not supporting multiuse +< HTTP/1.1 200 OK +< content-type: application/json +< content-length: 15 +< date: Wed, 30 Sep 2020 02:25:08 GMT +< +* Connection #0 to host localhost left intact +{"status":"OK"} +``` + +### `GET /keys` + +```bash +# Success + +## Request +curl -v localhost:9000/keys + +## Response +* Trying 127.0.0.1:9000... +* TCP_NODELAY set +* Connected to localhost (127.0.0.1) port 9000 (#0) +> GET /publicKeys HTTP/1.1 +> Host: localhost:9000 +> User-Agent: curl/7.68.0 +> Accept: */* +> +* Mark bundle as not supporting multiuse +< HTTP/1.1 200 OK +< content-type: application/json +< content-length: 116 +< date: Wed, 30 Sep 2020 02:25:36 GMT +< +* Connection #0 to host localhost left intact +{"keys":["b7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a"]} + +# Server Error + +## Preparation +## `chmod` keys directory to the octal 311 (-wx--x--x). + +## Request +curl -v localhost:9000/keys + +## Response +* Trying 127.0.0.1:9000... +* TCP_NODELAY set +* Connected to localhost (127.0.0.1) port 9000 (#0) +> GET /publicKeys HTTP/1.1 +> Host: localhost:9000 +> User-Agent: curl/7.68.0 +> Accept: */* +> +* Mark bundle as not supporting multiuse +< HTTP/1.1 500 Internal Server Error +< content-length: 43 +< date: Wed, 30 Sep 2020 02:26:09 GMT +< +* Connection #0 to host localhost left intact +{"error":"Storage error: PermissionDenied"} +``` + +### `POST /sign/:identifier` + +```bash +# Success + +## Request +curl -v -X POST -d @payload.json -H 'Content-Type: application/json' localhost:9000/sign/b7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a + +## Response +Note: Unnecessary use of -X or --request, POST is already inferred. +* Trying 127.0.0.1:9000... +* TCP_NODELAY set +* Connected to localhost (127.0.0.1) port 9000 (#0) +> POST /sign/b7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a HTTP/1.1 +> Host: localhost:9000 +> User-Agent: curl/7.68.0 +> Accept: */* +> Content-Type: application/json +> Content-Length: 84 +> +* upload completely sent off: 84 out of 84 bytes +* Mark bundle as not supporting multiuse +< HTTP/1.1 200 OK +< content-type: application/json +< content-length: 210 +< date: Wed, 30 Sep 2020 02:16:02 GMT +< +* Connection #0 to host localhost left intact +{"signature":"0xb5d0c01cef3b028e2c5f357c2d4b886f8e374d09dd660cd7dd14680d4f956778808b4d3b2ab743e890fc1a77ae62c3c90d613561b23c6adaeb5b0e288832304fddc08c7415080be73e556e8862a1b4d0f6aa8084e34a901544d5bb6aeed3a612"} + +# Bad Request Error + +## Request +curl -v -X POST -d 'foobar' -H 'Content-Type: application/json' localhost:9000/sign/b7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a + +## Response +Note: Unnecessary use of -X or --request, POST is already inferred. +* Trying 127.0.0.1:9000... +* TCP_NODELAY set +* Connected to localhost (127.0.0.1) port 9000 (#0) +> POST /sign/b7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a HTTP/1.1 +> Host: localhost:9000 +> User-Agent: curl/7.68.0 +> Accept: */* +> Content-Type: application/json +> Content-Length: 23 +> +* upload completely sent off: 23 out of 23 bytes +* Mark bundle as not supporting multiuse +< HTTP/1.1 400 Bad Request +< content-length: 38 +< date: Wed, 30 Sep 2020 02:15:05 GMT +< +* Connection #0 to host localhost left intact +{"error":"Unable to parse body message from JSON: Error(\"expected ident\", line: 1, column: 2)"} + +# No Keys Available + +## Request +curl -v -X POST -d @payload.json -H 'Content-Type: application/json' localhost:9000/sign/000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + +## Response +Note: Unnecessary use of -X or --request, POST is already inferred. +* Trying 127.0.0.1:9000... +* TCP_NODELAY set +* Connected to localhost (127.0.0.1) port 9000 (#0) +> POST /sign/000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 HTTP/1.1 +> Host: localhost:9000 +> User-Agent: curl/7.68.0 +> Accept: */* +> Content-Type: application/json +> Content-Length: 84 +> +* upload completely sent off: 84 out of 84 bytes +* Mark bundle as not supporting multiuse +< HTTP/1.1 404 Not Found +< content-length: 123 +< date: Wed, 30 Sep 2020 02:18:53 GMT +< +* Connection #0 to host localhost left intact +{"error":"Key not found: 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"} + +# Server Error + +## Preparation +## `chmod` both keys directory and file to the octal 311 (-wx--x--x). +## `chmod` back to 755 to delete them afterwards. + +## Request +curl -v -X POST -d @payload.json -H 'Content-Type: application/json' localhost:9000/sign/b7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a + +## Response +Note: Unnecessary use of -X or --request, POST is already inferred. +* Trying 127.0.0.1:9000... +* TCP_NODELAY set +* Connected to localhost (127.0.0.1) port 9000 (#0) +> POST /sign/b7354252aa5bce27ab9537fd0158515935f3c3861419e1b4b6c8219b5dbd15fcf907bddf275442f3e32f904f79807a2a HTTP/1.1 +> Host: localhost:9000 +> User-Agent: curl/7.68.0 +> Accept: */* +> Content-Type: application/json +> Content-Length: 84 +> +* upload completely sent off: 84 out of 84 bytes +* Mark bundle as not supporting multiuse +< HTTP/1.1 500 Internal Server Error +< content-length: 43 +< date: Wed, 30 Sep 2020 02:21:08 GMT +< +* Connection #0 to host localhost left intact +{"error":"Storage error: PermissionDenied"} +``` + +## Implementation + +Repository Url | Language | Organization | Commentary +--- | --- | --- | --- +[BLS Remote Signer](https://github.com/sigp/rust-bls-remote-signer) | Rust | Sigma Prime | Supports proposed specification. +[Web3signer](https://github.com/PegaSysEng/web3signer) | Java | PegaSys | Supports proposed specification, although with [slightly different methods](https://pegasyseng.github.io/web3signer/web3signer-eth2.html):
{`/sign` => `/api/v1/eth2/sign`, `/publicKeys` => `/api/v1/eth2/publicKeys`}. +[Remote Signing Wallet](https://docs.prylabs.network/docs/wallet/remote/) | Golang | Prysmatics Labs | Supports both gRPC and JSON over HTTP. + +## Security Considerations + +### Threat model + +Let's consider the following threats and their mitigations: + +Threat | Mitigation(s) +--- | --- +An attacker can spoof the validator client. | See the discussion at [Authentication](#authentication). +An attacker can send a crafted message to the signer, leading to a slashing offense. | It is the responsibility of the operator of the remote signer to add a validation module, as discussed at [Implementation of additional features](#implementation-of-additional-features). +An attacker can create, update, or delete secret keys. | Keys are not to be writable via any interface of the remote signer. +An attacker can repudiate a sent message. | Implement logging in the signer. Enhance it by sending logs to a syslog box. +An attacker can disclose the contents of a private key by retrieving the key from storage. | Storage in Hardware security module (HSM).
_or_
Storage in Secrets management applications (e.g. Hashicorp Vault). +An attacker can eavesdrop on the uploading of a secret key. | Upload the keys using a secure channel, based on each storage specification. +An attacker can eavesdrop on the retrieval of a key from the remote signer. | Always pass the data between storage and remote signer node using a secure channel. +An attacker can dump the memory in the remote signer to disclose a secret key. | Prevent physical access to the node running the remote signer.
_or_
Prevent access to the terminal of the node running the remote signer: Logs being sent to a syslog box. Deployments triggered by a simple, non-parameterized API.
_or_
Implement zeroization of the secret key at memory.
_or_
Explore the compilation and running of the remote signer in a Trusted execution environment (TEE). +An attacker can DoS the remote signer. | Implement IP filtering.
_or_
Implement Rate limiting. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3041.md b/EIPS/eip-3041.md new file mode 100644 index 00000000000000..3a21c44d1b91b3 --- /dev/null +++ b/EIPS/eip-3041.md @@ -0,0 +1,94 @@ +--- +eip: 3041 +title: Adds `baseFee` to `eth_getBlockByHash` +author: Abdelhamid Bakhta (@abdelhamidbakhta) +discussions-to: https://ethereum-magicians.org/t/eip-3041-add-basefee-in-eth-getblockbyhash-response/4825 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-10-13 +requires: 1474, 1559 +--- + +## Simple Summary +Add basefee field to `eth_getBlockByHash` RPC endpoint response. + +## Abstract +Adds `baseFee` property to the `eth_getBlockByHash` JSON-RPC request `result` object. This property will contain the value of the base fee for any block after the EIP-1559 fork. + +## Motivation +[EIP-1559](./eip-1559.md) introduces a base fee per gas in protocol. +This value is maintained under consensus as a new field in the block header structure. +Users may need value of the base fee at a given block. Base fee value is important to make gas price predictions more accurate. + +## Specification + +### `eth_getBlockByHash` + +#### Description + +Returns information about a block specified by hash. +Every block returned by this endpoint whose block number is before the [EIP-1559](./eip-1559.md) fork block **MUST NOT** include a `baseFee` field. +Every block returned by this endpoint whose block number is on or after the [EIP-1559](./eip-1559.md) fork block **MUST** include a `baseFee` field. + +#### Parameters + +Parameters remain unchanged. + +#### Returns +For the full specification of `eth_getBlockByHash` see [EIP-1474](./eip-1474.md). +Add a new JSON field to the `result` object for block headers containing a base fee (post [EIP-1559](./eip-1559.md) fork block). + +- {[`Quantity`](./eip-1474.md#quantity)} `baseFee` - base fee for this block + +#### Example + +```sh +# Request +curl -X POST --data '{ + "id": 1559, + "jsonrpc": "2.0", + "method": "eth_getBlockByHash", + "params":["0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", true] +}' + +# Response +{ + "id": 1559, + "jsonrpc": "2.0", + "result": { + "difficulty": "0x027f07", + "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", + "baseFee": "0x7" + "gasLimit": "0x9f759", + "gasUsed": "0x9f759", + "hash": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "logsBloom": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "miner": "0x4e65fda2159562a496f9f3522f89122a3088497a", + "nonce": "0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2", + "number": "0x1b4", + "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5", + "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": "0x027f07", + "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", + "timestamp": "0x54e34e8e" + "totalDifficulty": "0x027f07", + "transactions": [] + "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "uncles": [] + } +} +``` + +## Rationale +The addition of a single parameter instead of introducing a whole new endpoint was the simplest change that would be easiest to get integrated. +For backward compatibility we decided to not include the base fee in the response for pre-1559 blocks. + +## Backwards Compatibility +Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) fork block will omit the base fee field in the response. + +## Security Considerations +The added field (`baseFee`) is informational and does not introduce technical security issues. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3044.md b/EIPS/eip-3044.md new file mode 100644 index 00000000000000..73af4b98df9dc7 --- /dev/null +++ b/EIPS/eip-3044.md @@ -0,0 +1,94 @@ +--- +eip: 3044 +title: Adds `baseFee` to `eth_getBlockByNumber` +author: Abdelhamid Bakhta (@abdelhamidbakhta) +discussions-to: https://ethereum-magicians.org/t/eip-3044-add-basefee-to-eth-getblockbynumber/4828 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-10-14 +requires: 1474, 1559 +--- + +## Simple Summary +Add basefee field to `eth_getBlockByNumber` RPC endpoint response. + +## Abstract +Adds `baseFee` property to the `eth_getBlockByNumber` JSON-RPC request `result` object. This property will contain the value of the base fee for any block after the EIP-1559 fork. + +## Motivation +[EIP-1559](./eip-1559.md) introduces a base fee per gas in protocol. +This value is maintained under consensus as a new field in the block header structure. +Users may need value of the base fee at a given block. Base fee value is important to make gas price predictions more accurate. + +## Specification + +### `eth_getBlockByNumber` + +#### Description + +Returns information about a block specified by number. +Every block returned by this endpoint whose block number is before the [EIP-1559](./eip-1559.md) fork block **MUST NOT** include a `baseFee` field. +Every block returned by this endpoint whose block number is on or after the [EIP-1559](./eip-1559.md) fork block **MUST** include a `baseFee` field. + +#### Parameters + +Parameters remain unchanged. + +#### Returns +For the full specification of `eth_getBlockByNumber` see [EIP-1474](./eip-1474.md). +Add a new JSON field to the `result` object for block headers containing a base fee (post [EIP-1559](./eip-1559.md) fork block). + +- {[`Quantity`](./eip-1474.md#quantity)} `baseFee` - base fee for this block + +#### Example + +```sh +# Request +curl -X POST --data '{ + "id": 1559, + "jsonrpc": "2.0", + "method": "eth_getBlockByNumber", + "params":["latest", true] +}' + +# Response +{ + "id": 1559, + "jsonrpc": "2.0", + "result": { + "difficulty": "0x027f07", + "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", + "baseFee": "0x7" + "gasLimit": "0x9f759", + "gasUsed": "0x9f759", + "hash": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "logsBloom": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "miner": "0x4e65fda2159562a496f9f3522f89122a3088497a", + "nonce": "0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2", + "number": "0x1b4", + "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5", + "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": "0x027f07", + "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", + "timestamp": "0x54e34e8e" + "totalDifficulty": "0x027f07", + "transactions": [] + "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "uncles": [] + } +} +``` + +## Rationale +The addition of a single parameter instead of introducing a whole new endpoint was the simplest change that would be easiest to get integrated. +For backward compatibility we decided to not include the base fee in the response for pre-1559 blocks. + +## Backwards Compatibility +Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) fork block will omit the base fee field in the response. + +## Security Considerations +The added field (`baseFee`) is informational and does not introduce technical security issues. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3045.md b/EIPS/eip-3045.md new file mode 100644 index 00000000000000..f3a2f2c40603b2 --- /dev/null +++ b/EIPS/eip-3045.md @@ -0,0 +1,94 @@ +--- +eip: 3045 +title: Adds `baseFee` to `eth_getUncleByBlockHashAndIndex` +author: Abdelhamid Bakhta (@abdelhamidbakhta) +discussions-to: https://ethereum-magicians.org/t/add-basefee-to-eth-getunclebyblockhashandindex/4829 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-10-14 +requires: 1474, 1559 +--- + +## Simple Summary +Add basefee field to `eth_getUncleByBlockHashAndIndex` RPC endpoint response. + +## Abstract +Adds `baseFee` property to the `eth_getUncleByBlockHashAndIndex` JSON-RPC request `result` object. This property will contain the value of the base fee for any block after the EIP-1559 fork. + +## Motivation +[EIP-1559](./eip-1559.md) introduces a base fee per gas in protocol. +This value is maintained under consensus as a new field in the block header structure. +Users may need value of the base fee at a given block. Base fee value is important to make gas price predictions more accurate. + +## Specification + +### `eth_getUncleByBlockHashAndIndex` + +#### Description + +Returns information about an uncle specified by block hash and uncle index position +Every block returned by this endpoint whose block number is before the [EIP-1559](./eip-1559.md) fork block **MUST NOT** include a `baseFee` field. +Every block returned by this endpoint whose block number is on or after the [EIP-1559](./eip-1559.md) fork block **MUST** include a `baseFee` field. + +#### Parameters + +Parameters remain unchanged. + +#### Returns +For the full specification of `eth_getUncleByBlockHashAndIndex` see [EIP-1474](./eip-1474.md). +Add a new JSON field to the `result` object for block headers containing a base fee (post [EIP-1559](./eip-1559.md) fork block). + +- {[`Quantity`](./eip-1474.md#quantity)} `baseFee` - base fee for this block + +#### Example + +```sh +# Request +curl -X POST --data '{ + "id": 1559, + "jsonrpc": "2.0", + "method": "eth_getUncleByBlockHashAndIndex", + "params":["0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b", "0x0"] +}' + +# Response +{ + "id": 1559, + "jsonrpc": "2.0", + "result": { + "difficulty": "0x027f07", + "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", + "baseFee": "0x7" + "gasLimit": "0x9f759", + "gasUsed": "0x9f759", + "hash": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "logsBloom": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "miner": "0x4e65fda2159562a496f9f3522f89122a3088497a", + "nonce": "0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2", + "number": "0x1b4", + "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5", + "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": "0x027f07", + "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", + "timestamp": "0x54e34e8e" + "totalDifficulty": "0x027f07", + "transactions": [] + "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "uncles": [] + } +} +``` + +## Rationale +The addition of a single parameter instead of introducing a whole new endpoint was the simplest change that would be easiest to get integrated. +For backward compatibility we decided to not include the base fee in the response for pre-1559 blocks. + +## Backwards Compatibility +Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) fork block will omit the base fee field in the response. + +## Security Considerations +The added field (`baseFee`) is informational and does not introduce technical security issues. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3046.md b/EIPS/eip-3046.md new file mode 100644 index 00000000000000..d5ca817043c80a --- /dev/null +++ b/EIPS/eip-3046.md @@ -0,0 +1,94 @@ +--- +eip: 3046 +title: Adds `baseFee` to `eth_getUncleByBlockNumberAndIndex` +author: Abdelhamid Bakhta (@abdelhamidbakhta) +discussions-to: https://ethereum-magicians.org/t/add-basefee-to-eth-getunclebyblocknumberandindex/4830 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-10-14 +requires: 1474, 1559 +--- + +## Simple Summary +Add basefee field to `eth_getUncleByBlockNumberAndIndex` RPC endpoint response. + +## Abstract +Adds `baseFee` property to the `eth_getUncleByBlockNumberAndIndex` JSON-RPC request `result` object. This property will contain the value of the base fee for any block after the EIP-1559 fork. + +## Motivation +[EIP-1559](./eip-1559.md) introduces a base fee per gas in protocol. +This value is maintained under consensus as a new field in the block header structure. +Users may need value of the base fee at a given block. Base fee value is important to make gas price predictions more accurate. + +## Specification + +### `eth_getUncleByBlockNumberAndIndex` + +#### Description + +Returns information about an uncle specified by block number and uncle index position +Every block returned by this endpoint whose block number is before the [EIP-1559](./eip-1559.md) fork block **MUST NOT** include a `baseFee` field. +Every block returned by this endpoint whose block number is on or after the [EIP-1559](./eip-1559.md) fork block **MUST** include a `baseFee` field. + +#### Parameters + +Parameters remain unchanged. + +#### Returns +For the full specification of `eth_getUncleByBlockNumberAndIndex` see [EIP-1474](./eip-1474.md). +Add a new JSON field to the `result` object for block headers containing a base fee (post [EIP-1559](./eip-1559.md) fork block). + +- {[`Quantity`](./eip-1474.md#quantity)} `baseFee` - base fee for this block + +#### Example + +```sh +# Request +curl -X POST --data '{ + "id": 1559, + "jsonrpc": "2.0", + "method": "eth_getUncleByBlockNumberAndIndex", + "params":["latest", "0x0"] +}' + +# Response +{ + "id": 1559, + "jsonrpc": "2.0", + "result": { + "difficulty": "0x027f07", + "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", + "baseFee": "0x7" + "gasLimit": "0x9f759", + "gasUsed": "0x9f759", + "hash": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "logsBloom": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", + "miner": "0x4e65fda2159562a496f9f3522f89122a3088497a", + "nonce": "0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2", + "number": "0x1b4", + "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5", + "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": "0x027f07", + "stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff", + "timestamp": "0x54e34e8e" + "totalDifficulty": "0x027f07", + "transactions": [] + "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "uncles": [] + } +} +``` + +## Rationale +The addition of a single parameter instead of introducing a whole new endpoint was the simplest change that would be easiest to get integrated. +For backward compatibility we decided to not include the base fee in the response for pre-1559 blocks. + +## Backwards Compatibility +Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) fork block will omit the base fee field in the response. + +## Security Considerations +The added field (`baseFee`) is informational and does not introduce technical security issues. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3068.md b/EIPS/eip-3068.md new file mode 100644 index 00000000000000..8283305613fd99 --- /dev/null +++ b/EIPS/eip-3068.md @@ -0,0 +1,296 @@ +--- +eip: 3068 +title: Precompile for BN256 HashToCurve Algorithms +author: Dr. Christopher Gorman (@chgormanMH) +discussions-to: https://ethereum-magicians.org/t/pre-compile-for-bls/3973 +status: Stagnant +type: Standards Track +category: Core +created: 2020-10-23 +requires: 198, 1108 +--- + +## Simple Summary +This EIP defines a hash-to-curve precompile for use in BN256 +and would allow for cheaper BLS signature verification. + +## Abstract +There is currently no inexpensive way to perform BLS signature +verification for arbitrary messages. +This stems from the fact that there is no precompiled contract +in the EVM for a hash-to-curve algorithm for the BN256 elliptic curve. +The gas cost of calling a deterministic hash-to-curve algorithm +written in Solidity is approximately that of one pairing check, +although the latter requires an order of magnitude +more computation. +This EIP remedies this by implementing a hash-to-curve algorithm +for the BN256 G1 curve, which would reduce the cost of +signature verification to essentially that of the pairing check +precompiled contract. +We also include a hash-to-curve algorithm for the BN256 G2 group. + +## Motivation +The precompiled contracts in +[EIP-198](./eip-198.md) and +[EIP-1108](./eip-1108.md) +increased usage of cryptographic operations in the EVM +by reducing the gas costs. +In particular, the cost reduction from +[EIP-1108](./eip-1108.md) +helps increase the use of SNARKs in Ethereum +via an elliptic curve pairing check; +however, a hash-to-curve algorithm enabling arbitrary +BLS signature verification on BN256 in the EVM was noticeably missing. +There is interest in having a precompiled contract which would allow +for signature verification, as noted +[here](https://ethereum-magicians.org/t/pre-compile-for-bls/3973). + +At this time, we are able to perform addition, scalar multiplication, +and pairing checks in BN256. +Reducing these costs in +[EIP-1108](./eip-1108.md) +made [ETHDKG](https://github.com/PhilippSchindler/ethdkg), +a distributed key generation protocol in Ethereum, +less expensive. +ETHDKG by itself is useful; however, what it is lacking is +the ability to verify arbitrary BLS signatures. +Creating group signatures by aggregating partial signatures +is one goal of a DKG protocol. +The DKG enables the computation of partial signatures to be +combined into a group signature offline, but there is no +easy way to verify partial signatures or group signatures +in the EVM. + +In order to perform BLS signature validation, a hash-to-curve +algorithm is required. +While the MapToGroup method initially discussed in the original BLS +[paper](../assets/eip-3068/weilsigs.pdf) +works in practice, the nondeterministic nature of the algorithm +leaves something to be desired as we would like to bound +the overall computational cost in the EVM. +A deterministic method for mapping to BN curves is given +[here](../assets/eip-3068/latincrypt12.pdf); +in the paper, Fouque and Tibouchi proved their mapping +was indifferentiable from a random oracle. +This gives us the desired algorithm. + +## Specification +Here is the pseudocode for the `HashToG1` function: + +``` +function HashToG1(msg) + fieldElement0 = HashToBase(msg, 0x00, 0x01) + fieldElement1 = HashToBase(msg, 0x02, 0x03) + curveElement0 = BaseToG1(fieldElement0) + curveElement1 = BaseToG1(fieldElement1) + g1Element = ECAdd(curveElement0, curveElement1) + return g1Element +end function +``` + +Here is the pseudocode for `HashToBase`; +`msg` is the byte slice to be hashed while `dsp1` and `dsp2` +are domain separation parameters. +`fieldPrime` is the prime of the underlying field. + +``` +function HashToBase(msg, dsp1, dsp2) + hashResult0 = uint256(Keccak256(dsp1||msg)) + hashResult1 = uint256(Keccak256(dsp2||msg)) + constant = 2^256 mod fieldPrime + fieldElement0 = hashResult0*constant mod fieldPrime + fieldElement1 = hashResult1 mod fieldPrime + fieldElement = fieldElement0 + fieldElement1 mod fieldPrime + return fieldElement +end function +``` + +Here is the pseudocode for `BaseToG1`. +All of these operations are performed in the finite field. +`inverse` computes the multiplicative inverse in the underlying +finite field; we have the convention `inverse(0) == 0`. +`is_square(a)` computes the Legendre symbol of the element, +returning 1 if `a` is a square, -1 if `a` is not a square, +and 0 if `a` is 0. +`sqrt` computes the square root of the element in the finite +field; a square root is assumed to exist. +`sign0` returns the sign of the finite field element. + +``` +function BaseToG1(t) + # All operations are done in the finite field GF(fieldPrime) + # Here, the elliptic curve satisfies the equation + # y^2 == g(x) == x^3 + curveB + constant1 = (-1 + sqrt(-3))/2 + constant2 = -3 + constant3 = 1/3 + constant4 = g(1) + s = (constant4 + t^2)^3 + alpha = inverse(t^2*(constant4 + t^2)) + x1 = constant1 - constant2*t^4*alpha + x2 = -1 - x1 + x3 = 1 - constant3*s*alpha + a1 = x1^3 + curveB + a2 = x2^3 + curveB + residue1 = is_square(a1) + residue2 = is_square(a2) + index = (residue1 - 1)*(residue2 - 3)/4 + 1 + coef1 = ConstantTimeEquality(1, index) + coef2 = ConstantTimeEquality(2, index) + coef3 = ConstantTimeEquality(3, index) + x = coef1*x1 + coef2*x2 + coef3*x3 + y = sign0(t)*sqrt(x^3 + curveB) + return (x, y) +end function + +function sign0(t) + if t <= (fieldPrime-1)/2 + return 1 + else + return fieldPrime-1 + end if +end function + +function ConstantTimeEquality(a, b) + # This function operates in constant time + if a == b + return 1 + else + return 0 + end if +end function +``` + +In `HashToG2`, we first map to the underlying twist curve +and then clear the cofactor to map to G2. +Here is the pseudocode for `HashToG2`: + +``` +function HashToG2(msg) + fieldElement00 = HashToBase(msg, 0x04, 0x05) + fieldElement01 = HashToBase(msg, 0x06, 0x07) + fieldElement10 = HashToBase(msg, 0x08, 0x09) + fieldElement11 = HashToBase(msg, 0x0a, 0x0b) + fieldElement0 = (fieldElement00, fieldElement01) + fieldElement1 = (fieldElement10, fieldElement11) + twistElement0 = BaseToTwist(fieldElement0) + twistElement1 = BaseToTwist(fieldElement1) + twistElement = ECAdd(twistElement0, twistElement1) + g2Element = ClearCofactor(twistElement) + return g2Element +end function + +function ClearCofactor(twistElement) + return ECMul(twistElement, cofactor) +end function +``` + +Here is the pseudocode for `BaseToTwist`. + +``` +function BaseToTwist(t) + # All operations are done in the finite field GF(fieldPrime^2) + # Here, the twist curve satisfies the equation + # y^2 == g'(x) == x^3 + curveBPrime + constant1 = (-1 + sqrt(-3))/2 + constant2 = -3 + constant3 = 1/3 + constant4 = g'(1) + s = (constant4 + t^2)^3 + alpha = inverse(t^2*(constant4 + t^2)) + x1 = constant1 - constant2*t^4*alpha + x2 = -1 - x1 + x3 = 1 - constant3*s*alpha + a1 = x1^3 + curveBPrime + a2 = x2^3 + curveBPrime + residue1 = is_square(a1) + residue2 = is_square(a2) + index = (residue1 - 1)*(residue2 - 3)/4 + 1 + coef1 = ConstantTimeEquality(1, index) + coef2 = ConstantTimeEquality(2, index) + coef3 = ConstantTimeEquality(3, index) + x = coef1*x1 + coef2*x2 + coef3*x3 + y = sign0(t)*sqrt(x^3 + curveBPrime) + return (x, y) +end function +``` + +## Rationale +The BaseToG1 algorithm is based on the original Fouque and Tibouchi +[paper](../assets/eip-3068/latincrypt12.pdf) +with modifications based on Wahby and Boneh's +[paper](../assets/eip-3068/2019-403_BLS12_H2C.pdf). +There is freedom in choosing the HashToBase function +and this could easily be changed. +Within HashToBase, the particular hashing algorithm +(Keccak256 in our case) could also be modified. +It may be desired to change the call to `sign0` +at the end of BaseToG1 and BaseToTwist with `is_square`, +as this would result in the same deterministic map to curve from the +Fouque and Tibouchi +[paper](../assets/eip-3068/latincrypt12.pdf) +and ensure HashToG1 is indifferentiable from a random oracle; +they proved this result in their paper. +It may be possible to show that switching the `is_square` +call with `sign0` does not affect indifferentiability, +although this has not been proven. + +The HashToG2 algorithm follows from the Wahby and Boneh +[paper](../assets/eip-3068/2019-403_BLS12_H2C.pdf). +Algorithms for computing `inverse`, `is_square`, and `sqrt` +in finite field GF(fieldPrime^2) can be found +[here](../assets/eip-3068/2012-685_Square_Root_Even_Ext.pdf). + +We now discuss the potential gas cost for the HashToG1 +and HashToG2 operations. +On a local machine, ECMul was clocked at 68 microseconds +per operation. +The same machine clocked HashToG1 at 94 microseconds per operation +when hashing 32 bytes into G1 and 105 microseconds per operation +when hashing 1024 bytes into G1. +Given that it currently costs 6000 gas for ECMul, this gives us +an estimated gas cost for HashToG1 at `8500 + len(bytes)`. +Similarly, HashToG2 was clocked at 886 microseconds per operation +when hashing 32 bytes into G2 and 912 microseconds per operation when +hashing 1024 bytes into G2. +This allows us to estimate the gas cost at `80000 + 3*len(bytes)`. + +## Backwards Compatibility +There are no backward compatibility concerns. + +## Test Cases +TBD + +## Implementation +TBD + +## Security Considerations +Due to recent [work](../assets/eip-3068/2015-1027_exTNFS.pdf), the +128-bit security promised by the BN256 elliptic curve no longer applies; +this was mentioned in the Cloudflare BN256 +[library](https://github.com/cloudflare/bn256). +There has been some discussion on the exact security decrease +from this advancement; see these +[two](../assets/eip-3068/2016-1102_Assessing_NFS_Advances.pdf) +[papers](../assets/eip-3068/2017-334.pdf) +for different estimates. +The more conservative estimate puts the security of BN256 at +100-bits. +While this is likely still out of reach for many adversaries, +it should give us pause. +This reduced security was noted in the recent MadNet +[whitepaper](../assets/eip-3068/madnet.pdf), +and this security concern was partially mitigated by +requiring Secp256k1 signatures of the partial group signatures +in order for those partial signatures to be valid. +Full disclosure: the author of this EIP works for MadHive, +assisted in the development of MadNet, and +helped write the MadNet whitepaper. + +The security concerns of the BN256 elliptic curve +affect any operation using pairing check because it is +related to the elliptic curve pairing; +they are independent of this EIP. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3074.md b/EIPS/eip-3074.md new file mode 100644 index 00000000000000..52307e90a12b4f --- /dev/null +++ b/EIPS/eip-3074.md @@ -0,0 +1,355 @@ +--- +eip: 3074 +title: AUTH and AUTHCALL opcodes +description: Allow externally owned accounts to delegate control to a contract. +author: Sam Wilson (@SamWilsn), Ansgar Dietrichs (@adietrichs), Matt Garnett (@lightclient), Micah Zoltu (@micahzoltu) +discussions-to: https://ethereum-magicians.org/t/eip-3074-sponsored-transaction-precompile/4880 +status: Withdrawn +type: Standards Track +category: Core +created: 2020-10-15 +requires: 155 +withdrawal-reason: Superseded by EIP-7702 +--- + +## Abstract + +This EIP introduces two EVM instructions `AUTH` and `AUTHCALL`. The first sets a context variable `authorized` based on an ECDSA signature. The second sends a call as the `authorized` account. This essentially delegates control of the externally owned account (EOA) to a smart contract. + +## Motivation + +Adding more functionality to EOAs has been a long-standing feature request. The requests have spanned from implementing batching capabilities, allowing for gas sponsoring, expirations, scripting, and beyond. These changes often mean increased complexity and rigidity of the protocol. In some cases, it also means increased attack surfaces. + +This EIP takes a different approach. Instead of enshrining these capabilities in the protocol as transaction validity requirements, it allows users to *delegate* control of their EOA to a contract. This gives developers a flexible framework for developing novel transaction schemes for EOAs. A motivating use case of this EIP is that it allows any EOA to act like a smart contract wallet *without* deploying a contract. + +Although this EIP provides great benefit to individual users, the leading motivation for this EIP is "sponsored transactions". This is where the fee for a transaction is provided by a different account than the one that originates the call. + +With the extraordinary growth of tokens on Ethereum, it has become common for EOAs to hold valuable assets without holding any ether at all. Today, these assets must be converted to ether before they can be used to pay gas fees. However, without ether to pay for the conversion, it's impossible to convert them. Sponsored transactions break the circular dependency. + +## Specification + +### Conventions + + - **`top - N`** - the `N`th most recently pushed value on the EVM stack, where `top - 0` is the most recent. + - **`||`** - byte concatenation operator. + - **invalid execution** - execution that is invalid and must exit the current execution frame immediately, consuming all remaining gas (in the same way as a stack underflow or invalid jump). + +### Constants + +| Constant | Value | +| ---------------- | ------ | +| `MAGIC` | `0x04` | + +`MAGIC` is used for [EIP-3074](./eip-3074.md) signatures to prevent signature collisions with other signing formats. + +### Context Variables + +| Variable | Type | Initial Value | +| ------------------- | --------- |:------------- | +| `authorized` | `address` | unset | + +The context variable `authorized` shall indicate the active account for `AUTHCALL` instructions in the current frame of execution. If set, `authorized` shall only contain an account which has given the contract authorization to act on its behalf. An unset value shall indicate that no such account is set and that there is not yet an active account for `AUTHCALL` instructions in the current frame of execution. + +The variable has the same scope as the program counter -- `authorized` persists throughout a single frame of execution of the contract, but is not passed through any calls (including `DELEGATECALL`). If the same contract is being executed in separate execution frames (ex. a `CALL` to self), both frames shall have independent values for `authorized`. Initially in each frame of execution, `authorized` is always unset, even if a previous execution frame for the same contract has a value. + +### `AUTH` (`0xf6`) + +A new opcode `AUTH` shall be created at `0xf6`. It shall take three stack element inputs (the last two describing a memory range), and it shall return one stack element. + +#### Input + +##### Stack + +| Stack | Value | +| ---------- | ------------ | +| `top - 0` | `authority` | +| `top - 1` | `offset` | +| `top - 2` | `length` | + +##### Memory + +The final two stack arguments (`offset` and `length`) describe a range of memory. The format of the contents of that range is: + + - `memory[offset : offset+1 ]` - `yParity` + - `memory[offset+1 : offset+33]` - `r` + - `memory[offset+33 : offset+65]` - `s` + - `memory[offset+65 : offset+97]` - `commit` + +#### Output + +##### Stack + +| Stack | Value | +| ---------- | -------------| +| `top - 0` | `success` | + +##### Memory + +Memory is not modified by this instruction. + +#### Behavior + +If `length` is greater than 97, the extra bytes are ignored for signature verification (they still incur a gas cost as defined later). Bytes outside the range (in the event `length` is less than 97) are treated as if they had been zeroes. + +`authority` is the address of the account which generated the signature. If `EXTCODESIZE` of `authority` is not zero, consider the operation unsuccessful and unset `authorized`. + +The arguments (`yParity`, `r`, `s`) are interpreted as an ECDSA signature on the secp256k1 curve over the message `keccak256(MAGIC || chainId || nonce || invokerAddress || commit)`, where: + + - `chainId` is the current chain's [EIP-155](./eip-155.md) unique identifier padded to 32 bytes. + - `nonce` is the signer's current nonce, left-padded to 32 bytes. + - `invokerAddress` is the address of the contract executing `AUTH` (or the active state address in the context of `CALLCODE` or `DELEGATECALL`), left-padded with zeroes to a total of 32 bytes (ex. `0x000000000000000000000000AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`). + - `commit`, one of the arguments passed into `AUTH`, is a 32-byte value that can be used to commit to specific additional validity conditions in the invoker's pre-processing logic. + +Signature validity and signer recovery are handled analogously to transaction signatures, including the stricter `s` range for preventing ECDSA malleability. Note that `yParity` is expected to be `0` or `1`. + +If the signature is valid and the signer address is equal to `authority`, the context variable `authorized` is set to the `authority`. In particular, this is also true if `authority == tx.origin`, which used to be handled separately in earlier versions of this EIP (see Security Considerations). If the signature is instead invalid or the signer address does not equal `authority`, `authorized` is reset to an unset value. + +`AUTH` returns `1` if `authorized` is set, or `0` otherwise. + +#### Gas Cost + +The gas cost for `AUTH` is equal to the sum of: + + - fixed fee `3100`. + - memory expansion gas cost (`auth_memory_expansion_fee`). + - `100` if `authority` is warm, `2600` if it is cold (per [EIP-2929](./eip-2929.md)). + +The fixed fee is equal to the cost for the `ecrecover` precompile, plus a bit extra to cover a keccak256 hash and some additional logic. + +The memory expansion gas cost (`auth_memory_expansion_fee`) shall be calculated in the same way as `RETURN`, where memory is expanded if the specified range is outside the current allocation. + +### `AUTHCALL` (`0xf7`) + +A new opcode `AUTHCALL` shall be created at `0xf7`. It shall take seven stack elements and return one stack element. It matches the behavior of the existing `CALL` (`0xF1`) instruction, except where noted below. + +#### Input + +| Stack | Value | +| --------- | ------------ | +| `top - 0` | `gas` | +| `top - 1` | `addr` | +| `top - 2` | `value` | +| `top - 3` | `argsOffset` | +| `top - 4` | `argsLength` | +| `top - 5` | `retOffset` | +| `top - 6` | `retLength` | + +#### Output + +| Stack | Value | +| ---------- | --------- | +| `top - 0` | `success` | + +#### Behavior + +`AUTHCALL` is interpreted the same as `CALL`, except for (note: this list is also the order of precedence for the logical checks): + + - If `authorized` is unset, execution is invalid (as defined above). Otherwise, the caller address for the call is set to `authorized`. + - The gas cost, including how much gas is available for the subcall, is specified in the Gas Cost section. + - If the `gas` operand is equal to `0`, the instruction will send all available gas as per [EIP-150](./eip-150). + - If the gas available for the subcall would be less than `gas`, execution is invalid. + - There is no gas stipend, even for non-zero `value`. + - `value` is deducted from the balance of `authorized`. If `value` is higher than the balance of `authorized`, execution is invalid. + +`AUTHCALL` must increase the call depth by one. `AUTHCALL` must not increase the call depth by two as it would if it first called into the authorized account and then into the target. + +The return data area accessed with `RETURNDATASIZE` (`0x3d`) and `RETURNDATACOPY` (`0x3e`) must be set in the same way as the `CALL` instruction. + +Importantly, `AUTHCALL` does not reset `authorized`, but leaves it unchanged. + +#### Gas Cost + +The gas cost for `AUTHCALL` shall be the **sum** of: + + - static gas cost (`warm_storage_read`) + - memory expansion gas cost (`memory_expansion_fee`) + - dynamic gas cost (`dynamic_gas`) + - gas available for execution in the subcall (`subcall_gas`) + +The memory expansion gas cost (`memory_expansion_fee`) shall be calculated in the same way as `CALL`. + +The dynamic gas portion (`dynamic_gas`), and the gas available for execution in the subcall (`subcall_gas`) shall be calculated as: + +``` +dynamic_gas = 0 + +if addr not in accessed_addresses: + dynamic_gas += 2500 # cold_account_access - warm_storage_read + +if value > 0: + dynamic_gas += 6700 # NB: Not 9000, like in `CALL` + if is_empty(addr): + dynamic_gas += 25000 + +remaining_gas = available_gas - dynamic_gas +all_but_one_64th = remaining_gas - (remaining_gas // 64) + +if gas == 0: + subcall_gas = all_but_one_64th +elif all_but_one_64th < gas: + raise # Execution is invalid. +else: + subcall_gas = gas +``` + +As with `CALL`, the full gas cost is charged immediately, independently of actually executing the call. + +## Rationale + +### Signature in Memory + +The signature format (`yParity`, `r`, and `s`) is fixed, so it might seem curious that `auth` accepts a dynamic memory range. The signature is placed in memory so that `auth` can be upgraded in the future to work with contract accounts (which might use non-ECDSA signatures) and not just EOAs. + +### Signing Address `auth` Argument + +Including `authority` (the signing address) as an argument to `auth` allows future upgrades to the instruction to work with contract accounts, and not just EOAs. + +If `authority` were not included and multiple signature schemes allowed, it would not be possible to compute the authorizing account's address from just the signature alone. + +### Reserving One Sixty-Fourth of Available Gas + +`AUTHCALL` will not pass more than 63/64th of the available gas for the reasons enumerated in [EIP-150](./eip-150.md). + +### Throwing for Unset `authorized` During `AUTHCALL` + +A well-behaved contract should never reach an `AUTHCALL` without having successfully set `authorized` beforehand. The safest behavior, therefore, is to exit the current frame of execution immediately. This is especially important in the context of transaction sponsoring / relaying, which is expected to be one of the main use cases for this EIP. In a sponsored transaction, the inability to distinguish between a sponsee-attributable fault (like a failing sub-call) and a sponsor-attributable fault (like a failing `AUTH`) is especially dangerous and should be prevented because it charges unfair fees to the sponsee. + +### Another Sponsored Transaction EIP + +There are two general approaches to separating the "fee payer" from the "action originator". + +The first is introducing a new transaction type. This requires significant changes to clients to support and is generally less upgradeable than other solutions (e.g. this EIP). This approach is also not immediately compatible with account abstraction (AA). These proposals require a *signed* transaction from the sponsor's account, which is not possible from an AA contract, because it has no private key to sign with. The main advantage of new transaction types is that the validity requirements are enforced by the protocol, therefore invalid transactions do not pollute block space. + +The other main approach is to introduce a new mechanism in the EVM to masquerade as other accounts. This EIP introduces `AUTH` and `AUTHCALL` to make calls as EOAs. There are many different permutations of this mechanism. An alternative mechanism would be to add an opcode that can make arbitrary calls based on a similar address creation scheme as `CREATE2`. Although this mechanism would not benefit users today, it would immediately allow for those accounts to send and receive ether -- making it feel like a more first-class primitive. + +Besides better compatibility with AA, introducing a new mechanism into the EVM is a much less intrusive change than a new transaction type. This approach requires no changes in existing wallets, and little change in other tooling. + +`AUTHCALL`'s single deviation from `CALL` is to set `CALLER`. It implements the minimal functionality to enable sender abstraction for sponsored transactions. This single mindedness makes `AUTHCALL` significantly more composable with existing Ethereum features. + +More logic can be implemented around the `AUTHCALL` instruction, giving more control to invokers and sponsors without sacrificing security or user experience for sponsees. + +### What to Sign? + +As originally written, this proposal specified a precompile with storage to track nonces. Since a precompile with storage is unprecedented, a revision moved replay protection into the invoker contract, necessitating a certain level of user trust in the invoker. Expanding on this idea of trusted invokers, the other signed fields were eventually eliminated, one by one, until only `invoker` and `commit` remained. To appease concerns about cross-chain replay attacks and irrevocable signatures, the `chainId` and `nonce` fields returned to the signed message. + +The `invoker` binds a particular signed message to a single invoker. If invoker was not part of the message, any invoker could reuse the signature to completely compromise the EOA. This allows users to trust that their message will be validated as they expect, particularly the values committed to in `commit`. + +### Understanding `commit` + +Earlier iterations of this EIP included mechanisms for replay protection, and also signed over value, gas, and other arguments to `AUTHCALL`. After further investigation, we revised this EIP to its current state: explicitly delegate these responsibilities to the invoker contract. + +A user will specifically interact with an invoker they trust. Because they trust this contract to execute faithfully, they will "commit" to certain properties of a call they would like to make by computing a hash of the call values. They can be certain that the invoker will only allow the call to proceed if it is able to verify the values committed to (e.g. a nonce to protect against replay attacks). This certainty arises from the `commit` value that is signed over by the user. This is the hash of values which the invoker will validate. A safe invoker should accept the values from the user and compute the commit hash itself. This ensures that invoker operated on the same input that user authorized. + +![auth message format](../assets/eip-3074/auth-msg.png) + +Using `commit` as a hash of values allows for invokers to implement arbitrary constraints. For example, they could allow accounts to have `N` parallel nonces. Or, they could allow a user to commit to multiple calls with a single signature. This would allow multi-tx flows, such as [ERC-20](./eip-20.md) `approve`-`transfer` actions, to be condensed into a single transaction with a single signature verification. A commitment to multiple calls would look something like the diagram below. + +![multi-call auth message](../assets/eip-3074/auth-msg-multi-call.png) + +Another interesting use is to delegate control of the EOA to other key(s). This would mean the EOA signs a `commit` message with the address of the key(s) and an access policy, if applicable. When the delegate wants to make a call as the EOA it will construct a signature over the invoker-specified call format and relay it (with the actual call data) onto chain with the signature and commit that granted it access to the account. The invoker will then be able to determine that the EOA has allowed this alternative key to make calls on its behalf. + +![delegate auth message](../assets/eip-3074/auth-msg-delegate.png) + + +### Invoker Contracts + +The invoker contract is a trustless intermediary between the sponsor and sponsee. A sponsee signs over `invoker` to require the transaction to be processed only by a contract they trust. This allows them to interact with sponsors without needing to trust them. + +Choosing an invoker is similar to choosing a smart contract wallet implementation. It's important to choose one that has been thoroughly reviewed, tested, and accepted by the community as secure. We expect a few invoker designs to be utilized by most major transaction relay providers, with a few outliers that offer more novel mechanisms. + +An important note is that invoker contracts **MUST NOT** be upgradeable. If an invoker can be redeployed to the same address with different code, it would be possible to redeploy the invoker with code that does not properly verify `commit` and any account that signed a message over that invoker would be compromised. Although this sounds scary, it is no different than using a smart contract wallet via `DELEGATECALL`. If the wallet is redeployed with different logic, all wallets using its code could be compromised. + +### On Call Depth + +The EVM limits the maximum number of nested calls, and naively allowing a sponsor to manipulate the call depth before reaching the invoker would introduce a griefing attack against the sponsee. That said, with the 63/64th gas rule, and the cost of `AUTHCALL`, the stack is effectively limited to a much smaller depth than the hard maximum by the `gas` parameter. + +It is, therefore, sufficient for the invoker to guarantee a minimum amount of gas, because there is no way to reach the hard maximum call depth with any reasonable (i.e. less than billions) amount of gas. + +### Source of `value` + +In previous iterations of this EIP, it was thought that deducting value from an EOA mid-execution was problematic. This was due to an invariant of pending transactions which allows tx pools to statically determine the validity of a given transaction. + +However, after further investigation we found that breaking the invariant is safe. This is mostly due to the fact that the worst case is similar in both instances. + +Currently an attacker can queue many transactions in the tx pool, across many accounts, and invalidate them all at once with a block where each of the queued accounts send a tx moving their entire balance. This attack will become easier and cheaper after this EIP, because it will no longer require direct access to the block builder and will not cost a full 21000 gas to originate each tx. However, the attack does not have a substantial impact on the network, so reducing the difficulty and cost is not of concern. + +### Allowing `tx.origin` as Signer + +Allowing `authorized` to equal `tx.origin` enables simple transaction batching, where the sender of the outer transaction would be the signing account. The ERC-20 approve-then-transfer pattern, which currently requires two separate transactions, could be completed in a single transaction with this proposal. + +`AUTH` allows for signatures to be signed by `tx.origin`. For any such signatures, subsequent `AUTHCALL`s have `msg.sender == tx.origin` in their first layer of execution. Without EIP-3074, this situation can only ever arise in the topmost execution layer of a transaction. This EIP breaks that invariant and so affects smart contracts containing `require(msg.sender == tx.origin)` checks. This check can be used for at least three purposes: + + 1. Ensuring that `msg.sender` is an EOA (given that `tx.origin` always has to be an EOA). This invariant does not depend on the execution layer depth and, therefore, is not affected. + 2. Protecting against atomic sandwich attacks like flash loans, that rely on the ability to modify state before and after the execution of the target contract as part of the same atomic transaction. This protection would be broken by this EIP. However, relying on `tx.origin` in this way is considered bad practice, and can already be circumvented by miners conditionally including transactions in a block. + 3. Preventing reentrancy. + +Examples of (1) and (2) can be found in contracts deployed on Ethereum mainnet, with (1) being more common (and unaffected by this proposal.) On the other hand, use case (3) is more severely affected by this proposal, but the authors of this EIP did not find any examples of this form of reentrancy protection, though the search was non-exhaustive. + +This distribution of occurrences—many (1), some (2), and no (3)—is exactly what the authors of this EIP expect, because: + + - Determining if `msg.sender` is an EOA without `tx.origin` is difficult (if not impossible.) + - The only execution context which is safe from atomic sandwich attacks is the topmost context, and `tx.origin == msg.sender` is the only way to detect that context. + - In contrast, there are many direct and flexible ways of preventing reentrancy (ex. using a storage variable.) Since `msg.sender == tx.origin` is only true in the topmost context, it would make an obscure tool for preventing reentrancy, rather than other more common approaches. + +There are other approaches to mitigate this restriction which do not break the invariant: + + - Set `tx.origin` to a constant `ENTRY_POINT` address for `AUTHCALL`s. + - Set `tx.origin` to the invoker address for `AUTHCALL`s. + - Set `tx.origin` to a special address derived from any of the sender, invoker, and/or signer addresses. + - Disallow `authorized == tx.origin`. This would make the simple batching use cases impossible, but could be relaxed in the future. + +### `AUTHCALL` cheaper than `CALL` when sending value + +Sending non-zero value with `CALL` increases its cost by 9,000. Of that, 6,700 covers the increased overhead of the balance transfer and 2,300 is used as a stipend into the subcall to seed its gas counter. `AUTHCALL` does not provide a stipend and thus only charges the base 6,700. + +### In-Protocol Revocation + +This EIP has gone [back and forth](#what-to-sign) on how to deal with `AUTH` message revocation. Without revocation, this EIP is a supremely powerful and flexible primitive for developers. However, it does have risk for users who use insecure and/or actively malicious invokers. + +Much of the risk is due to the new ability for users to batch many operations in a single transaction. It becomes easier for an account to be drained. This is a risk that will continue to grow, regardless of the adoption of this EIP, due to overwhelming desire for the feature and attempts to support it at the protocol level and at the app level. + +A new class of risk is introduced for insecure and buggy invokers. If an invoker has implemented replay protection, as per the authors' recommendation, this should substantially contain the blast radius. However, if the bug allows an adversary to circumvent the replay protection mechanism, it may give them full access to any EOA which has interacted with the vulnerable invoker. + +Although this is a truly catastrophic event which is not expected to be possible via reputable wallets, it is a serious consideration. Without in-protocol revocation, users have no way to remove their account from the vulnerable invoker. + +For this reason, `AUTH` requires the `nonce` in the message to be equal to the signer's current nonce. This way, a single tx from the EOA will cause the nonce to increase, invalidating all outstanding authorizations. + +### Failing on `EXTCODESIZE` check + +In [EIP-3607](./eip-3607), it was determined that the protocol should reject any transaction which originates from an account with code. Although this EIP focused on transaction origination, the authors of EIP-3074 feel the intention is clear: an account that has both code and a known private key should not be allowed to make arbitrary calls on behalf of said account. Therefore, the property is upheld in this EIP. For full rationale, please refer to [EIP-3607](./eip-3607). + +## Backwards Compatibility + +Although this EIP poses no issues for backwards compatibility, there are concerns that it limits future changes to accounts by further enshrining ECDSA signatures. For example, it might be desirable to eradicate the concept of EOAs altogether, and replace them with smart contract wallets that emulate the same behavior. This is fully compatible with the EIP as written, however, it gets tricky if users can then elect to "upgrade" their smart contract wallets to use other methods of authentication -- e.g. convert into a multi-sig. Without any changes, `AUTH` would not respect this new logic and continue allowing the old private key to perform actions on behalf of the account. + +A solution to this would be at the same time that EOAs are removed, to modify the logic of `AUTH` to actually call into the account with some standard message and allow the account to determine if the signature / witness is valid. Further research should be done to understand how invokers would need to change in this situation and how best to write them in a future-compatible manner. + +## Security Considerations + +### Secure Invokers + +The following is a non-exhaustive list of checks/pitfalls/conditions that invokers *should* be wary of: + + - Replay protection (ex. a nonce) should be implemented by the invoker, and included in `commit`. Without it, a malicious actor can reuse a signature, repeating its effects. + - `value` should be included in `commit`. Without it, a malicious sponsor could cause unexpected effects in the callee. + - `gas` should be included in `commit`. Without it, a malicious sponsor could cause the callee to run out of gas and fail, griefing the sponsee. + - `addr` and `calldata` should be included in `commit`. Without them, a malicious actor may call arbitrary functions in arbitrary contracts. + +A poorly implemented invoker can *allow a malicious actor to take near complete control over a signer's EOA*. + +### Allowing `tx.origin` as Signer + +Allowing `authorized` to equal `tx.origin` has the possibility to: + + - Break atomic sandwich protections which rely on `tx.origin`; + - Break reentrancy guards of the style `require(tx.origin == msg.sender)`. + +The authors of this EIP believe the risks of allowing `authorized` to equal `tx.origin` are acceptable for the reasons outlined in the Rationale section. + +### Sponsored Transaction Relayers + +It is possible for the `authorized` account to cause sponsored transaction relayers to spend gas without being reimbursed by either invalidating the authorization (i.e. increasing the account's nonce) or by sweeping the relevant assets out of the account. Relayers should be designed with these cases in mind, possibly by requiring a bond to be deposited or by implementing a reputation system. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3076.md b/EIPS/eip-3076.md new file mode 100644 index 00000000000000..24b8245676872d --- /dev/null +++ b/EIPS/eip-3076.md @@ -0,0 +1,261 @@ +--- +eip: 3076 +title: Slashing Protection Interchange Format +description: A JSON interchange format for proof of stake validators to migrate slashing protection data between clients. +author: Michael Sproul (@michaelsproul), Sacha Saint-Leger (@sachayves), Danny Ryan (@djrtwo) +discussions-to: https://ethereum-magicians.org/t/eip-3076-validator-client-interchange-format-slashing-protection/4883 +status: Last Call +last-call-deadline: 2021-11-03 +type: Standards Track +category: Interface +created: 2020-10-27 +--- + +## Abstract + +A standard format for transferring a key's signing history allows validators to easily switch between clients without the risk of signing conflicting messages. While a common keystore format provides part of the solution, it does not contain any information about a key's signing history. For a validator moving their keys from client A to client B, this could lead to scenarios in which client B inadvertently signs a message that conflicts with an earlier message signed with client A. The interchange format described here provides a solution to this problem. + +## Motivation + +The proof of stake (PoS) protocol penalises validators for voting in ways that could result in two different versions of the chain being finalised. These types of penalties are called slashings. + +For a validator following the protocol correctly, there is, in principle, no risk of being slashed. However, changing clients (from client A to client B, say) can result in a slashing risk if client B is unaware of the blocks and attestations that were signed with client A. + +This can occur if client A and client B do not agree on what the present time is. For example, say client A's time is accidentally set to a day in the future (225 epochs), and a validator switches from client A to client B without giving B a record of the blocks and attestations signed with A. The validator in question now runs the risk of attesting to two different blocks in the same epoch (a slashable offence) for the next 225 epochs (since they've already voted on these epochs with client A, and now stand to vote on them again with client B). Such time-skew bugs have been observed in the wild. + +Another situation in which slashing protection is critical is in the case of re-orgs. During a re-org it is possible for a validator to be assigned new attestation duties for an epoch in which it has already signed an attestation. In this case it is essential that the record of the previous attestation is available, even if the validator just moved from one client to another in the space of a single epoch. + +## Specification + +### JSON Schema + +A valid interchange file is one that adheres to the following JSON schema, and is interpreted according to the [Conditions](#conditions). + +```json +{ + "title": "Signing history", + "description": "This schema provides a record of the blocks and attestations signed by a set of validators", + "type": "object", + "properties": { + "metadata": { + "type": "object", + "properties": { + "interchange_format_version": { + "type": "string", + "description": "The version of the interchange format that this document adheres to" + }, + "genesis_validators_root": { + "type": "string", + "description": "Calculated at Genesis time; serves to uniquely identify the chain" + } + }, + "required": [ + "interchange_format_version", + "genesis_validators_root" + ] + }, + "data": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "pubkey": { + "type": "string", + "description": "The BLS public key of the validator (encoded as a 0x-prefixed hex string)" + }, + "signed_blocks": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "slot": { + "type": "string", + "description": "The slot number of the block that was signed" + }, + "signing_root": { + "type": "string", + "description": "The output of compute_signing_root(block, domain)" + } + }, + "required": [ + "slot" + ] + } + ] + }, + "signed_attestations": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "source_epoch": { + "type": "string", + "description": "The attestation.data.source.epoch of the signed attestation" + }, + "target_epoch": { + "type": "string", + "description": "The attestation.data.target.epoch of the signed attestation" + }, + "signing_root": { + "type": "string", + "description": "The output of compute_signing_root(attestation, domain)" + } + }, + "required": [ + "source_epoch", + "target_epoch" + ] + } + ] + } + }, + "required": [ + "pubkey", + "signed_blocks", + "signed_attestations" + ] + } + ] + } + }, + "required": [ + "metadata", + "data" + ] +} +``` + +### Example JSON Instance + +```json +{ + "metadata": { + "interchange_format_version": "5", + "genesis_validators_root": "0x04700007fabc8282644aed6d1c7c9e21d38a03a0c4ba193f3afe428824b3a673" + }, + "data": [ + { + "pubkey": "0xb845089a1457f811bfc000588fbb4e713669be8ce060ea6be3c6ece09afc3794106c91ca73acda5e5457122d58723bed", + "signed_blocks": [ + { + "slot": "81952", + "signing_root": "0x4ff6f743a43f3b4f95350831aeaf0a122a1a392922c45d804280284a69eb850b" + }, + { + "slot": "81951" + } + ], + "signed_attestations": [ + { + "source_epoch": "2290", + "target_epoch": "3007", + "signing_root": "0x587d6a4f59a58fe24f406e0502413e77fe1babddee641fda30034ed37ecc884d" + }, + { + "source_epoch": "2290", + "target_epoch": "3008" + } + ] + } + ] +} +``` + +### Conditions + +After importing an interchange file with data field `data`, a signer must respect the following conditions: + +1. Refuse to sign any block that is slashable with respect to the blocks contained in `data.signed_blocks`. For details of what constitutes a slashable block, see `process_proposer_slashing` (from `consensus-specs`). If the `signing_root` is absent from a block, a signer must assume that any new block with the same `slot` is slashable with respect to the imported block. + +2. Refuse to sign any block with `slot <= min(b.slot for b in data.signed_blocks if b.pubkey == proposer_pubkey)`, except if it is a repeat signing as determined by the `signing_root`. + +3. Refuse to sign any attestation that is slashable with respect to the attestations contained in `data.signed_attestations`. For details of what constitutes a slashable attestation, see `is_slashable_attestation_data`. + +4. Refuse to sign any attestation with source epoch less than the minimum source epoch present in that signer's attestations (as seen in `data.signed_attestations`). In pseudocode: + +```python3 +source.epoch < + min(att.source_epoch + for att in data.signed_attestations + if att.pubkey == attester_pubkey) +``` + +{:start="5"} +5. Refuse to sign any attestation with target epoch less than or equal to the minimum target epoch present in that signer's attestations (as seen in `data.signed_attestations`), except if it is a repeat signing as determined by the `signing_root`. In pseudocode: + +```python3 +target_epoch <= + min(att.target_epoch + for att in data.signed_attestations + if att.pubkey == attester_pubkey) +``` + +### Additional Information + +- The `interchange_format_version` version is set to 5. + +- A signed block or attestation's `signing_root` refers to the message data (hash tree root) that gets signed with a BLS signature. It allows validators to re-sign and re-broadcast blocks or attestations if asked. + +- The `signed_blocks` `signing_root`s are calculated using `compute_signing_root(block, domain)`: where `block` is the block (of type `BeaconBlock` or `BeaconBlockHeader`) that was signed, and `domain` is equal to `compute_domain(DOMAIN_BEACON_PROPOSER, fork, metadata.genesis_validators_root)`. + +- The `signed_attestations` `signing_root`s are calculated using `compute_signing_root(attestation, domain)`: where `attestation` is the attestation (of type `AttestationData`) that was signed, and `domain` is equal to `compute_domain(DOMAIN_BEACON_ATTESTER, fork, metadata.genesis_validators_root)`. + + +## Rationale + +### Supporting Different Strategies + +The interchange format is designed to be flexible enough to support the full variety of slashing protection strategies that clients may implement, which may be categorised into two main types: + +1. **Complete**: a database containing every message signed by each validator. +2. **Minimal**: a database containing only the latest messages signed by each validator. + +The advantage of the minimal strategy is its simplicity and succinctness. Using only the latest messages for each validator, safe slashing protection can be achieved by refusing to sign messages for slots or epochs prior. + +On the other hand, the complete strategy can provide safe slashing protection while also avoiding false positives (meaning that it only prevents a validator from signing if doing so would guarantee a slashing). + +The two strategies are unified in the interchange format through the inclusion of [conditions](#conditions) (2), (4) and (5). This allows the interchange to transfer detailed or succinct information, as desired. + +### Integer Representation + +Most fields in the JSON schema are strings. For fields in which it is possible to encode the value as either a string or an integer, strings were chosen. This choice was made in order to avoid issues with different languages supporting different ranges of integers (specifically JavaScript, where the `number` type is a 64-bit float). If a validator is yet to sign a block or attestation, the relevant list is simply left empty. + +### Versioning + +The `interchange_format_version` is set to 5 because the specification went through several breaking changes during its design, incorporating feedback from implementers. + + +## Backwards Compatibility + +This specification is not backwards-compatible with previous draft versions that used version numbers less than 5. + + +## Security Considerations + +In order to minimise risk and complexity, the format has been designed to map cleanly onto the internal database formats used by implementers. Nevertheless, there are a few pitfalls worth illuminating. + +### Advice for Complete Databases + +For implementers who use a complete record of signed messages to implement their slashing protection database, we make the following recommendations: + +- You MUST ensure that, in addition to importing all of the messages from an interchange, all the [conditions](#conditions) are enforced. In particular, conditions (2), (4) and (5) may not have been enforced by your implementation before adopting the interchange format. Our recommendation is to enforce these rules at all times, to keep the implementation clean and minimise the attack surface. For example: your slashing protection mechanism should not sign a block with a slot number less than, or equal to, the minimum slot number of a previously signed block, _irrespective_ of whether that minimum-slot block was imported from an interchange file, or inserted as part of your database's regular operation. +- If your database records the signing roots of messages in addition to their slot/epochs, you should ensure that imported messages without signing roots are assigned a suitable dummy signing root internally. We suggest using a special "null" value which is distinct from all other signing roots, although a value like `0x0` may be used instead (as it is extremely unlikely to collide with any real signing root). +- Care must be taken to avoid signing messages within a gap in the database (an area of unknown signing activity). This could occur if two interchanges were imported with a large gap between the last entry of the first and the first entry of the second. Signing in this gap is not safe, and would violate conditions (2), (4) and (5). It can be avoided by storing an explicit low watermark in addition to the actual messages of the slashing protection database, or by pruning on import so that the oldest messages from the interchange become the oldest messages in the database. + +### Advice for Minimal Databases + +For implementers who wish to implement their slashing protection database by storing only the latest block and attestation for each validator, we make the following recommendations: + +- During import, make sure you take the _maximum_ slot block and _maximum_ source and target attestations for each validator. Although the [conditions](#conditions) require the minimums to be enforced, taking the maximums from an interchange file and merging them with any existing values in the database is the recommended approach. For example, if the interchange file includes blocks for validator `V` at slots 4, 98 and 243, then the latest signed block for validator `V` should be updated to the one from slot 243. However, if the database has already included a block for this validator at a slot greater than 243, for example, slot 351, then the database's existing value should remain unchanged. + +### General Recommendations + +- To avoid exporting an outdated interchange file -- an action which creates a slashing risk -- your implementation should only allow the slashing protection database to be exported when the validator client or signer is _stopped_ -- in other words, when the client or signer is no longer adding new messages to the database. +- Similarly, your implementation should only allow an interchange file to be imported when the validator client is stopped. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3085.md b/EIPS/eip-3085.md new file mode 100644 index 00000000000000..22a576b13e2035 --- /dev/null +++ b/EIPS/eip-3085.md @@ -0,0 +1,149 @@ +--- +eip: 3085 +title: wallet_addEthereumChain RPC Method +description: Adds an RPC method to add EVM-compatible chains +author: Erik Marks (@rekmarks), Pedro Gomes (@pedrouid), Pandapip1 (@Pandapip1) +discussions-to: https://ethereum-magicians.org/t/eip-3085-wallet-addethereumchain/5469 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-11-01 +requires: 155 +--- + +## Abstract + +This EIP adds a wallet-namespaced RPC method: `wallet_addEtherereumChain`, providing a standard interface for adding chains to Ethereum wallets. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. + +This proposal defines a new RPC method, `wallet_addEthereumChain`. + +### `wallet_addEthereumChain` + +The `wallet_addEthereumChain` method is used to suggest to the wallet that a new chain be added to the wallet's list of chains. It takes a single parameter and returns `null` if the chain was added successfully, or an error if the chain was not added. + +#### `wallet_addEthereumChain` Parameters + +The `wallet_addEthereumChain` method takes a single parameter, an `EthereumChainAddRequest` object, which is defined as follows: + +```typescript +interface AddEthereumChainParameter { + chainId: string; + blockExplorerUrls?: string[]; + chainName?: string; + iconUrls?: string[]; + nativeCurrency?: { + name: string; + symbol: string; + decimals: number; + }; + rpcUrls?: string[]; +} +``` + +Only the `chainId` is required per this specification, but a wallet MAY require any other fields listed, impose additional requirements on them, or ignore them outright. + +If a field does not meet the requirements of this specification and the wallet does not ignore the field, the wallet MUST reject the request. + +The `chainId` is the integer ID of the chain as a hexadecimal string, as per [EIP-155](./eip-155.md). The `blockExplorerUrls`, `iconUrls`, and `rpcUrls` fields are arrays of strings, each of which MUST be a valid URL. The `nativeCurrency` field is an object with `name`, `symbol`, and `decimals` fields, where `decimals` is a non-negative integer, and is to be interpreted like in [EIP-20](./eip-20.md). The `chainName` field is a string that is the human-readable name of the chain. + +The wallet MUST reject the request if the `chainId` is not a valid hexadecimal string, or if the `chainId` is not a valid chain ID. + +The wallet MUST reject the request if the `rpcUrls` field is not provided, or if the `rpcUrls` field is an empty array. The wallet MUST reject the request if the `rpcUrls` contains any strings that are not valid URLs. The wallet must reject the request if the `chainId` does not match the value of the `eth_chainId` method for any of the RPC urls. + +The wallet MUST reject the request if the `nativeCurrency` field is provided, and any of the `name`, `symbol`, or `decimals` fields are missing. The wallet MUST reject the request if the `decimals` field is a negative integer. + +The wallet MUST reject the request if the `blockExplorerUrls` field is provided, and any of the URLs are not valid URLs. + +The wallet MUST reject the request if the `iconUrls` field is provided, and any of the URLs are not valid URLs or do not point to a valid image. + +The wallet MUST reject any URLs that use the `file:` or `http:` schemes. + +#### `wallet_addEthereumChain` Returns + +The method MUST return `null` if the request was successful, and an error otherwise. The wallet MAY reject the request for any reason. + +The chain MUST NOT be assumed to be automatically selected by the wallet, even if the wallet does not reject the request. + +A request to add a chain that was already added SHOULD be successful, unless the user declines the request or the validation fails. + +The wallet MUST NOT allow the same `chainId` to be added multiple times. See [Security Considerations](#security-considerations) for more information. + +## Rationale + +The design of `wallet_addEthereumChain` is deliberately ignorant of what it means to "add" a chain to a wallet. +The meaning of "adding" a chain to a wallet depends on the wallet implementation. + +When calling the method, specifying the `chainId` will always be necessary, since in the universe of Ethereum chains, the [EIP-155](./eip-155.md) chain ID is effectively the chain GUID. +The remaining parameters amount to what, in the estimation of the authors, a wallet will minimally require in order to effectively support a chain and represent it to the user. +The network ID (per the `net_version` RPC method) is omitted since it is effectively superseded by the chain ID. + +For [security reasons](#security-considerations), a wallet should always attempt to validate the chain metadata provided by the requester, and may choose to fetch the metadata elsewhere entirely. +Either way, only the wallet can know which chain metadata it needs from the requester in order to "add" the chain. +Therefore, all parameters except `chainId` are specified as optional, even though a wallet may require them in practice. + +This specification does not mandate that the wallet "switches" its "active" or "currently selected" chain after a successful request, if the wallet has a concept thereof. +Just like the meaning of "adding" a chain, "switching" between chains is a wallet implementation detail, and therefore out of scope. + +## Security Considerations + +`wallet_addEthereumChain` is a powerful method that exposes the end user to serious risks if implemented incorrectly. +Many of these risks can be avoided by validating the request data in the wallet, and clearly disambiguating different chains in the wallet UI. + +### Chain IDs + +Since the chain ID used for transaction signing determines which chain the transaction is valid for, handling the chain ID correctly is of utmost importance. +The wallet should: + +- Ensure that a submitted chain ID is valid. + - It should be a `0x`-prefixed hexadecimal string per [EIP-695](./eip-695.md), and parse to an integer number. +- Prevent the same chain ID from being added multiple times. + - See the next section for how to handle multiple RPC endpoints. +- Only use the submitted chain ID to sign transactions, **never** a chain ID received from an RPC endpoint. + - A malicious or faulty endpoint could return arbitrary chain IDs, and potentially cause the user to sign transactions for unintended chains. +- Verify that the specified chain ID matches the return value of `eth_chainId` from the endpoint, as described above. + +### RPC Endpoints and RPC URLs + +Wallets generally interact with chains via an RPC endpoint, identified by some URL. +Most wallets ship with a set of chains and corresponding trusted RPC endpoints. +The endpoints identified by the `rpcUrls` parameter cannot be assumed to be honest, correct, or even pointing to the same chain. +Moreover, even trusted endpoints can expose users to privacy risks depending on their data collection practices. + +Therefore, the wallet should: + +- Inform users that their on-chain activity and IP address will be exposed to RPC endpoints. +- If an endpoint is unknown to the wallet, inform users that the endpoint may behave in unexpected ways. +- Observe good web security practices when interacting with the endpoint, such as require HTTPS. +- Clearly inform the user which RPC URL is being used to communicate with a chain at any given moment, and inform the user of the risks of using multiple RPC endpoints to interact with the same chain. + +### Validating Chain Data + +A wallet that implements `wallet_addEthereumChain` should expect to encounter requests for chains completely unknown to the wallet maintainers. +That said, community resources exist that can be leveraged to verify requests for many Ethereum chains. +The wallet should maintain a list of known chains, and verify requests to add chains against that list. +Indeed, a wallet may even prefer its own chain metadata over anything submitted with a `wallet_addEthereumChain` request. + +### UX + +Adding a new chain to the wallet can have significant implications for the wallet's functionality and the experience of the user. +A chain should never be added without the explicit consent of the user, and different chains should be clearly differentiated in the wallet UI. +In service of these goals, the wallet should: + +- When receiving a `wallet_addEthereumChain` request, display a confirmation informing the user that a specific requester has requested that the chain be added. +- Ensure that any chain metadata, such as `nativeCurrency` and `blockExplorerUrls`, are validated and used to maximum effect in the UI. +- If any images are provided via `iconUrls`, ensure that the user understands that the icons could misrepresent the actual chain added. +- If the wallet UI has a concept of a "currently selected" or "currently active" chain, ensure that the user understands when a chain added using `wallet_addEthereumChain` becomes selected. + +### Preserving User Privacy + +Although a request to add a chain that was already added should generally be considered a success, treating such requests as _automatic_ successes leaks information to requesters about the chains a user has added to their wallet. +In the interest of preserving user privacy, implementers of `wallet_addEthereumChain` should consider displaying user confirmations even in these cases. +If the user denies the request, the wallet should return the same user rejection error as normal so that requesters cannot learn which chains are supported by the wallet without explicit permission to do so. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3091.md b/EIPS/eip-3091.md new file mode 100644 index 00000000000000..a2174d3c52d2da --- /dev/null +++ b/EIPS/eip-3091.md @@ -0,0 +1,55 @@ +--- +eip: 3091 +title: Block Explorer API Routes +description: API Routes for Blockchain explorers +author: Pedro Gomes (@pedrouid), ligi (@ligi) +discussions-to: https://ethereum-magicians.org/t/eip-3091-block-explorer-api-routes/4907 +status: Stagnant +type: Standards Track +category: Interface +created: 2020-11-02 +--- + +## Abstract + +This proposal brings standardization between block explorers API routes when linking transactions, blocks, accounts and tokens. + +## Motivation + +Currently wallets and dapps link transactions and accounts to block explorer web pages but as chain diversity and layer two solutions grow it becomes harder to maintain a consistent user experience. Adding new chains or layer two solutions becomes harder given these endpoints are inconsistent. Standardizing the API routes to these links improves interoperability between wallets and block explorers. + +## Specification + +Block explorers will route their webpages accordingly for the following data: + +### Blocks + +`/block/` + +### Transactions + +`/tx/` + +### Accounts + +`/address/` + +### Tokens + +`/token/` + +## Rationale + +The particular paths used in this proposal are chosen to be compatible with the majority of existing block explorers. + +## Backwards Compatibility + +Incompatible block explorers can use redirects to their existing API routes in order to conform to this EIP. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3102.md b/EIPS/eip-3102.md new file mode 100644 index 00000000000000..376a91b14f8412 --- /dev/null +++ b/EIPS/eip-3102.md @@ -0,0 +1,182 @@ +--- +eip: 3102 +title: Binary trie structure +author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin) +discussions-to: https://ethresear.ch/t/binary-trie-format/7621 +status: Stagnant +type: Standards Track +category: Core +created: 2020-09-01 +--- + +## Simple Summary + +Change the storage structure from hexary to binary, merge the account and storage tries, and use blake2b. + +## Abstract + +This proposal presents a binary structure and merkelization rule for the account and storage tries, which are merged into a single “state” trie. RLP and most of the MPT’s optimizations are dropped to simplify the design. Keccak256 is replaced with blake2b. + +## Motivation + +The current design of the Merkle Patricia Trie (MPT) uses an hexary trie. Hexary Merkle trees are more shallow than their binary counterparts, which means less hashing. +Over the course of the 5 years of Ethereum’s existence, it has become apparent that disk accesses are a greater bottleneck than hashing. Clients are therefore moving away from a storage model in which all internal nodes are stored, in favor of a flat (key, value) storage model first used by turbo-geth, in which the intermediate nodes are recalculated only when needed. + +There is a push for making Ethereum easier to use in a stateless fashion. Binary tries make for smaller (~4x) proofs than hexary tries, making it the design of choice for a stateless-friendly Ethereum. + +For that same reason, the account and storage tries are merged in order to have a single proof for all changes. + +The MPT design is also rife with uncanny optimizations for size, that have a limited effect - at the cost of prohibitive complexity. For example, nesting for children whose RLP is less than 32 bytes saves an estimated 1MB of disk space. A paltry compared to the 300GB required by a fast sync at the time of this writing. These optimizations are a significant source of errors, and therefore a consensus-breaking risk. +The reliance on RLP has also been criticized for its complexity, while the overhead of a general-purpose encoding scheme isn’t warranted for the rigid structure of a Merkle trie. + +The desire to switch the storage model from an hexary trie to a binary trie provides an opportunity to adopt a simpler trie architecture that pushes optimizations from the protocol level down to that of the client implementors. + +## Specification + +### Conventions + +| Code | Description | +| :-: | - | +| `u256(x)` | Big endian, 32-byte representation of number _x_ | +|`||` | Byte-wise concatenation operator| +| `++` | Bit-wise concatenation operator | +| `0b0101` | The binary string `0101` | +| `hash()` | The usual hashing function | +| `empty_hash` | The empty hash: `hash("")` | +| `length(x)` | The byte length of object `x` | +| `d[a..b]` | The big-endian bit sequence taken from byte sequence `d`, starting at bit index `a`, up to and including the bit at index `b`. | + +### Notable changes from the hexary structure + + * Account and storage tries are merged, with key length between 32 and 64 bytes; + * RLP is no longer used; + * The "leaf marker" bit used in the hex prefix is also dropped. Leaves are identified as nodes with no children; + * Serialized nodes are hashed, no matter how small the byte length of the serialized nodes. + +### The trie + +#### Structure + +The trie structure is made up of _nodes_. A node `N ≡ (N_l,N_r,N_p,N_v)` has the following 4 components: + + * `N_l` is the hash to the node's _left child_. If the node does not have a left child, then `N_l` is the empty hash `empty_hash`; + * `N_r` is the hash to the node's _right child_. If the node does not have a right child, then `N_r` is the empty hash `empty_hash`; + * the optional `N_p` is the node's _prefix_ : every key into the subtrie rooted at `N` is prefixed by this bit string; + * `N_v` is the _value_ stored at this node. The value is **only present in leaf nodes**. + +Nodes with `empty_hash` as both children are called _leaf nodes_, and the remaining nodes are known as _internal nodes_. + +#### Accessing account's balance, nonce, code, storage root and storage slots + +Assuming an account `A ≡ (A_b, A_n, A_c, A_s)` at address `A_a`, the following elements can be found at the following addresses: + + * The account balance `A_b` can be found at key `hash(A_a)[0..253] ++ 0b00` and is of type `uint256`; + * The account nonce `A_n` can be found at key `hash(A_a)[0..253] ++ 0b01` and is of type `uint64`; + * The code `A_c` is an arbitrary-length byte sequence that can be found at key `hash(A_a)[0..253] ++ 0b10`; + * The root of the storage trie `A_s` can be found at key `hash(A_a)[0..253] ++ 0b11` + * The storage slot number `k` can be found at key `hash(A_a)[0..253] ++ 0b11 ++ hash(k)`. + +After [EIP-2926](./eip-2926.md) has been rolled out, `A_c` will represent the root of the code merkelization tree. The key accessing code chunk number `c` is `hash(A_a)[0..253] ++ 0b10 ++ u256(c)`. + +In the unlikely future case that extra items are to be added to the trie at account level, a third bit can be reserved for future use. + +### Node merkelization rule + +Leaves and nodes that have no prefix are hashed according to the rule below: + +``` +internal_hash = hash(left_child_hash || right_child_hash) +leaf_hash = hash(hash(key) || hash(leaf_value)) +``` + +If a prefix is present, the length of the path from the root to the prefixed node is further concatenated with the output of the prefix-less rule, and hashed again: + +``` +internal_hash_with_prefix = hash(u256(path_length_u256 - 1) || internal_hash) +leaf_hash_with_prefix = hash(u256(path_length_u256 - 1) || leaf_hash) +``` + +## Rationale + +### blake2b + +BLAKE2 offers better performance, which is key to compensate for the loss of performance associated to a ~4x increase in the number of nodes. + +BLAKE3 offers even better performance. No official golang release exists at the time of the writing of this document. This presents a security risk, and therefore BLAKE2 is considered instead. + +### Merging of the account and storage tries + +The trend in clients is to store the keys and values in a "flat" database. Having the key of any storage slot prefixed with the address key of the account it belongs to helps grouping all of an account's data on disk, as well as simplifying the witness structure. + +### Prefixes and extension nodes + +An alternative proposal has been made, which provides optimal witnesses. The trade-off is that extension nodes must be removed. + +``` +node_hash = hash(left_child_hash || right_child_hash) +leaf_hash = hash(0 || leaf_value) +``` + +The removal of extension nodes induces 40x higher hashing costs (on the order of 25ms for a trie with only 1k leaves) and as a result they have been kept. + +An attempt to keep extension nodes for witness and not the merkelization rule can be found [here](https://notes.ethereum.org/m5VMkX8FRvi0Q_OOR7TF4A). + +Getting rid of complex methods like RLP, the hex prefix and children nesting is already offering great simplification. + +### 2x32-byte inputs + +It has been requested to keep each node hash calculation as a function that takes two 256-bit integer as an input and outputs one 256-bit integer. This property is expected to play nice with circuit constructions and is therefore expected to greatly help with future zero-knowledge applications. + +### Binary tries + +Binary tries have been chosen primarily because they reduce the witness size. In general, in an `N`-element tree with each element having `k` children, the average length of a branch is roughly `32 * (k-1) * log(N) / log(k)` plus a few percent for overhead. 32 is the length of a hash; the `k-1` refers to the fact that a Merkle proof needs to provide all `k-1` sister nodes at each level, and `log(N) / log(k)` is an approximation of the number of levels in the tree (eg. a tree where each node has 5 children, with 625 nodes total, would have depth 4, as `625 = 5**4` and so `log(625) / log(5) = 4`). + +For any `N`, the expression is minimized at `k = 2`. Here's a table of branch lengths for different `k` values assuming `N = 2**24`: + +| `k` (children per node) | Branch length (chunks) | Branch length (bytes) | +| - | - | - | +| 2 | 1 * 24 = 24 | 768 | +| 4 | 3 * 12 = 36 | 1152 | +| 8 | 7 * 8 = 56 | 1792 | +| 16 | 15 * 6 = 90 | 2880 | + +Actual branch lengths will be slightly larger than this due to uneven distribution and overhead, but the pattern of `k=2` being by far the best remains. + +The ethereum tree was originally hexary because this would reduce the number of database reads (eg. 6 instead of 24 in the above example). It is now understood that this reasoning was flawed, because nodes can still "pretend" that a binary tree is a hexary (or even 256-ary) tree at the database layer (eg. see https://ethresear.ch/t/optimizing-sparse-merkle-trees/3751), and thereby get the best-of-both-worlds of having the low proof sizes of the tree being binary from a hash-structure perspective and at the same time a much more efficient representation in the database. + +Additionally, binary trees are expected to be widely used in Eth2, so this path improves forward-compatibility and reduces long-run total complexity for the protocol. + +### Path length instead of bit prefix + +In order to remove the complexity associated with byte manipulation, only the bit-length of the extension is used to merkelize a node with a prefix. + +Storing the length of the path from the root node instead of that from the parent node has the nice property that siblings need not be hashed when deleting a leaf. + +![Sibling deletion diagram](../assets/eip-3102/sibling.svg) + +_On the left, a trie with the prefix length, and on the right, a trie with the full path length. Each both have values `10000100` and `10000000`. After deleting `10000100`,the sibling node has to be updated in the left tree, while it need not be in the case on the right._ + +### Value hashing + +Except for the code, all values in the trie are less than 32 bytes. EIP-2926 introduces code chunks, with `CHUNK_SIZE = 32 bytes`. The hashing of the leaf's value could therefore be saved. The authors of the EIP are however considering a future increase of `CHUNK_SIZE`, making `hash(value)` the future-proof choice. + +## Backwards Compatibility + +A hard fork is required in order for blocks to have a trie root using a different structure. + +## Test Cases + +TBD + +## Implementation + + * As of [commit 0db87e187dc0bfb96046a47e3d6768c93a2e3331](https://github.com/gballet/multiproof-rs/commit/6d22b1aef9548581826b3c04b3e00d6cc709388c), [multiproof-rs](https://github.com/gballet/multiproof-rs) implements this merkelization rule in the `hash_m5()` function, found in file `src/binary_tree.rs`. + * An implementation of this structure for go-ethereum is available [in this branch](https://github.com/gballet/go-ethereum/tree/rebased-binary-trie-m5-full-path). + +## Security Considerations + +Issues could arise when performing the transition. In particular, a heavy conversion process could incentivize clients to wait the transition out. This could lead to a lowered network security at the time of the transition. A transition process has been proposed with [EIP-2584](./eip-2584.md). + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3135.md b/EIPS/eip-3135.md new file mode 100644 index 00000000000000..357486d011dcbc --- /dev/null +++ b/EIPS/eip-3135.md @@ -0,0 +1,7 @@ +--- +eip: 3135 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3135.md diff --git a/EIPS/eip-3143.md b/EIPS/eip-3143.md new file mode 100644 index 00000000000000..1b48eac57f9836 --- /dev/null +++ b/EIPS/eip-3143.md @@ -0,0 +1,53 @@ +--- +eip: 3143 +title: Increase block rewards to 5 ETH +author: Ben Tinner (@Terra854) +discussions-to: https://ethereum-magicians.org/t/eip-3143-increase-block-rewards-to-5-eth/5061 +status: Stagnant +type: Standards Track +category: Core +created: 2020-12-01 +--- + +## Simple Summary +Changes the block reward paid to proof-of-work (POW) miners to 5 ETH. + +## Abstract +Starting with `FORK_BLKNUM` block rewards will be increased to a base of 5 ETH, uncle and nephew rewards will be adjusted accordingly. + +## Motivation +Currently, the transaction fees (tx fees) portion of the mining rewards makes up a significant portion of the total rewards per block, at times almost exceeded the block reward of 2 ETH. This have resulted in situations where at times of low tx fees, POW miners decide to point their rigs away from ETH as they will always prefer to mine coins that are the most profitable at any point in time, reducing the security of the ETH network till transaction activity picks up again. By increasing the block rewards back to the original 5 ETH when the network first started, the voliatility will be reduced in terms of the percentage of tx fees that make up the mining rewards per block while increasing the total rewards per block, making it more financially attractive to POW miners to mine ETH barring any gigantic ETH price drops. The increase in block rewards will also allow smaller POW miners ample opporturnity to build up their stores of ETH so that when the time comes to fully transition to ETH 2.0, they may be more willing to become validators as they already have earned the requite amount of ETH needed to do so as opposed to having to spend tens of thousands of dollars to purchase the required ETH directly, increasing the number of validators in the network and therefore strengthening network security. + +Therefore, the ultimate end goal for this EIP is to give POW miners more incentive to switch to POS once ETH 2.0 is fully implemented since the transition will take a few years to complete and during that time, they will be incentivised to hold on to the tokens instead of selling it straight away in order to prepare to be a validator for ETH 2.0, reducing the selling pressure on ETH and increasing it's value in the long run. A side effect of miners staying on Ethereum is that network security will be assured during the transition period. + +## Specification +#### Adjust Block, Uncle, and Nephew rewards +Adjust the block reward to `new_block_reward`, where + + new_block_reward = 5_000_000_000_000_000_000 if block.number >= FORK_BLKNUM else block.reward + +(5E18 wei, or 5,000,000,000,000,000,000 wei, or 5 ETH). + +Analogue, if an uncle is included in a block for `block.number >= FORK_BLKNUM` such that `block.number - uncle.number = k`, the uncle reward is + + new_uncle_reward = (8 - k) * new_block_reward / 8 + +This is the existing formula for uncle rewards, simply adjusted with `new_block_reward`. + +The nephew reward for `block.number >= FORK_BLKNUM` is + + new_nephew_reward = new_block_reward / 32 + +This is the existing formula for nephew rewards, simply adjusted with `new_block_reward`. + +## Rationale +A 5 ETH base reward was chosen as a middle ground between wanting to prevent too high of an inflation rate (10.4% per annum for the first year at 5 ETH per block) and converting as many POW miners as possible into POS validators by making it easier to amass the required ETH needed through POW mining. + +## Backwards Compatibility +There are no known backward compatibility issues with the introduction of this EIP. + +## Security Considerations +There are no known security issues presented by this change. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3155.md b/EIPS/eip-3155.md new file mode 100644 index 00000000000000..a3620384b20979 --- /dev/null +++ b/EIPS/eip-3155.md @@ -0,0 +1,178 @@ +--- +eip: 3155 +title: EVM trace specification +description: A JSON format for EVM traces +author: Martin Holst Swende (@holiman), Marius van der Wijden (@MariusVanDerWijden) +discussions-to: https://ethereum-magicians.org/t/eip-3155-create-evm-trace-specification/5007 +status: Last Call +last-call-deadline: 2025-03-01 +type: Standards Track +category: Interface +created: 2020-12-07 +--- + +## Abstract + +Introduce a new JSON standard for EVM traces during execution of state tests. + +## Motivation + +The Ethereum Virtual Machine executes all smart contract code on ethereum. +In order to debug smart contracts and state tests better, a common format was introduced to log every execution step of the EVM. +This format was implemented by Go-Ethereum, Parity-Ethereum, Nethermind and Besu. +Since the common format was not well-defined, the implementations differed slightly, making it hard to develop adequate tooling which reduces the usefulness of tracing significantly. + +This EIP has multiple goals: + +- Move the specification to a more visible place to encourage new clients to implement it +- Strictly define corner cases that were not addressed in the previous version +- Allow for updates to the specification in case new fields are introduced during execution +- Provide sample output + +Implementing this EIP in all major clients allows us to create meaningful differential fuzzers that fuzz EVM implementations for the mainnet and all upcoming hardforks. +It also helps to find differences in execution quickly in the case of a chain split. + +This EIP will enable users to create better differential fuzzing infrastructure to compare the EVM implementations of all major Ethereum clients against each other. +This could help to find bugs that are currently present in the client implementations. + +## Specification + +Clients should be able to execute simple transactions as well as code and return traces. In the following, we will call this client CUT (client under test) and use go-ethereum's +`evm` binary for code examples. + +### Datatypes + +| Type | Explanation | Example | +|------------|----------------------------------------------------------------|---------------------| +| Number | Plain json number | "pc":0 | +| Hex-Number | Hex-encoded number | "gas":"0x2540be400" | +| String | Plain string | "opName":"PUSH1" | +| Hex-String | Hex-encoded string | | +| Array of x | Array of x encoded values | | +| Key-Value | Key-Value structure with key and values encoded as hex strings | | +| Boolean | Json bool can either be true or false | "pass": true | + +### Output + +The CUT MUST output a `json` object for EACH operation. + +#### Required Fields + +| Name | Type | Explanation | +|--------------|----------------------|------------------------------------------| +| `pc` | Number | Program Counter | +| `op` | Number | OpCode | +| `gas` | Hex-Number | Gas left before executing this operation | +| `gasCost` | Hex-Number | Gas cost of this operation | +| `memSize` | Number | Size of memory array | +| `stack` | Array of Hex-Numbers | Array of all values on the stack | +| `depth` | Number | Depth of the call stack | +| `returnData` | Hex-String | Data returned by function call | +| `refund` | Hex-Number | Amount of **global** gas refunded | + +#### Optional Fields + +| Name | Type | Explanation | +|---------------|----------------------|---------------------------------------------------------------------| +| `opName` | String | Name of the operation | +| `error` | Hex-String | Description of an error (should contain revert reason if supported) | +| `memory` | Array of Hex-Strings | Array of all allocated values | +| `storage` | Key-Value | Array of all stored values | + +*Example:* + +``` +{"pc":0,"op":96,"gas":"0x2540be400","gasCost":"0x3","memory":"0x","memSize":0,"stack":[],"depth":1,"error":null,"opName":"PUSH1"} +``` + +- The `stack`, `memory` and `memSize` are the values *before* execution of the op. +- All array attributes (`stack`, `memory`) MUST be initialized to empty arrays (`"stack":[]`) NOT to null. +- If the CUT will not be outputting values for `memory` or `storage` then the `memory` and `storage` fields are omitted. + This can happen either because the CUT does not support tracing these fields or it has been configured not to trace it. +- The `memSize` field MUST be present regardless of `memory` support. +- Clients SHOULD implement a way to disable recording the storage as the stateroot includes all storage updates. +- Clients SHOULD output the fields in the same order as listed in this EIP. + +The CUT MUST NOT output a line for the `STOP` operation if an error occurred: + +*Example:* + +``` +{"pc":2,"op":0,"gas":"0x2540be3fd","gasCost":"0x0","memory":"0x","memSize":0,"stack":["0x40"],"depth":1,"error":null,"opName":"STOP"} +``` + +### Summary and Error Handling + +At the end of execution, the CUT MUST print summary info; this info SHOULD have the following fields. +The summary should be a single `jsonl` object. + +#### Required Fields + +| Name | Type | Explanation | +|-------------|------------|--------------------------------------------------------| +| `stateRoot` | Hex-String | Root of the state trie after executing the transaction | +| `output` | | Return values of the function | +| `gasUsed` | Hex-Number | All gas used by the transaction | +| `pass` | Boolean | Bool whether transaction was executed successfully | + +#### Optional Fields + +| Name | Type | Explanation | +|--------|--------|-------------------------------------------------------| +| `time` | Number | Time in nanoseconds needed to execute the transaction | +| `fork` | String | Name of the fork rules used for execution | + +*Example*: + +``` +{"stateRoot":"0xd4c577737f5d20207d338c360c42d3af78de54812720e3339f7b27293ef195b7","output":"","gasUsed":"0x3","pass":"true","time":141485} +``` + +## Rationale + +This EIP is largely based on the previous non-official documentation for EVM tracing. +It tries to cover as many corner cases as possible to enable true client compatibility. +The datatypes and if a field is optional is chosen to be as compatible with current implementations as possible. + +## Backwards Compatibility + +This EIP is fully backward compatible with ethereum as it only introduces a better tracing infrastructure that is optional for clients to implement. + +### Clients + +This EIP is fully backward compatible with go-ethereum. OpenEthereum, Besu and Nethermind clients would have to change their JSON output of +`openethereum-evm` `evmtool` and +`nethtest` slightly do adhere to the new and stricter specs. New clients would need to implement this change if they want to be part of the differential fuzzing group. + +## Test Cases + +```bash +${BESU_HOME}/bin/evmtool --code 0x604080536040604055604060006040600060025afa6040f3 {"pc":0,"op":96,"gas":"0x2540be400","gasCost":"0x3","memSize":0,"stack":[],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":2,"op":128,"gas":"0x2540be3fd","gasCost":"0x3","memSize":0,"stack":["0x40"],"depth":1,"refund":0,"opName":"DUP1"} +{"pc":3,"op":83,"gas":"0x2540be3fa","gasCost":"0xc","memSize":0,"stack":["0x40","0x40"],"depth":1,"refund":0,"opName":"MSTORE8"} +{"pc":4,"op":96,"gas":"0x2540be3ee","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":[],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":6,"op":96,"gas":"0x2540be3eb","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40"],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":8,"op":85,"gas":"0x2540be3e8","gasCost":"0x4e20","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x40"],"depth":1,"refund":0,"opName":"SSTORE"} +{"pc":9,"op":96,"gas":"0x2540b95c8","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":[],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":11,"op":96,"gas":"0x2540b95c5","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40"],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":13,"op":96,"gas":"0x2540b95c2","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0"],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":15,"op":96,"gas":"0x2540b95bf","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40"],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":17,"op":96,"gas":"0x2540b95bc","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40","0x0"],"depth":1,"refund":0,"opName":"PUSH1"} +{"pc":19,"op":90,"gas":"0x2540b95b9","gasCost":"0x2","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40","0x0","0x2"],"depth":1,"refund":0,"opName":"GAS"} +{"pc":20,"op":250,"gas":"0x2540b95b7","gasCost":"0x24abb676c","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40","0x0","0x2","0x2540b95b7"],"depth":1,"refund":0,"opName":"STATICCALL"} +{"pc":21,"op":96,"gas":"0x2540b92a7","gasCost":"0x3","memory":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b00000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x1"],"returnData":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b","depth":1,"refund":0,"opName":"PUSH1"} +{"pc":23,"op":243,"gas":"0x2540b92a4","gasCost":"0x0","memory":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b00000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x1","0x40"],"returnData":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b","depth":1,"refund":0,"opName":"RETURN"} +{"stateRoot":"0x8fa0dcc7f1d2383c89e5737c2843632db881c0946e80b71fe7175365e6538797","output":"0x40","gasUsed":"0x515c","pass":true,"fork":"Istanbul"} +``` + +## Security Considerations + +Tracing is expensive. + +Exposing an endpoint for creating traces publicly could open up a denial of service vector. + +Clients should consider putting trace endpoints behind a separate flag from other endpoints. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3156.md b/EIPS/eip-3156.md new file mode 100644 index 00000000000000..b3f20e5d49f318 --- /dev/null +++ b/EIPS/eip-3156.md @@ -0,0 +1,7 @@ +--- +eip: 3156 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3156.md diff --git a/EIPS/eip-3198.md b/EIPS/eip-3198.md new file mode 100644 index 00000000000000..fdad71935dfae2 --- /dev/null +++ b/EIPS/eip-3198.md @@ -0,0 +1,62 @@ +--- +eip: 3198 +title: BASEFEE opcode +author: Abdelhamid Bakhta (@abdelhamidbakhta), Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-3198-basefeeopcode/5162 +status: Final +type: Standards Track +category: Core +created: 2021-01-13 +requires: 1559 +--- + +## Simple Summary +Adds an opcode that gives the EVM access to the block's base fee. + +## Abstract + +Add a `BASEFEE (0x48)` that returns the value of the base fee of the current block it is executing in. + +## Motivation +The intended use case would be for contracts to get the value of the base fee. This feature would enable or improve existing use cases, such as: +- Contracts that need to set bounties for anyone to "poke" them with a transaction could set the bounty to be `BASEFEE + x`, or `BASEFEE * (1 + x)`. This makes the mechanism more reliable, because they will always pay "enough" regardless of market conditions. +- Gas futures can be implemented based on it. This would be more precise than gastokens. +- Improve the security for state channels, plasma, optirolls and other fraud proof driven solutions. Having the `BASEFEE` as an input allows you to lengthen the challenge period automatically if you see that the `BASEFEE` is high. + +## Specification +Add a `BASEFEE` opcode at `(0x48)`, with gas cost `G_base`. + +| Op | Input | Output | Cost | +|:----: |:-----: |:------: |:----: | +| 0x48 | 0 | 1 | 2 | + +## Rationale + +### Gas cost +The value of the base fee is needed to process transactions. That means it's value is already available before running the EVM code. +The opcode does not add extra complexity and additional read/write operations, hence the choice of `G_base` gas cost. + +## Backwards Compatibility +There are no known backward compatibility issues with this opcode. + +## Test Cases + +### Nominal case +Assuming current block base fee is `7 wei`. +This should push the value `7` (left padded byte32) to the stack. + +Bytecode: `0x4800` (`BASEFEE, STOP`) + +| Pc | Op | Cost | Stack | RStack | +|-------|-------------|------|-----------|-----------| +| 0 | BASEFEE | 2 | [] | [] | +| 1 | STOP | 0 | [7] | [] | + +Output: 0x +Consumed gas: `2` + +## Security Considerations +The value of the base fee is not sensitive and is publicly accessible in the block header. There are no known security implications with this opcode. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3220.md b/EIPS/eip-3220.md new file mode 100644 index 00000000000000..87add1747e91f1 --- /dev/null +++ b/EIPS/eip-3220.md @@ -0,0 +1,76 @@ +--- +eip: 3220 +title: Crosschain Identifier Specification +author: Weijia Zhang (@weijia31415), Peter Robinson (@drinkcoffee) +discussions-to: https://ethereum-magicians.org/t/eip-3220-crosschain-id-specification/5446 +status: Stagnant +type: Standards Track +category: Core +created: 2020-10-21 +--- + +## Simple Summary + +A self-verifying unique blockchain identifier that deals with forks. + +## Abstract + +The crosschain-id is a 32 byte hex string and with some bytes extracted from blockchain hash and some manually defined to characterize a blockchain. +We also propose a registration and lookup service to retrieve blockchain metadata from the crosschain-id. + +## Motivation + +With the success of Bitcoin and Ethereum, various blockchains such as EOS, Ripple, Litecoin, Besu, Wanchain and the like have been developed and are growing at a fast pace. There are also other private and consortium blockchains such as Hyperledger Fabric, Hyperledger Besu, Stellar, Corda, Quorum that only allow nodes with permitted identities to join the blockchain network. The growth of public and private blockchains imposes challenges for inter-chain interoperability, particularly when these chains are heterogeneous and incompatible. Enterprise Ethereum Alliance formed Crosschain Interoperability Task Force (CITF) to look into common crosschain problems and solutions. CITF team noticed that there is a lack of unique identifier to charaterise and describe a blockchain. Several proprosals were discussed in EEA Crosschain Interoperability Task Force meetings and discussions. + +[EIP-155](./eip-155.md) provides a unique identifier to a blockchain to provide simple relay attack protection. This specification defines an integer for Chainid for a blockchain and sign the chainid into a transaction data and hence present attackers to send same transaction to different blockchains. This specification will require blockchains to define a chainid and register the chainid in a public repository. + +The challenge of using an integer for chainid is that it is not broad enough to cover all blockchains and it does not prevent different blockchains using the same chainid. Also, it does not address the issue for two forked blockchains having the same chainid. + +Hence there is need for a more robust blockchain identifier that will overcome these drawbacks, especially for crosschain operations where multiple chains are involved. A blockchain identifier (crosschain id) should be unique and satisfy the following requirements: + +* should provide identification, description, and discovery of blockchains. +* should provide unique identification of each blockchain in the crosschain service ecosystem. +* should provide descriptions for a blockchain identities such as chainId, name, type, consensus scheme etc. +* should provide discovery mechanism for supported blockchains and also for new blockchains in the ecosystem. +* should provide a mechanism for a joining blockchain to register to the ecosystem. +* should provide a mechanism for a blockchain to edit properties or unregister from the crosschain ecosystem. +* should provide a mechanism to get some critical information of the blockchain +* should provide a mechanism to differentiate an original blockchain and a forked blockchain +* should provide a mechanism to verify a chainid without external registration service + +## Specification + +### Definition of a 32 byte crosschain id + +| Name | Size(bytes) | Description | +|---------------|-------------|-------------| +| Truncated Block Hash | 16 | This is the block hash of the genesis block or the block hash of the block immediate prior to the fork for a fork of a blockchain. The 16 bytes is the 16 least significant bytes, assuming network byte order.| +|Native Chain ID| 8 | This is the **Chain Id** value that should be used with the blockchain when signing transactions. For blockchains that do not have a concept of **Chain Id**, this value is zero.| +|Chain Type| 2 | Reserve 0x00 as undefined chaintype. 0x01 as mainnet type. 0x1[0-A]: testnet, 0x2[0-A]: private development network| +| Governance Identifier | 2 | For new blockchains, a governance_identifier can be specified to identify an original **owner** of a blockchain, to help settle forked / main chain disputes. For all existing blockchains and for blockchains that do not have the concept of an **owner**, this field is zero. | +| Reserved | 3 | Reserved for future use. Use 000000 for now. | +| Checksum | 1 | Used to verify the integrity of the identifier. This integrity check is targeted at detecting Crosschain Identifiers mis-typed by human users. The value is calculated as the truncated SHA256 message digest of the rest of the identifier, using the least significant byte, assuming network byte order. Note that this checksum byte only detects integrity with a probability of one in 256. This probability is adequate for the intended usage of detecting typographical errors by people manually entering the Crosschain Identifier. | + + +## Rationale + +We have considered various alternative specifications such as using a random unique hex string to represent a blockchain. The drawback of this method is that the random id can not be used to verify a blockchain's intrinsic identity such as the blockhash of the genesis block. A second alternative is simply using a genesis blockhash to represent a blockchain id for crosschain operations. The drawback of this is that this id does not have information about the property of the blockchain and it has problem when a blockchain is forked into two blockchain. + +## Backwards Compatibility + +Crosschainid can be backward compatible with EIP-155. The crosschain id contains an 8 byte segment to record the `Native Chain ID`. +For Ethereum chains, that can be used for a value intended to be used with EIP-155. + +## Security Considerations + +Collision of crosschain id: Two blockchains can contain the same crosschain id and hence making the mistakenly transfer assets to a wrong blockchain. +This security concern is addressed by comparing the hash of the crosschain id with the hash of the genesis block. If it matches, then the crosschain id is verified. If not, the crosschain id can be compared with the forked blockhash. If none of the blockhash match the crosschain id hash, then the crosschain id cannot be verified. + +Preventing relay attack: Although crosschain id by itself is different from chainid and it is not signed into blockchain transaction, the crosschain id can still be used for presenting relay attack. An application that handles crosschain transaction can verified the crosschain id with its blockhash and decide whether the transaction is valid or not. Any transaction with a non-verifiable crosschain id should be rejected. + +The crosschain-id are not required to be signed into blockchaid tx. +For blockchains that do not cryptographically sign crosschain id into the blocks, the crosschain id cannot be verified with the blocks itself and have to be verified with external smart contract address and offchain utilities implemented based on the crosschain id specification. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3224.md b/EIPS/eip-3224.md new file mode 100644 index 00000000000000..7d22ce6165ce0a --- /dev/null +++ b/EIPS/eip-3224.md @@ -0,0 +1,7 @@ +--- +eip: 3224 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3224.md diff --git a/EIPS/eip-3234.md b/EIPS/eip-3234.md new file mode 100644 index 00000000000000..72fccc38651821 --- /dev/null +++ b/EIPS/eip-3234.md @@ -0,0 +1,7 @@ +--- +eip: 3234 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3234.md diff --git a/EIPS/eip-3238.md b/EIPS/eip-3238.md new file mode 100644 index 00000000000000..3fa3a6c9bed155 --- /dev/null +++ b/EIPS/eip-3238.md @@ -0,0 +1,39 @@ +--- +eip: 3238 +title: Difficulty Bomb Delay to Q2/2022 +author: Afri Schoedon (@q9f) +discussions-to: https://github.com/ethereum/EIPs/issues/3239 +type: Standards Track +category: Core +status: Stagnant +created: 2021-01-25 +--- + +## Simple Summary +Delays the difficulty bomb so 30 second blocks won't happen until around Q2/2022. + +## Abstract +Starting with `FORK_BLOCK_NUMBER` the client will calculate the difficulty based on a fake block number suggesting to the client that the difficulty bomb is adjusting eleven million blocks later than the actual block number. + +## Motivation +Even after the Ethereum 2.0 mainnet launch, Ethash proof-of-work mining on the legacy chain should be feasible. It should allow miners sealing new blocks every 13~15 seconds on average for another ten months and allow both Ethereum 1.x and Ethereum 2.0 developers to conclude the merge. + +## Specification +#### Relax Difficulty with Fake Block Number +For the purposes of `calc_difficulty`, simply replace the use of `block.number`, as used in the exponential ice age component, with the formula: + + fake_block_number = max(0, block.number - 11_000_000) if block.number >= FORK_BLOCK_NUMBER else block.number + +## Rationale +This will delay the ice age by another ~26 million seconds (approximately ~9.89 months), so the chain would be back at ~30 second block times in Q2/2022. Hopefully, by then the Eth1-to-Eth2 merge will be concluded and the ice age fulfilled its task. + +## Backwards Compatibility +This EIP is not forward compatible and introduces backwards incompatibilities in the difficulty calculation. Therefore, it should be included in a scheduled hardfork at a certain block number. It's suggested to consider this EIP either with or shortly after the Berlin hard-fork but not later than July 2021. + +Alternatively, in order to maintain stability of the system, a it can be considered to activate this EIP along with EIP-1559 fee market changes in a bundle. With the delay of the ice age, there is a desire to no further increase inflation and rather incentivize users to participate in proof-of-stake consensus instead. + +## Security Considerations +There are no known security issues with this proposal. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3267.md b/EIPS/eip-3267.md new file mode 100644 index 00000000000000..c44fe3e481a54a --- /dev/null +++ b/EIPS/eip-3267.md @@ -0,0 +1,69 @@ +--- +eip: 3267 +title: Giving Ethereum fees to Future Salaries +author: Victor Porton (@vporton), Victor Porton +discussions-to: https://ethereum-magicians.org/t/discussion-of-eip-3267/5343 +status: Stagnant +type: Standards Track +category: Core +created: 2021-02-13 +--- + +## Simple Summary +Transfer a part of Ethereum transfer/mining fees to Future Salaries contract + +## Abstract +Transfer a part (exact fractions - TBD) of mining/transfer fees + (probably: TBD) some minted ETH to the `DonateETH` contract configured to transfer to `SalaryWithDAO` contract. + +## Motivation +This proposal solves two problems at once: + +1. It provides a big amount of "money" to common good producers. That obviously personally benefits common good producers, allowing them to live better human lives, it increases peoples' and organizations' both abilities and incentives to produce common goods. That benefits the humanity as a whole and the Ethereum ecosystem in particular. See more in the discussion why it's crucial. + +2. This would effectively decrease circulating ETH supply. The necessity to decrease the (circulating) ETH supply (by locking ETH in Future Salaries system for a long time) is a well-known important thing to be done. + +Paradoxically, it will directly benefit miners/validators, see the discussion. + +## Specification +(TBD) + +`SalaryWithDAO` = `TBD` (`address`) + +`DefaultDAOInterface` = `TBD` (`address`) + +`MintPerPeriod` = `TBD` (`uint256`) + +`TransferFraction` = `TBD` (0..1) + +`MineFraction` = `TBD` (0..1) + +[The contract's source](../assets/eip-3267/contracts/README.md) + +Prior to `FORK_BLOCK_NUMBER`, `SalaryWithDAO` and `DefaultDAOInterface` contracts will be deployed to the network and exist at the above specified addresses. + +Change the Ethereum clients to transfer at every ETH transfer and every ETH mine a fixed fraction `TransferFraction` of the transferred ETH and `MineFraction` of the mined ETH to a fixed account (decide the account number, it can be for example `0x00000000000000000000000000000000000000001` or even `0x00000000000000000000000000000000000000000` or a random account). + +Change the Ethereum clients to mint `MintPerPeriod` ETH to the contract `DonateETH` every some time (e.g. the first transaction of the first block every UTC day - TBD how often). + +Change the Ethereum clients to every some time (e.g. the second transaction of the first block every UTC day - TBD how often) transfer the entire ETH from this account to the contract `DonateETH`. + +Because this EIP solves a similar problem, cancel any other EIPs that burn ETH (except gas fees) during transfers or mining. (TBD: We should transfer more ETH in this EIP than we burned accordingly older accepted EIPs, because this EIP has the additional advantages of: 1. funding common goods; 2. better aligning values of ETH and values of tokens). + +## Rationale +The Future Salaries is the _only_ known system of distributing significant funds to common good producers. (Quadratic funding aimed to do a similar thing, but in practice as we see on GitCoin it favors a few developers, ignores project of highly advanced scientific research that is hard to explain to an average developer, and encourages colluding, and it just highly random due to small number of donors. Also quadratic funding simply does not gather enough funds to cover common good needs). So this EIP is the only known way to recover the economy. + +The economical model of Future Salaries is described in [this research article preprint](../assets/eip-3267/science-salaries.pdf). + +Funding multiple oracles with different finish time would alleviate the future trouble that the circulating ETH (or other tokens) supply would suddenly increase when the oracle finishes. It would effectively exclude some ETH from the circulation forever. + +## Backwards Compatibility +Because transferring to the aforementioned account is neither mining nor a transaction, we get a new kinds of ETH transfers, so there may be some (expected moderate impact) troubles with applications that have made assumptions about ETH transfers all occurring either as miner payments or transactions. + +## Security Considerations +The security considerations are: +- The DAO that controls account restoration may switch to a non-effective or biased way of voting (for example to being controlled by one human) thus distributing funds unfairly. This problem could be solved by a future fork of Ethereum that would "confiscate" control from the DAO. + +See more in the discussion. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3298.md b/EIPS/eip-3298.md new file mode 100644 index 00000000000000..daa52e7df42625 --- /dev/null +++ b/EIPS/eip-3298.md @@ -0,0 +1,95 @@ +--- +eip: 3298 +title: Removal of refunds +author: Vitalik Buterin (@vbuterin), Martin Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/eip-3298-removal-of-refunds/5430 +status: Stagnant +type: Standards Track +category: Core +created: 2021-02-26 +--- + +## Simple Summary + +Remove gas refunds for SSTORE and SELFDESTRUCT. + +## Motivation + +Gas refunds for SSTORE and SELFDESTRUCT were originally introduced to motivate application developers to write applications that practice "good state hygiene", clearing storage slots and contracts that are no longer needed. However, they are not widely used for this, and poor state hygiene continues to be the norm. It is now widely accepted that the only solution to state growth is some form of [statelessness or state expiry](https://hackmd.io/@HWeNw8hNRimMm2m2GH56Cw/state_size_management), and if such a solution is implemented, then disused storage slots and contracts would start to be ignored automatically. + +Gas refunds additionally have multiple harmful consequences: + +* Refunds give rise to [GasToken](https://gastoken.io/). GasToken has benefits in moving gas space from low-fee periods to high-fee periods, but it also has downsides to the network, particularly in exacerbating state size (as state slots are effectively used as a "battery" to save up gas) and inefficiently clogging blockchain gas usage +* Refunds increase block size variance. The theoretical maximum amount of actual gas consumed in a block is nearly twice the on-paper gas limit (as refunds add gas space for subsequent transactions in a block, though refunds are capped at 50% of a transaction's gas used). This is [not fatal](https://notes.ethereum.org/@vbuterin/eip_1559_spikes), but is still undesirable, especially given that refunds can be used to maintain 2x usage spikes for far longer than EIP 1559 can. + +## Specification + +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | TBD | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +Do not apply the `refund`. + +The description above is sufficient to describe the change, but for the sake of clarity we enumerate all places where gas refunds are currently used and which should/could be removed within a node implementation. + +1. Remove all use of the "refund counter" in SSTORE gas accounting, as defined in [EIP 2200](https://eips.ethereum.org/EIPS/eip-2200). Particularly: + + * If a storage slot is changed and the _current value_ equals the _original value_, but does not equal the _new value_, `SSTORE_RESET_GAS` is deducted (plus `COLD_SLOAD_COST` if [prescribed by EIP 2929 rules](https://eips.ethereum.org/EIPS/eip-2929#sstore-changes)), but no modifications to the refund counter are made. + * If a storage slot is changed and the _current value_ equals neither the _new value_ nor the _original value_ (regardless of whether or not the latter two are equal), `SLOAD_GAS` is deducted (plus `COLD_SLOAD_COST` if [prescribed by EIP 2929 rules](https://eips.ethereum.org/EIPS/eip-2929#sstore-changes)), but no modifications to the refund counter are made. + +2. Remove the `SELFDESTRUCT` refund. + +## Rationale + +A full removal of refunds is the simplest way to solve the issues with refunds; any gains from partial retention of the refund mechanism are not worth the complexity that that would leave remaining in the Ethereum protocol. + +## Backwards Compatibility + +Refunds are currently only applied _after_ transaction execution, so they cannot affect how much gas is available to any particular call frame during execution. Hence, removing them will not break the ability of any code to execute, though it will render some applications economically nonviable. + +[GasToken](https://gastoken.io/) in particular will become valueless. DeFi arbitrage bots, which today frequently use either established GasToken schemes or a custom alternative to reduce on-chain costs, would benefit from rewriting their code to remove calls to these no-longer-functional gas storage mechanisms. + +## Implementation + +An implementation can be found here: https://gist.github.com/holiman/460f952716a74eeb9ab358bb1836d821#gistcomment-3642048 + +## Test case changes + +* The "original", "1st", "2nd", "3rd" columns refer to the value of storage slot 0 before the execution and after each SSTORE. +* The "Berlin (cold)" column gives the post-Berlin (EIP 2929) gas cost assuming the storage slot had not yet been accessed. +* The "Berlin (hot)" column gives the post-Berlin gas cost assuming the storage slot has already been accessed. +* The "Berlin (hot) + norefund" column gives the post-Berlin gas cost assuming the storage slot has already been accessed, **and assuming this EIP has been implemented**. + +Gas costs are provided with refunds subtracted; if the number is negative this means that refunds exceed gas costs. The 50% refund limit is not applied (due to the implied assumption that this code is only a small fragment of a much larger execution). + +If refunds were to be removed, this would be the comparative table +| Code | Original | 1st | 2nd | 3rd | Istanbul | Berlin (cold) | Berlin (hot)| Berlin (hot)+norefund | +| -- | -- | -- | -- | -- | -- | -- | -- | -- | +| `0x60006000556000600055` | 0 | 0 | 0 | | 1612 | 2312 | 212 | 212 | +| `0x60006000556001600055` | 0 | 0 | 1 | | 20812 | 22212 | 20112 | 20112 | +| `0x60016000556000600055` | 0 | 1 | 0 | | 1612 | 2312 | 212 | 20112 | +| `0x60016000556002600055` | 0 | 1 | 2 | | 20812 | 22212 | 20112 | 20112 | +| `0x60016000556001600055` | 0 | 1 | 1 | | 20812 | 22212 | 20112 | 20112 | +| `0x60006000556000600055` | 1 | 0 | 0 | | -9188 | -9888 | -11988 | 3012 | +| `0x60006000556001600055` | 1 | 0 | 1 | | 1612 | 2312 | 212 | 3012 | +| `0x60006000556002600055` | 1 | 0 | 2 | | 5812 | 5112 | 3012 | 3012 | +| `0x60026000556000600055` | 1 | 2 | 0 | | -9188 | -9888 | -11988 | 3012 | +| `0x60026000556003600055` | 1 | 2 | 3 | | 5812 | 5112 | 3012 | 3012 | +| `0x60026000556001600055` | 1 | 2 | 1 | | 1612 | 2312 | 212 | 3012 | +| `0x60026000556002600055` | 1 | 2 | 2 | | 5812 | 5112 | 3012 | 3012 | +| `0x60016000556000600055` | 1 | 1 | 0 | | -9188 | -9888 | -11988 | 3012 | +| `0x60016000556002600055` | 1 | 1 | 2 | | 5812 | 5112 | 3012 | 3012 | +| `0x60016000556001600055` | 1 | 1 | 1 | | 1612 | 2312 | 212 | 212 | +| `0x600160005560006000556001600055` | 0 | 1 | 0 | 1 | 21618 | 22318 | 20218 | 40118 | +| `0x600060005560016000556000600055` | 1 | 0 | 1 | 0 | -8382 | -9782 | -11882 | 5918 | + +## Security Considerations + +TBD + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3300.md b/EIPS/eip-3300.md new file mode 100644 index 00000000000000..d120916957c9f7 --- /dev/null +++ b/EIPS/eip-3300.md @@ -0,0 +1,78 @@ +--- +eip: 3300 +title: Phase out refunds +author: William Morriss (@wjmelements) +discussions-to: https://ethereum-magicians.org/t/eip-3300-phase-out-refunds/5434 +status: Stagnant +type: Standards Track +category: Core +created: 2020-02-26 +--- + +## Simple Summary +Phases out the `SSTORE` and `SELFDESTRUCT` gas refunds. + +## Abstract +This EIP would define a block when the `SSTORE` and `SELFDESTRUCT` refunds would begin to diminish. +The refund would step linearly downward, eroding the implicit value of such refunds at an accelerating pace. + +## Motivation +Refunds increase block elasticity, so the block gas target can exceed the number established by miners by up to 2x. +This can cause hesitancy for miners to increase the block gas target. + +Refunds, tokenized or not, are valuable to their holders, especially during congestion. +If refunds must be removed, a gradual change in their value would be less-disruptive to the gas market than sudden abolition. +Refund consumption would proceed, especially during periods of congestion, and the refunds would be cleaned up from the state. +Refund creation, driven by demand, would naturally diminish as the efficiency of the refunds fall. +As the refund value approaches the activation cost, the implicit value of the refunds will approach zero, but in periods of congestion they will be cleaned up. + +This change is less work for the protocol developers than compensation and cleanup, while likely still achieving cleanup. + + +## Specification +Parameters: +* `FORK_BLOCK_NUM`: EIP-3300 activation block +* `REFUND_DECAY_STEP`: 1 gas +* `REFUND_DECAY_FREQUENCY`: 100 blocks + +Computed: +* `REFUND_DECAY`: `REFUND_DECAY_STEP * ceil((block.number + 1 - FORK_BLOCK_NUM) / REFUND_DECAY_FREQUENCY)` + + +On the block this EIP activates, and again every `REFUND_DECAY_FREQUENCY` blocks, all gas refunds, including `SELFDESTRUCT` and `SSTORE` would diminish by `REFUND_DECAY_STEP`, until 0. +The current difference is called the `REFUND_DECAY`, which shall be subtracted from each gas refund. + +For gas-cost regimes with refund removals that cancel prior refunds, the invariant that the refund counter cannot go negative will be preserved by diminishing the magnitude of those removals by `REFUND_DECAY`, until 0. + + +### EIP-2929 +The refunds as of EIP-2929 are as follows: + +* 24000 for SELFDESTRUCT +* `SSTORE_RESET_GAS - SLOAD_GAS` (5000 - 100) +* `SSTORE_SET_GAS - SLOAD_GAS` (20000 - 100) +* `SSTORE_SET_GAS - SLOAD_GAS` (20000 - 100) +* `SSTORE_CLEARS_SCHEDULE` (15000) + + +Each of these refunds would be decreased by the current `REFUND_DECAY`. + +There is also a case where `SSTORE_CLEARS_SCHEDULE` is removed from the refund counter. +That removal will also diminish by `REFUND_DECAY_STEP` until 0, maintaining the non-negative refund counter invariant. + + +## Rationale +Persisted refunds would become worthless before they fall below their activation cost. +Once the refunds are worthless, they can be removed by another hard fork without waiting for 0. +The rate of diminishing specified would currently require (24000-5000) * 100 = 1,900,000 blocks for `SELFDESTRUCT` and (15000-5000) * 100 = 1,000,000 blocks for `SSTORE`. +This timeframe is currently about a year, which should be enough flexibility for the remaining refunds to be consumed. + + +## Backwards Compatibility +This proposal breaks gas refunds, which contribute to block elasticity. +The effect of this will be increased gas price volatility: higher highs and lower lows. + +Because the refund counter is separate from the gas counter, the block-to-block gas changes will not break `eth_estimateGas`. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3322.md b/EIPS/eip-3322.md new file mode 100644 index 00000000000000..e865e06c84c03f --- /dev/null +++ b/EIPS/eip-3322.md @@ -0,0 +1,68 @@ +--- +eip: 3322 +title: Account gas storage opcodes +author: William Morriss (@wjmelements) +discussions-to: https://ethereum-magicians.org/t/eip-3322-efficient-gas-storage/5470 +status: Stagnant +type: Standards Track +category: Core +created: 2020-03-04 +--- + +## Simple Summary +Allows contract accounts to store gas that can be transferred to the refund counter. + +## Abstract +Contracts can persist gas for later transfer to the refund counter. +Three opcodes are introduced to read, add to, and use this gas counter. + +## Motivation +The refund mechanism is currently being used by gas tokens to arbitrage gas price. +This brings gas supply elasticity and price stability by moving gas from blocks with less demand to blocks with more demand. +Unfortunately this rewards unnecessary state growth. +By introducing a superior gas storage mechanism, the gas market will require less storage and computation. + +## Specification +Contract accounts gain an unsigned gas refund counter, initially zero. + +Three new opcodes are introduced to manage this state. + +* `SELFGAS` (`0x49`): Pushes the current account's gas refund counter onto the stack. +Shares gas pricing with `SELFBALANCE`. +* `USEGAS` (`0x4a`): Pops `amount` from the stack. +The minimum of `amount` and the current account's gas refund counter is transferred to the execution context's refund counter. +Costs `5000` gas. +* `STOREGAS` (`0x4b`): Pops `amount` from the stack. +Costs `5000 + amount` gas. +Increases the current account's gas refund counter by `amount`. + +## Rationale +By reusing the execution context's refund counter we can reuse its 50% DoS protection, which limits its block elasticity contribution to 2x. + +The gas costs are based on similar opcodes `SELFBALANCE` and `SSTORE`. + +Most accounts will store no gas, so the per-account storage overhead should be minimal or even zero in the normal case. + +The opcode numbers chosen are in the same `0x4X` range as `SELFBALANCE` and `GASLIMIT`. + +## Backwards Compatibility +Because the gas is added to the refund counter, no compatibility issues are anticipated. + +## Test Cases +| Code | Used Gas | Refund | Original | Final | +|------------------|----------|--------|----------|-------| +| 0x60004900 | 5003 | 0 | 0 | 0 | +| 0x60034900 | 5003 | 2 | 2 | 0 | +| 0x60034900 | 5003 | 3 | 3 | 0 | +| 0x60034900 | 5003 | 3 | 4 | 1 | +| 0x60034960034900 | 10006 | 4 | 4 | 0 | +| 0x60034960034900 | 10006 | 6 | 6 | 0 | +| 0x484900 | 5010 | 100000 | 100000 | 0 | +| 0x61ffff4a00 | 70538 | 0 | 0 | 65535 | + + +## Security Considerations +DoS is already limited by the 50% refund limit. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3326.md b/EIPS/eip-3326.md new file mode 100644 index 00000000000000..20113ebd8457f1 --- /dev/null +++ b/EIPS/eip-3326.md @@ -0,0 +1,130 @@ +--- +eip: 3326 +title: Wallet Switch Ethereum Chain RPC Method (`wallet_switchEthereumChain`) +author: Erik Marks (@rekmarks) +discussions-to: https://ethereum-magicians.org/t/eip-3326-wallet-switchethereumchain +status: Stagnant +type: Standards Track +category: Interface +created: 2021-03-04 +requires: 155, 695 +--- + +## Simple Summary + +An RPC method for switching the wallet's active Ethereum chain. + +## Abstract + +The `wallet_switchEthereumChain` RPC method allows Ethereum applications ("dapps") to request that the wallet switches its active Ethereum chain, if the wallet has a concept thereof. +The caller must specify a chain ID. +The wallet application may arbitrarily refuse or accept the request. +`null` is returned if the active chain was switched, and an error otherwise. + +Important cautions for implementers of this method are included in the [Security Considerations](#security-considerations) section. + +## Motivation + +All dapps require the user to interact with one or more Ethereum chains in order to function. +Some wallets only supports interacting with one chain at a time. +We call this the wallet's "active chain". +`wallet_switchEthereumChain` enables dapps to request that the wallet switches its active chain to whichever one is required by the dapp. +This enables UX improvements for both dapps and wallets. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC-2119](https://www.ietf.org/rfc/rfc2119.txt). + +### `wallet_switchEthereumChain` + +The method accepts a single object parameter with a `chainId` field. +The method returns `null` if the wallet switched its active chain, and an error otherwise. + +The method presupposes that the wallet has a concept of a single "active chain". +The active chain is defined as the chain that the wallet is forwarding RPC requests to. + +#### Parameters + +`wallet_switchEthereumChain` accepts a single object parameter, specified by the following TypeScript interface: + +```typescript +interface SwitchEthereumChainParameter { + chainId: string; +} +``` + +If a field does not meet the requirements of this specification, the wallet **MUST** reject the request. + +- `chainId` + - **MUST** specify the integer ID of the chain as a hexadecimal string, per the [`eth_chainId`](./eip-695.md) Ethereum RPC method. + - The chain ID **MUST** be known to the wallet. + - The wallet **MUST** be able to switch to the specified chain and service RPC requests to it. + +#### Returns + +The method **MUST** return `null` if the request was successful, and an error otherwise. + +If the wallet does not have a concept of an active chain, the wallet **MUST** reject the request. + +### Examples + +These examples use JSON-RPC, but the method could be implemented using other RPC protocols. + +To switch to Mainnet: + +```json +{ + "id": 1, + "jsonrpc": "2.0", + "method": "wallet_switchEthereumChain", + "params": [ + { + "chainId": "0x1", + } + ] +} +``` + +To switch to the Goerli test chain: + +```json +{ + "id": 1, + "jsonrpc": "2.0", + "method": "wallet_switchEthereumChain", + "params": [ + { + "chainId": "0x5", + } + ] +} +``` + +## Rationale + +The purpose `wallet_switchEthereumChain` is to provide dapps with a way of requesting to switch the wallet's active chain, which they would otherwise have to ask the user to do manually. + +The method accepts a single object parameter to allow for future extensibility at virtually no cost to implementers and consumers. + +For related work, see [EIP-3085: `wallet_addEthereumChain`](./eip-3085.md) and [EIP-2015: `wallet_updateEthereumChain`](./eip-2015.md). +`wallet_switchEthereumChain` intentionally forgoes the chain metadata parameters included in those EIPs, since it is purely concerned with switching the active chain, regardless of RPC endpoints or any other metadata associated therewith. + +## Security Considerations + +For wallets with a concept of an active chain, switching the active chain has significant implications for pending RPC requests and the user's experience. +If the active chain switches without the user's awareness, a dapp could induce the user to take actions for unintended chains. + +In light of this, the wallet should: + +- Display a confirmation whenever a `wallet_switchEthereumChain` is received, clearly identifying the requester and the chain that will be switched to. + - The confirmation used in [EIP-1102](./eip-1102.md) may serve as a point of reference. +- When switching the active chain, cancel all pending RPC requests and chain-specific user confirmations. + +### Preserving User Privacy + +Automatically rejecting requests for chains that aren't supported or have yet to be added by the wallet allows requesters to infer which chains are supported by the wallet. +Wallet implementers should consider whether this communication channel violates any security properties of the wallet, and if so, take appropriate steps to mitigate it. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3332.md b/EIPS/eip-3332.md new file mode 100644 index 00000000000000..082ceaa1b78ace --- /dev/null +++ b/EIPS/eip-3332.md @@ -0,0 +1,97 @@ +--- +eip: 3332 +title: MEDGASPRICE Opcode +author: Justice Hudson (@jchancehud) +discussions-to: https://ethereum-magicians.org/t/medgasprice-opcode-eip/5480 +status: Withdrawn +type: Standards Track +category: Core +created: 2021-03-05 +--- + +## Simple Summary + +An opcode for getting the median gas price of the parent block. + +## Abstract + +Adds `MEDGASPRICE (0x46)` opcode that returns the median gas price for the parent block. + +## Motivation + +With the emergence of rollups as core mechanisms in scaling Ethereum there are a number of common transactions that can be front-run. Optimistic rollups rely on the submission of fraud proofs to maintain the integrity of their systems. As a result actors submitting fraud proofs typically receive a financial reward for doing so. This opens a trivial front-running strategy of watching the mempool for fraud proof submissions and copying such transactions with a much higher gas price to reap the reward. Such front-runners do not perform validation independently and de-incentivize others from performing validation. Adding a mechanism enforcing an upper bound on gas prices for a transaction could be an effective defense against such front-running attacks. + +Consider a smart contract that wants to implement a first come first serve mechanism. Such a mechanism must defeat the inherently pay-to-win nature of the gas price market. Enforcing a maximum gas price for a transaction relies on the fact that transactions of the same gas price are generally processed in a first in first out way by Ethereum miners. A contract currently has few options for setting a max gas price: + +- Set a constant value at a reasonable rate given the current gas prices +- Allow an individual or group of individuals to adjust a max gas price over time + +More elaborate schemes could likely be constructed but all would involve storing gas price information on chain increasing the number of transactions and costing Ether. + +Given a median gas price opcode a contract can set a maximum gas price as a function of the last blocks gas price. This can easily be implemented using a strategy such as the following: + +``` +// Assume that block.medgasprice is bound to MEDGASPRICE (0x46) + +function submitFraudProof(bytes calldata proof) public { + require(tx.gasprice <= maxGasPrice()); + // process the fraud proof and provide a reward (if valid) +} + +function maxGasPrice() public view returns (uint) { + return 3 * block.medgasprice; +} +``` + +Given the contract implementation above a client would simply call `maxGasPrice` to determine the gas price to use when submitting a fraud proof. This particular implementation allows up to 3x the median gas price of the last block to be used. + +### Forwards Compatibility + +[EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) plans to change the fee market in a number of ways. Most notably is the creation of a base fee that is burned. In this context an "inclusion fee" still exists as a part of the total fee. Consider the following two cases: + +#### Block sizes are increasing (all available gas is being consumed) + +In this case there will be bidding contention in the inclusion fee to incentivize miners to include transactions. A median gas price operator would still be helpful as an attacker could supply a high inclusion fee to bump honest transactions. + +#### Block sizes are decreasing (excess gas is available) + +In this case an attacker could specify a high inclusion fee to incentivize miners to include their transaction early in the block. Miners are incentivized to do so as including expensive transactions first reduces the risk of a revert (and partial refund) occurring. + +Given these two cases this EIP seems relevant in the context of EIP-1559. + +Post EIP-1559 `MEDGASPRICE (0x46)` should return the median `effective_gas_price` of the previous block. + +[EIP-3198](https://eips.ethereum.org/EIPS/eip-3198) is required for the above strategies to be implemented. With the inclusion of `BASEFEE (0x48)` a contract can subtract the `base_fee_per_gas` from the `effective_gas_price` to determine the inclusion fee per gas being paid for the transaction and thus implement an upper bound. + +## Specification + +If `block.number >= TBD`, add a new opcode `MEDGASPRICE (0x46)`: + +Pushes the median gas price of the parent block onto the stack. + +| Op | Input | Output | Cost | +|:----: |:-----: |:------: |:----: | +| 0x46 | 0 | 1 | 8 | + +## Rationale + +Having access to the current gas price economy allows contracts to implement more robust and automated logic surrounding acceptable transaction gas prices. + +### Naming note + +The name `MEDGASPRICE` was chosen because the median gas price of the network can only be calculated from the latest complete block. Thus transactions being executed should expect the median gas price to be calculated from the previous block. + +## Backwards Compatibility + +There are no known backwards incompabitility issues. + +## Security Considerations + +The strategy described for preventing front-running by setting an upper bound on the gas price of transactions has a few caveats: + +1. It relies on miners being impartial. Reordering transactions with the same gas price is a trivial means of defeating this strategy. +2. The value returned by `MEDGASPRICE (0x46)` may fluctuate rapidly between blocks. If a transaction is not included immediately it may either fail (if the gas price drops) or become vulnerable to front-running (if the gas price increases). + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3336.md b/EIPS/eip-3336.md new file mode 100644 index 00000000000000..81015e9bf3d804 --- /dev/null +++ b/EIPS/eip-3336.md @@ -0,0 +1,71 @@ +--- +eip: 3336 +title: Paged memory allocation for the EVM +author: Nick Johnson (@arachnid) +discussions-to: https://ethereum-magicians.org/t/eips-3336-and-3337-improving-the-evms-memory-model/5482 +status: Stagnant +type: Standards Track +category: Core +created: 2021-03-06 +--- + +## Simple Summary +Changes the memory model for the EVM to use pagination. + +## Abstract +Presently, the EVM charges for memory as a linear array starting at address 0 and extending to the highest address that has been read from or written to. This suffices for simple uses, but means that compilers have to generate programs that use memory compactly, which leads to wasted gas with reallocation of memory elements, and makes some memory models such as separate heap and stack areas impractical. This EIP proposes changing to a page-based billing model, which adds minimal complexity to implementations, while providing for much more versatility in EVM programs. + +## Motivation +Most modern computers implement "virtual memory" for userspace programs, where programs have access to a large address space, with pages of RAM that are allocated as needed by the OS. This allows them to distribute data throughout memory in ways that minimises the amount of reallocation and copying that needs to go on, and permits flexible use of memory for data with different lifetimes. Implementing a simple version of paged memory inside the EVM will provide the same flexibility to compilers targeting the EVM. + +## Specification +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | TBD | +| `PAGE_BITS` | 10 | +| `PAGE_BASE_COST` | 96 | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +### Changes to memory allocation in EVM implementations +Memory is now allocated in pages of `2**PAGE_BITS` bytes each. The most significant `256 - PAGE_BITS` bits of each memory address denote the page number, while the least significant `PAGE_BITS` bits of the memory address denote the location in the page. Pages are initialized to contain all zero bytes and allocated when the first byte from a page is read or written. + +EVM implementations are encouraged to store the pagetable as an associative array (eg, hashtable or dict) mapping from page number to an array of bytes for the page. + +### Changes to memory expansion gas cost +Presently, the total cost to extend the memory to `a` words long is `Cmem(a) = 3 * a + floor(a ** 2 / 512)`. If the memory is already `b` words long, the incremental cost is `Cmem(a) - Cmem(b)`. `a` is the number of words required to cover the range from memory address 0 to the last word that has been read or written by the EVM. + +Under this EIP, we define a new memory cost function, based on the number of allocated pages. This function is `Cmem'(p) = max(PAGE_BASE_COST * (p - 1) + floor(2 * (p - 1) ** 2), 0)`. As above, if the memory already contains `q` pages, the incremental cost is `Cmem'(p) - Cmem'(q)`. + +### Changes to `MLOAD` and `MSTORE` +Loading a word from memory or storing a word to memory requires instantiating any pages that it touches that do not already exist, with the resulting gas cost as described above. If the word being loaded or stored resides in a single page, the gas cost remains unchanged at 3 gas. If the word being loaded spans two pages, the cost is 6 gas. + +### Changes to other memory-touching opcodes +`CALLDATACOPY`, `CODECOPY`, `EXTCODECOPY`, `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE`, `MSTORE8` and any other opcodes that read or write memory are modified as follows: + - Any page they touch for reading or writing is instantiated if it is not already. + - Memory expansion gas is charged as described above. + +## Rationale +### Memory expansion gas cost +The new gas cost follows the same curve as the previous one, while ensuring that the new gas cost is always less than or equal to the previous cost. This prevents existing programs that make assumptions about memory allocation gas costs from resulting in errors, without unduly discounting memory below what it costs today. Intuitively, a program that uses up to a page boundary pays for one page less than they would under the old model, while a program that uses one word more than a page boundary pays for one word less than they would under the old model. + +We believe that this incremental reduction will not have a significant impact on the effective gas limit, as it gets proportionally smaller as programs use more RAM. + +### Additional cost for MLOADs and MSTOREs spanning two pages +Loading or storing data spanning two memory pages requires more work from the EVM implementation, which must split the word at the page boundary and update the two (possibly disjoint) pages. Since we cannot guarantee loads and stores in existing EVM programs are page-aligned, we cannot prohibit this behaviour for efficiency. Instead, we propose treating each as two loads or stores for gas accounting purposes. This discourages the use of this functionality, and accounts for the additional execution cost, without prohibiting it outright. + +This will result in additional gas costs for any programs that perform these operations. We believe this to be minimal, and hope to do future analysis to confirm this. + +## Backwards Compatibility +The new function for memory expansion gas cost is designed specifically to avoid backwards compatibility issues by always charging less than or equal to the amount the current EVM would charge. Under some circumstances existing programs will be charged more for MLOADs and MSTOREs that span page boundaries as described above; we believe these changes will affect a minimum of programs and have only a small impact on their gas consumption. + +## Test Cases +TBD + +## Security Considerations +Potential CPU DoS issues arising from additional work done under the new model are alleviated by charging more for non-page-aligned reads and writes. Charges for memory expansion asymptotically approach those currently in force, so this change will not permit programs to allocate substantially more memory than they can today. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3337.md b/EIPS/eip-3337.md new file mode 100644 index 00000000000000..73ac30414505fa --- /dev/null +++ b/EIPS/eip-3337.md @@ -0,0 +1,99 @@ +--- +eip: 3337 +title: Frame pointer support for memory load and store operations +author: Nick Johnson (@arachnid) +discussions-to: https://ethereum-magicians.org/t/eips-3336-and-3337-improving-the-evms-memory-model/5482 +status: Stagnant +type: Standards Track +category: Core +created: 2021-03-06 +requires: 3336 +--- + +## Simple Summary +Introduces four new opcodes for loading data from and storing data to memory offset by a frame pointer. + +## Abstract +This EIP introduces four new opcodes, `MLOADFP`, `MSTOREFP`, `GETFP` and `SETFP` that allow for more efficient memory access offset by a user-controlled quantity called the "frame pointer". This permits compilers to more efficiently offload ephemeral data such as local variables to memory instead of the EVM's evaluation stack, which has a number of benefits, including the effective elimination of restrictions on the number of local variables in a function. + +## Motivation +In most commonly used VMs, ephemeral data such as local variables, function arguments, and return addresses is stored in a region of memory called the stack. In contrast to the EVM's evaluation stack, this area of memory is randomly accessible, and thus can store an arbitrary amount of data, which can be referenced from anywhere they remain in scope. Although this model is possible in the current EVM design, it is made difficult by the linear model of memory (addressed in [EIP-3336](./eip-3336.md)) and by the lack of opcodes for relative memory access commonly found in other architectures. This EIP proposes new opcodes that permit this form of memory use, without imposing undue burden on EVM implementers or on runtime efficiency. + +In the current EVM model, a compiler wishing to use this pattern would have to store the frame pointer - which points to the start or end of the current memory stack frame - in memory, and load it each time they wish to reference it. For example, loading a value from memory offset by the frame pointer would require the following sequence of operations: + +| Opcode | Gas used | +|-----------|----------| +| `PUSHn x` | 3 | +| `PUSH1 0` | 3 | +| `MLOAD` | 3 | +| `ADD` | 3 | +| `MLOAD` | 3 | + +This consumes a total of 15 gas, and takes up at least 7 bytes of bytecode each time it is referenced. In contrast, after this EIP, the equivalent sequence of operations is: + +| Opcode | Gas used | +|-----------|----------| +| `PUSH1 x` | 3 | +| `MLOADFP` | 3 | + +This consumes only 6 gas, and takes at least 3 bytes of bytecode. The effort required from the EVM implementation is equivalent, costing only one extra addition operation over a regular `MLOAD`. The alternative of storing values on the stack, which requires 3 gas and 1 byte of bytecode for a `DUPn` operation, but it is now at most twice as efficient rather than 5 times as efficient, making storing values in memory a viable alternative. + +Likewise, before this EIP a frame-pointer relative store requires the following sequence of operations: +| Opcode | Gas used | +|-----------|----------| +| `PUSHn x` | 3 | +| `PUSH1 0` | 3 | +| `MLOAD` | 3 | +| `ADD` | 3 | +| `MSTORE` | 3 | + +This consumes 15 gas and at least 7 bytes of bytecode. After this EIP, the equivalent sequence of operations is: + +| Opcode | Gas used | +|-----------|----------| +| `PUSHn x` | 3 | +| `MSTOREFP`| 3 | + +Consuming only 6 gas and at least 3 bytes of bytecode, while once again only requiring EVM implementations to do one extra addition operation. The alternative of storing values on the stack requires 6 gas and 2 bytes of bytecode for the sequence `SWAPn POP`, making it no more efficient than memory storage. + +## Specification +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | TBD | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +### Frame pointer +A new EVM internal state variable called the "frame pointer" is introduced. This is a signed integer that starts at 0. + +### `SETFP` opcode +A new opcode, `SETFP` is introduced with value `0x5c`. This opcode costs `G_low` (3 gas) and takes one argument from the stack. The argument is stored as the new value of the frame pointer. + +### `GETFP` opcode +A new opcode, `GETFP` is introduced with value `0x5d`. This opcode costs `G_low` (3 gas) and takes no arguments. It takes the current value of the frame pointer and pushes it to the stack. + +### `MLOADFP` opcode +A new opcode `MLOADFP` is introduced with value `0x5e`. This opcode acts in all ways identical to `MLOAD`, except that the value of the frame pointer is added to the address before loading data from memory. An attempt to load data from a negative address should be treated identically to an invalid opcode, consuming all gas and reverting the current execution context. + +### `MSTOREFP` opcode +A new opcode `MSTOREFP` is introduced with value `0x5f`. This opcode acts in all ways identical to `MSTORE`, except that the value of the frame pointer is added to the address before storing data to memory. An attempt to store data to a negative address should be treated identically to an invalid opcode, consuming all gas and reverting the current execution context. + +## Rationale +### Cost of new opcodes +The cost of the new opcodes `MLOADFP` and `MSTOREFP` reflects the cost of `MLOAD` and `MSTORE`. They are generally equivalent in cost with the exception of an extra addition operation, which imposes negligible cost. + +The cost of the new opcodes `SETFP` and `GETFP` is based on other common low-cost opcodes such as `PUSH` and `POP`. + +### Absence of `MSTORE8FP` +`MSTORE8FP` opcode was not included because it is expected that it would be used infrequently, and there is a desire to minimise the size of the instruction set and to conserve opcodes for future use. + +## Backwards Compatibility +This EIP exclusively introduces new opcodes, and as a result should not impact any existing programs unless they operate under the assumption that these opcodes are undefined, which we believe will not be the case. + +## Security Considerations +DoS risks are mitigated by correct pricing of opcodes to reflect current execution costs. No other security considerations pertain to this EIP. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3338.md b/EIPS/eip-3338.md new file mode 100644 index 00000000000000..0b61fe18b671d1 --- /dev/null +++ b/EIPS/eip-3338.md @@ -0,0 +1,55 @@ +--- +eip: 3338 +title: Limit account nonce to 2^52 +author: Micah Zoltu (@MicahZoltu), Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-2681-limit-account-nonce-to-2-64-1/4324 +status: Withdrawn +withdrawal-reason: Withdrawn in favor of [EIP-2681](./eip-2681.md) +type: Standards Track +category: Core +created: 2021-03-07 +--- + +## Abstract + +Limit account nonce to be between `0` and `2^52`. + +## Motivation + +Account nonces are currently specified to be arbitrarily long unsigned integers. Dealing with arbitrary length data in the state witnesses is not optimal, therefore this EIP will allow proofs to represent the nonce in a more optimized way. + +Additionally it could prove beneficial to transaction formats, where some improvements are potentially sought by at least three other proposals. + +Lastly, this facilitates a minor optimisation in clients, because the nonce no longer needs to be kept as a 256-bit number. + +## Specification + +If `block.number >= FORK_BLOCK` introduce two new restrictions: + +1. Consider any transaction invalid, where the nonce exceeds `2^52`. +2. The `CREATE` instruction to abort with an exceptional halt, where the account nonce is `2^52`. + +## Rationale + +1. It is unlikely for any nonce to reach or exceed the proposed limit. If one would want to reach that limit via external transactions, it would cost at least `21000 * (2^64-1) = 387_381_625_547_900_583_915_000` gas. + +2. It must be noted that in the past, in the Morden testnet, each new account had a starting nonce of `2^20` in order to differentiate transactions from mainnet transactions. +This mode of replay protection is out of fashion since [EIP-155](./eip-155.md) introduced a more elegant way using chain identifiers. + +3. Most clients already consider the nonce field to be 64-bit, such as go-ethereum. + +4. All integer values <= 2^52 can be encoded in a 64-bit floating point without any loss of precision, making this value easy to work with in languages that only have floating point number support. + +## Backwards Compatibility + +While this is a breaking change, no actual effect should be visible: + +1. There is no account in the state currently which would have a nonce exceeding that value. As of November 2020, the account `0xea674fdde714fd979de3edf0f56aa9716b898ec8` is responsible for the highest account nonce at approximately 29 million. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3368.md b/EIPS/eip-3368.md new file mode 100644 index 00000000000000..6c186b22a8edd4 --- /dev/null +++ b/EIPS/eip-3368.md @@ -0,0 +1,50 @@ +--- +eip: 3368 +title: Increase block rewards to 3 ETH, with 2 Year Decay to 1 ETH Scheduled +author: Michael D. Carter (@BitsBeTrippin) +discussions-to: https://ethereum-magicians.org/t/eip-3368-block-reward-increase-w-decay-for-next-two-years/5550 +status: Stagnant +type: Standards Track +category: Core +created: 2021-03-12 +--- + +## Simple Summary +Changes the block reward paid to proof-of-work (POW) miners to 3 ETH from existing 2 ETH and starts a decay schedule for next two years to 1 ETH Block Reward. + +## Abstract +Set the block reward to 3 ETH and then decrease it slightly every block for 4,724,000 blocks (approximately 2 years) until it reaches 1 ETH. + +## Motivation +A sudden drop in PoW mining rewards could result in a sudden precipitous decrease in mining profitability that may drive miners to auction off their hashrate to the highest bidder while they figure out what to do with their now "worthless" hardware. If enough hashrate is auctioned off in this way at the same time, an attacker will be able to rent a large amount of hashing power for a short period of time at relatively low cost vs. reward and potentially attack the network. By setting the block reward to X (where X is enough to offset the sudden profitability decrease) and then decreasing it over time to Y (where Y is a number below the sudden profitability decrease), we both avoid introducing long term inflation while at the same time spreading out the rate that individual miners cross into a transitional range. This approach offers a higher level of confidence and published schedule of yield, while allowing mining participants time to gracefully repurpose/sell their hardware. This greatly increases ethereums PoW security by keeping incentives aligned to ethereum and not being force projected to short term brokerage for the highest bidder. Additionally the decay promotes a known schedule of a deflationary curve, aligning to the overall Minimal Viable Issuance directive aligned to a 2 year transition schedule for Proof of Stake, consensus replacement of Proof of Work. Security is paramount in cryptocurrency blockchains and the risk to a 51% non-resistant chain is real. The scope of Ethereum's current hashrate has expanded to hundreds of thousands of new participants and over 2.5x original ATH hashrate/difficulty. While the largest by hashrate crypto is bitcoin, ethereum is not far behind the total network size in security aspects. This proposal is focused to keep that superiority in security one of the key aspects. + +## Specification +Adjust block, uncle, and nephew rewards +### Constants +* `TRANSITION_START_BLOCK_NUMBER: TBD` +* `TRANSITION_DURATION: 4_724_000` (about two years) +* `TRANSITION_END_BLOCK_NUMBER: FORK_BLOCK_NUMBER + TRANSITION_DURATION` +* `STARTING_REWARD: 3_000_000_000_000_000_000` +* `ENDING_REWARD: 1_000_000_000_000_000_000` +* `REWARD_DELTA: STARTING_REWARD - ENDING_REWARD` +### Block Reward +```py +if block.number >= TRANSITION_END_BLOCK_NUMBER: + block_reward = ENDING_REWARD +elif block.number = TRANSITION_START_BLOCK_NUMBER: + block_reward = STARTING_REWARD +elif block.number > TRANSITION_START_BLOCK_NUMBER: + block_reward = STARTING_REWARD - REWARD_DELTA * TRANSITION_DURATION / (block.number - TRANSITION_START_BLOCK_NUMBER) +``` + +## Rationale +2 years was chosen because it gives miners sufficient time to find alternative uses for their hardware and/or get their hardware back out onto the open market (e.g., in the form of gaming GPUs) without flooding the market suddenly. This proposal should ONLY be considered as a last resort as something we have in our pocket should the "network need to attract hashing power quickly and then bleed it off over time" rather than "something that is scheduled to be included in X hard fork" ; Recommendation to have in a fast track state, but NOT deployed to mainnet unless needed. + +## Backwards Compatibility +There are no known backward compatibility issues with the introduction of this EIP. + +## Security Considerations +There are no known security issues with the introduction of this EIP. + +## Copyright +Copyright and related rights waived via CC0. diff --git a/EIPS/eip-3372.md b/EIPS/eip-3372.md new file mode 100644 index 00000000000000..9ac605a523ee7f --- /dev/null +++ b/EIPS/eip-3372.md @@ -0,0 +1,123 @@ +--- +eip: 3372 +title: 5 FNV primes for ethash +status: Stagnant +type: Standards Track +category: Core +author: mineruniter969 (@mineruniter969), mineruniter969 +discussions-to: https://ethereum-magicians.org/t/eip-3372-apply-minor-modifications-to-the-ethash-algorithm-to-break-current-asic-implementations-eip-969-resubmission/5655 +created: 2021-03-13 +--- + +## Simple Summary + +Introduce 5 new FNV primes into the ethash algorithm. + +## Abstract + +This EIP is to kick current ASIC implementations out of the network to keep the Ethereum network secure and healthy by changing the `fnv` constants. + +## Motivation + +ASICs provide a severe centralization risk for the Ethereum network. If we do not get rid of them, small GPU miners will be forced to exit the Ethereum mining because EIP-1559 will make them mining at a loss. Furthermore, ASIC production will be concentrated only at one or two parties, which will make the Ethereum hashrate centralized. Also, it is worth noting that Ethash ASIC machines cost 10k+ USD, while GPUs are priced less than 1000 USD. + +With GPUs, miners can switch to other mining algorithms, but with ASICs, it is impossible. Leaving everything as-is will almost certainly a very tough (from the side of miners) integration of the Ethereum 2.0. + +In short, this EIP is required to keep the Ethereum network stable and decentralized by keeping the ASIC business away. + +## Specification + +If `block.number >= ETHASH11_BLKNUM`, activate the `ethash1.1` algorithm version. + +### ethash1.1 + +Prior to this change, `fnv` hash function is used throughout the `hashimoto` function. `fnv` is identical for all steps, `ethash1.1` will introduce additional `fnvA`, `fnvB`, `fnvC`, `fnvD`, and `fnvE` functions. All those functions will have different FNV constants. + +``` +// Previously used FNV prime +#define FNV_PRIME_0 0x1000193 + +// New FNV primes +#define FNV_PRIME_A 0x10001a7 +#define FNV_PRIME_B 0x10001ab +#define FNV_PRIME_C 0x10001cf +#define FNV_PRIME_D 0x10001e3 +#define FNV_PRIME_E 0x10001f9 +``` + +Prior to this EIP, all parts of Ethash are using the `fnv` (hereinafter referenced as `fnv0`) function. As of the introduction of this EIP: +* `fnvA` replaces `fnv0` in the DAG item selection step +* `fnvB` replaces `fnv0` in the DAG item mix step +* `fnvC(fnvD(fnvE` replaces `fnv0(fnv0(fnv0(` in the compress mix step +* `fnv0` in the DAG generation step should remain unchanged. + +## Rationale + +ASIC Miners have become a threat to the future of Ethereum and a hard fork is required to remove them from the network before additional damage is caused. EIP-3372 proposes the minimum necessary to do so and will not affect ETH stakeholders or the network like Ethash 2.0 would. The threat ASICs pose is legal, social, moral, technical, monetary, and environmental. As we continue to come closer to the merge ASICs will attack the network and the developers personally as they have done in the past because miners will always pursue profits. + +Legally and socially ASIC's have previously been a threat and a nuisance. As Hudson describes Linzhi attacked the EF and developers personally seeking to spread lies and misinformation while sending legal threats during discussions around EIP-1057. His account is [here](https://github.com/Souptacular/linzhi) and in his own words + +> ASIC manufacturer Linzhi has both pressured me and told lies + +With their attacks and harassment on staff demonstrated in the below image: +![](upload://n8TJsS8hEEH4DXYJ2WDzblm5qJo.jpeg) + +Socially and morally the Ethereum community must adopt a no-tolerance policy towards personal attacks on its developers. It is only because of the core developers that Ethereum has value, the community cannot allow large companies free reign to attack them personally and must seek to protect each developer as they are a resource that keeps Ethereum viable. Multiple developers were "burned" during this event. As we accelerate the merge, it is likely that ASIC companies will repeat their actions and again attack the developers personally while pursuing legal options. This is seen not only by their actions during EIP-1057 but recent discussion around EIP-969 where legal threats from them caused the champion of that EIP to dropout and forcing me to submit this EIP anonymously. Ethereum cannot allow its actors to be threatened without consequence and this is a fight that must happen now while they are weak rather than pre-merge where they are stronger which will result in a delayed merge and hurt the value of Ethereum. + +ASICs have the greatest incentives and resources to commit bad acts because they are centralized in farms this is why Vitalik designed ETH to be ASIC-resistant because ASICs had ruined BTC's principles of decentralization. Each day their power and control over the network grows. ASICs are against the founding principles of Ethereum which promotes a decentralized system run by common people, not a single owner of large warehouses. F2Pool which consists largely of ASIC farms has become the #3 largest pool controlling around 10% of hashrate. Their farms can be viewed on their webpage. In November 2020 they were 23TH/s yet today they are 45.6 TH/s. That's a doubling in 4 months and their growth is accelerating as additional ASICs come online. ASICs are becoming a threat that will soon dominate the network and action must be taken now to head them off. + +ASICs on F2Pool have long been known to be "bad actors" on the BTC network. They are known for market manipulation and dumping BTC to manipulate prices (I could not post the source link as this is a new account). What will these ASICs do once they find out that they are about to lose millions prior to the merge? Ethereum is not just a network it is a community and they will use their financial resources and pour millions into delaying the merge as they launch legal case after legal case. They will attack the developers and the community as they seek to squeeze every last dollar. + +The reason Ethereum was founded on the principle of being anti-ASIC is because Vitalik had seen the damage ASICs had caused to the BTC network as they pursued profits rather than the betterment of the network. GPU miners are decentralized and disorganized which makes them a much lower threat than warehouses under one central corporation that is outside the legal system and thus cannot be held to account for bad acts. + +EIP-3372 also works to protect the environment. Post merge, gpus will go into the secondary market or move to other coins. However, ASICs will become junk. As more ASICs are produced, Ethereum increases its environmental footprint. These ASICs are being mass produced in greater numbers despite it being public that the merge is being accelerated. It is clear that these ASIC manufacturers and buyers must either be ignorant of the accelerated merge or plan to delay it. Because they dump their ETH they have no stake in the network except the money they can squeeze from it and if by making trouble they can give themselves another day than they will do it. + +Finally, Ethereum has always sought to pursue "minimum issuance". By reducing the amount of miners that can pose a threat to the network, Ethereum also decreases how much it needs to pay for protection. Some EIP's are being prepared to increase miner incomes post EIP-1559 should a threat appear. EIP-3372 eliminates the need to pay more for security and allows miners to be paid less without compromising the network's security. As we go forward closer to the merge, the community must reduce attack vectors so as to reduce the cost of the merge itself and maximize the security of the network. The community already pays too much for protection and by reducing threats we can reduce this cost. ASIC warehouse farms are dumping all the ETH they make which is suppressing the price of ETH. Although rare, several individual GPU miners are taking part in staking or have gone on to join the community in development or our financial endeavors. They thus are more valuable to the community than a warehouse of future junk. There is no need for the Ethereum community to continue to pay for soon-to-be obsolete hardware that will end up in landfills. + +### Technical Overview + +Ethash 1.1 will replace the only FNV prime with five new primes at the stage of the hash computation. The prime used for the DAG generation is remained unchanged, while all others are be changed. This will not prevent ASIC companies from creating new ASICs that adapt but so close to the merge it is unlikely they will do so, and even if they do they are unlikely to be able to produce enough to again be a threat. +The choice of FNV constants are based on the formal specification that is available on [https://tools.ietf.org/html/draft-eastlake-fnv-14#section-2.1](https://ietf) + +We apologize for the delay in submitting the justification for this EIP. As the community may or may not be aware, the original champion was forced to stop working on this EIP due to legal attacks from ASIC companies. It has taken us this long to review his work and find a new champion. To protect ourselves we are submitting this anonymously and would request the community's aid in our endeavor to maintain our anonymity and some lenience given the circumstances and threats we face pursuing this EIP. + +## Backwards Compatibility + +Mining hardware that is optimized for ethash may no longer work if the `fnv` constants are baked into the hardware and cannot be changed. + +## Test Vectors + +```json +{ + "first": { + "nonce": "4242424242424242", + "mixHash": "aa6a928db9b548ebf20fc9a74e9200321426f1c2db1571636cdd3a33eb162b36", + "header": "f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a09178d0f23c965d81f0834a4c72c6253ce6830f4022b1359aaebfc1ecba442d4ea056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808080a058f759ede17a706c93f13030328bcea40c1d1341fb26f2facd21ceb0dae57017884242424242424242", + "seed": "0000000000000000000000000000000000000000000000000000000000000000", + "result": "3972318778d2af9d3c5c3dfc463bc2a5ebeebd1a7a04392708ff94d29aa18c5f", + "cache_size": 16776896, + "full_size": 1073739904, + "header_hash": "2a8de2adf89af77358250bf908bf04ba94a6e8c3ba87775564a41d269a05e4ce", + "cache_hash": "35ded12eecf2ce2e8da2e15c06d463aae9b84cb2530a00b932e4bbc484cde353" + }, + "second": { + "nonce": "307692cf71b12f6d", + "mixHash": "4a2ef8287dc21f5def0d4e9694208c56e574b1692d7b254822a3f4704d8ad1ba", + "header": "f901f7a01bef91439a3e070a6586851c11e6fd79bbbea074b2b836727b8e75c7d4a6b698a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794ea3cb5f94fa2ddd52ec6dd6eb75cf824f4058ca1a00c6e51346be0670ce63ac5f05324e27d20b180146269c5aab844d09a2b108c64a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302004002832fefd880845511ed2a80a0e55d02c555a7969361cf74a9ec6211d8c14e4517930a00442f171bdb1698d17588307692cf71b12f6d", + "seed": "0000000000000000000000000000000000000000000000000000000000000000", + "result": "5ab98957ba5520d4e367080f442e37a047cfd9d2857b6e00dd12d82900d108a6", + "cache_size": 16776896, + "full_size": 1073739904, + "header_hash": "100cbec5e5ef82991290d0d93d758f19082e71f234cf479192a8b94df6da6bfe", + "cache_hash": "35ded12eecf2ce2e8da2e15c06d463aae9b84cb2530a00b932e4bbc484cde353" + } +} +``` + +## Security Considerations + +There are no known security issues with this change. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3374.md b/EIPS/eip-3374.md new file mode 100644 index 00000000000000..d77d8cf90f2e2e --- /dev/null +++ b/EIPS/eip-3374.md @@ -0,0 +1,58 @@ +--- +eip: 3374 +title: Predictable Proof-of-Work (POW) Sunsetting +author: Query0x (@Query0x) +discussions-to: https://ethereum-magicians.org/t/eip-3374-predictable-proof-of-work-sunsetting +status: Withdrawn +type: Standards Track +category: Core +created: 2021-03-13 +--- + +## Simple Summary +Sets block reward to 3 and reduces it to 1 linearly over the course of about 1 year. + +## Abstract +Sets the block reward to 3 ETH and then incrementally decreases it every block for 2,362,000 blocks (approximately 1 year) until it reaches 1 ETH. + +## Motivation +Unnecessarily abrupt changes to the Ethereum ecosystem cause disruption and disharmony resulting in the disenfranchisement of community members while undermining stability and confidence. While moves from Proof-of-Work to Proof-of-Stake will undoubtedly cause friction between those community members vested in either, all benefit from a measured, predictable transition. + +This proposal: + +1) Is issuance neutral over 1 year, and reduces issuance beyond that. +2) Sets an initial block reward of 3; +3) Introduces an ongoing, predictable reduction in future mining rewards down to 1, effectively "sunsetting" POW and codifying the move to POS; +4) Reduces economic incentives for continued development of ASICs; +5) Allows the impacts of decreasing miner rewards to be measured and monitored rather than relying on conjecture and game theory, so adjustments can be made if necessary. + + +## Specification +### Constants +* `TRANSITION_START_BLOCK_NUMBER: TBD` +* `TRANSITION_DURATION: 2_362_000` // (about one year) +* `TRANSITION_END_BLOCK_NUMBER: FORK_BLOCK_NUMBER + TRANSITION_DURATION` +* `STARTING_REWARD: 3_000_000_000_000_000_000` +* `ENDING_REWARD: 1_000_000_000_000_000_000` +* `REWARD_DELTA: STARTING_REWARD - ENDING_REWARD` +### Block Reward +```py +if block.number >= TRANSITION_END_BLOCK_NUMBER: + block_reward = ENDING_REWARD +elif block.number == TRANSITION_START_BLOCK_NUMBER: + block_reward = STARTING_REWARD +elif block.number > TRANSITION_START_BLOCK_NUMBER: + block_reward = STARTING_REWARD - REWARD_DELTA * TRANSITION_DURATION / (block.number - TRANSITION_START_BLOCK_NUMBER) +``` + +## Rationale +Picking starting and ending block reward values that are equidistant from the current block reward rate of 2 ensures the impact of this EIP will be issuance neutral over the one year time frame. Temporarily raising the block reward to 3 blunts the initial impact of a sudden miner revenue decrease and the continual reductions thereafter codify Ethereum's move to POS by increasingly disincentivizing POW. Importantly, this approach moderates the rate of change so impacts and threats can be measured and monitored. + +## Backwards Compatibility +There are no known backward compatibility issues with the introduction of this EIP. + +## Security Considerations +There are no known security issues with the introduction of this EIP. + +## Copyright +Copyright and related rights waived via CC0. diff --git a/EIPS/eip-3382.md b/EIPS/eip-3382.md new file mode 100644 index 00000000000000..06788cb6911328 --- /dev/null +++ b/EIPS/eip-3382.md @@ -0,0 +1,51 @@ +--- +eip: 3382 +title: Hardcoded Block Gas Limit +author: Philippe Castonguay (@PhABC) +discussions-to: https://ethereum-magicians.org/t/eip-3382-hardcoded-gas-limit +status: Withdrawn +withdrawal-reason: The author prefers [EIP-3756](./eip-3756.md) +type: Standards Track +category: Core +created: 2021-03-13 +--- + +## Simple Summary + +Hardcode the block gas limit to `12,500,000` gas per block. + +## Abstract + +Updates the block validation rules such that a block is invalid if the `gas_limit` header field is not equal to `12,500,000`. + +## Motivation + +Both Ethereum's Proof of Work and Proof of Stake designs assume that block producers are financially rational, but does not assume block producers to be benevolent. There is one exception however, and it is when block producers choose the gas limit of a block where it is assumed that block producers care about the long term health and decentralisation of the chain. Indeed, the block gas limit is one of the only parameters in Ethereum that is not dictated by node consensus, but instead is chosen by block producers. This decision was initially made to allow urgent changes in the block gas limit if necessary. Both drastically increasing or decreasing this parameter could have serious consequences that may not be desired. It is therefore a critical parameter that should require node consensus to avoid any sudden harmful change imposed by a small number of actors on the rest of the network. + +## Specification +Refer to `gasLimit` as `gasTarget` post EIP-1559. + +### Added Consensus Constraint + +As of `FORK_BLOCK_NUMBER`, the `header.gasLimit` **MUST** be equal to `BLOCK_GAS_LIMIT`, where `BLOCK_GAS_LIMIT` is a hardcoded constant set to `12,500,000`. + +## Rationale + +### Keeping gasLimit in Block Headers + +While it would be possible to remove the `gasLimit` field from block headers, it would change the data structure to be hashed, which could lead to unintended consequences. It is therefore easier to leave the gasLimit as part of block headers. + +### Chosen Gas Limit + +The `12,500,000` value is being proposed as it's the current block gas limit as of time of writing this EIP. The actual amount could be altered with a subsequent EIP to avoid deviating from the core intent of this EIP. + +## Backwards Compatibility + +This EIP is backward compatible. + +## Security Considerations +Rapid changes to the gas limit will likely be more difficult to execute, which could be problematic if an urgent situation arise that required changing the gas limit. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3386.md b/EIPS/eip-3386.md new file mode 100644 index 00000000000000..45c38d76ceed16 --- /dev/null +++ b/EIPS/eip-3386.md @@ -0,0 +1,7 @@ +--- +eip: 3386 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3386.md diff --git a/EIPS/eip-3403.md b/EIPS/eip-3403.md new file mode 100644 index 00000000000000..bee317c77b1197 --- /dev/null +++ b/EIPS/eip-3403.md @@ -0,0 +1,134 @@ +--- +eip: 3403 +title: Partial removal of refunds +author: Vitalik Buterin (@vbuterin), Martin Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/eip-3298-removal-of-refunds/5430 +status: Stagnant +type: Standards Track +category: Core +created: 2021-03-16 +--- + +## Simple Summary + +Remove gas refunds for SELFDESTRUCT, and restrict gas refunds for SSTORE to one specific case. + +## Motivation + +Gas refunds for SSTORE and SELFDESTRUCT were originally introduced to motivate application developers to write applications that practice "good state hygiene", clearing storage slots and contracts that are no longer needed. However, they are not widely used for this, and poor state hygiene continues to be the norm. It is now widely accepted that the only solution to state growth is some form of statelessness or state expiry, and if such a solution is implemented, then disused storage slots and contracts would start to be ignored automatically. + +Gas refunds additionally have multiple harmful consequences: + +* Refunds give rise to GasToken. GasToken has benefits in moving gas space from low-fee periods to high-fee periods, but it also has downsides to the network, particularly in exacerbating state size (as state slots are effectively used as a "battery" to save up gas) and inefficiently clogging blockchain gas usage +* Refunds increase block size variance. The theoretical maximum amount of actual gas consumed in a block is nearly twice the on-paper gas limit (as refunds add gas space for subsequent transactions in a block, though refunds are capped at 50% of a transaction's gas used). This is not fatal, but is still undesirable, especially given that refunds can be used to maintain 2x usage spikes for far longer than EIP 1559 can. + +### The mutex usecase + +There are two typical ways to implement mutexes: '0-1-0' and '1-2-1. Let's see how they differ + +- '0-1-0': + - Istanbul: 1612 + - Berlin: 212 + - NoRefund: 20112 + - EIP-3403: 1112 +- '1-2-1': + - Istanbul: 1612 + - Berlin: 212 + - NoRefund: 3012 + - EIP-3403: 3012 + + +**Note**: In reality, there are never a negative gas cost, since the refund is capped at 0.5 * gasUsed. +However, these tables show the negative values, since a more real-world scenario would likely spend the +extra gas on other operations.' + +## Specification + +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | TBD | +| `SSTORE_REFUND_GAS` | 19000 | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +1. Remove the `SELFDESTRUCT` refund. +2. Remove the `SSTORE` refund in all cases except for one specific case: if the _new value_ and _original value_ of the storage slot both equal 0 but the _current value_ does not (those terms being defined as in [EIP-1283](https://eips.ethereum.org/EIPS/eip-1283)), refund `SSTORE_REFUND_GAS` gas. + +## Rationale + +Preserving refunds in the `new = original = 0 != current` case ensures that a few key use cases that deserve favorable gas cost treatment continue to receive favorable gas cost treatment, particularly: + +* Anti-reentrancy locks (typically flipped from 0 to 1 right before a child call begins, and then flipped back to 0 when the child call ends) +* ERC20 approve-and-send (the "approved value" goes from zero to nonzero when the token transfer is approved, and then back to zero when the token transfer processes) + +It also preserves two key goals of EIP 3298: + +1. Gas tokens continue to be non-viable, because each 19000 refund is only possible because of 19000 extra gas that was paid for flipping that storage slot from zero to nonzero earlier in the same transaction, so you can't clear some storage slots and use that saved gas to fill others. +2. The total amount of gas _spent on execution_ is capped at the gas limit. Every 19000 refund for flipping a storage slot non from zero -> zero is only possible because of 19000 extra gas paid for flipping that slot from zero -> nonzero earlier in the same transaction; that gas paid for a storage write and expansion that were both reverted and so do not actually need to be applied to the Merkle tree. Hence, this extra gas does not contribute to risk. + +## Backwards Compatibility + +Refunds are currently only applied _after_ transaction execution, so they cannot affect how much gas is available to any particular call frame during execution. Hence, removing them will not break the ability of any code to execute, though it will render some applications economically nonviable. + +Gas tokens in particular will become valueless. DeFi arbitrage bots, which today frequently use either established gas token schemes or a custom alternative to reduce on-chain costs, would benefit from rewriting their code to remove calls to these no-longer-functional gas storage mechanisms. + +## Test Cases + +### 2929 Gas Costs + +Note, there is a difference between 'hot' and 'cold' slots. This table shows the values as of [EIP-2929](./eip-2929.md) assuming that all touched storage slots were already 'hot' (the difference being a one-time cost of `2100` gas). + +| Code | Used Gas | Refund | Original | 1st | 2nd | 3rd | Effective gas (after refund) +| -- | -- | -- | -- | -- | -- | -- | -- | +| `0x60006000556000600055` | 212 | 0| 0 | 0 | 0 | | 212 | +| `0x60006000556001600055` | 20112 | 0| 0 | 0 | 1 | | 20112 | +| `0x60016000556000600055` | 20112 | 19900| 0 | 1 | 0 | | 212 | +| `0x60016000556002600055` | 20112 | 0| 0 | 1 | 2 | | 20112 | +| `0x60016000556001600055` | 20112 | 0| 0 | 1 | 1 | | 20112 | +| `0x60006000556000600055` | 3012 | 15000| 1 | 0 | 0 | | -11988 | +| `0x60006000556001600055` | 3012 | 2800| 1 | 0 | 1 | | 212 | +| `0x60006000556002600055` | 3012 | 0| 1 | 0 | 2 | | 3012 | +| `0x60026000556000600055` | 3012 | 15000| 1 | 2 | 0 | | -11988 | +| `0x60026000556003600055` | 3012 | 0| 1 | 2 | 3 | | 3012 | +| `0x60026000556001600055` | 3012 | 2800| 1 | 2 | 1 | | 212 | +| `0x60026000556002600055` | 3012 | 0| 1 | 2 | 2 | | 3012 | +| `0x60016000556000600055` | 3012 | 15000| 1 | 1 | 0 | | -11988 | +| `0x60016000556002600055` | 3012 | 0| 1 | 1 | 2 | | 3012 | +| `0x60016000556001600055` | 212 | 0| 1 | 1 | 1 | | 212 | +| `0x600160005560006000556001600055` | 40118 | 19900| 0 | 1 | 0 | 1 | 20218 | +| `0x600060005560016000556000600055` | 5918 | 17800| 1 | 0 | 1 | 0 | -11882 | + +### With EIP-3403 partial refunds + +If refunds were to be partially removed, as specified [here](https://github.com/ethereum/EIPs/pull/3403/), this would be the comparative table. **This table also assumes touched storage slots were already 'hot'**. + +| Code | Used Gas | Refund | Original | 1st | 2nd | 3rd | Effective gas (after refund) +| -- | -- | -- | -- | -- | -- | -- | -- | +| `0x60006000556000600055` | 212 | 0| 0 | 0 | 0 | | 212 | +| `0x60006000556001600055` | 20112 | 0| 0 | 0 | 1 | | 20112 | +| `0x60016000556000600055` | 20112 | 19000| 0 | 1 | 0 | | 1112 | +| `0x60016000556002600055` | 20112 | 0| 0 | 1 | 2 | | 20112 | +| `0x60016000556001600055` | 20112 | 0| 0 | 1 | 1 | | 20112 | +| `0x60006000556000600055` | 3012 | 0| 1 | 0 | 0 | | 3012 | +| `0x60006000556001600055` | 3012 | 0| 1 | 0 | 1 | | 3012 | +| `0x60006000556002600055` | 3012 | 0| 1 | 0 | 2 | | 3012 | +| `0x60026000556000600055` | 3012 | 0| 1 | 2 | 0 | | 3012 | +| `0x60026000556003600055` | 3012 | 0| 1 | 2 | 3 | | 3012 | +| `0x60026000556001600055` | 3012 | 0| 1 | 2 | 1 | | 3012 | +| `0x60026000556002600055` | 3012 | 0| 1 | 2 | 2 | | 3012 | +| `0x60016000556000600055` | 3012 | 0| 1 | 1 | 0 | | 3012 | +| `0x60016000556002600055` | 3012 | 0| 1 | 1 | 2 | | 3012 | +| `0x60016000556001600055` | 212 | 0| 1 | 1 | 1 | | 212 | +| `0x600160005560006000556001600055` | 40118 | 19000| 0 | 1 | 0 | 1 | 21118 | +| `0x600060005560016000556000600055` | 5918 | 0| 1 | 0 | 1 | 0 | 5918 | + +## Security Considerations + +Refunds are not visible to transaction execution, so this should not have any impact on transaction execution logic. + +The maximum amount of gas that can be spent on execution in a block is limited to the gas limit, if we do not count zero-to-nonzero SSTOREs that were later reset back to zero. It is okay to not count those, because if such an SSTORE is reset, storage is not expanded and the client does not need to actually adjust the Merke tree; the gas consumption is refunded, but the effort normally required by the client to process those opcodes is also cancelled. **Clients should make sure to not do a storage write if `new_value = original_value`; this was a prudent optimization since the beginning of Ethereum but it becomes more important now.** + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3416.md b/EIPS/eip-3416.md new file mode 100644 index 00000000000000..b3c50c81b16980 --- /dev/null +++ b/EIPS/eip-3416.md @@ -0,0 +1,104 @@ +--- +eip: 3416 +title: Median Gas Premium +author: HexZorro (@hexzorro), Mojtaba Tefagh (@mtefagh) +discussions-to: https://ethereum-magicians.org/t/eip-3416-median-gas-premium/5755 +status: Stagnant +type: Standards Track +category: Core +created: 2021-03-18 +--- + +## Simple Summary + +A transaction pricing mechanism with a fixed-per-block network fee and a median inclusion fee with additive updates. + +## Abstract + +There is a base fee per gas in protocol, which can move up or down by a maximum of 1/8 in each block. The base fee per gas is adjusted by the protocol to target an average gas usage per block instead of an absolute gas usage per block. The base fee is increased when blocks are over the gas limit target and decreases when blocks are under the gas limit target. Transaction senders specify their fees by providing *only one value*: + +* The fee cap which represents the maximum total (base fee + gas premium) that the transaction sender would be willing to pay to get their transaction included, resembles the current maximum gas price specified by senders but in this protocol change proposal the final gas price paid, most of the time, will be lower than the proposed by the transaction sender. + +Then there is a gas premium that is directly computed as 50% of (fee cap - base fee). This gas premium gets added onto the base fee to calculate the gas price that will be used in the weighted median computation. The gas premium, determined directly by a specified fee cap, can either be set to a fairly low value to compensate miners for uncle rate risk only with the base fee, or to a high value to compete during sudden bursts of activity. Using all transactions that the miner wants to include in the block, a **weighted median gas premium** is computed, not considering in the computation 5% of gas price outliers on the upper-side for extra robustness against miner manipulation. + +## Motivation + +We target the following goals: + +* Gas prices spikes are mathematically smoothed out. EIP1559 does not seems to really tackle gas premium volatility and UX. +* Maintain gas price preference, i.e. transaction senders willing to pay extra in fees will be rewarded with early preferential inclusion in the blocks, because the miners want to maximize their profits and include transactions with higher fee caps first to maximize the median. +* Final gas price paid by the sender is, most of the time, smaller than the maximum gas price specified by sender. +* Gas pricing is more robust to sender manipulation or miner manipulation. + +Ethereum currently prices transaction fees using a simple auction mechanism, where users send transactions with bids ("gasprices") and miners choose transactions with the highest bids, and transactions that get included pay the bid that they specify. This leads to several large sources of inefficiency: + +* **Current extreme volatility of gas prices is hurting user experience**: if you observe online gas price metrics, the current trends in recommended gas prices can change substantially by the minute, making the user experience in the network very awkward. Also, gas volatility makes the mining business more unpredictable and costly, because miners need to spend money hedging the risks. +* **Mismatch between volatility of transaction fee levels and social cost of transactions**: bids to include transactions on mature public blockchains, that have enough usage so that blocks are full, tend to be extremely volatile. On Ethereum, minimum bids range between 1 nanoeth (10^9 nanoeth = 1 ETH), but sometimes go over 100 nanoeth and have reached over 200 nanoeth. This clearly creates many inefficiencies, because it's absurd to suggest that the cost incurred by the network from accepting one more transaction into a block actually is 200x more when gas prices are 200 nanoeth than when they are 1 nanoeth; in both cases, it's a difference between 8 million gas and 8.02 million gas. +* **Needless delays for users**: because of the hard per-block gas limit coupled with natural volatility in transaction volume, transactions often wait for several blocks before getting included, but this is socially unproductive; no one significantly gains from the fact that there is no "slack" mechanism that allows one block to be bigger and the next block to be smaller to meet block-by-block differences in demand. +* **Inefficiencies of first price auctions**: The current approach, where transaction senders publish a transaction with a bid a maximum fee, miners choose the highest-paying transactions, and everyone pays what they bid. This is well-known in mechanism design literature to be highly inefficient, and so complex fee estimation algorithms are required. But even these algorithms often end up not working very well, leading to frequent fee overpayment. We need a more stable fee metric that is computed inside the protocol. + +The proposal in this EIP is to start with a base fee amount which is adjusted up and down by the protocol based on how congested the network is. When the network exceeds the target per-block gas usage, the base fee increases slightly and when capacity is below the target, it decreases slightly. Because these base fee changes are constrained, the maximum difference in base fee from block to block is predictable. This then allows wallets to auto-set the gas fees for users in a highly reliable fashion. It is expected that most users will not have to manually adjust gas fees, even in periods of high network activity. For most users the base fee will be estimated by their wallet and a small gas premium related to the urgency and the priority they want to instill into the transaction. + +## Specification + +### Definitions + +This is a classic fork without a long migration time. + +* `FORK_BLOCK_NUMBER`: TBD. Block number at or after which EIP-3416 transactions are valid. +* `GAS_TARGET_MAX_CHANGE`: `1 // 1024`. +* `BLOCK_GAS_USED`: total gas consumed by transaction included in the block. +* `PARENT_GAS_USED`: same as `BLOCK_GAS_USED` for parent block. +* `CURRENT_BLOCK`: The current block that is being worked with (either being validated, or being produced). +* `BASE_FEE`: 16th item in the block header. Represents the amount of attoeth burned for every unit of gas a transaction uses. +* `PARENT_BASE_FEE`: same as `BASE_FEE` for parent block. +* `BASE_FEE_MAX_CHANGE`: `1 // 8` +* `INITIAL_BASE_FEE` : Median gas price in `FORK_BLOCK_NUMBER - 1`. + +### Process + +* At `block.number == FORK_BLOCK_NUMBER` we set `BASE_FEE = INITIAL_BASE_FEE` +* `BASE_FEE` is set, from `FORK_BLOCK_NUMBER + 1`, as follows + * Let `GAS_DELTA = (PARENT_GAS_USED - PARENT_GAS_TARGET) // PARENT_GAS_TARGET` (possibly negative). + * Set `BASE_FEE = PARENT_BASE_FEE + GAS_DELTA * BASE_FEE_MAX_CHANGE` +* Transactions since `FORK_BLOCK_NUMBER` are encoded the same as the current ones `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` where `v,r,s` is a signature of `rlp([nonce, gasPrice, gasLimit, to, value, data])` and `gasPrice` is the `FEE_CAP` specified by the sender according to this proposal. +* To produce transactions since `FORK_BLOCK_NUMBER`, the new `FEE_CAP` field (maintaining legacy name of `gasPrice` in the transaction) is set as follows (and the `GAS_PREMIUM` is computed as specified): + * `FEE_CAP`: `tx.gasPrice`, serves as the absolute maximum that the transaction sender is willing to pay. + * `GAS_PREMIUM = (FEE_CAP - BASE_FEE) / 2` serves as a sender-preferred median premium to the miner, beyond the base fee. + * If `FEE_CAP < BASE_FEE` then the transaction is considered invalid and cannot be included in the current block, but might be included in future blocks. +* During transaction execution, for EIP3416 transactions we calculate the cost to the `tx.origin` and the gain to the `block.coinbase` as follows: + * Set `GASPRICE = BASE_FEE + median((tx_i.gasPrice - BASE_FEE) / 2)` among all transactions `tx_i` included in the same block, *weighted by gas consumed* and not including the top 5% of outlier gas price in calculation. By weighted median without 5% of the upper-side outliers, we mean that each gas unit spent is ordered according to the corresponding transaction by `BASE_FEE + tx.gasPrice / 2` and then the value chosen will be the one separating the lower 95% in two parts. + * Let `GASUSED` be the gas used during the transaction execution/state transition. + * The `tx.origin` initially pays `GASPRICE * tx.gasLimit`, and gets refunded `GASPRICE * (tx.gasLimit - GASUSED)`. + +The miners can still use a `greedy` strategy to include new transactions in the proposed blocks by adding the transactions ordered by larger `FEE_CAP` first. This is similar to how current blocks are filled, and is a consequence of `FEE_CAP` and `GAS_PREMIUM` being a positive linear function of each other. + +## Rationale + +The rationale behind the premium being 50% of (fee cap - base fee) is that at any given point the average network sender has an average fee cap, and we assume that between base fee and fee cap the sender has no specific preference, as long as the transaction is included in some block. Then, the sender is happy with a median premium among this uniform range. Another justification can be that the user also knows that this new version of the pricing protocol for the complete block uses a median, then is fair for him to apply a median within his preferential range, assuming an uniform sampling there. Simulations ([here](https://hackmd.io/c6kyRNMuTnKf_SlolmevRg#An-improvement-for-the-premium)) with Ethereum gas data shows indeed that median one of the most robust metric.s + +The 5% top outliers removal, not considered in the median, or similar number, is to give extra robustness against miner manipulation, because as current network utilization has been around 97% for the last 6 months the miners can include their own transactions on the empty 3% to try to manipulate and increase the median price (even this manipulation effect will be very small on the final price). + +The rationale for the `BASE_FEE` update formula is that we are using an additive version (`PARENT_BASE_FEE + GAS_DELTA * BASE_FEE_MAX_CHANGE`) to avoid an attack of senders sending this fee to zero. This attack was simulated and observed for multiplicative formula proposed in previous version (`PARENT_BASE_FEE + PARENT_BASE_FEE * GAS_DELTA * BASE_FEE_MAX_CHANGE`). See an article about the attack and the simulation [here](https://mtefagh.github.io/fee/). + +Another rationale for the additive `BASE_FEE` update formula is that it guarantees (see [this](https://pdfs.semanticscholar.org/3d2d/773983c5201b58586af463f045befae5bbf2.pdf) article) that the optimal execution strategy (scheduling broadcasts in order to pay less fee) for a batch of nonurgent transactions is to spread the transactions across different blocks which in turn helps to avoid network congestion and lowers volatility. For the multiplicative formula, it is exactly the reverse, that is, spikes (dumping all your transactions at once) are incentivized as described [here](https://ethresear.ch/t/path-dependence-of-eip-1559-and-the-simulation-of-the-resulting-permanent-loss/8964). + +The rationale for the `BASE_FEE_MAX_CHANGE` being `1 // 8` is that the `BASE_FEE` is designed to be very adaptative to block utilization changes. + +## Backwards Compatibility + +The backward compatibility is very straightforward because there are no new fields added to the transactions. Pricing of the gas per block on the miner/validator side is still fast to compute but a little more complex. Changes only affect miners/validators. Wallets are no affected by this proposal. + +## Test Cases + +TBD. + +## Security Considerations + +* Senders cannot manipulate the minimum fee because the minimum `BASE_FEE` is controlled by the miners with small increments or decrements on each new block proposed. +* Above the `BASE_FEE` the senders have a very limited ability to manipulate and lower the final gas price they pay because they have to move the weighted median close to `BASE_FEE` and, as we know, this is a very robust statistic. +* Miners have a very limited ability to manipulate and raise the final gas price paid by senders above `BASE_FEE` because to influence the final gas price they have to stuff fake transactions beyond the top 5% of the blocks. In average and currently, only the top 3% of the block is empty, so to fill-up 5% of the block they need to start dropping profitable transactions to reach 5%. Only beyond 5% of the top block gas they can start moving the median a little and the median is still a very robust statistic, not liable to being easily manipulated. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3436.md b/EIPS/eip-3436.md new file mode 100644 index 00000000000000..b2476b0c7f9adf --- /dev/null +++ b/EIPS/eip-3436.md @@ -0,0 +1,116 @@ +--- +eip: 3436 +title: Expanded Clique Block Choice Rule +author: Danno Ferrin (@shemnon) +discussions-to: https://ethereum-magicians.org/t/eip-3436-expanded-clique-block-choice-rule/5809 +status: Stagnant +type: Standards Track +category: Core +created: 2021-03-25 +requires: 225 +--- + +## Simple Summary + +Add a four step block rule to Clique that should reduce block production deadlocks + +## Abstract + +The current specification of Clique allows for multiple competing blocks from producers but does not +provide any strategies to pick blocks aside from the current "highest total difficulty" rule. This +EIP proposes a four step choice rule of highest total difficulty, shortest chain, most recently +in-turn, and lowest hash. This would prevent deadlocks that have occurred in production systems. + +## Motivation + +There has been more than one deadlock in the Goerli multi-client Clique network. The number of +active validators was greater than 1/2 of the available validators so a chain halt should not have +occurred. The halt was resolved by an inactive validator coming back on line. The state of the chain +was in one of two configurations of 8 validators that can result in a chain halt. Three of the four +clients observed a choice sequence of lowest total difficulty followed by first observed block. Geth +added one extra rule of preferring the shortest chain before preferring the first observed block. +This fork would have resolved itself with Geth's rule, but there is still a configuration where the +chain can halt with a shortest chain rule. + +## Specification + +When a Clique validator is arbitrating the canonical status between two different chain head blocks, +they should choose the canonical block with the following ordered priorities. + +1. Choose the block with the most total difficulty. +2. Then choose the block with the lowest block number. +3. Then choose the block whose validator had the least recent in-turn block assignment. +4. Then choose the block with the lowest hash. + +When resolving rule 3 clients should use the following formula, where `validator_index` is the integer +index of the validator that signed the block when sorted as per epoch checkpointing, +`header_number` is the number of the header, and `validator_count` is the count of the current +validators. Clients should choose the block with the **largest** value. Note that an in-turn block +is considered to be the most recent in-turn block. + +``` +(header_number - validator_index) % validator_count +``` + +When resolving rule 4 the hash should be converted into an unsigned 256 bit integer. + +## Rationale + +Two scenarios of a halted chain are known based on the current total difficulty then first observed +rule. One of the scenarios is also resistant to the shortest chain rule. + +For the first scenario where chains of different lengths can halt consider a block with 8 +validators, whose addresses sort to the same order as their designation in this example. A fully +in-order chain exists and validator number 8 has just produced an in-turn block and then validators +5, 7 and 8 go offline, leaving validators 1 to 6 to produce blocks. Two forks form, one with an +in-order block from validator 1 and then an out of order block from validator 3. The second fork +forms from validators 2, 4, and 6 in order. Both have a net total difficulty of 3 more than the +common ancestor. So in this case if both forks become aware of the other fork then both are +considered equally viable and neither set of validators should switch to the newly observed fork. In +this case, adding a shortest chain rule would break the deadlock as the even numbered validators +would adopt the shorter chain. + +For the second scenario with the same validator set and in-order chain with validator 7 having just +produced an in order block, then validators 7 and 8 go offline. Two forks form, 1,3,5 on one side +and 2,4,6 on the other. Both forks become aware of the other fork after producing their third block. +In this case both forks have equal total difficulty and equal length. So Geth's rule would not break +the tie and only the arrival of one of the missing validators fix the chain. In a worst case +scenario the odd and even chains would produce a block for 7 and 8 respectively, and chain halt +would result with no validators that have not chosen a fork. Only a manual rollback would fix this. + +One consideration when formulating the rules is that the block choice should be chosen so that it +would encourage the maximum amount of in-order blocks. Selecting a chain based on shortest chain +implicitly prefers the chain with more in-order blocks. When selecting between competing out of +order chains the validator who is closest to producing an in-order block in the future should have +their chain declined so that they are available to produce an in-order block sooner. + +At least one client has been observed producing multiple blocks at the same height with the same +difficulty, so a final catch-all standard of lowest block hash should break any remaining ties. + +## Backwards Compatibility + +The current block choice rules are a mix of most total difficulty and most total difficulty plus +shortest chain. + +As long as the majority of the active validators implement the block choice rules then a client who +only implements the existing difficulty based rule will eventually align with the chain preferred by +these rules. If less than a majority implement these rules then deadlocks can still occur, and +depend on the first observation of problematic blocks, which is no worse than the current situation. + +If clients only partially implement the rule as long as every higher ranked rule is also implemented +then the situation will be no worse than today. + +## Security Considerations + +Malicious and motivated attackers who are participating in the network can force the chain to halt +with well crafted block production. With a fully deterministic choice rule the opportunity to halt +is diminished. Attackers still have the same opportunities to flood the network with multiple blocks +at the same height. A deterministic rule based on the lowest hash reduces the impact of such a +flooding attack. A malicious validator could exploit this deterministic rule to produce a +replacement block. Such an attack exists in current implementations but a deterministic hash rule +makes such replacements more likely. However the impact of such an attack seems low to trivial at +this time. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3440.md b/EIPS/eip-3440.md new file mode 100644 index 00000000000000..f5bffc59f651b3 --- /dev/null +++ b/EIPS/eip-3440.md @@ -0,0 +1,7 @@ +--- +eip: 3440 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3440.md diff --git a/EIPS/eip-3448.md b/EIPS/eip-3448.md new file mode 100644 index 00000000000000..ddc7e16c821104 --- /dev/null +++ b/EIPS/eip-3448.md @@ -0,0 +1,7 @@ +--- +eip: 3448 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3448.md diff --git a/EIPS/eip-3450.md b/EIPS/eip-3450.md new file mode 100644 index 00000000000000..ca9c83ea69128e --- /dev/null +++ b/EIPS/eip-3450.md @@ -0,0 +1,7 @@ +--- +eip: 3450 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3450.md diff --git a/EIPS/eip-3455.md b/EIPS/eip-3455.md new file mode 100644 index 00000000000000..b9083d4a5cd2b1 --- /dev/null +++ b/EIPS/eip-3455.md @@ -0,0 +1,71 @@ +--- +eip: 3455 +title: SUDO Opcode +description: A new opcode is introduced to allow calling from an arbitrary sender address. +author: William Morriss (@wjmelements), Baptiste Vauthey (@thabaptiser) +discussions-to: https://ethereum-magicians.org/t/eip-3455-sudo-opcode/5860 +status: Stagnant +type: Standards Track +category: Core +created: 2021-04-01 +--- + +## Abstract +A new opcode, `SUDO`, is introduced with the same parameters as `CALL`, plus another parameter to specify the sender address. + +## Motivation +There are many use cases for being able to set the sender. + +Many tokens are stuck irretrievably because nobody has the key for the owner address. +In particular, at address zero there is approximately 17 billion USD in tokens and ether, according to etherscan. +With `SUDO`, anyone could free that value, leading to an economic boom that would end poverty and world hunger. +Instead it is sitting there idle like the gold in Fort Knox. +`SUDO` fixes this. + +It is a common mistake to send [ERC-20](./eip-20.md) tokens to the token address instead of the intended recipient. +This happens because users paste the token address into the recipient fields. +Currently there is no way to recover these tokens. +`SUDO` fixes this. + +Many scammers have fraudulently received tokens and ETH via trust-trading. +Their victims currently have no way to recover their funds. +`SUDO` fixes this. + +Large amounts of users have accidentally locked up tokens and ether by losing their private keys. +This is inefficient and provides a bad user experience. +To accommodate new and inexperienced users, there needs to be a way to recover funds after the private key has been lost. +`SUDO` fixes this. + +Finally, there are many tokens and ether sitting in smart contracts locked due to a bug. +We could finally close EIP issue #156. +We cannot currently reclaim ether from stuck accounts. +`SUDO` fixes this. + +## Specification +Adds a new opcode (`SUDO`) at `0xf8`. +`SUDO` pops 8 parameters from the stack. +Besides the sender parameter, the parameters shall match `CALL`. + +1. Gas: Integer; Maximum gas allowance for message call, safely using current gas counter if the counter is lower +2. Sender: Address, truncated to lower 40 bytes; Sets `CALLER` inside the call frame +3. To: Address, truncated to lower 40 bytes; sets `ADDRESS` +4. Value: Integer, raises exception amount specified is less than the value in Sender account; transferred with call to recipient balance, sets `CALLVALUE` +5. InStart: Integer; beginning of memory to use for `CALLDATA` +6. InSize: Integer; length of memory to use for `CALLDATA` +7. OutStart: Integer; beginning of memory to replace with `RETURNDATA` +8. OutSize: Integer; maximum `RETURNDATA` to place in memory + +Following execution, `SUDO` pushes a result value to the stack, indicating success or failure. +If the call ended with `STOP`, `RETURN`, or `SELFDESTRUCT`, `1` is pushed. +If the call ended with `REVERT`, `INVALID`, or an EVM assertion, `0` is pushed. + +## Rationale +The `GAS` parameter is first so that callers can tediously compute how much of their remaining gas to send at the last possible moment. +The remaining parameters inherited from `CALL` are in the same order, with sender inserted between. + + +## Security Considerations +It will be fine. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3475.md b/EIPS/eip-3475.md new file mode 100644 index 00000000000000..cc27918838a153 --- /dev/null +++ b/EIPS/eip-3475.md @@ -0,0 +1,7 @@ +--- +eip: 3475 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3475.md diff --git a/EIPS/eip-3508.md b/EIPS/eip-3508.md new file mode 100644 index 00000000000000..8c22e237901e5b --- /dev/null +++ b/EIPS/eip-3508.md @@ -0,0 +1,100 @@ +--- +eip: 3508 +title: Transaction Data Opcodes +author: Alex Papageorgiou (@alex-ppg) +discussions-to: https://ethereum-magicians.org/t/eip-draft-transaction-data-opcodes/6017 +status: Stagnant +type: Standards Track +category: Core +created: 2021-04-16 +--- + +## Simple Summary + +Provide access to original transaction data. + +## Abstract + +This EIP introduces the following three EVM instructions: `ORIGINDATALOAD`, `ORIGINDATASIZE`, and `ORIGINDATACOPY`. + +These three instructions are meant to provide access to the original transaction's `data` payload, enabling a gas-efficient way of accessing large data payloads in cross-contract calls. + +## Motivation + +As the Ethereum development scene matures, more ambitious and complex features are introduced into smart contracts more often than not requiring the utilization of complex and at times large data structures. Given the inherent limits of the EVM, however, transporting large data structures in between contracts is a costly task that can at times lead to even futile scenarios whereby the gas consumption of such an operation is impossible to execute within the gas limit bounds as well as without sacrificing a large chunk of ETH to facilitate its gas cost. + +The purpose of this EIP is to render these features viable by introducing a way via which multi-contract systems are able to access the same in-memory data source without necessarily transmitting the full payload between them. + +This EIP enables elaborate smart contract features to become part of a larger call-chain by efficiently reading data from the original transaction payload rather than requiring the data to be passed in as call-level data. Its inclusion will mainly benefit advanced trustless schemes to manifest, such as efficient verification of Merkle Patricia trees validating the storage value of a particular Ethereum block or EVM-based layer 2 solutions. + +A side-effect of this change is that smart contract systems relying entirely on origin data inherently guarantee that the data they receive has not been malformed by an intermediate smart contract call. + +## Specification + +### ORIGINDATALOAD (`0x47`), ORIGINDATASIZE (`0x48`) and ORIGINDATACOPY (`0x49`) + +These instructions are meant to operate similarly to their call-prefixed counterparts with the exception that they instead operate on the original `data` of a transaction instead of the current call's data. In detail: + +- ORIGINDATALOAD (`0x47`) performs similarly to CALLDATALOAD (`0x35`) +- ORIGINDATASIZE (`0x48`) performs similarly to CALLDATASIZE (`0x36`) +- ORIGINDATACOPY (`0x49`) performs similarly to CALLDATACOPY (`0x37`) + +As the data is retrieved once again from the execution environment, the costs for the three instructions will be `G_verylow`, `G_base` and `G_base + G_verylow * (number of words copied, rounded up)` respectively. + +The transaction data the `ORIGINDATA*` opcodes operate on will be equivalent to the `calldata` specified in the `args*` parameter to the nearest `AUTHCALL` (`0xf7`) up the stack. If there is no `AUTHCALL` in the stack then `ORIGINDATA*` will operate on the transaction's original `data` field. + +This interaction ensures full compatibility with [EIP-3074](./eip-3074.md) and ensures that no form of discrimination is introduced back into the system by this EIP e.g. by contracts entirely relying on `ORIGINDATA*` and thus allowing only EOAs to supply data to them. + +## Rationale + +### AUTHCALL (`0xf7`) Interaction + +The [EIP-3074](./eip-3074.md) that will be part of the London fork has introduced a new call instruction called `AUTHCALL` (`0xf7`) that will replace a transaction's `ORIGIN` (`0x32`) with the context variable `authorized`. The intention of `AUTHCALL` is to prevent discrimination between smart contracts and EOAs which `ORIGIN` initially facilitated and as a result, it is sensible also replace the values retrieved by the `ORIGINDATA*` opcodes to the ones used in the `AUTHCALL`. + +### Naming Conventions + +The `ORIGIN`-prefixed instructions attempted to conform to the existing naming convention of `CALL`-prefixed instructions given the existence of the `ORIGIN` (`0x32`) instruction which is equivalent to the `CALLER` (`0x33`) instruction but on the original transaction's context. + +### Instruction Address Space + +The instruction address space of the `0x30-0x3f` has been exhausted by calls that already provide information about the execution context of a call so a new range had to be identified that is suitable for the purposes of the EIP. + +Given that the [EIP-1344](./eip-1344.md) `CHAINID` opcode was included at `0x46`, it made sense to include additional transaction-related data beyond it since the Chain ID is also included in transaction payloads apart from the blocks themselves, rendering the `0x46-0x4f` address space reserved for more transaction-related data that may be necessary in the future, such as the EOA's nonce. + +### Gas Costs + +The opcodes ORIGINDATALOAD (`0x47`), ORIGINDATASIZE (`0x48`), and ORIGINDATACOPY (`0x49`) essentially perform the same thing as opcodes CALLDATALOAD (`0x35`), CALLDATASIZE (`0x36`), and CALLDATACOPY (`0x37`) respectively and thus share the exact same gas costs. + +### Instruction Space Pollution + +One can argue that multiple new EVM instructions pollute the EVM instruction address space and could cause issues in assigning sensible instruction codes to future instructions. This particular issue was assessed and a methodology via which the raw RLP encoded transaction may be accessible to the EVM was ideated. This would _future-proof_ the new instruction set as it would be usable for other members of the transaction that may be desired to be accessible on-chain in the future, however, it would also cause a redundancy in the `ORIGIN` opcode. + +## Backwards Compatibility + +The EIP does not alter or adjust existing functionality provided by the EVM and as such, no known issues exist. + +## Test Cases + +TODO. + +## Security Considerations + +### Introspective Contracts + +Atomically, the `ORIGINDATALOAD` and `ORIGINDATACOPY` values should be considered insecure as they can easily be spoofed by creating an entry smart contract with the appropriate function signature and arguments that consequently invokes other contracts within the call chain. In brief, one should always assume that `tx.data != calldata` and these instructions should not be used as an introspection tool alone. + +### Denial-of-Service Attack + +An initial concern that may arise from this EIP is the additional contextual data that must be provided at the software level of nodes to the EVM in order for it to be able to access the necessary data via the `ORIGINDATALOAD` and `ORIGINDATACOPY` instructions. + +This would lead to an increase in memory consumption, however, this increase should be negligible if at all existent given that the data of a transaction should already exist in memory as part of its execution process; a step in the overall inclusion of a transaction within a block. + +### Multi-Contract System Gas Reduction + +Given that most complex smart contract systems deployed on Ethereum today rely on cross-contract interactions whereby values are passed from one contract to another via function calls, the `ORIGIN`-prefixed instruction set would enable a way for smart contract systems to acquire access to the original transaction data at any given step in the call chain execution which could result in cross-contract calls ultimately consuming less gas if the data passed between them is reduced as a side-effect of this change. + +The gas reduction, however, would be an implementation-based optimization that would also be solely applicable for rudimentary memory arguments rather than storage-based data, the latter of which is most commonly utilized in these types of calls. As a result, the overall gas reduction observed by this change will be negligible for most implementations. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3520.md b/EIPS/eip-3520.md new file mode 100644 index 00000000000000..8e83f74a042b28 --- /dev/null +++ b/EIPS/eip-3520.md @@ -0,0 +1,89 @@ +--- +eip: 3520 +title: Transaction Destination Opcode +author: Alex Papageorgiou (@alex-ppg) +discussions-to: https://ethereum-magicians.org/t/eip-3520-transaction-destination-opcode/6058 +status: Stagnant +type: Standards Track +category: Core +created: 2021-04-16 +requires: 3508 +--- + +## Simple Summary + +Provide access to the original recipient of a transaction. + +## Abstract + +This EIP introduces the following EVM instruction: `ENTRYPOINT`. + +This instruction is meant to provide access to the original recipient of the transaction, the `to` address, enabling new ways of introspection to be applied in conjunction with [EIP-3508](./eip-3508.md). + +## Motivation + +It is undeniable that smart contracts are becoming more interconnected than ever. Up until this point, smart contracts have entirely relied on compliant interfaces and introspection to introduce a new step in the call chain of a complex multi-contract interaction. However, this presents a forwards-only approach which limits the types of interactions that can manifest. + +The purpose of this EIP is to provide a way via which a contract is able to identify the entry-point of a transaction on the blockchain and deduce what was the original intention of the transaction by applying introspection on the original transaction data itself. + +This EIP enables the development of new types of smart contracts as it can open new pathways for [EIP-721](./eip-721) NFTs and [EIP-20](./eip-20) tokens to detect which action their transaction is part of, such as detecting a liquidity provision to a decentralized exchange or a loan within a collateralized lending protocol. + +## Specification + +### ENTRYPOINT (`0x4a`) + +The `ENTRYPOINT` instruction uses 0 stack arguments and pushes the original `to` member of the transaction onto the stack. The address yielded by the instruction is a 160-bit value padded to 256-bits. The operation costs `G_base` to execute, similarly to `ORIGIN` (`0x32`). + +The address returned by the `ENTRYPOINT` opcode will be equivalent to the `to` address parameter specified in the nearest `AUTHCALL` up the stack. If there is no `AUTHCALL` in the stack then `ENTRYPOINT` will retrieve the original transaction's `to` field. + +## Rationale + +### AUTHCALL (`0xf7`) Interaction + +The [EIP-3074](./eip-3074.md) introduced a new call instruction called `AUTHCALL` (`0xf7`) that will replace a transaction's `ORIGIN` (`0x32`) with the context variable `authorized`. The intention of `AUTHCALL` is to prevent discrimination between smart contracts and EOAs which `ORIGIN` initially facilitated. The `ENTRYPOINT` opcode by itself re-introduces discrimination into the system as it indirectly allows one to evaluate whether the smart contract code being executed is done so by an EOA by validating that `ENTRYPOINT == ADDRESS` where `ADDRESS` (`0x30`) retrieves the currently executing account address. Therefore, it is sensible also replace the values retrieved by the `ENTRYPOINT` opcode to the target of an `AUTHCALL`. + +This interaction ensures full compatibility with [EIP-3074](./eip-3074.md) and ensures that no form of discrimination is introduced back into the system by this EIP. + +### Naming Conventions + +The `ENTRYPOINT` instruction came to be by defining a sensible name that immediately and clearly depicts what it is meant to achieve by signaling the first interaction of a particular call, i.e. the entry-point. + +### Instruction Address Space + +Equivalent to [EIP-3508](./eip-3508). + +### Gas Cost + +The opcode ENTRYPOINT (`0x4a`) essentially performs the same thing as the opcode ORIGIN (`0x32`) and thus shares the exact same gas cost. + +### Dependency on EIP-3508 + +The `ENTRYPOINT` (`0x4a`) instruction alone has no perceivable benefit as it can be replaced by the `AUTHCALL` (`0xf7`) instruction and as such should solely be introduced to the system in conjunction with the `ORIGINDATA*` opcodes defined in [EIP-3508](./eip-3508.md). + +## Backwards Compatibility + +The EIP does not alter or adjust existing functionality provided by the EVM and as such, no known issues exist. + +## Test Cases + +TODO. + +## Security Considerations + +### Introspective Contracts + +The `ENTRYPOINT` instruction allows the association of the `ORIGINDATALOAD` and `ORIGINDATACOPY` values with a particular smart contract address and interface, enabling introspection to be applied based on the function signature invoked and the arguments provided to reliably deduce the call-path via which a particular smart contract was invoked and allowing a more granular level of interaction to be defined in such special cases. + +However, this type of introspection should solely be applied on pre-approved contracts rather than user-defined ones as the value stemming from this type of introspection entirely relies on a contract's code immutability and proper function, both of which a user supplied contract can easily bypass. + +### Caller Discrimination + +The instructions of this EIP should not be utilized as a way to discriminate between EOA callers and smart contracts, as this type of differentiation can be broken by an `AUTHCALL` as defined in the specification chapter. + +### Contract Creation Behaviour + +The behaviour of the `ENTRYPOINT` opcode during a contract creation will result in the opcode yielding the zero-address as the first address interacted with in the transaction. This should be taken into account by contract implementations in a similar fashion to how `ecrecover` invalid signatures are handled to prevent software misbehaviours from arising. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3521.md b/EIPS/eip-3521.md new file mode 100644 index 00000000000000..b88a08bcd21f6d --- /dev/null +++ b/EIPS/eip-3521.md @@ -0,0 +1,105 @@ +--- +eip: 3521 +title: Reduce access list cost +author: Matt Garnett (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-3521-reduce-access-list-cost/6072 +status: Stagnant +type: Standards Track +category: Core +created: 2021-04-15 +requires: 2028, 2930 +--- + +## Simple Summary + +Reduce the cost of declaring `tx.to` storage keys in access lists. + +## Motivation + +Currently, a transaction must read at least 25 distinct storage slots in `tx.to` +before it's more expensive to forego an access list. + +``` +ACCESS_LIST_ADDRESS_COST + (ACCESS_LIST_STORAGE_KEY_COST + WARM_STORAGE_READ_COST) * x = COLD_SLOAD_COST * x +x = 24 +``` + +EIP-2930 requires the address under which the storage keys reside be declared +explicitly, since it must be added to the EIP-2929 `accessed_addresses` list. +However, `tx.to` is a special case that is added by default, so paying +`ACCESS_LIST_ADDRESS_COST` for `tx.to` is essentially paying twice for the same +address. Avoiding overpayment here will reduce the differential to just 5 unique +reads before using an access list is cheaper -- making them a more attractive +option. + +## Specification + +Treat the first occurrence of `tx.to` in an access list as `calldata` for gas +accounting purposes. Do not charge `ACCESS_LIST_ADDRESS_COST` for it. Storage +keys underneath the address are unaffected. + +If `tx.to == nil`, `tx.to` is defined be the derived contract address created by +the transaction. + +## Rationale + +### Why charge at all? + +EIP-2930 is specifically written to make access lists simple to reason about and +validate. It may be possible to modify the structure of the access list to avoid +including `tx.to` explicitly, but this would renege on the spirit of EIP-2930. + +### Why charge as `calldata`? + +The cost of `calldata` was thoroughly analyzed in EIP-2028 to determine +a fair value that is not susceptible to denial-of-service attacks. We consider +this the lower bound on how much transaction data should cost. Since there is +no computation burden imposed for adding `tx.to` to the `accessed_addresses` +map (it's added by default by [EIP-2929](./eip-2929.md)), there is no reason to charge more than +the absolute minimum for the data. + +## Test Cases +``` +{ + "0xffffffffffffffffffffffffffffffffffffffff": [] +} +cost = 320 + +{ + "0x00ffffffffffffffffffffffffffffffffffffff": [] +} +cost = 308 + +{ + "0xffffffffffffffffffffffffffffffffffffffff": [] + "0xffffffffffffffffffffffffffffffffffffffff": [] +} +cost = 2720 + +{ + "0xffffffffffffffffffffffffffffffffffffffff": [ + "0x00" + ] + "0xffffffffffffffffffffffffffffffffffffffff": [] +} +cost = 4620 + +{ + "0xffffffffffffffffffffffffffffffffffffffff": [ + "0x00" + ] + "0xffffffffffffffffffffffffffffffffffffffff": [ + "0x00" + ] +} +cost = 6520 +``` + +## Backwards Compatibility +No issues. + +## Security Considerations +None. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3525.md b/EIPS/eip-3525.md new file mode 100644 index 00000000000000..dc908298645131 --- /dev/null +++ b/EIPS/eip-3525.md @@ -0,0 +1,7 @@ +--- +eip: 3525 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3525.md diff --git a/EIPS/eip-3529.md b/EIPS/eip-3529.md new file mode 100644 index 00000000000000..f962230d6f7855 --- /dev/null +++ b/EIPS/eip-3529.md @@ -0,0 +1,140 @@ +--- +eip: 3529 +title: Reduction in refunds +author: Vitalik Buterin (@vbuterin), Martin Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/eip-3529-reduction-in-refunds-alternative-to-eip-3298-and-3403-that-better-preserves-existing-clearing-incentives/6097 +status: Final +type: Standards Track +category: Core +created: 2021-04-22 +requires: 2200, 2929, 2930 +--- + +## Simple Summary + +Remove gas refunds for `SELFDESTRUCT`, and reduce gas refunds for `SSTORE` to a lower level where the refunds are still substantial, but they are no longer high enough for current "exploits" of the refund mechanism to be viable. + +## Motivation + +Gas refunds for `SSTORE` and `SELFDESTRUCT` were originally introduced to motivate application developers to write applications that practice "good state hygiene", clearing storage slots and contracts that are no longer needed. However, the benefits of this technique have proven to be far lower than anticipated, and gas refunds have had multiple unexpected harmful consequences: + +* Refunds give rise to GasToken. GasToken has benefits in moving gas space from low-fee periods to high-fee periods, but it also has downsides to the network, particularly in exacerbating state size (as state slots are effectively used as a "battery" to save up gas) and inefficiently clogging blockchain gas usage +* Refunds increase block size variance. The theoretical maximum amount of actual gas consumed in a block is nearly twice the on-paper gas limit (as refunds add gas space for subsequent transactions in a block, though refunds are capped at 50% of a transaction's gas used). This is not fatal, but is still undesirable, especially given that refunds can be used to maintain 2x usage spikes for far longer than EIP-1559 can. + + +## Specification + +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | TBD | +| `MAX_REFUND_QUOTIENT` | 5 | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +1. Remove the `SELFDESTRUCT` refund. +2. Replace `SSTORE_CLEARS_SCHEDULE` (as defined in [EIP-2200](./eip-2200.md)) with `SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST` (4,800 gas as of [EIP-2929](./eip-2929.md) + [EIP-2930](./eip-2930.md)) +3. Reduce the max gas refunded after a transaction to `gas_used // MAX_REFUND_QUOTIENT` + +Remark: Previously _max gas refunded_ was defined as `gas_used // 2`. Here we +name the constant `2` as `MAX_REFUND_QUOTIENT` and change its value to `5`. + +## Rationale + +In [EIP-2200](./eip-2200.md#specification), three cases for refunds were introduced: + +1. If the original value is nonzero, and the new value is zero, add `SSTORE_CLEARS_SCHEDULE` (currently 15,000) gas to the refund counter +2. If the original value is zero, the current value is nonzero, and the new value is zero, add `SSTORE_SET_GAS - SLOAD_GAS` (currently 19,900) gas to the refund counter +3. If the original value is nonzero, the current value is a different nonzero value, and the new value equals the original value, add `SSTORE_RESET_GAS - SLOAD_GAS` (currently 4,900) gas to the refund counter + +Of these three, only (1) enables gastokens and allows a block to expend more gas on execution than the block gas limit. (2) does not have this property, because for the 19,900 refund to be obtained, _the same storage slot_ must have been changed from zero to nonzero previously, costing 20,000 gas. The inability to obtain gas from clearing one storage slot and use it to edit another storage slot means that it cannot be used for gas tokens. Additionally, obtaining the refund requires _reverting_ the effect of the storage write and expansion, so the refunded gas does not contribute to a client's load in processing a block. (3) behaves similarly: the 4,900 refund can only be obtained when 5,000 gas had previously been spent on the same storage slot. + +This EIP deals with case (1). We can establish under what conditions a gastoken is nonviable (ie. you cannot get more gas out of a storage slot than you put in) by using a similar "pairing" argument, mapping each refund to a previous expenditure in the same transaction on the same storage slot. lf a storage slot is changed to zero when its original value is nonzero, there are two possibilities: + +1. This could be the first time that the storage slot is set to zero. In this case, we can pair this event with the `SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST` minimum cost of reading and editing the storage slot for the first time. +2. This could be the second or later time that the storage slot is set to zero. In this case, we can pair this event with the most recent previous time that the value was set _away_ from zero, in which `SSTORE_CLEARS_SCHEDULE` gas is _removed_ from the refund. + +For the second and later event, it does not matter what value `SSTORE_CLEARS_SCHEDULE` has, because every refund of that size is paired with a refund _removal_ of the same size. This leaves the first event. For the total gas expended on the slot to be guaranteed to be positive, we need `SSTORE_CLEARS_SCHEDULE <= SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST`. And so this EIP simply decreases `SSTORE_CLEARS_SCHEDULE` to the sum of those two costs. + +One alternative intuition for this EIP is that there will not be a net refund for clearing data that has not yet been read (which is often "useless" data), but there will continue to be a net refund for clearing data that has been read (which is likely to be "useful" data). + +## Backwards Compatibility + +Refunds are currently only applied _after_ transaction execution, so they cannot affect how much gas is available to any particular call frame during execution. Hence, removing them will not break the ability of any code to execute, though it will render some applications economically nonviable. + +Gas tokens will become valueless. DeFi arbitrage bots, which today frequently use either established gas token schemes or a custom alternative to reduce on-chain costs, would benefit from rewriting their code to remove calls to these no-longer-functional gas storage mechanisms. + +However, fully preserving refunds in the `new = original = 0 != current` case, and keeping _some_ refund in the other `nonzero -> zero` cases, ensures that a few key use cases that receive (and deserve) favorable gas cost treatment continue to do so. For example, `zero -> nonzero -> zero` storage set patterns continue to cost only ~100 gas. Two important examples of such patterns include: + +* Anti-reentrancy locks (typically flipped from 0 to 1 right before a child call begins, and then flipped back to 0 when the child call ends) +* ERC20 approve-and-send (the "approved value" goes from zero to nonzero when the token transfer is approved, and then back to zero when the token transfer processes) + +### Effect on storage clearing incentives + +A criticism of earlier refund removal EIPs ([EIP-3298](./eip-3298.md) and [EIP-3403](./eip-3403.md)) is that these EIPs fully remove the incentive to set a value to zero, encouraging users to not fully clear a storage slot if they expect even the smallest probability that they will want to use that storage slot again. + +For example, if you have 1 unit of an ERC20 token and you are giving away or selling your entire balance, you could instead only give away 0.999999 units and leave the remainder behind. If you ever decide to re-acquire more of that token with the same account in the future, you would only have to pay 5000 gas (2100 for the read + 2900 for nonzero-to-nonzero set) for the `SSTORE` instead of 22100 (20000 for the zero-to-nonzero set). Today, this is counterbalanced by the 15000 refund for clearing, so you only have an incentive to do this if you are more than `15000 / 17100 = 87.7%` sure that you will use the slot again; with EIP-3298 or EIP-3403 the counterbalancing incentive would not exist, so setting to nonzero is better if your chance of using the slot again is _any_ value greater than 0%. + +A refund of 4800 gas remains, so there is only be an incentive to keep a storage slot nonzero if you expect a probability of more than `4800 / 17100 = 28.1%` that you will use that slot again. This is not perfect, but it is likely higher than the average person's expectations of later re-acquiring a token with the same address if they clear their entire balance of it. + +The capping of refunds to 1/5 of gas expended means that this refund can only be used to increase the amount of storage write operations needed to process a block by at most 25%, limiting the ability to use this mechanic for storage-write-focused denial-of-service attacks. + +## Test Cases + +### EIP-2929 Gas Costs + +Note, there is a difference between 'hot' and 'cold' slots. This table shows the values as of [EIP-2929](./eip-2929.md) assuming that all touched storage slots were already 'hot' (the difference being a one-time cost of `2100` gas). + +| Code | Used Gas | Refund | Original | 1st | 2nd | 3rd | Effective gas (after refund) +| -- | -- | -- | -- | -- | -- | -- | -- | +| `0x60006000556000600055` | 212 | 0| 0 | 0 | 0 | | 212 | +| `0x60006000556001600055` | 20112 | 0| 0 | 0 | 1 | | 20112 | +| `0x60016000556000600055` | 20112 | 19900| 0 | 1 | 0 | | 212 | +| `0x60016000556002600055` | 20112 | 0| 0 | 1 | 2 | | 20112 | +| `0x60016000556001600055` | 20112 | 0| 0 | 1 | 1 | | 20112 | +| `0x60006000556000600055` | 3012 | 15000| 1 | 0 | 0 | | -11988 | +| `0x60006000556001600055` | 3012 | 2800| 1 | 0 | 1 | | 212 | +| `0x60006000556002600055` | 3012 | 0| 1 | 0 | 2 | | 3012 | +| `0x60026000556000600055` | 3012 | 15000| 1 | 2 | 0 | | -11988 | +| `0x60026000556003600055` | 3012 | 0| 1 | 2 | 3 | | 3012 | +| `0x60026000556001600055` | 3012 | 2800| 1 | 2 | 1 | | 212 | +| `0x60026000556002600055` | 3012 | 0| 1 | 2 | 2 | | 3012 | +| `0x60016000556000600055` | 3012 | 15000| 1 | 1 | 0 | | -11988 | +| `0x60016000556002600055` | 3012 | 0| 1 | 1 | 2 | | 3012 | +| `0x60016000556001600055` | 212 | 0| 1 | 1 | 1 | | 212 | +| `0x600160005560006000556001600055` | 40118 | 19900| 0 | 1 | 0 | 1 | 20218 | +| `0x600060005560016000556000600055` | 5918 | 17800| 1 | 0 | 1 | 0 | -11882 | + +### With reduced refunds + +If refunds were to be partially removed, by changing `SSTORE_CLEARS_SCHEDULE` from 15000 to 4800 (and removing selfdestruct refund) this would be the comparative table. + +| Code | Used Gas | Refund | Original | 1st | 2nd | 3rd | Effective gas (after refund) +| -- | -- | -- | -- | -- | -- | -- | -- | +| `0x60006000556000600055` | 212 | 0| 0 | 0 | 0 | | 212 | +| `0x60006000556001600055` | 20112 | 0| 0 | 0 | 1 | | 20112 | +| `0x60016000556000600055` | 20112 | 19900| 0 | 1 | 0 | | 212 | +| `0x60016000556002600055` | 20112 | 0| 0 | 1 | 2 | | 20112 | +| `0x60016000556001600055` | 20112 | 0| 0 | 1 | 1 | | 20112 | +| `0x60006000556000600055` | 3012 | 4800| 1 | 0 | 0 | | -1788 | +| `0x60006000556001600055` | 3012 | 2800| 1 | 0 | 1 | | 212 | +| `0x60006000556002600055` | 3012 | 0| 1 | 0 | 2 | | 3012 | +| `0x60026000556000600055` | 3012 | 4800| 1 | 2 | 0 | | -1788 | +| `0x60026000556003600055` | 3012 | 0| 1 | 2 | 3 | | 3012 | +| `0x60026000556001600055` | 3012 | 2800| 1 | 2 | 1 | | 212 | +| `0x60026000556002600055` | 3012 | 0| 1 | 2 | 2 | | 3012 | +| `0x60016000556000600055` | 3012 | 4800| 1 | 1 | 0 | | -1788 | +| `0x60016000556002600055` | 3012 | 0| 1 | 1 | 2 | | 3012 | +| `0x60016000556001600055` | 212 | 0| 1 | 1 | 1 | | 212 | +| `0x600160005560006000556001600055` | 40118 | 19900| 0 | 1 | 0 | 1 | 20218 | +| `0x600060005560016000556000600055` | 5918 | 7600| 1 | 0 | 1 | 0 | -1682 | + +## Security Considerations + +Refunds are not visible to transaction execution, so this should not have any impact on transaction execution logic. + +The maximum amount of gas that can be spent on execution in a block is limited to the gas limit, if we do not count zero-to-nonzero `SSTORE`s that were later reset back to zero. It is okay to not count those, because if such an `SSTORE` is reset, storage is not expanded and the client does not need to actually adjust the Merke tree; the gas consumption is refunded, but the effort normally required by the client to process those opcodes is also cancelled. **Clients should make sure to not do a storage write if `new_value = original_value`; this was a prudent optimization since the beginning of Ethereum but it becomes more important now.** + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3534.md b/EIPS/eip-3534.md new file mode 100644 index 00000000000000..2876b58f15765c --- /dev/null +++ b/EIPS/eip-3534.md @@ -0,0 +1,312 @@ +--- +eip: 3534 +title: Restricted Chain Context Type Transactions +author: Isaac Ardis (@whilei) +discussions-to: https://ethereum-magicians.org/t/eip-3534-restricted-chain-context-transaction-type/6112 +status: Stagnant +type: Standards Track +category: Core +created: 2021-04-20 +requires: 2718, 2930 +--- + +## Simple Summary + +Defines a new transaction type with constraints on ancestor block hash, block author, and/or block timestamp. + +## Abstract + +We introduce a new EIP-2718 transaction type with the format `0x4 || rlp([chainId, chainContext, nonce, gasPrice, gasLimit, to, value, data, access_list, yParity, senderR, senderS])`. + +This proposed `chainContext` element adds a constraint on the validity of a transaction to a chain segment meeting the referenced value(s). Four contexts are defined as subclasses of this type: + +- `segmentId` +- `eligibleMinerList` +- `ineligibleMinerList` +- `expiry` + +These contexts can be used in arbitrary combinations. Annotated context value combinations are referenced by a composite integer prefix on the annotation. + +## Motivation + +Establish a protocol-based mechanism with which transactions are able to articulate constraints on eligible chain contexts. +Generally, these constraints give the consumer (the transactor) an ability to express requirements about the transaction's relationship to blockchain data and its provenance. + +- Restrict transaction applicability to a chain context that is currently available and reasoned about under some subjective view. + - Introduces a way for transactions to describe a dependency on their current view of a chain. +- Restrict transaction applicability to a chain context following some foregoing block (and its transactions). + - Introduces a way for transactions to describe ancestral dependencies at a "macro" (block) level. + Indirectly, this offers a way for a transaction to depend on the presence of another, so long as the dependent transaction is in a different block. +- Restrict transaction applicability to blocks benefitting, or _not_ benefitting, a preferred/spurned miner address or addresses. + - Introduces an opportunity/market for miners to compete for consumers' transactions; under the status quo, the current miner-transaction processing service is almost perfectly homogeneous from the consumer perspective. +- Restrict transaction applicability time span. + - Introduces an alternative (to the status quo) way for consumers/transactors to have transactions invalidated/ejected from the transaction pool. + +## Specification + +### Parameters + +- `FORK_BLOCK_NUMBER` `TBD` +- `TRANSACTION_TYPE_NUMBER` `0x4`. See EIP-2718. + +As of `FORK_BLOCK_NUMBER`, a new EIP-2718 transaction is introduced with `TransactionType` `TRANSACTION_TYPE_NUMBER`. + +The EIP-2718 `TransactionPayload` for this transaction is `rlp([chainId, chainContext, nonce, gasPrice, gasLimit, to, value, data, access_list, yParity, senderR, senderS])`. + +The EIP-2718 `ReceiptPayload` for this transaction is `rlp([status, cumulativeGasUsed, logsBloom, logs])`. + +### Definitions + +- `chainContext`. The transaction is only valid for blockchain data satisfying ALL OF the annotations. +- `ANNOTATION_COMPOSITE_PREFIX`. A positive integer between `1` and `0xff` that represents the set of subclass annotations in the `chainContext` (_ie._ _which_ chain context subclasses should the provided values be applied to). This value should be the sum of the subclass' `ANNOTATION_PREFIX`s. +- `ANNOTATION_PREFIX`s are defined for Subclasses as octal-derived positive integers, limited to the set `2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7`. + +The `chainContext` value should be of the form `ANNOTATION_COMPOSITE_PREFIX || [{subclass value}...]`, where +- `...` means "zero or more of the things to the left," and +- `||` denotes the byte/byte-array concatenation operator. + +The `chainContext` value should be encoded as `ANNOTATION_COMPOSITE_PREFIX || rlp[{subclass value}...]`. + +### Validation + +The values defined as subclasses below acts as constraints on transaction validity for specific chain contexts. +Transactions defining constraints which are not satisfied by their chain context should be rejected as invalid. +Blocks containing invalid transactions should be rejected as invalid themselves, per the _status quo_. + +### Subclass Combination + +`chainContext` values annotating more than one subclass reference should provide those values in the following sequential order: + +1. `ANCESTOR_ID` +2. `ELIGIBLE_MINER_LIST` +3. `INELIGIBLE_MINER_LIST` +4. `EXPIRY` + +As above, the `ANNOTATION_COMPOSITE_PREFIX` should be the sum of the designated subclass' `ANNOTATION_PREFIX`s. +### Subclasses + +- An `ANNOTATION_PREFIX` value is used to represent each of the available context subclasses. + +#### `ancestorId` + +- `ANNOTATION_PREFIX` `1`. +- `ANCESTOR_ID` `bytes`. A byte array between 4 and 12 bytes in length. + +The `ANCESTOR_ID` is a reference to a specific block by concatenating the byte representation of a block number and the first 4 bytes of its hash. +The block number's should be encoded as a big endian value and should have left-padding 0's removed. +The block number value may be omitted in case of reference to the genesis block. + +The `ANCESTOR_ID` value should be RLP encoded as a byte array for hashing and transmission. + +#### `eligibleMinerList` + +- `ANNOTATION_PREFIX` `2`. +- `ELIGIBLE_MINER_LIST` `[address...]`. A list of addresses. +- `MAX_ELEMENTS` `3`. The maximum number of addresses that can be provided. + +The `ELIGIBLE_MINER_LIST` value is an array of unique, valid addresses. +Any block containing a transaction using this value must have a block beneficiary included in this set. + +The `ELIGIBLE_MINER_LIST` value should be of the type `[{20 bytes}+]`, where `+` means "one or more of the thing to the left." +Non-unique values are not permitted. + +The `ELIGIBLE_MINER_LIST` value should be RLP encoded for hashing and transmission. + +An `ELIGIBLE_MINER_LIST` value may NOT be provided adjacent to an `INELIGIBLE_MINER_LIST` value. + +#### `ineligibleMinerList` + +- `ANNOTATION_PREFIX` `4`. +- `INELIGIBLE_MINER_LIST` `[address...]`. A list of addresses. +- `MAX_ELEMENTS` `3`. The maximum number of addresses that can be provided. + +The `INELIGIBLE_MINER_LIST` value is an array of unique, valid addresses. +Any block containing a transaction using this value must not have a block beneficiary included in this set. + +The `INELIGIBLE_MINER_LIST` value should be of the type `[{20 bytes}+]`, where `+` means "one or more of the thing to the left." +Non-unique values are not permitted. + +The `INELIGIBLE_MINER_LIST` value should be RLP encoded for hashing and transmission. + +An `INELIGIBLE_MINER_LIST` value may NOT be provided adjacent to an `ELIGIBLE_MINER_LIST` value. + +#### `expiry` + +- `ANNOTATION_PREFIX` `8`. +- `EXPIRY` `integer`. A positive, unsigned scalar. + +The `EXPIRY` value is a scalar equal to the maximum valid block `timestamp` for a block including this transaction. + +The `EXPIRY` value should be RLP encoded as an integer for hashing and transmission. + +## Rationale + +### Subclasses + +Subclasses are defined with a high level of conceptual independence, and can be modified and/or extended independently from this EIP. +Their specification definitions allow arbitrary mutual (`AND`) combinations. + +This design is intended to form a proposal which offers a concrete set of specifics while doing so with enough flexibility for extension or modification later. + +#### `ANNOTATION_PREFIX` + +`ANNOTATION_PREFIX` values' use of octal-derived values, ie. `1, 2, 4, 8, 16, 32, 64, 128`, follows a conventional pattern of representing combinations from a limited set uniquely and succinctly, eg. Unix-style file permissions. +This EIP defines four of the eight possible context subclasses; this seems to leave plenty of room for future growth in this direction if required. +If this limit is met or exceeded, doing so will require a hard fork _de facto_ (by virtue of making consensus protocol facing changes to transaction validation schemes), so revising this scheme as needed should be only incidental and trivial. + +#### `ancestorId` + +Constrains the validity of a transaction by referencing a prior canonical block by number and hash. +The transaction is only valid when included in a block which has the annotated block as an ancestor. + +Practically, the "designated allowable chain segment" can be understood as the segment of blocks from `0..ancestorId` inclusive. + +##### Redundancy to `chainId` + +This pattern can be understood as a correlate of [EIP-155](./eip-155)'s `chainId` specification. +EIP155 defines the restriction of transactions between chains; limiting the applicability of any EIP-155 transaction to a chain with the annotated ChainID. +`ancestorId` further restricts transaction application to one subsection ("segment") of one chain. + +From this constraint hierarchy, we note that an implementation of `ancestorId` can make `chainId` conceptually redundant. + +##### So why keep `chainId`? + +`chainId` is maintained as an invariant because: + +- The use of the transaction type proposed by this EIP is optional, implying the continued necessity of `chainId` in the protocol infrastructure and tooling for legacy and other transaction types. +- The presence of `ancestorId` in the transaction type proposed by this EIP is optional. If the value is not filled by an RCC transaction, the demand for `chainId` remains. +- A `chainId` value is not necessarily redundant to `ancestorId`, namely in cases where forks result in living chains. For example, an `ancestorId` reference to block `1_919_999` would be ambiguous between Ethereum and Ethereum Classic. +- It would be possible to specify the omission of `chainId` in case of `ancestorId`'s use. This would add infrastructural complexity for the sake of removing the few bytes `chainId` typically requires; we do not consider this trade-off worth making. + - `chainId` is used as the `v` value (of `v,r,s`) in the transaction signing scheme; removing or modifying this incurs complexity at a level below encoded transaction fields, demanding additional infrastructural complexity for implementation. +- The proposed design for `ancestorId` does not provide perfect precision (at the benefit of byte-size savings). + In the small chance that the value is ambiguous, the `chainId` maintains an infallible guarantee for a transaction's chain specificity. + +#### `eligibleMinerList` + +The transaction is only valid when included in a block having an `etherbase` contained in the annotated list of addresses. +The use of "whitelist" (`eligibleMinerList`) in conjunction with a "blacklist" (`ineligibleMinerList`) is logically inconsistent; their conjunction is not allowed. + +A `MAX_ELEMENTS` limit of `3` is chosen to balance the interests of limiting the potential size of transactions, and to provide a sufficient level of articulation for the user. At the time of writing, the top 3 miners of Ethereum (by block, measured by known public addresses) account for 52% of all blocks produced. + +#### `ineligibleMinerList` + +The transaction is only valid when included in a block having an `etherbase` _not_ contained in the annotated list of addresses. +The use of "blacklist" (`ineligibleMinerList`) in conjunction with a "whitelist" (`eligibleMinerList`) is logically inconsistent; their conjunction is not allowed. + +A `MAX_ELEMENTS` limit of `3` is chosen to balance the interests of limiting the potential size of transactions, and to provide a sufficient level of articulation for the user. At the time of writing, the top 3 miners of Ethereum (by block, measured by known public addresses) account for 52% of all blocks produced. + +#### `expiry` + +The transaction is only valid when included in a block having a `timestamp` less than the value annotated. +A positive integer is used because that corresponds to the specified type of block `timestamp` header values. + +### Subclass Combination + +Since subclasses use octal-based values for `ANNOTATION_PREFIX`, they can be distinguishably combined as sums, provided as we assume annotation cardinality (ie ordering). +For example: + +- `ANNOTATION_PREFIX` `1` signals `ancestorId` exclusively. +- `ANNOTATION_PREFIX` `2` signals `eligibleMinerList` exclusively. +- `ANNOTATION_PREFIX` `4` signals `ineligibleMinerList` exclusively. +- `ANNOTATION_PREFIX` `8` signals `expiry` exclusively. +- `ANNOTATION_PREFIX` `1+2=3` combines `ancestorId` and `eligibleMinerList`. +- `ANNOTATION_PREFIX` `1+4=5` combines `ancestorId` and `ineligibleMinerList`. +- `ANNOTATION_PREFIX` `1+8=9` combines `ancestorId` and `expiry`. +- `ANNOTATION_PREFIX` `1+2+8=11` combines `ancestorId` and `eligibleMinerList` and `expiry`. +- `ANNOTATION_PREFIX` `1+4+8=13` combines `ancestorId` and `ineligibleMinerList` and `expiry`. +- `ANNOTATION_PREFIX` `2+4=6` is NOT PERMITTED. It would combine `eligibleMinerList` and `ineligibleMinerList`. +- `ANNOTATION_PREFIX` `1+2+4+8=15` is NOT PERMITTED. It would combine `eligibleMinerList` and `ineligibleMinerList` (and `ancestorId` and `expiry`). + +Since ordering is defined and demanded for multiple values, annotated references remain distinguishable. For example: + +- `chainContext` `3[e4e1c0e78b1ec3,[Df7D7e053933b5cC24372f878c90E62dADAD5d42]]` - Transaction can only be included in a block having a canonical ancestor block numbered `15_000_000` and with a hash prefixed with the bytes `e78b1ec3`, and if the containing block uses `Df7D7e053933b5cC24372f878c90E62dADAD5d42` as the beneficiary. +- `chainContext` `10[[Df7D7e053933b5cC24372f878c90E62dADAD5d42],1619008030]` - Transaction can only be included in a block naming `Df7D7e053933b5cC24372f878c90E62dADAD5d42` as the `etherbase` beneficiary, and which has a timestamp greater than `1619008030` (Wed Apr 21 07:27:10 CDT 2021). + + +### EIP-2930 Inheritance +The [EIP-2930 Optional Access List Type Transaction](https://eips.ethereum.org/EIPS/eip-2930) is used as an assumed "base" transaction type for this proposal. +However, this is NOT a conceptual dependency; the included `accessList` portion of this proposal (the only differential from post-EIP-155 legacy transaction fields) can readily be removed. +Standing on the shoulders of EIP-2930 is only intended to support and further the adoption of next-generation transactions. + +### Signature target + +The signature signs over the transaction type as well as the transaction data. +This is done to ensure that the transaction cannot be “re-interpreted” as a transaction of a different type. + +## Backwards Compatibility + +There are no known backward compatibility issues. + +## Test Cases + +| Segment ID | Block Number | Canonical Block Hash | +| --- | --- | --- | +| `e78b1ec3` | `0` | `0xe78b1ec31bcb535548ce4b6ef384deccad1e7dc599817b65ab5124eeaaee3e58` | +| `01e78b1ec3` | `1` | `0xe78b1ec31bcb535548ce4b6ef384deccad1e7dc599817b65ab5124eeaaee3e58` | +| `e4e1c0e78b1ec3` | `15_000_000` | `0xe78b1ec31bcb535548ce4b6ef384deccad1e7dc599817b65ab5124eeaaee3e58` | +| `e8d4a50fffe78b1ec3` | `999_999_999_999` | `0xe78b1ec31bcb535548ce4b6ef384deccad1e7dc599817b65ab5124eeaaee3e58` | +| `7fffffffffffffffe78b1ec3` | `9223372036854775807` | `0xe78b1ec31bcb535548ce4b6ef384deccad1e7dc599817b65ab5124eeaaee3e58` | + +Further test cases, TODO. + +## Security Considerations + +### Why 4 bytes of a block hash is "safe enough" for the `ancestorId` + +__TL;DR__: The chance of an ineffectual `ancestorId` is about 1 in between ~4 billion and ~40 billion, with the greater chance for intentional duplication scenarios, eg. malicious reorgs. + +__If a collision _does_ happen__, that means the transaction will be valid on both segments (as is the case under the status quo). + +Four bytes, instead of the whole hash (32 bytes), was chosen only to reduce the amount of information required to cross the wire to implement this value. +Using the whole hash would result in a "perfectly safe" implementation, and every additional byte reduces the chance of collision exponentially. + +The goal of the `ancestorId` is to disambiguate one chain segment from another, and in doing so, enable a transaction to define with adequate precision which chain it needs to be on. +When a transaction's `ancestorId` references a block, we want to be pretty sure that that reference won't get confused with a different block than the one the author of the transaction had in mind. + +We assume the trait of collision resistance is uniformly applicable to all possible subsets of the block hash value, so our preference of using the _first_ 4 bytes is arbitrary and functionally equivalent to any other subset of equal length. + +For the sake of legibility and accessibility, the following arguments will reference the hex representation of 4 bytes, which is 8 characters in length, eg. `e78b1ec3`. + +The chance of a colliding `ancestorId` is `1/(16^8=4_294_967_296)` times whatever we take the chance of the existence of an equivalently-numbered block (on an alternative chain) to be. Assuming a generous ballpark chance of 10% (`1/10`) for any given block having a public uncle, this yields `(1/(16^8=4_294_967_296) * 1/10`. Note that this ballpark assumes "normal" chain and network behavior. In the case of an enduring competing chain segment, this value rises to 100% (`1`). + +### `eligibleMinerList` + +Miners who do not find themselves listed in an annotated `eligibleMinerList` should be expected to immediately remove the transaction from their transaction pool. + +In a pessimistic outlook, we should also expect that these ineligible nodes would not offer rebroadcasts of these transactions, potentially impacting the distribution (and availability) of the transactions to their intended miners. On the other hand, miners are incentivized to make themselves available for reception of such transactions, and there are many ways this is feasible both on-network and off-. + +The author of a transaction using the `eligibleMinerList` must assume that the "general availability" of the blockchain state database for such a transaction will be lower than a nonrestrictive transaction (since only a subset of miners will be able to process the transaction). + +A final consideration is the economics of a whitelisted miner concerning the processing order of transactions in which they are whitelisted and those without whitelists. +Transactions without whitelists would appear at first glean to be more competitive, and thus should be processed with priority. +However, miners following such a strategy may find their reputation diminished, and, in the worst case, see the assertive preferences of transaction authors shift to their competitors and beyond their reach. + +### `ineligibleMinerList` + +In addition to the concerns and arguments presented by `eligibleMinerList` above, there is a unique concern for `ineligibleMinerList`: in order for a miner entity to avoid ineligibility by a blacklist, they only need to use an alternative adhoc address as the block beneficiary. +In principle, this is ineluctable. + +However, there are associated costs to the "dodging" miner that should be considered. + +- The creation of an account requires time and energy. But indeed, this work can be done at any convenient time and circumstance. Probably marginal, but non-zero. +- The transfer of funds from multiple accounts requires a commensurate number of transactions. Block rewards are applied after transactions are processed, so the miner is unable to simultaneously shift funds from an adhoc account to a target account in the same block they mine (which would otherwise be a "free" transaction). +- In using an adhoc address to dodge a blacklist, the miner may also cause their ineligibility from contemporary whitelist transactions. + +### Validation costs + +Miner lists and expiry depend on easily cached and contextually available conditions (ie. the containing block header). The infrastructural overhead costs for enforcing these validations are expected to be nominal. + +Validation of `ancestorId` demands the assertion of a positive database hit by block number (thereby cross-referencing a stored block's hash). +This necessary lookup can be (and maybe already is) cached, but we must expect less than 100% hits on cached values, since the lookup value is arbitrary. +With that in mind, however, the value provided to a transaction using a deep `ancestorId` is increasingly marginal, so we should expect +most transactions using this field to use a relatively small set of common, shallow, cache-friendly values. + +### Transaction size increase + +The proposed additional fields potentially increase transaction size. +The proposed fields are not associated with any gas costs, establishing no protocol-defined economic mitigation for potential spam. +However, transactions which are considered by a miner to be undesirable can be simply dropped from the transaction pool and ignored. + +## Copyright + +Copyright and related rights waved via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3540.md b/EIPS/eip-3540.md new file mode 100644 index 00000000000000..6b34d1bf71c45a --- /dev/null +++ b/EIPS/eip-3540.md @@ -0,0 +1,260 @@ +--- +eip: 3540 +title: EOF - EVM Object Format v1 +description: EOF is an extensible and versioned container format for EVM bytecode with a once-off validation at deploy time. +author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast), Andrei Maiboroda (@gumb0), Matt Garnett (@lightclient), Piotr Dobaczewski (@pdobacz) +discussions-to: https://ethereum-magicians.org/t/evm-object-format-eof/5727 +status: Review +type: Standards Track +category: Core +created: 2021-03-16 +requires: 3541, 3860 +--- + +## Abstract + +We introduce an extensible and versioned container format for the EVM with a once-off validation at deploy time. The version described here brings the tangible benefit of code and data separation, and allows for easy introduction of a variety of changes in the future. This change relies on the reserved byte introduced by [EIP-3541](./eip-3541.md). + +To summarise, EOF bytecode has the following layout: + +``` +magic, version, (section_kind, section_size_or_sizes)+, 0,
+``` + +## Motivation + +On-chain deployed EVM bytecode contains no pre-defined structure today. Code is typically validated in clients to the extent of `JUMPDEST` analysis at runtime, every single time prior to execution. This poses not only an overhead, but also a challenge for introducing new or deprecating existing features. + +Validating code during the contract creation process allows code versioning without an additional version field in the account. Versioning is a useful tool for introducing or deprecating features, especially for larger changes (such as significant changes to control flow, or features like account abstraction). + +The format described in this EIP introduces a simple and extensible container with a minimal set of changes required to both clients and languages, and introduces validation. + +The first tangible feature it provides is separation of code and data. This separation is especially beneficial for on-chain code validators (like those utilised by layer-2 scaling tools, such as Optimism), because they can distinguish code and data (this includes deployment code and constructor arguments too). Currently, they a) require changes prior to contract deployment; b) implement a fragile method; or c) implement an expensive and restrictive jump analysis. Code and data separation can result in ease of use and significant gas savings for such use cases. Additionally, various (static) analysis tools can also benefit, though off-chain tools can already deal with existing code, so the impact is smaller. + +A non-exhaustive list of proposed changes which could benefit from this format: + +- Including a `JUMPDEST`-table (to avoid analysis at execution time) and/or removing `JUMPDEST`s entirely. +- Introducing static jumps (with relative addresses) and jump tables, and disallowing dynamic jumps at the same time. +- Multibyte opcodes without any workarounds. +- Representing functions as individual code sections instead of subroutines. +- Introducing special sections for different use cases, notably Account Abstraction. + +## Specification + +The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “NOT RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +In order to guarantee that every EOF-formatted contract in the state is valid, we need to prevent already deployed (and not validated) contracts from being recognized as such format. This is achieved by choosing a byte sequence for the *magic* that doesn't exist in any of the already deployed contracts. + +### Remarks + +If code starts with the `MAGIC`, it is considered to be EOF formatted, otherwise it is considered to be *legacy* code. For clarity, the `MAGIC` together with a version number *n* is denoted as the *EOFn prefix*, e.g. *EOF1 prefix*. + +EOF-formatted contracts are created using new instructions which are introduced in a separate EIP. + +The opcode `0xEF` is currently an undefined instruction, therefore: *It pops no stack items and pushes no stack items, and it causes an exceptional abort when executed.* This means legacy *initcode* or already deployed legacy *code* starting with this instruction will continue to abort execution. + +Unless otherwise specified, all integers are encoded in big-endian byte order. + +### Code validation + +We introduce *code validation* for new contract creation. To achieve this, we define a format called EVM Object Format (EOF), containing a version indicator, and a ruleset of validity tied to a given version. + +Legacy code is not affected by EOF code validation. + +Code validation is performed during contract creation, and is elaborated on in separate EIPs. +The EOF format itself and its formal validation are described in the following sections. + +### Container specification + +EOF container is a binary format with the capability of providing the EOF version number and a list of EOF sections. + +The container starts with the EOF prefix: + +| description | length | value | | +|-------------|----------|------------|--------------------| +| magic | 2-bytes | 0xEF00 | | +| version | 1-byte | 0x01–0xFF | EOF version number | + +The EOF prefix is followed by at least one section header. Each section header contains two fields, `section_kind` and either `section_size` or `section_size_list`, depending on the kind. `section_size_list` is a list of size values when multiple sections of this kind are allowed, encoded as a count of items followed by the items. + +| description | length | value | | +|-------------------|---------|---------------|-------------------| +| section_kind | 1-byte | 0x01–0xFF | `uint8` | +| section_size | 2-bytes | 0x0000–0xFFFF | `uint16` | +| section_size_list | dynamic | n/a | `uint16, uint16+` | + +The list of section headers is terminated with the *section headers terminator byte* `0x00`. The body content follows immediately after. + +#### Container validation rules + +1. `version` MUST NOT be `0`. +2. `section_kind` MUST NOT be `0`. The value `0` is reserved for *section headers terminator byte*. +3. There MUST be at least one section (and therefore section header). +5. Stray bytes outside of sections MUST NOT be present. This includes trailing bytes after the last section. + +### EOF version 1 + +EOF version 1 is made up of several EIPs, including this one. Some values in this specification are only discussed briefly. To understand the full scope of EOF, it is necessary to review each EIP in-depth. + +#### Container + +The EOF version 1 container consists of a `header` and `body`. + +``` +container := header, body +header := + magic, version, + kind_type, type_size, + kind_code, num_code_sections, code_size+, + [kind_container, num_container_sections, container_size+,] + kind_data, data_size, + terminator +body := types_section, code_section+, container_section*, data_section +types_section := (inputs, outputs, max_stack_increase)+ +``` + +*note: `,` is a concatenation operator, `+` should be interpreted as "one or more" of the preceding item, `*` should be interpreted as "zero or more" of the preceding item, and `[item]` should be interpreted as an optional item.* + +#### Header + +| name | length | value | description | +|------------------------|---------|-----------------------|--------------------------------------------------------------------------------------------------------------| +| magic | 2 bytes | 0xEF00 | | +| version | 1 byte | 0x01 | EOF version | +| kind_type | 1 byte | 0x01 | kind marker for type section | +| type_size | 2 bytes | 0x0004-0x1000 | 16-bit unsigned big-endian integer denoting the length of the type section content, 4 bytes per code section | +| kind_code | 1 byte | 0x02 | kind marker for code size section | +| num_code_sections | 2 bytes | 0x0001-0x0400 | 16-bit unsigned big-endian integer denoting the number of the code sections | +| code_size | 2 bytes | 0x0001-0xFFFF | 16-bit unsigned big-endian integer denoting the length of the code section content | +| kind_container | 1 byte | 0x03 | kind marker for container size section | +| num_container_sections | 2 bytes | 0x0001-0x0100 | 16-bit unsigned big-endian integer denoting the number of the container sections | +| container_size | 4 bytes | 0x00000001-0xFFFFFFFF | 32-bit unsigned big-endian integer denoting the length of the container section content | +| kind_data | 1 byte | 0xFF | kind marker for data size section | +| data_size | 2 bytes | 0x0000-0xFFFF | 16-bit unsigned big-endian integer denoting the length of the data section content (*) | +| terminator | 1 byte | 0x00 | marks the end of the header | + +(*) For not yet deployed containers this can be greater than the actual content length. + +#### Body + +| name | length | value | description | +|--------------------|----------|---------------|------------------------------------------------------------------| +| types_section | variable | n/a | stores code section metadata | +| inputs | 1 byte | 0x00-0x7F | number of stack elements the code section consumes | +| outputs | 1 byte | 0x00-0x7F | number of stack elements the code section returns | +| max_stack_increase | 2 bytes | 0x0000-0x03FF | maximum increase of the operand stack height by the code section | +| code_section | variable | n/a | arbitrary bytecode | +| container_section | variable | n/a | arbitrary EOF-formatted container | +| data_section | variable | n/a | arbitrary sequence of bytes | + +**NOTE**: A special value of `outputs` being `0x80` is designated to denote non-returning functions as defined in a separate EIP. + +#### EOF version 1 validation rules + +The following validity constraints are placed on the container format: + +- `types_size` is divisible by `4` +- the number of code sections must be equal to `types_size / 4` +- data body length may be shorter than `data_size` for a not yet deployed container +- the total size of a container must not exceed `MAX_INITCODE_SIZE` (as defined in [EIP-3860](./eip-3860.md)) + +### Changes to execution semantics + +For an EOF contract: + +- Execution starts at the first byte of code section 0 +- `CODESIZE`, `CODECOPY`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, `GAS` are rejected by validation in EOF contracts, with no replacements +- `CALL`, `DELEGATECALL`, `STATICCALL` are rejected by validation in EOF contracts, replacement instructions to be introduced in a separate EIP. +- `DELEGATECALL` (or any replacement instruction for EOF) from an EOF contract to a non-EOF contract (legacy contract, EOA, empty account) is disallowed, and it should fail in the same mode as if the call depth check failed. We allow legacy to EOF path for existing proxy contracts to be able to use EOF upgrades. + +For a legacy contract: + +- If the target account of `EXTCODECOPY` is an EOF contract, then it will copy up to 2 bytes from `EF00`, as if that would be the code. +- If the target account of `EXTCODEHASH` is an EOF contract, then it will return `0x9dbf3648db8210552e9c4f75c6a1c3057c0ca432043bd648be15fe7be05646f5` (the hash of `EF00`, as if that would be the code). +- If the target account of `EXTCODESIZE` is an EOF contract, then it will return 2. + +**NOTE** Like for legacy targets, the aforementioned behavior of `EXTCODECOPY`, `EXTCODEHASH` and `EXTCODESIZE` does not apply to EOF contract targets mid-creation, i.e. those report same as accounts without code. + +## Rationale + +EVM and/or account versioning has been discussed numerous times over the past years. This proposal aims to learn from them. +See "Ethereum account versioning" on the Fellowship of Ethereum Magicians Forum for a good starting point. + +### Execution vs. creation time validation + +This specification introduces creation time validation, which means: + +- All created contracts with *EOFn* prefix are valid according to version *n* rules. This is very strong and useful property. The client can trust that the deployed code is well-formed. +- In the future, this allows to serialize `JUMPDEST` map in the EOF container and eliminate the need of implicit `JUMPDEST` analysis required before execution. +- Or to completely remove the need for `JUMPDEST` instructions. +- This helps with deprecating EVM instructions and/or features. +- The biggest disadvantage is that deploy-time validation of EOF code must be enabled in two hard-forks. However, the first step ([EIP-3541](./eip-3541.md)) is already deployed in London. + +The alternative is to have execution time validation for EOF. This is performed every single time a contract is executed, however clients may be able to cache validation results. This *alternative* approach has the following properties: + +- Because the validation is consensus-level execution step, it means the execution always requires the entire code. This makes *code merkleization impractical*. +- Can be enabled via a single hard-fork. +- Better backwards compatibility: data contracts starting with the `0xEF` byte or the *EOF prefix* can be deployed. This is a dubious benefit, however. + +### The MAGIC + +1. The first byte `0xEF` was chosen because it is reserved for this purpose by [EIP-3541](./eip-3541.md). + +2. The second byte `0x00` was chosen to avoid clashes with three contracts which were deployed on **Mainnet**: + - `0xca7bf67ab492b49806e24b6e2e4ec105183caa01`: `EFF09f918bf09f9fa9` + - `0x897da0f23ccc5e939ec7a53032c5e80fd1a947ec`: `EF` + - `0x6e51d4d9be52b623a3d3a2fa8d3c5e3e01175cd0`: `EF` + +3. No contracts starting with `0xEF` bytes exist on public testnets: Goerli, Ropsten, Rinkeby, Kovan and Sepolia at their London fork block. + +**NOTE**: This EIP MUST NOT be enabled on chains which contain bytecodes starting with `MAGIC` and not being valid EOF. + +### EOF version range start with 1 + +The version number 0 will never be used in EOF, so we can call legacy code *EOF0*. +Also, implementations may use APIs where 0 version number denotes legacy code. + +### Section structure + +We have considered different questions for the sections: + +- Streaming headers (i.e. `section_header, section_data, section_header, section_data, ...`) are used in some other formats (such as WebAssembly). They are handy for formats which are subject to editing (adding/removing sections). That is not a useful feature for EVM. One minor benefit applicable to our case is that they do not require a specific "header terminator". On the other hand they seem to play worse with code chunking / merkleization, as it is better to have all section headers in a single chunk. +- Whether to have a header terminator or to encode `number_of_sections` or `total_size_of_headers`. Both raise the question of how large of a value these fields should be able to hold. A terminator byte seems to avoid the problem of choosing a size which is too small without any perceptible downside, so it is the path taken. +- (EOF1) Whether to encode section sizes as fixed 16-bit (32-bit for container section size) values or some kind of variable length field (e.g. LEB128). We have opted for fixed size. Should this be limiting in the future, a new EOF version could change the format. Besides simplifying client implementations, not using LEB128 also greatly simplifies on-chain parsing. +- Whether or not to have more structure to the container header for all EOF versions to follow. In order to allow future formats optimized for chunking and merkleization (verkleization) it was decided to keep it generic and specify the structure only for a specific EOF version. + +### Data-only contracts + +See section [Lack of `EXTDATACOPY` in EIP-7480](./eip-7480.md#lack-of-extdatacopy). + +### EOF1 contracts can only `DELEGATECALL` EOF1 contracts + +Currently contracts can selfdestruct in three different ways (directly through `SELFDESTRUCT`, indirectly through `CALLCODE` and indirectly through `DELEGATECALL`). [EIP-3670](./eip-3670.md) disables the first two possibilities, however the third possibility remains. Allowing EOF1 contracts to only `DELEGATECALL` other EOF1 contracts allows the following strong statement: EOF1 contract can never be destructed. Attacks based on `SELFDESTRUCT` completely disappear for EOF1 contracts. These include destructed library contracts (e.g. Parity Multisig). + +### EOF1 containers have a size limit + +Imposing an EOF-validation time limit for the size of EOF containers provides a reference limit of how large the containers should EVM implementations be able to handle when validating and processing containers. `MAX_INITCODE_SIZE` was chosen for EOF1, as it is what contract creation currently allows for. + +Given one of the main reasons for the limit is to avoid attack vectors on `JUMPDEST`-analysis, and EOF removes the need for `JUMPDEST`-analysis and introduces a cost structure for deploy-time analysis, in the future this limit could be increased or even lifted for EOF. + +### `kind_data` could be `0x04` not `0xff` + +Putting the data section last as `0xff` has the advantage of aligning with the fact that it always comes last. We're avoiding a situation that a new section kind would need to go before the data section and break the section kind ordering. At the same time, data section being last is advantageous because it is the section which gets data appended to during contract deployment. + +## Backwards Compatibility + +This is a breaking change given that any code starting with `0xEF` was not deployable before (and resulted in exceptional abort if executed), but now some subset of such codes can be deployed and executed successfully. + +The choice of `MAGIC` guarantees that none of the contracts existing on the chain are affected by the new rules. + +## Security Considerations + +With the anticipated EOF extensions, the validation is expected to have linear computational and space complexity. +We think that the validation cost is sufficiently covered by: + +- [EIP-3860](./eip-3860.md) for *initcode*, +- high per-byte cost of deploying *code*. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3541.md b/EIPS/eip-3541.md new file mode 100644 index 00000000000000..fc364983e4b04d --- /dev/null +++ b/EIPS/eip-3541.md @@ -0,0 +1,69 @@ +--- +eip: 3541 +title: Reject new contract code starting with the 0xEF byte +author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast), Andrei Maiboroda (@gumb0), Alexey Akhunov (@AlexeyAkhunov), Christian Reitwiessner (@chriseth), Martin Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/evm-object-format-eof/5727 +status: Final +type: Standards Track +category: Core +created: 2021-03-16 +--- + +## Abstract + +Disallow new code starting with the `0xEF` byte to be deployed. Code already existing in the account trie starting with `0xEF` byte is not affected semantically by this change. + +## Motivation + +Contracts conforming to the EVM Object Format (EOF) are going to be validated at deploy time. In order to guarantee that every EOF-formatted contract in the state is valid, we need to prevent already deployed (and not validated) contracts from being recognized as such format. This will be achieved by choosing a byte sequence for the *magic* that doesn't exist in any of the already deployed contracts. To prevent the growth of the search space and to limit the analysis to the contracts existing before this fork, we disallow the starting byte of the format (the first byte of the magic). + +Should the EVM Object Format proposal not be deployed in the future, the *magic* can be used by other features depending on versioning. In the case versioning becomes obsolete, it is simple to roll this back by allowing contracts starting with the `0xEF` byte to be deployed again. + +## Specification + +After `block.number == HF_BLOCK` new contract creation (via create transaction, `CREATE` or `CREATE2` instructions) results in an exceptional abort if the _code_'s first byte is `0xEF`. + +### Remarks + +The *initcode* is the code executed in the context of the *create* transaction, `CREATE`, or `CREATE2` instructions. The *initcode* returns *code* (via the `RETURN` instruction), which is inserted into the account. See section 7 ("Contract Creation") in the Yellow Paper for more information. + +The opcode `0xEF` is currently an undefined instruction, therefore: *It pops no stack items and pushes no stack items, and it causes an exceptional abort when executed.* This means *initcode* or already deployed *code* starting with this instruction will continue to abort execution. + +The exceptional abort due to *code* starting with `0xEF` behaves exactly the same as any other exceptional abort that can occur during *initcode* execution, i.e. in case of abort all gas provided to a `CREATE*` or create transaction is consumed. + +## Rationale + +The `0xEF` byte was chosen because it resembles **E**xecutable **F**ormat. + +Contracts using unassigned opcodes are generally understood to be at risk of changing semantics. Hence using the unassigned `0xEF` should have lesser effects, than choosing an assigned opcode, such as `0xFD` (`REVERT`), `0xFE` (`INVALID)`, or `0xFF` (`SELFDESTRUCT`). Arguably while such contracts may not be very useful, they are still using valid opcodes. + +Analysis in May 2021, on `18084433` contracts in state, showed that there are 0 existing contracts starting with the `0xEF` byte, as opposed to 1, 4, and 12 starting with `0xFD`, `0xFE`, and `0xFF`, respectively. + +## Test Cases + +Each test case below may be executed in 3 different contexts: +- create transaction (no account code) +- `CREATE`, with account code: `0x6000356000523660006000f0151560165760006000fd5b` (Yul code: `mstore(0, calldataload(0)) if iszero(create(0, 0, calldatasize())) { revert(0, 0) }`), +- `CREATE2`, with account code: `0x60003560005260003660006000f5151560185760006000fd5b` (Yul code: `mstore(0, calldataload(0)) if iszero(create2(0, 0, calldatasize(), 0)) { revert(0, 0) }`) + +| Case | Calldata | Expected result | +| -------- | -------- | -------- | +| deploy one byte `ef` | `0x60ef60005360016000f3` | new contract not deployed, transaction fails | +| deploy two bytes `ef00` | `0x60ef60005360026000f3` | new contract not deployed, transaction fails | +| deploy three bytes `ef0000` | `0x60ef60005360036000f3` | new contract not deployed, transaction fails | +| deploy 32 bytes `ef00...00` | `0x60ef60005360206000f3` | new contract not deployed, transaction fails | +| deploy one byte `fe` | `0x60fe60005360016000f3` | new contract deployed, transaction succeeds | + +## Backwards Compatibility + +This is a breaking change given new code starting with the `0xEF` byte will not be deployable, and contract creation will result in a failure. However, given bytecode is executed starting at its first byte, code deployed with `0xEF` as the first byte is not executable anyway. + +While this means no currently executable contract is affected, it does rejects deployment of new data contracts starting with the `0xEF` byte. + +## Security Considerations + +The authors are not aware of any security or DoS risks posed by this change. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3554.md b/EIPS/eip-3554.md new file mode 100644 index 00000000000000..046317046a6422 --- /dev/null +++ b/EIPS/eip-3554.md @@ -0,0 +1,58 @@ +--- +eip: 3554 +title: Difficulty Bomb Delay to December 2021 +author: James Hancock (@madeoftin) +discussions-to: https://ethereum-magicians.org/t/eip-3554-ice-age-delay-targeting-december-2021/6188 +status: Final +type: Standards Track +category: Core +created: 2021-05-06 +--- + +## Simple Summary +Delays the difficulty bomb to show effect the first week of December 2021. + +## Abstract +Starting with `FORK_BLOCK_NUMBER` the client will calculate the difficulty based on a fake block number suggesting to the client that the difficulty bomb is adjusting 9,700,000 blocks later than the actual block number. + +## Motivation +Targeting for the Shanghai upgrade and/or the Merge to occur before December 2021. Either the bomb can be readjusted at that time, or removed all together. + +## Specification +#### Relax Difficulty with Fake Block Number +For the purposes of `calc_difficulty`, simply replace the use of `block.number`, as used in the exponential ice age component, with the formula: +```py + fake_block_number = max(0, block.number - 9_700_000) if block.number >= FORK_BLOCK_NUMBER else block.number +``` +## Rationale + +The following script predicts a .1 second delay to blocktime the first week of december and a 1 second delay by the end of the month. This gives reason to address because the effect will be seen, but not so much urgency we don't have space to work around if needed. + +```python +def predict_diff_bomb_effect(current_blknum, current_difficulty, block_adjustment, months): + ''' + Predicts the effect on block time (as a ratio) in a specified amount of months in the future. + Vars used in last prediction: + current_blknum = 12382958 + current_difficulty = 7393633000000000 + block adjustment = 9700000 + months = 6 + ''' + blocks_per_month = (86400 * 30) // 13.3 + future_blknum = current_blknum + blocks_per_month * months + diff_adjustment = 2 ** ((future_blknum - block_adjustment) // 100000 - 2) + diff_adjust_coeff = diff_adjustment / current_difficulty * 2048 + return diff_adjust_coeff + + +diff_adjust_coeff = predict_diff_bomb_effect(12382958,7393633000000000,9700000,6) +``` + +## Backwards Compatibility +No known backward compatibility issues. + +## Security Considerations +Misjudging the effects of the difficulty can mean longer blocktimes than anticipated until a hardfork is released. Wild shifts in difficulty can affect this number severely. Also, gradual changes in blocktimes due to longer-term adjustments in difficulty can affect the timing of difficulty bomb epochs. This affects the usability of the network but unlikely to have security ramifications. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3561.md b/EIPS/eip-3561.md new file mode 100644 index 00000000000000..4f7e495cc95398 --- /dev/null +++ b/EIPS/eip-3561.md @@ -0,0 +1,7 @@ +--- +eip: 3561 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3561.md diff --git a/EIPS/eip-3569.md b/EIPS/eip-3569.md new file mode 100644 index 00000000000000..c7e67bcdf4946e --- /dev/null +++ b/EIPS/eip-3569.md @@ -0,0 +1,7 @@ +--- +eip: 3569 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3569.md diff --git a/EIPS/eip-3584.md b/EIPS/eip-3584.md new file mode 100644 index 00000000000000..c5261b116041c6 --- /dev/null +++ b/EIPS/eip-3584.md @@ -0,0 +1,125 @@ +--- +eip: 3584 +title: Block Access List +author: Gajinder Singh (@g11in), Piper Merriam (@pipermerriam) +discussions-to: https://ethresear.ch/t/block-access-list-v0-1/9505 +status: Stagnant +type: Standards Track +category: Core +created: 2021-05-22 +requires: 2929, 2930 +--- + +## Simple Summary +A proposal to build a block's `access_list` and include its fingerprint `AccessListRoot` in the block header. + +## Abstract +[EIP-2929](./eip-2929.md)/[EIP-2930](./eip-2930.md) centers around normalizing the (low) gas costs of data/storage accesses made by a transaction as well as providing for (and encouraging) a new transaction type format: +``` +0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, access_list, yParity, senderR, senderS]) +``` +that makes upfront `access_list` declarations, where `access_list` is some `[[{20 bytes}, [{32 bytes}...]]...]` map of `AccessedAddress=> AccessedStorageKeys`. + +The first *accesses* of these upfront *declarations* are charged at discounted price (roughly ~`10%`) and first accesses outside this list are charged higher price. Reason is upfront access declaration provides for a way to *preload/optimize/batch* loading these locations while executing the transaction. +This inadvertently leads to generation of transaction `access_list` that has all (first) accesses (declared or not) made by a transaction. +This proposal is to collate these *transaction* `access_list`s for all the transactions in a **block** `access_list` document and include its *fingerprint* in the block header. + +## Motivation +Motivation for collating the *transaction* `access_list`s for all the transactions in a **block**’s `access_list` is to have an *access index* of the block with following benefits: +1. Block execution/validation optimizations/parallelization/cache warm-up by enabling construction of *a partial order* for access and hence execution (hint: *chains* in this *poset* can be parallelized). +2. Enabling partial inspection and fetching/serving of a block data/state by *light sync* or *fast sync* protocols concerned with a subset of addresses. +3. Possible future extension of this list to serve as index for bundling, serving and fetching witness data for *stateless* protocols. + +## Specification +A block `access_list` represents: +``` +Set [ + AccessedAddress, + List [AccessedStorageKeys] , + Set [ AccessedInBlockTransactionNumber, List [ AccessedStorageKeys ]] +] +``` +A **canonical** construction of such an `access_list` is specified as below. + +### Canonical Block Access List +An `access_list` is defined to be comprised of many `access_list_entry` elements: +``` +access_list := [access_list_entry, ...] +``` + +An `access_list_entry` is a 3-tuple of: +* address +* sorted list of storage keys of the address accessed across the entire block +* sorted list of 2-tuples of: + * transaction index in which the address or any of its storage keys were accessed + * sorted list of storage keys which were accessed + +``` +access_list := [access_list_entry, ...] +access_list_entry := [address, storage_keys, accesses_by_txn_index] +address := bytes20 +accesses_by_txn_index := [txn_index_and_keys, ...] +txn_index_and_keys := [txn_index, storage_keys] +txn_index := uint64 # or uint256 or whatever +storage_keys := [storage_key, ...] +storage_key := bytes32 +``` + +Additional sorting rules for the above are that: +* `access_list` is sorted by the `address` +* `storage_keys` is sorted +* `accesses_by_txn_index` is sorted by `txn_index` + +Additional validation rules for the above are that: +* Each unique `address` may only appear at most once in `access_list` +* Each `storage_key` may only appear at most once in `storage_keys` +* Each `txn_index` may only appear at most once in `txn_index_and_keys` + +All sorting is in increasing order. + +### AccessListRoot +An `AccessListRoot` is a URN *like* encoding `Hash/Commitment` of the canonical `access_list` as well as the construction type ( `sha256` ) and serialization type ( `json` ), i.e. +``` +AccessListRoot := "urn:sha256:json:0x${ SHA256( access_list.toJSONString('utf8') ).toHexString() }" +``` +where `0x${ SHA256 (...)...}` is the `SHA256` hashed `32` bytes hex string as indicated by leading `0x`. + +### Additional Block Validation +Validating a new block requires an additional validation check that the block’s `AccessListRoot` matches the one generated by executing the block using the construction as defined by the `AccessListRoot` URN. + +## Rationale +### Sorting of canonical `access_list` +It is specified to be sorted in lexicographic ordering or integer sorting wherever applicable and specified. Sorting with respect to access time was considered but didn't seem to provide any additional benefit at the cost of adding implementation complexity and bookkeeping. + +### `AccessListRoot` +`AccessListRoot` is generated to prevent any *griefing* attacks and hence will need to be included (and validated) in the *block header*. +Even though `AccessListRoot` is currently specified to be a simple `sha256` hash of the canonical `access_list`, it would be beneficial to consider other constructions +* a tree structure (`merkle`/`verkle`). It will be a bit more expensive but will enable partial downloading, inspection and validation of the `access_list`. +* a normal `kate` commitment can also be generated to enable this partial capability and is recommended as validating partial fetch of access list chunks would be very simple. + +Also serialization of the `access_list` is currently specified as a normal `JSON String` dump and these parameters could vary from construction to construction, but for the sake of simplicity, it can always be `sha256` hashed to get a consistent `32` bytes hex string root. + +So this AccessListRoot could evolve to `urn:merkle:ssz:...` or to `urn:kate:...` or to any other scheme as per requirement. And the idea of having the `AccessListRoot` as URN *like* structure is to enable upgradation to these paths without affecting block structure. + + +### Future extensions of `access_list` +We can extend the notion of a block’s `access_list` to include witnesses: +``` +access_list := Set[ + Address, + List [ AddressWitnesses ], + Set [ AccessedStorageKey, List [ StorageKeyWitnesses] ], + Set [ AccessedInBlockTransactionNumber, List [ AccessedStorageKeys ] ] +] +``` +and then get to define the a canonical specification for building the fingerprint. +This will allow an incremental path to partial or full statelessness, where it would be easy to bundle/request **witnesses** using this `access_list`. + +## Backwards Compatibility +The extra block validation will only be mandatory post the block number this EIP comes into effect, but the clients can still provide a way to generate (and possibly store) this access list on request (via the `JSON/RPC` api). However this is optional and client dependent. + +## Security Considerations +There are no known security issues as a result of this change. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3589.md b/EIPS/eip-3589.md new file mode 100644 index 00000000000000..366b587d703e0b --- /dev/null +++ b/EIPS/eip-3589.md @@ -0,0 +1,7 @@ +--- +eip: 3589 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3589.md diff --git a/EIPS/eip-3607.md b/EIPS/eip-3607.md new file mode 100644 index 00000000000000..6d604006d60d27 --- /dev/null +++ b/EIPS/eip-3607.md @@ -0,0 +1,96 @@ +--- +eip: 3607 +title: Reject transactions from senders with deployed code +description: Do not allow transactions for which `tx.sender` has any code deployed. +author: Dankrad Feist (@dankrad), Dmitry Khovratovich (@khovratovich), Marius van der Wijden (@MariusVanDerWijden) +discussions-to: https://github.com/ethereum/EIPs/issues/3608 +status: Final +type: Standards Track +category: Core +created: 2021-06-10 +--- + +## Abstract + +Ethereum addresses are currently only 160 bits long. This means it is possible to create a collision between a contract account and an Externally Owned Account (EOA) using an estimated `2**80` computing operations, which is feasible now given a large budget (ca. 10 billion USD). The fix in this EIP prevents the worst possible attack, where a safe looking contract (e.g. a token wrapper or an AMM-type contract) is deployed to attract user funds, which can then be spent using the EOA key for the same address. The fix is to never allow to use an address that already has code deployed as an EOA address. + +## Motivation + +### Generating address collisions + +By creating keys for `2**80` EOAs and simulating the deployment of `2**80` contracts from these EOAs (one each), one expects to find about one collision where an EOA has the same address as one contract. + +This very simple form of the attack requires the storage of `2**80` addresses, which is a practical barrier: It would require `2.4*10**25` bytes of memory (24 Yottabyte). However, there are cycle finding algorithms that can perform the collision search without requiring large amounts of storage. An estimate for the complexity has been made [here](https://hackmd.io/Vzhp5YJyTT-LhWm_s0JQpA). We estimate that a collision between a contract and an EOA could be found in about one year with an investment of ca. US$10 billion in hardware and electricity. + +### Background + +There is currently a discussion to move to 256-bit addresses on Ethereum, which would increase collision resistance to a complexity of `2**128` which is currently thought infeasible for the foreseeable future. However, with 160 bit addresses, the collision problem can be effectively solved now, as demonstrated above. + +Most attacks that can occur via address collisions are quite impractical: They involve users sending funds to an address before a contract is deployed. This is a very rare application in practice and users can easily circumvent the attack by never sending funds to a contract until it has been safely deployed with enough confirmations. + +However, the yellow paper does not explicitly specify how a client should handle the case where a transaction is sent from an account that already has contract code deployed; presumably because this was considered infeasible at the time. The assumption is that most client would allow this transaction in their current state. + +This EIP is to specify this behaviour to always forbid such transactions. This fixes most realistic or serious attacks due to address collisions. + + +## Specification + +Any transaction where `tx.sender` has a `CODEHASH != EMPTYCODEHASH` MUST be rejected as invalid, where `EMPTYCODEHASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`. +The invalid transaction MUST be rejected by the client and not be included in a block. +A block containing such a transaction MUST be considered invalid. + +## Rationale + +We note that it was always expected that a contract account's behaviour is constrained by the code in that contract -- which means that the account's funds should not suddenly be spendable by some private key. It was just implicitly assumed in the past that a 160 bit address length is enough to provide collision resistance, and thus that this case could never occur. In that sense, this EIP should be seen as a clarification of protocol behaviour in a previously undefined case rather than an explicit upgrade of consensus rules. + +This does not exclude all possible attack vectors, only the most serious one. Further possible attack vectors via address collisions between contracts and EOAs are: +1. An attacker can convince a user to send funds to an account before it is deployed. Some applications require this behaviour (e.g. state channels). +2. A chain reorg can happen after a contract is deployed. If the reorg removes the contract deployment transaction the funds can still be accessed using the private key. +3. A contract can self destruct, with the stated intention that ERC20s (or other tokens) in the contract would be burned. However, they can now be accessed by a key for that address. + +All these scenarios are much harder to exploit for an attacker, and likely have much lower yield making the attacks unlikely to be economically viable. + +## Backwards Compatibility + +It is unlikely that an attack like this has already occurred on the Ethereum mainnet, or we would very likely have heard of it. It is inconceivable that someone would use this as a "feature" to make a contract an EOA at the same time, when they could simply do this by adding some methods to the contract instead of spending billions on building hardware to find hash collisions. + +Private networks may have deployed contracts which also work as EOAs at genesis and should check that this upgrade does not impact their workflows. + +Clients might choose to disable this rule for RPC calls like `eth_call` and `eth_estimateGas` as some Multi-Sig contracts use these calls to create transactions as if they originated from the multisig contract itself. + +## Test Cases + +Given a genesis allocation of +``` +Address: 0x71562b71999873DB5b286dF957af199Ec94617F7 +Balance: 1000000000000000000 // 1 ether +Nonce: 0, +Code: 0xB0B0FACE", +``` +Every transaction sent by the private key corresponding to `0x715656...` ( +`b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291`) should be rejected. +These transaction must be rejected and not included in a block. + +## Reference Implementation + +The following check must be added to the state transition checks after checking that the nonce of the sender is correct. +The sender is the address recovered from the signature of the transaction. +``` +// Make sure the sender is an EOA +Set ch to the CodeHash of the sender account +if ch is not equal to EmptyCodeHash then + return ErrSenderNoEOA +end if +``` + +A diff to implement EIP-3607 in go-ethereum can be found [here](../assets/eip-3607/geth.diff) + +## Security Considerations + +This EIP is a strict security upgrade: It simply makes some transactions that were formerly valid now invalid. There is no legitimate use for such transactions, so there should be no security downsides. + +This EIP can be implemented as a soft fork because the new validity rules are a strict superset of the previous validity rules. + + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3643.md b/EIPS/eip-3643.md new file mode 100644 index 00000000000000..5a68a2e19e5d9e --- /dev/null +++ b/EIPS/eip-3643.md @@ -0,0 +1,7 @@ +--- +eip: 3643 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3643.md diff --git a/EIPS/eip-3651.md b/EIPS/eip-3651.md new file mode 100644 index 00000000000000..d94c694c6f1229 --- /dev/null +++ b/EIPS/eip-3651.md @@ -0,0 +1,45 @@ +--- +eip: 3651 +title: Warm COINBASE +description: Starts the `COINBASE` address warm +author: William Morriss (@wjmelements) +discussions-to: https://ethereum-magicians.org/t/eip-3651-warm-coinbase/6640 +status: Final +type: Standards Track +category: Core +created: 2021-07-12 +requires: 2929 +--- + +## Abstract + +The `COINBASE` address shall be warm at the start of transaction execution, in accordance with the actual cost of reading that account. + +## Motivation + +Direct `COINBASE` payments are becoming increasingly popular because they allow conditional payments, which provide benefits such as implicit cancellation of transactions that would revert. +But accessing `COINBASE` is overpriced; the address is initially cold under the access list framework introduced in [EIP-2929](./eip-2929.md). +This gas cost mismatch can incentivize alternative payments besides ETH, such as [ERC-20](./eip-20.md), but ETH should be the primary means of paying for transactions on Ethereum. + +## Specification + +At the start of transaction execution, `accessed_addresses` shall be initialized to also include the address returned by `COINBASE` (`0x41`). + +## Rationale + +The addresses currently initialized warm are the addresses that should already be loaded at the start of transaction validation. +The `ORIGIN` address is always loaded to check its balance against the gas limit and the gas price. +The `tx.to` address is always loaded to begin execution. +The `COINBASE` address should also be always be loaded because it receives the block reward and the transaction fees. + +## Backwards Compatibility + +There are no known backward compatibility issues presented by this change. + +## Security Considerations + +There are no known security considerations introduced by this change. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3668.md b/EIPS/eip-3668.md new file mode 100644 index 00000000000000..a84cf0257fb76f --- /dev/null +++ b/EIPS/eip-3668.md @@ -0,0 +1,7 @@ +--- +eip: 3668 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3668.md diff --git a/EIPS/eip-3670.md b/EIPS/eip-3670.md new file mode 100644 index 00000000000000..2e6d3115aec61c --- /dev/null +++ b/EIPS/eip-3670.md @@ -0,0 +1,142 @@ +--- +eip: 3670 +title: EOF - Code Validation +description: Validate EOF bytecode for correctness at the time of deployment. +author: Alex Beregszaszi (@axic), Andrei Maiboroda (@gumb0), Paweł Bylica (@chfast) +discussions-to: https://ethereum-magicians.org/t/eip-3670-eof-code-validation/6693 +status: Stagnant +type: Standards Track +category: Core +created: 2021-06-23 +requires: 3540 +--- + +## Abstract + +Introduce code validation at contract creation time for EOF formatted ([EIP-3540](./eip-3540.md)) +contracts. Reject contracts which contain truncated `PUSH`-data or undefined instructions. +Legacy bytecode (code which is not EOF formatted) is unaffected by this change. + +## Motivation + +Currently existing contracts require no validation of correctness and EVM implementations can decide +how they handle truncated bytecode or undefined instructions. This change aims to bring code +validity into consensus, so that it becomes easier to reason about bytecode. +Moreover, EVM implementations may require fewer paths to decide which instruction is valid in +the current execution context. + +If there's a desire to introduce new instructions without bumping the EOF version, having undefined instructions already deployed could potentially break such contracts, as some instructions might change their behavior. Rejecting to deploy undefined instructions allows +introducing new instructions with or without bumping the EOF version. + +### EOF1 forward compatibility + +The EOF1 format provides following forward compatibility properties: + +1. New instructions can be defined for previously unassigned opcodes. These instructions may have immediate values. +2. Mandatory EOF sections may be made optional. +3. New optional EOF sections may be introduced. They can be placed in any order in relation to previously defined sections. + +## Specification + +This feature is introduced on the same block EIP-3540 is enabled, therefore every EOF1-compatible bytecode MUST be validated according to these rules. + +1. Previously deprecated instructions `CALLCODE` (0xf2) and `SELFDESTRUCT` (0xff), as well as instructions deprecated in EIP-3540, are invalid and their opcodes are undefined. (**NOTE** there are more instructions deprecated and rejected in EOF, as specced out by separate EIPs) +2. At contract creation time *code validation* is performed on each code section of the EOF container. The code is invalid if any of the checks below fails. For each instruction: + 1. Check if the opcode is defined. The `INVALID` (0xfe) is considered defined. + 2. Check if all instructions' immediate bytes are present in the code (code does not end in the middle of instruction). + +## Rationale + +### Immediate data + +Allowing implicit zero immediate data for `PUSH` instructions introduces inefficiencies to EVM implementations without any practical use-case (the value of a `PUSH` instruction at the code end cannot be observed by EVM). This EIP requires all immediate bytes to be explicitly present in the code. + +### Rejection of deprecated instructions + +The deprecated instructions `CALLCODE` (0xf2) and `SELFDESTRUCT` (0xff) are removed from the `valid_opcodes` list to prevent their use in the future. + +### BLOCKHASH instruction + +The `BLOCKHASH` instruction is well replaced by the system contract introduced in [EIP-2935](./eip-2935). +However, despite a replacement being introduced this opcode has not been deprecated. +This opcode will remain valid in EOF not to differentiate from legacy bytecode. + +## Backwards Compatibility + +This change poses no risk to backwards compatibility, as it is introduced at the same time EIP-3540 is. The validation does not cover legacy bytecode (code which is not EOF formatted). + +## Test Cases + +### Contract creation + +Each case should be tested by submitting an EOF container to EOF contract creation (as specced out in a separate EIP). Each case should be tested with code placed in code sections at different indices. + +### Valid codes + +- EOF code containing `INVALID` +- EOF code with data section containing bytes that are undefined instructions + +### Invalid codes + +- EOF code containing an undefined instruction +- EOF code ending with incomplete `PUSH` instruction + +## Reference Implementation + +```python +# The ranges below are as specified by Execution Specs for Shanghai. +# Note: range(s, e) excludes e, hence the +1 +shanghai_opcodes = [ + *range(0x00, 0x0b + 1), + *range(0x10, 0x1d + 1), + 0x20, + *range(0x30, 0x3f + 1), + *range(0x40, 0x48 + 1), + *range(0x50, 0x5b + 1), + 0x5f, + *range(0x60, 0x6f + 1), + *range(0x70, 0x7f + 1), + *range(0x80, 0x8f + 1), + *range(0x90, 0x9f + 1), + *range(0xa0, 0xa4 + 1), + # Note: 0xfe is considered assigned. + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xfa, 0xfd, 0xfe, 0xff +] + +# Drop the opcodes deprecated and rejected in here and in EIP-3540 +rejected_in_eof = [ + 0x38, 0x39, 0x3b, 0x3c, 0x3f, 0x5a, 0xf1, 0xf2, 0xf4, 0xfa, 0xff +] +valid_opcodes = [op for op in shanghai_opcodes not in rejected_in_eof] + +immediate_sizes = 256 * [0] +immediate_sizes[0x60:0x7f + 1] = range(1, 32 + 1) # PUSH1..PUSH32 + + +# Raises ValidationException on invalid code +def validate_instructions(code: bytes): + # Note that EOF1 already asserts this with the code section requirements + assert len(code) > 0 + + pos = 0 + while pos < len(code): + # Ensure the opcode is valid + opcode = code[pos] + if opcode not in valid_opcodes: + raise ValidationException("undefined opcode") + + # Skip immediate data + pos += 1 + immediate_sizes[opcode] + + # Ensure last instruction's immediate doesn't go over code end + if pos != len(code): + raise ValidationException("truncated immediate") +``` + +## Security Considerations + +See [Security Considerations of EIP-3540](./eip-3540.md#security-considerations). + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3675.md b/EIPS/eip-3675.md new file mode 100644 index 00000000000000..efa51f543490bd --- /dev/null +++ b/EIPS/eip-3675.md @@ -0,0 +1,341 @@ +--- +eip: 3675 +title: Upgrade consensus to Proof-of-Stake +description: Specification of the consensus mechanism upgrade on Ethereum Mainnet that introduces Proof-of-Stake +author: Mikhail Kalinin (@mkalinin), Danny Ryan (@djrtwo), Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-3675-upgrade-consensus-to-proof-of-stake/6706 +status: Final +type: Standards Track +category: Core +created: 2021-07-22 +requires: 2124 +--- + + +## Abstract + +This EIP deprecates Proof-of-Work (PoW) and supersedes it with the new Proof-of-Stake consensus mechanism (PoS) driven by the beacon chain. Information on the bootstrapping of the new consensus mechanism is documented in [EIP-2982](./eip-2982.md). Full specification of the beacon chain can be found in the `ethereum/consensus-specs` repository. + +This document specifies the set of changes to the block structure, block processing, fork choice rule and network interface introduced by the consensus upgrade. + + +## Motivation + +The beacon chain network has been up and running since December 2020. Neither safety nor liveness failures were detected during this period of time. This long period of running without failure demonstrates the sustainability of the beacon chain system and its readiness to become a security provider for the Ethereum Mainnet. + +To understand the motivation of introducing the Proof-of-Stake consensus see the Motivation section of [EIP-2982](./eip-2982.md#motivation). + + +## Specification + +### Definitions + +* **PoW block**: Block that is built and verified by the existing proof-of-work mechanism. In other words, a block of the Ethereum network before the consensus upgrade. +* **PoS block**: Block that is built and verified by the new proof-of-stake mechanism. +* **Terminal PoW block**: A PoW block that satisfies the following conditions -- +`pow_block.total_difficulty >= TERMINAL_TOTAL_DIFFICULTY` *and* `pow_block.parent_block.total_difficulty < TERMINAL_TOTAL_DIFFICULTY`. +There can be more than one terminal PoW block in the network, e.g. multiple children of the same pre-terminal block. +* **`TERMINAL_TOTAL_DIFFICULTY`** The amount of total difficulty reached by the network that triggers the consensus upgrade. Ethereum Mainnet configuration **MUST** have this parameter set to the value `58750000000000000000000`. +* **`TRANSITION_BLOCK`** The earliest PoS block of the canonical chain, i.e. the PoS block with the lowest block height. +* **`POS_FORKCHOICE_UPDATED`** An event occurring when the state of the proof-of-stake fork choice is updated. +* **`FORK_NEXT_VALUE`** A block number set to the `FORK_NEXT` parameter for the upcoming consensus upgrade. +* **`TERMINAL_BLOCK_HASH`** Designates the hash of the terminal PoW block if set, i.e. if not stubbed with `0x0000000000000000000000000000000000000000000000000000000000000000`. +* **`TERMINAL_BLOCK_NUMBER`** Designates the number of the terminal PoW block if `TERMINAL_BLOCK_HASH` is set. + +#### PoS events + +Events having the `POS_` prefix in the name (PoS events) are emitted by the new proof-of-stake consensus mechanism. They signify the corresponding assertion that has been made regarding a block specified by the event. The underlying logic of PoS events can be found in the beacon chain specification. On the occurrence of each PoS event the corresponding action that is specified by this EIP **MUST** be taken. + +The details provided below must be taken into account when reading those parts of the specification that refer to the PoS events: +* Reference to a block that is contained by PoS events is provided in a form of a block hash unless another is explicitly specified. +* A `POS_FORKCHOICE_UPDATED` event contains references to the head of the canonical chain and to the most recent finalized block. Before the first finalized block occurs in the system the finalized block hash provided by this event is stubbed with `0x0000000000000000000000000000000000000000000000000000000000000000`. +* **`FIRST_FINALIZED_BLOCK`** The first finalized block that is designated by `POS_FORKCHOICE_UPDATED` event and has the hash that differs from the stub. + + +### Client software configuration + +The following set of parameters is a part of client software configuration and **MUST** be included into its binary distribution: +* `TERMINAL_TOTAL_DIFFICULTY` +* `FORK_NEXT_VALUE` +* `TERMINAL_BLOCK_HASH` +* `TERMINAL_BLOCK_NUMBER` + +*Note*: If `TERMINAL_BLOCK_HASH` is stubbed with `0x0000000000000000000000000000000000000000000000000000000000000000` then `TERMINAL_BLOCK_HASH` and `TERMINAL_BLOCK_NUMBER` parameters **MUST NOT** take an effect. + + +### PoW block processing + +PoW blocks that are descendants of any terminal PoW block **MUST NOT** be imported. This implies that a terminal PoW block will be the last PoW block in the canonical chain. + + +### Constants + +| Name | Value | +|-|-| +| **`MAX_EXTRA_DATA_BYTES`** | `32` | + +### Block structure + +Beginning with `TRANSITION_BLOCK`, a number of previously dynamic block fields are deprecated by enforcing these values to instead be constants. Each block field listed in the table below **MUST** be replaced with the corresponding constant value. + +| Field | Constant value | Comment | +|-|-|-| +| **`ommersHash`** | `0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347` | `= Keccak256(RLP([]))` | +| **`difficulty`** | `0` | | +| **`mixHash`** | `0x0000000000000000000000000000000000000000000000000000000000000000` | | +| **`nonce`** | `0x0000000000000000` | | +| **`ommers`** | `[]` | `RLP([]) = 0xc0` | + +Beginning with `TRANSITION_BLOCK`, the validation of the block's **`extraData`** field changes: The length of the block's **`extraData`** **MUST** be less than or equal to **`MAX_EXTRA_DATA_BYTES`** bytes. + +*Note*: Logic and validity conditions of block fields that are *not* specified here **MUST** remain unchanged. Additionally, the overall block format **MUST** remain unchanged. + +*Note*: Subsequent EIPs may override the constant values specified above to provide additional functionality. For an example, see [EIP-4399](./eip-4399.md). + + +### Block validity + +Beginning with `TRANSITION_BLOCK`, the block validity conditions **MUST** be altered by the following: +* Remove verification of the block's **`difficulty`** value with respect to the difficulty formula. +* Remove verification of the block's **`nonce`** and **`mixHash`** values with respect to the Ethash function. +* Remove all validation rules that are evaluated over the list of ommers and each member of this list. +* Add verification of the fields noted in the [block structure](#block-structure) section. + +*Note*: If one of the new rules fails then the block **MUST** be invalidated. + +*Note*: Validity rules that are not specified in the list above **MUST** remain unchanged. + +#### Transition block validity + +In addition to satisfying the above conditions, `TRANSITION_BLOCK` **MUST** be a child of a terminal PoW block. That is, a parent of `TRANSITION_BLOCK` **MUST** satisfy terminal PoW block conditions. + + +### Block and ommer rewards + +Beginning with `TRANSITION_BLOCK`, block and ommer rewards are deprecated. Specifically, the following actions **MUST** be taken: +* Remove increasing the balance of the block's **`beneficiary`** account by the block reward. +* Remove increasing the balance of the block's **`beneficiary`** account by the ommer inclusion reward per each ommer. +* Remove increasing the balance of the ommer's **`beneficiary`** account by the ommer block reward per each ommer. + +*Note*: Transaction fee mechanics affecting the block's `beneficiary` account **MUST** remain unchanged. + + +### Fork choice rule + +If set, `TERMINAL_BLOCK_HASH` parameter affects the PoW heaviest chain rule in the following way: +* Canonical blockchain **MUST** contain a block with the hash defined by `TERMINAL_BLOCK_HASH` parameter at the height defined by `TERMINAL_BLOCK_NUMBER` parameter. + +*Note*: This rule is akin to block hash whitelisting functionality already present in client software implementations. + +As of the first `POS_FORKCHOICE_UPDATED` event, the fork choice rule **MUST** be altered in the following way: +* Remove the existing PoW heaviest chain rule. +* Adhere to the new PoS LMD-GHOST rule. + +The new PoS LMD-GHOST fork choice rule is specified as follows. On each occurrence of a `POS_FORKCHOICE_UPDATED` event including the first one, the following actions **MUST** be taken: +* Consider the chain starting at genesis and ending with the head block nominated by the event as the canonical blockchain. +* Set the head of the canonical blockchain to the corresponding block nominated by the event. +* Beginning with the `FIRST_FINALIZED_BLOCK`, set the most recent finalized block to the corresponding block nominated by the event. + +Changes to the block tree store that are related to the above actions **MUST** be applied atomically. + +*Note*: This rule **MUST** be strictly enforced. "Optimistic" updates to the head **MUST NOT** be made. That is -- if a new block is processed on top of the current head block, this new block becomes the new head if and only if an accompanying `POS_FORKCHOICE_UPDATED` event occurs. + +### Network + +#### Fork identifier + +For the purposes of the [EIP-2124](./eip-2124.md) fork identifier, nodes implementing this EIP **MUST** set the `FORK_NEXT` parameter to the `FORK_NEXT_VALUE`. + +#### devp2p + +The networking stack **SHOULD NOT** send the following messages if they advertise the descendant of any terminal PoW block: +* `NewBlockHashes (0x01)` +* `NewBlock (0x07)` + +Beginning with receiving the `FIRST_FINALIZED_BLOCK`, the networking stack **MUST** discard the following ingress messages: +* `NewBlockHashes (0x01)` +* `NewBlock (0x07)` + +Beginning with receiving the finalized block next to the `FIRST_FINALIZED_BLOCK`, the networking stack **MUST** remove the handlers corresponding to the following messages: +* `NewBlockHashes (0x01)` +* `NewBlock (0x07)` + +Peers that keep sending these messages after the handlers have been removed **SHOULD** be disconnected. + +*Note:* The logic of message handlers that are not affected by this section **MUST** remain unchanged. + + +## Rationale + +The changes specified in this EIP target a minimal requisite set of consensus and client software modifications to safely replace the existing proof-of-work consensus algorithm with the new proof-of-stake consensus represented by the already in-production beacon chain. + +This EIP was designed to minimize the complexity of hot-swapping the live consensus of the Ethereum network. Both the safety of the operation and time to production were taken into consideration. Additionally, a minimal changeset helps ensure that *most* smart contracts and services will continue to function as intended during and after the transition with little to no required intervention. + +### Total difficulty triggering the upgrade + +See [Security considerations](#terminal-total-difficulty-vs-block-number). + +### Parameterizing terminal block hash + +See [Security considerations](#terminal-pow-block-overriding). + +### Halting the import of PoW blocks + +See [Security considerations](#halt-the-importing-of-pow-blocks). + +### Replacing block fields with constants + +Deprecated block fields are replaced with constant values to ensure the block format remains backwards compatible. Preserving the block format aids existing smart contracts and services in providing uninterrupted service during and after this transition. + +Particularly, this is important for those smart contracts that verify Merkle proofs of transaction/receipt inclusion and state by validating the hash of externally provided block header against the corresponding value returned by the `BLOCKHASH` operation. + +This change introduces an additional validity rule that enforces the replacement of deprecated block fields. + +### Replacing `difficulty` with `0` + +After deprecating the proof-of-work the notion of difficulty no longer exists and replacing the block header **`difficulty`** field with `0` constant is semantically sound. + +### Changing block validity rules + +The rule set enforcing the PoW seal validity is replaced with the corresponding PoS rules along with the consensus upgrade as the rationale behind this change. + +An additional rule validating a set of deprecated block fields is required by the block format changes introduced by this specification. + +### Removing block rewards + +Existing rewards for producing and sealing blocks are deprecated along with the PoW mechanism. The new PoS consensus becomes both responsible for sealing blocks and for issuing block rewards once this specification enters into effect. + +### Supplanting fork choice rule + +The fork choice rule of the PoW mechanism becomes completely irrelevant after the upgrade and is replaced with the corresponding rule of the new PoS consensus mechanism. + +### Remove of `POS_CONSENSUS_VALIDATED` + +In prior draft versions of this EIP, an additional POS event -- `POS_CONSENSUS_VALIDATED` -- was required as a validation condition for blocks. This event gave the signal to either fully incorporate or prune the block from the block tree. + +This event was removed for two reasons: +1. This event was an unnecessary optimization to allow for pruning of "bad" blocks from the block tree. This optimization was unnecessary because the PoS consensus would never send `POS_FORKCHOICE_UPDATED` for any such bad blocks or their descendants, and eventually any such blocks would be able to be pruned after a PoS finality event of an alternative branch in the block tree. +2. This event was dangerous in some scenarios because a block could be referenced by two *different* and conflicting PoS branches. Thus for the same block in some scenarios, both a `POS_CONSENSUS_VALIDATED == TRUE` and `POS_CONSENSUS_VALIDATED == FALSE` event could sent, entirely negating the ability to safely perform the optimization in (1). + +### EIP-2124 fork identifier + +The value of `FORK_NEXT` in EIP-2124 refers to the block number of the next fork a given node knows about and `0` otherwise. + +The number of `TRANSITION_BLOCK` cannot be known ahead of time given the dynamic nature of the transition trigger condition. As the block will not be known a priori, nodes can't use its number for `FORK_NEXT` and in light of this fact an explicitly set `FORK_NEXT_VALUE` is used instead. + +### Removing block gossip + +After the upgrade of the consensus mechanism only the beacon chain network will have enough information to validate a block. Thus, block gossip provided by the `eth` network protocol will become unsafe and is deprecated in favour of the block gossip existing in the beacon chain network. + +It is recommended for the client software to not propagate descendants of any terminal PoW block to reduce the load on processing the P2P component and stop operating in the environment with unknown security properties. + +### Restricting the length of `extraData` + +The `extraData` field is defined as a maximum of `32` bytes in the yellow paper. Thus mainnet and most PoW testnets cap the value at `32` bytes. `extraData` fields of greater length are used by clique testnets and other networks to carry special signature/consensus schemes. This EIP restricts the length of `extraData` to `32` bytes because any network that is transitioning from another consensus mechanism to a beacon chain PoS consensus mechanism no longer needs extended or unbounded `extraData`. + +## Backwards Compatibility + +This EIP introduces backward incompatibilities in block validity, block rewards and fork choice rule. + +The design of the consensus upgrade specified by this document does not introduce backward incompatibilities for existing applications and services built on top of Ethereum except for those that are described in the [EVM](#evm) section below or heavily depends on the PoW consensus in any other way. + + +### EVM + +Although this EIP does not introduce any explicit changes to the EVM there are a couple of places where it may affect the logic of existing smart contracts. + +#### DIFFICULTY + +`DIFFICULTY` operation will always return `0` after this EIP takes effect and deprecates the **`difficulty`** field by replacing it with `0` constant. + +*Note:* Altering the `DIFFICULTY` semantics to return randomness accumulated by the beacon chain is under consideration but will be introduced in a separate EIP. + +#### BLOCKHASH + +Pseudo-random numbers obtained as the output of `BLOCKHASH` operation become more insecure after this EIP takes effect and the PoW mechanism (which decreases the malleability of block hashes) gets supplanted by PoS. + + +## Test Cases + +* Block validity + * Beginning with `TRANSITION_BLOCK`, block is invalidated if any of the following is true: + * `ommersHash != Keccak256(RLP([]))` + * `difficulty != 0` + * `nonce != 0x0000000000000000` + * `len(extraData) > MAX_EXTRA_DATA_BYTES` + * Beginning with `TRANSITION_BLOCK`, block rewards aren't added to `beneficiary` account +* Client software adheres to PoS LMD-GHOST rule + * Head and finalized blocks are set according to the recent `POS_FORKCHOICE_UPDATED` event + * No fork choice state is updated unless `POS_FORKCHOICE_UPDATED` event is received +* Transition process + * Client software doesn't process any PoW block beyond a terminal PoW block + * Beginning with `TRANSITION_BLOCK`, client software applies new block validity rules + * Beginning with the first `POS_FORKCHOICE_UPDATED`, client software switches its fork choice rule to PoS LMD-GHOST + * `TRANSITION_BLOCK` must be a child of a terminal PoW block + * `NewBlockHashes (0x01)` and `NewBlock (0x07)` network messages are discarded after receiving the `FIRST_FINALIZED_BLOCK` + + +## Security Considerations + +### Beacon chain + +See Security Considerations section of [EIP-2982](./eip-2982.md#security-considerations). + +### Transition process + +The transition process used to take this specification into effect is a more sophisticated version of a hardfork -- the regular procedure of applying backwards incompatible changes in the Ethereum network. This process has multiple successive steps instead of the normal block-height point condition of simpler hardforks. + +The complexity of this upgrade process stems from this fork targeting the underlying consensus mechanism rather than the execution layer within the consensus mechanism. Although the design seeks simplicity where possible, safety and liveness considerations during this transition have been prioritized. + +#### Terminal total difficulty vs block number + +Using a pre-defined block number for the hardfork is unsafe in this context due to the PoS fork choice taking priority during the transition. + +An attacker may use a minority of hash power to build a malicious chain fork that would satisfy the block height requirement. Then the first PoS block may be maliciously proposed on top of the PoW block from this adversarial fork, becoming the head and subverting the security of the transition. + +To protect the network from this attack scenario, difficulty accumulated by the chain (total difficulty) is used to trigger the upgrade. + +#### Ability to jump between terminal PoW blocks + +There could be the case when a terminal PoW block is not observed by the majority of network participants due to (temporal) network partitioning. In such a case, this minority would switch their fork choice to the new rule provided by the PoS rooted on the minority terminal PoW block that they observed. + +The transition process allows the network to re-org between forks with different terminal PoW blocks as long as (a) these blocks satisfy the terminal PoW block conditions and (b) the `FIRST_FINALIZED_BLOCK` has not yet been received. This provides resilience against adverse network conditions during the transition process and prevents irreparable forks/partitions. + +#### Halt the importing of PoW blocks + +Suppose the part of the client software that is connected to the beacon chain network goes offline before the Ethereum network reaches the `TERMINAL_TOTAL_DIFFICULTY` and stays offline while the network meets this threshold. Such an event makes the client software unable to switch to PoS and allows it to keep following the PoW chain if this chain is being built beyond the terminal PoW block. Depending on how long the beacon chain part was offline, it could result in different adverse effects such as: +* The client has no post-state for the terminal PoW block (the state has been pruned) which prevents it from doing the re-org to the PoS chain and leaving syncing from scratch as the only option to recover. +* An application, a user or a service uses the data from the wrong fork (PoW chain that is kept being built) which can cause security issues on their side. + +Not importing PoW blocks that are beyond the terminal PoW block prevents these adverse effects on safety/re-orgs in the event of software or configuration failures *in favor* of a liveness failure. + +#### Terminal PoW block overriding + +There is a mechanism allowing for accelerating the consensus upgrade in emergency cases. +This EIP considers the following emergency case scenarios for the acceleration to come into effect: +* A drop of the network hashing rate which delays the upgrade significantly. +* Attacks on the PoW network before the upgrade. + +The first case can be safely accelerated by updating the following parameters: +* `TERMINAL_TOTAL_DIFFICULTY` -- reset to a value that is closer in time than the original one. +* `FORK_NEXT_VALUE` -- adjust accordingly. + +The second, more dire attack scenario requires a more invasive override: +* `TERMINAL_BLOCK_HASH` -- set to the hash of a certain block to become the terminal PoW block. +* `TERMINAL_BLOCK_NUMBER` -- set to the number of a block designated by `TERMINAL_BLOCK_HASH`. +* `TERMINAL_TOTAL_DIFFICULTY` -- set to the total difficulty value of a block designated by `TERMINAL_BLOCK_HASH`. +* `FORK_NEXT_VALUE` -- adjust accordingly. + +*Note*: Acceleration in the second case is considered for the most extreme of scenarios because it will result in a non-trivial liveness failure on Ethereum Mainnet. + +### Ancient blocks are no longer a requisite for a network security + +Keeping historical blocks starting from genesis is essential in the PoW network. A header of every block that belongs to a particular chain is required to justify the validity of this chain with respect to the PoW seal. + +Validating the entire history of the chain is not required by the new PoS mechanism. Instead, the sync process in the PoS network relies on weak subjectivity checkpoints, which are historical snapshots shared by peers on the network. This means historical blocks beyond weak subjectivity checkpoint are no longer a requisite for determining the canonical blockchain. + +Specification of weak subjectivity checkpoints can be found in the `ethereum/consensus-specs` repository. + + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3690.md b/EIPS/eip-3690.md new file mode 100644 index 00000000000000..deeb8f7edd4896 --- /dev/null +++ b/EIPS/eip-3690.md @@ -0,0 +1,267 @@ +--- +eip: 3690 +title: EOF - JUMPDEST Table +description: A special EOF section for storing the list of JUMPDESTs, which simplifies execution time analysis. +author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast), Andrei Maiboroda (@gumb0) +discussions-to: https://ethereum-magicians.org/t/eip-3690-eof-jumpdest-table/6806 +status: Stagnant +type: Standards Track +category: Core +created: 2021-06-23 +requires: 3540, 3670 +--- + +## Abstract + +Introduce a section in the EOF format ([EIP-3540](./eip-3540.md)) for storing the list of `JUMPDEST`s, validate the correctness of this list at the time of contract creation, and remove the need for `JUMPDEST`-analysis at execution time. In EOF contracts, the `JUMPDEST` instruction is not needed anymore and becomes invalid. Legacy contracts are entirely unaffected by this change. + +## Motivation + +Currently existing contracts require no validation of correctness, but every time they are executed, a list must be built containing all the valid jump-destinations. This is an overhead which can be avoided, albeit the effect of the overhead depends on the client implementation. + +With the structure provided by EIP-3540 it is easy to store and transmit a table of valid jump-destinations instead of using designated `JUMPDEST` (0x5b) opcodes in the code. + +The goal of this change is that we trade less complexity (and processing time) at execution time for more complexity at contract creation time. Through benchmarks we have identified that the mandatory execution preparation time is the same as before for extreme cases (i.e. deliberate edge cases), while it is ~10x faster for the average case. + +Finally, this change puts an implicit bound on "initcode analysis" which is now limited to jumpdests section loading of max size of 0xffff. The legacy code remains vulnerable. + +## Specification + +This feature is introduced on the very same block [EIP-3540](./eip-3540.md) is enabled, therefore every EOF1-compatible bytecode MUST have a JUMPDEST-table if it uses jumps. + +*Remark:* We rely on the notation of *initcode*, *code* and *creation* as defined by [EIP-3540](./eip-3540.md), and extend validation rules of [EIP-3670](./eip-3670.md). + +### EOF container changes + +1. A new EOF section called `jumpdests` (`section_kind = 3`) is introduced. It contains a sequence of *n* unsigned integers *jumploci*. +2. The *jumploci* values are encoded with [unsigned LEB128](https://en.wikipedia.org/wiki/LEB128#Unsigned_LEB128). + + | description | encoding | + |---------------------|-----------------| + | jumploc0 | unsigned LEB128 | + | jumploc1 | unsigned LEB128 | + | ... | | + | jumplocn | unsigned LEB128 | + +3. The jump destinations represent the set of valid code positions as arguments to jump instructions. They are delta-encoded therefore partial sum must be performed to retrieve the absolute offsets. + ```python + def jumpdest(n: int, jumpdests_table: list[int]) -> int: + return sum(jumpdests_table[:n+1]) + ``` + +### Validation rules + +> This section extends contract creation validation rules (as defined in EIP-3540). + +4. The `jumpdests` section MUST be present if and only if the `code` section contains `JUMP` or `JUMPI` opcodes. +5. If the `jumpdests` section is present it MUST directly precede the `code` section. In this case a valid EOF bytecode will have the form of `format, magic, version, [jumpdests_section_header], code_section_header, [data_section_header], 0, [jumpdests_section_contents], code_section_contents, [data_section_contents]`. +6. The LEB128 encoding of a `jumploc` must be valid: the encoding must be complete and not read out of `jumpdests` section. As an additional constraint, the shortest possible encoding must be used. +7. With an exception of the first entry, the value of `jumploc` MUST NOT be 0. +8. Every `jumploc` MUST point to a valid opcode. They MUST NOT point into PUSH-data or outside of the code section. +9. The `JUMPDEST` (0x5b) instruction becomes undefined (Note: According to rules of EIP-3670, deploying the code will fail if it contains `JUMPDEST`) + +### Execution + +10. When executing `JUMP` or `JUMPI` instructions, the jump destination MUST be in the `jumpdests` table. Otherwise, the execution aborts with *bad jump destination*. In case of `JUMPI`, the check is done only when the jump is to be taken (no change to the previous behaviour). + +## Rationale + +### Jumpdests section is bounded + +The length of the `jumpdests` section is bounded by the EOF maximum section size value 0xffff. Moreover, for deployed code this is additionally limited by the max bytecode size 0x6000. Then any valid `jumpdests` section may not be larger than 0x3000. + +### Delta encoding + +Delta-encoding is very efficient for this job. From a quick analysis of a small set of contracts `JUMPDEST` opcodes are relatively close to each other. In the delta-encoding the values almost never exceed 128. Combined with any form of variable-length quantity (VLQ) where values < 128 occupy one byte, encoding of single jumpdest takes ~1 byte. We also remove `JUMPDEST` opcodes from the code section therefore the total bytecode length remains the same if extreme examples are ignored. + +By extreme examples we mean contracts having a distance between two subsequent JUMPDESTs larger than 128. Then the LEB128 encoding of such distance requires more than one byte and the total bytecode size will increase by the additional number of bytes used. + +### LEB128 for offsets + +The LEB128 encoding is the most popular VLQ used in DWARF and WebAssembly. + +LEB128 allows encoding a fixed value with arbitrary number of bytes by having zero payloads for most significant bits of the value. To ensure there exists only single encoding of a given value, we additionally require the shortest possible LEB128 encoding to be used. This constraint is also required by WebAssembly. + +### Size-prefix for offsets + +This is another option for encoding inspired by UTF-8. The benefit is that the number of following bytes is encoded in the first byte (the top two bits), so the expected length is known upfront. + +A simple decoder is the following: +```python +def decode(input: bytes) -> int: + size_prefix = input[0] >> 6 + if size_prefix == 0: + return input[0] & 0x3f + elif size_prefix == 1: + return (input[0] & 0x3f) << 8 | input[1] + elif size_prefix == 2: + return (input[0] & 0x3f) << 16 | (input[1] << 8) | input[2] + # Do not support case 3 + assert(False) +``` + +### Empty table + +In case code does not use jumps, an empty JUMPDEST table is represented by omitting `jumpdests` section as opposed to a section that is always present, but allowed to be empty. This is consistent with the requirement of EIP-3540 for section size to be non-zero. Additionally, omitting the section saves 3 bytes of code storage. + +### Why jumpdests before code? + +The contents of `jumpdests` section are always needed to start EVM execution. For chunked and/or merkleized bytecode it is more efficient to have `jumpdests` just after the EOF header so they can share the same first chunk(s). + +### Code chunking / merkleization + +In code chunking the contract code is split into (fixed size) chunks. Due to the requirement of jumpdest-analysis, it must be known where the first instruction starts in a given chunk, in case the split happened within a PUSH-data. This is commonly accomplished with reserving the first byte of the chunk as the "first instruction offset" (FIO) field. + +With this EIP, code chunking does not need to have such a field. However, the jumpdest table must be provided instead (for all the chunks up until the last jump location used during execution). + +### Benchmarks / performance analysis + +We compared the performance of `jumpdests` section loading to JUMPDEST analysis in evmone/Baseline interpreter. In both cases a bitset of valid jumpdest positions is built. + +We used the worst case for `jumpdests` section as the benchmark baseline. This is the case where every position in the code section is valid jumpdest. I.e. the bytecode has as many jumpdests as possible making the jumpdests section as large as possible. The encoded representation is `0x00, 0x01, 0x01, 0x01, ...`. + +This also happen to be the worst case for the JUMPDEST analysis. + +Further, we picked 5 popular contracts from the Ethereum mainnet. + +| case | size | num JUMPDESTs | JUMPDEST analysis (cycles/byte) | jumpdests load (cycles/byte) | performance change | +| ----------------- | ----- | ----- | ---- | ---- | ------- | +| worst | 65535 | 65535 | 9.11 | 9.36 | 2.75% | +| RoninBridge | 1760 | 71 | 3.57 | | -89.41% | +| UniswapV2ERC20 | 2319 | 61 | 2.10 | | -88.28% | +| DepositContract | 6358 | 123 | 1.86 | | -90.24% | +| TetherToken | 11075 | 236 | 1.91 | | -89.58% | +| UniswapV2Router02 | 21943 | 468 | 2.26 | | -91.17% | + +For the worst case the performance difference between JUMPDEST analysis and jumpdests section loading is very small. The performance very slow compared to memory copy (0.15 cycles/byte). + +However, the maximum length for the worst cases is different. For JUMPDEST analysis this is 24576 (0x6000) for deployed contracts and only limited by EVM memory cost in case of _initcode_ (can be over 1MB). For jumpdests sections, the limit is 12288 for deployed contracts (the deployed bytecode length limit must be split equally between jumpdests and code sections). For _initcode_ case, the limit is 65535 because this is the maximum section size allowed by EOF. + +For "popular" contracts the gained efficiency is ~10x because the jumpdests section is relatively small compared to the code section and therefore there is much less bytes to loop over than in JUMPDEST analysis. + +## Reference Implementation + +We extend the `validate_code()` function of [EIP-3670](./eip-3670.md): +```python +# The same table as in EIP-3670 +valid_opcodes = ... + +# Remove JUMPDEST from the list of valid opcodes +valid_opcodes.remove(0x5b) + +# This helper decodes a single unsigned LEB128 encoded value +# This will abort on truncated (short) input +def leb128u_decode(input: bytes) -> (int, int): + ret = 0 + shift = 0 + consumed_bytes = 0 + while True: + # Check for truncated input + assert(consumed_bytes < len(input)) + # Only allow up to 4-byte long leb128 encodings + assert(consumed_bytes <= 3) + input_byte = input[consumed_bytes] + consumed_bytes += 1 + ret |= (input_byte & 0x7f) << shift + if (input_byte & 0x80) == 0: + # Do not allow additional leading zero bits. + assert(input_byte != 0 || consumed_bytes == 0) + break + shift += 7 + return (ret, consumed_bytes) + +# This helper parses the jumpdest table into a list of relative offsets +# This will abort on truncated (short) input +def parse_table(input: bytes) -> list[int]: + jumpdests = [] + pos = 0 + while pos < len(input): + value, consumed_bytes = leb128u_decode(input[pos:]) + jumpdests.append(value) + pos += consumed_bytes + return jumpdests + +# This helper translates the delta offsets into absolute ones +# This will abort on invalid 0-value entries +def process_jumpdests(delta: list[int]) -> list[int]: + jumpdests = [] + partial_sum = 0 + first = True + for d in delta: + if first: + first = False + else: + assert(d != 0) + partial_sum += d + jumpdests.append(partial_sum) + return jumpdests + +# Fails with assertion on invalid code +# Expects list of absolute jumpdest offsets +def validate_code(code: bytes, jumpdests: list[int]): + pos = 0 + while pos < len(code): + # Ensure the opcode is valid + opcode = code[pos] + pos += 1 + assert(opcode in valid_opcodes) + + # Remove touched offset + try: + jumpdests.remove(pos) + except ValueError: + pass + + # Skip pushdata + if opcode >= 0x60 and opcode <= 0x7f: + pos += opcode - 0x60 + 1 + + # Ensure last PUSH doesn't go over code end + assert(pos == len(code)) + + # The table is invalid if there are untouched locations + assert(len(jumpdests) == 0) +``` + +## Test Cases + +#### Valid bytecodes + +- No jumpdests +- Every byte is a jumpdest +- Distant jumpdests (0x7f and 0x3f01 bytes apart) +- Max number of jumpdests + - 1-byte offset encoding: initcode of max size (64K) with jumpdest at each byte - table contains 65536 1-byte offsets, first one is 0x00, all others equal 0x01 + - 2-byte offset encoding: inicode of max size with jumpdests 0x80 (128) bytes apart - table contains 512 offsets, first one is 0x7f (127), all others equal 0x8001 + - 3-byte offset encoding: inicode of max size with jumpdests 0x4000 (16384) bytes apart - table contains 4 offsets: 0xFF7F (16383), 0x808001, 0x808001, 0x808001 + +#### Invalid bytecodes + +- Empty jumpdest section +- Multiple jumpdest sections +- jumpdest section after the code section +- jumpdest section after the data section +- Final jumploc in the table is truncated (not a valid LEB128) +- LEB128 encoding with extra 0s (non-minimal encoding) +- Jumpdest location pointing to PUSH data +- Jumpdest location out of code section bounds + - pointing into data section + - pointing into jumpdest section + - pointing outside container bounds +- Duplicate jumpdest locations (0 deltas in table other than 1st offset) +- Code containing `JUMP` but no jumpdest table +- Code containing `JUMPI` but no jumpdest table +- Code containing jumpdest table but not `JUMP`/`JUMPI` +- Code containing `JUMPDEST` + +## Backwards Compatibility + +This change poses no risk to backwards compatibility, as it is introduced at the same time EIP-3540 is. The requirement of a JUMPDEST table does not cover legacy bytecode. + +## Security Considerations + +The authors are not aware of any security or DoS risks posed by this change. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3709.md b/EIPS/eip-3709.md new file mode 100644 index 00000000000000..3d8e771353d756 --- /dev/null +++ b/EIPS/eip-3709.md @@ -0,0 +1,45 @@ +--- +eip: 3709 +title: Remove Support for Type 1 Transactions +author: Gregory Markou (@GregTheGreek) +discussions-to: https://ethereum-magicians.org/t/eip-3709-deprecate-type-1-transactions/6810 +status: Stagnant +type: Standards Track +category: Interface +created: 2021-08-07 +requires: 1559 +--- + +## Simple Summary + +Deprecates usage of [EIP-2718](./eip-2718.md) `TransactionType` 1 in wallets and providers, upgrading all type 1 transactions to a type 2 transaction. + +## Abstract + +Since both `TransactionType` 1 and 2 contain `access_list`, we propose the removal of offering `TransactionType` 1 from wallets and providers, instead the transaction will be converted to `TransactionType` 2 to make use of the new gas properties introduced by [EIP-1559](./eip-1559.md). + +## Motivation + +[EIP-2930](./eip-2930.md) was introduced as the first `TransactionType`, type 1, with the intention of adding `access_list` to the `TransactionPayload`. [EIP-1559](./eip-1559.md) introduced the second `TransactionType` 2, which is represented as `rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list, signature_y_parity, signature_r, signature_s])`. The intention behind EIP-1559 was to enhance the user experience surrounding gas fees, and as we move forward we expect that the majority of the network will begin to using `TransactionType` 2 instead of the legacy style transactions. `TransactionType` 1 is a legacy transaction with the addition of `access_list` meaning that users will not benefit from enhancements made by EIP-1559. `TransactionType` 2 contains `access_list`, thus there is no reason to further support `TransactionType` 1 if the end goal is to push users towards using `TransactionType` 2 anyway. + + +## Specification + +For wallets and providers, if a user submits a transaction for signing with where `TransactionType == 0x1`, the developer should upgrade the transaction to meet the criteria of transaction of type 2. + +The following fields need to be changed, or amended: +- `access_list`: Nothing changes and it should remain in the transaction. +- `type`: Should change from `0x1` to `0x2`. +- `gas_price`: Should be removed in favour of `max_fee_per_gas` & `max_priority_fee_per_gas` (see [EIP-1559](./eip-1559.md) for proper usage). + +## Rationale + +Improve the user experience for submitting transactions, and move away from legacy style transactions. + +## Security Considerations + +There are no known security considerations at this time. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3722.md b/EIPS/eip-3722.md new file mode 100644 index 00000000000000..37c188bc0c1475 --- /dev/null +++ b/EIPS/eip-3722.md @@ -0,0 +1,7 @@ +--- +eip: 3722 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3722.md diff --git a/EIPS/eip-3754.md b/EIPS/eip-3754.md new file mode 100644 index 00000000000000..c0260b4922d694 --- /dev/null +++ b/EIPS/eip-3754.md @@ -0,0 +1,7 @@ +--- +eip: 3754 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3754.md diff --git a/EIPS/eip-3756.md b/EIPS/eip-3756.md new file mode 100644 index 00000000000000..59fe6a4cd3522d --- /dev/null +++ b/EIPS/eip-3756.md @@ -0,0 +1,55 @@ +--- +eip: 3756 +title: Gas Limit Cap +description: Set an in-protocol cap for the gas limit +author: lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-3756-gas-limit-cap/6921 +status: Stagnant +type: Standards Track +category: Core +created: 2021-08-21 +--- + +## Abstract + +Set an in-protocol cap for the gas limit of 30,000,000. + +## Motivation + +A high gas limit increases pressure on the network. In the benign case, it +increases the size of the state and history faster than we can sustain. In the +malicious case, it amplifies the devastation of certain denial-of-service +attacks. + +## Specification + +As of the fork block `N`, consider blocks with a `gas_limit` greater than +`30,000,000` invalid. + +## Rationale + +### Why Cap the Gas Limit + +The gas limit is currently under the control of block proposers. They have the +ability to increase the gas limit to whatever value they desire. This allows +them to bypass the EIP and All Core Devs processes in protocol decisions that +may negatively affect the security and/or decentralization of the network. + +### No Fixed Gas Limit + +A valuable property of proposers choosing the gas limit is they can scale it +down quickly if the network becomes unstable or is undergoing certain types of +attacks. For this reason, we maintain their ability to lower the gas limit +_below_ 30,000,000. + +## Backwards Compatibility +No backwards compatibility issues. + +## Test Cases +TBD + +## Security Considerations +No security considerations. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3770.md b/EIPS/eip-3770.md new file mode 100644 index 00000000000000..ab8a0be4e426a3 --- /dev/null +++ b/EIPS/eip-3770.md @@ -0,0 +1,7 @@ +--- +eip: 3770 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3770.md diff --git a/EIPS/eip-3772.md b/EIPS/eip-3772.md new file mode 100644 index 00000000000000..3692470f74261b --- /dev/null +++ b/EIPS/eip-3772.md @@ -0,0 +1,7 @@ +--- +eip: 3772 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3772.md diff --git a/EIPS/eip-3779.md b/EIPS/eip-3779.md new file mode 100644 index 00000000000000..e8c02082a69dfe --- /dev/null +++ b/EIPS/eip-3779.md @@ -0,0 +1,413 @@ +--- +eip: 3779 +title: Safer Control Flow for the EVM +description: Ensure an essential level of safety for EVM code. +author: Greg Colvin (@gcolvin), Greg Colvin , Brooklyn Zelenka (@expede) +discussions-to: https://ethereum-magicians.org/t/eip-3779-safe-control-flow-for-the-evm/6975 +status: Withdrawn +type: Standards Track +category: Core +created: 2021-08-30 +withdrawal-reason: material moved to EIP-2315 +--- + +## Abstract + +We define a safe EVM contract as one that cannot encounter an exceptional halting state. In general, we cannot prove safety for Turing-complete programs. But we can prove a useful subset. + +This EIP specifies validity rules to ensure that: +> Valid contracts will not halt with an exception unless they either +> * throw `out of gas` or +> * recursively overflow stack. + +This EIP does not introduce any new opcodes. Rather, it restricts the use of existing and proposed control-flow instructions. The restrictions must be validated at contract initialization time – not at runtime – by the provided algorithm or its equivalent. This algorithm must take time and space near-linear in the size of the contract, so as not to be a denial of service vulnerability. + +This specification is entirely semantic. It imposes no further syntax on bytecode, as none is required to ensure the specified level of safety. Ethereum Virtual Machine bytecode is just that -- a sequence of bytes that when executed causes a sequence of changes to the machine state. The safety we seek here is simply to not, as it were, jam up the gears. + +## Motivation + +### Safety + +For our purposes we define a safe EVM contract as one that cannot encounter an exceptional halting state. From the standpoint of security it would be best if unsafe contracts were never placed on the blockchain. Unsafe code can attempt to overflow stack, underflow stack, execute invalid instructions, and jump to invalid locations. + +Unsafe contracts are exploits waiting to happen. + +Validating contract safety requires traversing the contract code. So in order to prevent denial of service attacks all jumps, including the existing `JUMP` and `JUMPI`, and also the other proposed jumps -- `RJUMP`, `RJUMPI`, `RJUMPSUB` and `RETURNSUB` -- must be validated at initialization time, and in time and space linear in the size of the code. + +#### Static Jumps and Subroutines + +The relative jumps of [EIP-4200](./eip-4200) and the simple subroutines of [EIP-2315](./eip-2315) provide a complete set of static control flow instructions: +> `RJUMP` _offset_ +* Jumps to _IP+offset_. +> `RJUMPI` _offset_ +* Jumps if the top of stack is non-zero. +> `RJUMPSUB` offset +* Pushes _IP+1_ on the return stack and jumps to _IP+offset_. +> `RETURNSUB` +* Jumps to the address popped off the return stack. + +Note that each jump creates at most two paths of control through the code, such that the complexity of traversing the entire control-flow graph is linear in the size of the code. + +#### *Dynamic Jumps* + +Dynamic jumps, where the destination of a `JUMP` or `JUMPI` is not known until runtime, are an obstacle to proving validity in linear time -- any jump can be to any destination in the code, potentially requiring time quadratic in the size of code. For this reason we have two real choices. + +1. Deprecate dynamic jumps. This is easily done: + +> Define `JUMP` and `JUMPI` as `INVALID` for the purposes of EOF Code Validation + +2. Constrain dynamic jumps. This requires static analysis. + +Consider the simplest and most common case. +``` +PUSH address +JUMP +``` +This is effectively a static jump. + +Another important use of `JUMP` is to implement the return jump from a subroutine. So consider this example of calling and returning from a minimal subroutine: +``` +TEST_SQUARE: + jumpdest + push RTN_SQUARE + 0x02 + push SQUARE + jump +RTN_SQUARE + jumpdest + swap1 + jump + +SQUARE: + jumpdest + dup1 + mul + swap1 + jump +``` +The return address -`RTN_SQUARE` - and the destination address - `SQUARE` - are pushed on the stack as constants and remain unchanged as they move on the stack, such that only those constants are passed to each `JUMP`. They are effectively static. We can track the motion of constants on the `data stack` at validation time, so *we do not need unconstrained dynamic jumps to implement subroutines.* + +*The above is the simplest analysis that suffices. A more powerful analysis that takes in more use cases is possible -- slower, but still linear-time.* + +#### Validation + +We can validate the safety of contracts with a static analysis that takes time and space linear in the size of the *code*, as shown below. And since we can, we should. + +### Performance + +Validating safe control flow at initialization time has potential performance advantages. +* Static jumps do not need to be checked at runtime. +* Stack underflow does not need to be checked for at runtime. + +## Specification + +### Validity + +> In theory, theory and practice are the same. In practice, they're not. -- Albert Einstein + +We define a _safe_ EVM contract as one that cannot encounter an exceptional halting state. We validate _safety_ at initialization time to the extent practical. + +#### *Exceptional Halting States* + +The *execution* of each instruction is defined in the Yellow Paper as a change to the EVM state that preserves the invariants of EVM state. At runtime, if the execution of an instruction would violate an invariant the EVM is in an exceptional halting state. The Yellow Paper defined five such states. +1. Insufficient gas +2. More than 1024 stack items +3. Insufficient stack items +4. Invalid jump destination +5. Invalid instruction + +*A program is safe iff no execution can lead to an exceptional halting state.* + +*We would like to consider EVM programs valid iff they are safe.* + +*In practice*, we must be able to validate *code* in linear time to avoid denial of service attacks. And we must support dynamically-priced instructions, loops, and recursion, which can use arbitrary amounts of gas and stack. + +Thus our validation cannot consider concrete computations -- it only performs a limited symbolic execution of the _code_. This means we will reject programs if we detect any invalid execution paths, even if those paths are not reachable at runtime. And we will count as valid programs that may not always produce correct results. + +We can detect only _non-recursive_ stack overflows at *validation time*, so we must check for the first two states at _runtime_: +* `out of gas` and +* stack overflow. + +The remaining three states we can check at *validation time*: +* stack underflow, +* invalid jump, and +* invalid instruction. + +That is to say: +> Valid contracts will not halt with an exception unless they either +> * throw `out of gas` or +> * recursively overflow stack. + +#### *Constraints on Valid Code* + +* Every instruction is valid. +* Every jump is valid: + * Every`JUMP` and `JUMPI` is *static*. + * No `JUMP`, `JUMPI`, `RJUMP`, `RJUMPI`, or `RJUMPSUB` addresses immediate data. +* The stacks are always valid: + * The _number_ of items on the `data stack` is always positive, and at most 1024. + * The _number_ of items on the `return stack` is always positive, and at most 1024. +* The data stack is consistently aligned: + * The _number_ of items on the `data stack` between the current `stack pointer` and the `stack pointer` on entry to the most recent basic block is the same for each _execution_ of a _byte_code_. + +We define a `JUMP` or `JUMPI` instruction to be *static* if its `jumpsrc` argument was first placed on the stack via a `PUSH…` and that value has not changed since, though it may have been copied via a `DUP…` or `SWAP…`. + +The `RJUMP`, `RJUMPI` and `RJUMPSUB`instructions take their destination as an immediate argument, so they are *static*. + +Taken together, these rules allow for code to be validated by traversing the control-flow graph, in time and space linear in the size of the code, following each edge only once. + +_Note: The definition of 'static' for `JUMP` and `JUMPI` is the bare minimum needed to implement subroutines. Deeper analyses could be proposed that would validate a larger and probably more useful set of jumps, at the cost of more expensive (but still linear) validation._ + + +## Rationale + +Demanding *static* destinations for all jumps means that all jump destinations can be validated at initialization time, not runtime. + +Bounding the stack pointers catches all `data stack` and non-recursive`return stack` overflows. + +Requiring a consistently aligned`data stack` prevents stack underflow. It can also catch such errors as misaligned stacks due to irreducible control flows and calls to subroutines with the wrong number of arguments. + +## Backwards Compatibility + +These changes affect the semantics of EVM code – the use of `JUMP`, `JUMPI`, and the stack are restricted, such that some *code* that would otherwise run correctly will nonetheless be invalid EVM *code*. + +## Reference Implementation + +The following is a pseudo-Go implementation of an algorithm for predicating code validity. An equivalent algorithm must be run at initialization time. + +This algorithm performs a symbolic execution of the program that recursively traverses the _code_, emulating its control flow and stack use and checking for violations of the rules above. + +It runs in time equal to `O(vertices + edges)` in the program's control-flow graph, where edges represent control flow and the vertices represent _basic blocks_ -- thus the algorithm takes time proportional to the size of the _code_. + +_Note: All valid code has a control-flow graph that can be traversed in time and space linear in the length of the code. That means that some other static analyses and code transformations that might otherwise require quadratic time can also be written to run in near-linear time, including one-pass and streaming compilers._ + +### Validation Function + +***Note:** This function is a work in progress, and the version below is known to be incorrect.* + +For simplicity's sake we assume that _jumpdest analysis_ has been done and that we have some helper functions. +* `isValidInstruction(pc)` returns true if `pc` points at a valid instruction +* `isValidJumpdest(dest)` returns true if `dest` is a valid jumpdest +* `immediateData(pc)` returns the immediate data for the instruction at `pc`. +* `advancePC(pc)` returns next `pc`, skipping any immediate data. +* `removed_items(pc)` returns the number of items removed from the `dataStack` by the instruction at `pc`. +* `added_items(pc)` returns the number of items added to the `dataStack` by the instruction at `pc`. + +``` +var bytecode [codeLen]byte +var subMin [codeLen]int +var subMax [codeLen]int +var subDelta [codeLen]int +var visited [codeLen]bool +var dataStack [1024]int + +// validate a path through the control flow of the bytecode at pc +// and return the maximum number of stack items used down that path +// or else the PC and an error +// +// by starting at pc:=0 the entire program is recursively evaluated +// +func validate(pc := 0, sp := 0, rp := 0) int, error { + minStack := 0 + maxStack := 0 + deltaStack := 0 + for pc < codeLen { + if !isValidInstruction(pc) { + return 0,0,0,invalid_instruction + } + + // if we have jumped here before return to break cycle + if visited[pc] { + + // stack is not aligned if deltas not the same + if ??? { + return 0,0,0,invalid_stack + } + return minStack, maxStack, sp + } + visited[pc] = true + switch bytecode[pc] { + + // successful termination + case STOP: + return minStack, maxStack, sp + case RETURN: + return minStack, maxStack, sp + + case SELFDESTRUCT: + return minStack, maxStack, sp + case REVERT: + return minStack, maxStack, sp + case INVALID: + return 0,0,0,invalid_instruction + + case RJUMP: + + // check for valid jump destination + if !isValidJumpdest(jumpdest) { + return 0,0,0,invalid_destination + } + + // reset pc to destination of jump + pc += immediateData(pc) + + case RJUMPI: + + // recurse to validate true side of conditional + jumpdest = pc + immediateData(pc) + if !isValidJumpdest(pc + jumpdest) { + return 0,0,0,invalid_destination + } + minRight, maxLeft, deltaRight, err = + validate(jumpdest, sp, rp) + + err { + return 0,0,0,err + } + + // recurse to validate false side of conditional + pc = advancePC(pc) + minRight, maxRight, deltaRight, err = + validate(pc, sp, rp) + if err { + return 0,0,0,err + } + + // both paths valid, so return max + minStack = min(minStack, min(minLeft, minRight)) + maxStack += max(maxLeft, maxRight) + deltaStack += max(deltaLeft, deltaRight) + return minStack, maxStack, deltaStack + + case RJUMPSUB: + + // check for valid jump destination + jumpdest = immediateData(pc) + if !isValidJumpdest(pc + jumpdest) { + return 0,0,0,invalid_destination + } + + pc += jumpdest + + // recurse to validate subroutine call + minSub, maxSub, deltaSub, err = validate(jumpdest, sp, rp) + if err { + return 0,0,0,err + } + subMin[pc] = minSub + subMax[pc] = maxSub + subDelta[pc] = deltaSub + minStack = min(minStack, sp) + maxStack = max(maxStack, sp) + pc = advancePC(pc) + + case RETURNSUB: + + maxStack = max(maxStack, sp) + return minStack, maxStack, sp, nil + + ///////////////////////////////////////////////////// + // + // The following are to be included only if we take + // + // Option 2 + // + // and do not deprecate JUMP and JUMPI + // + case JUMP: + // pop jump destination + jumpdest = dataStack[--sp] + if !valid_jumpdest(jumpdest) { + return 0,0,0,invalid_destination + } + pc = jumpdest + case JUMPI: + // pop jump destination and conditional + jumpdest = dataStack[--sp] + jumpif = dataStack[--sp] + if sp < 0 {} + return 0,0,0,stack_underflow + } + if !valid_jumpdest(jumpdest) { + return 0,0,0,invalid_destination + } + + // recurse to validate true side of conditional + if !isValidJumpdest(jumpdest) { + return 0,0,0,invalid_destination + } + maxLeft, err = validate(jumpdest, sp, rp) + if err { + return 0,0,0,err + } + + // recurse to validate false side of conditional + pc = advance_pc(pc) + maxRight, err = validate(pc, sp, rp) + if err { + return 0,0,0,err + } + + // both sides valid, return max + maxStack += max(maxLeft, maxRight) + return minStack, maxStack, sp + case PUSH1 <= bytecode[pc] && bytecode[pc] <= PUSH32 { + sp++ + if (sp > 1023) { + return 0,0,0,stack_overflow + } + maxStack = max(maxStack, sp) + dataStack[sp] = immediateData(pc) + pc = advancePC(pc) + case DUP1 <= bytecode[pc] && bytecode[pc] <= DUP32 { + dup = sp - (bytecode[pc] - DUP1) + if dup < 0 { + return 0,0,0,stack_underflow + } + sp++ + if (sp > 1023) { + return 0,0,0,stack_overflow + } + maxStack = max(maxStack, sp) + dataStack[sp] = dataStack[dup] + pc = advancePC(pc) + case SWAP1 <= bytecode[pc] && bytecode[pc] <= SWAP32 { + swap = sp - (bytecode[pc] - SWAP1) + if swap < 0 { + return 0,0,0,stack_underflow + } + temp := dataStack[swap] + dataStack[swap] = dataStack[0] + dataStack[0] = temp + pc = advancePC(pc) + // + ///////////////////////////////////////////////////// + + default: + + // apply other instructions to stack pointer + sp -= removed_items(pc) + if (sp < 0) { + return 0,0,0,stack_underflow + } + minStack = min(minStack, sp) + sp += added_items(pc) + if (sp > 1023) { + return 0,0,0,stack_overflow + } + maxStack = max(maxStack, sp) + pc = advancePC(pc) + } + } + + // successful termination + return minStack, maxStack, sp +} +``` +## Security Considerations + +This EIP is intended to ensure an essential level of safety for EVM code deployed on the blockchain. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-3788.md b/EIPS/eip-3788.md new file mode 100644 index 00000000000000..b5e343e8d0a90e --- /dev/null +++ b/EIPS/eip-3788.md @@ -0,0 +1,60 @@ +--- +eip: 3788 +title: Strict enforcement of chainId +description: Reject transactions that do not explicitly have the same chainId as the node's configuration. +author: Gregory Markou (@GregTheGreek) +discussions-to: https://ethereum-magicians.org/t/discussion-to-eip-3788-strict-enforcement-of-chainid/7001 +status: Stagnant +type: Standards Track +category: Core +created: 2021-09-02 +requires: 155 +--- + +## Abstract + +Reject transactions that do not explicitly have the same chainId as the node's configuration. + +## Motivation + +Per [EIP-155](./eip-155.md) a transaction with a `chainId = 0` is considered to be a valid +transaction. This was a feature to offer developers the ability to submit replayable transactions +across different chains. With the rise of evm compatible chains, many of which use forks, or packages +from popular Ethereum clients, we are putting user funds at risk. This is because most wallet +interfaces do not expose the chainId to the user, meaning they typically do not have insight +into what chainId they are signing. Should a malicious actor (or accidental) choose to, they +can easily have users submit transactions with a `chainId = 0` on a non-mainnet network, allowing +the malicious actor to replay the transaction on ethereum mainnet (or other networks for that matter) +as a grief or sophisticated attack. + +## Specification + +As of the fork block `N`, consider transactions with a `chaindId = 0` to be invalid. Such that +transactions are verified based on the nodes configuration. Eg: +``` +if (node.cfg.chainId != tx.chainId) { + // Reject transaction +} +``` + +## Rationale + +The configuration set by the node is the main source of truth, and thus should be explicitly used +when deciding how to filter out a transaction. This check should exist in two places, as a filter +on the JSON-RPC (eg: `eth_sendTransaction`), and strictly enforced on the EVM during transaction +validation. + +This ensures that users will not have transactions pending that will be guaranteed to fail, and +prevents the transaction from being included in a block. + +## Backwards Compatibility +This breaks all applications or tooling that submit transactions with a `chainId == 0` after block number `N`. + +## Test Cases +TBD + +## Security Considerations +It should be noted this will not prevent a malicious actor from deploying a network with `chainId = 1`, or copying any other networks chainId. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3855.md b/EIPS/eip-3855.md new file mode 100644 index 00000000000000..6f85bd73336de4 --- /dev/null +++ b/EIPS/eip-3855.md @@ -0,0 +1,64 @@ +--- +eip: 3855 +title: PUSH0 instruction +description: Introduce a new instruction which pushes the constant value 0 onto the stack +author: Alex Beregszaszi (@axic), Hugo De la cruz (@hugo-dc), Paweł Bylica (@chfast) +discussions-to: https://ethereum-magicians.org/t/eip-3855-push0-instruction/7014 +status: Final +type: Standards Track +category: Core +created: 2021-02-19 +--- + +## Abstract + +Introduce the `PUSH0` (`0x5f`) instruction, which pushes the constant value 0 onto the stack. + +## Motivation + +Many instructions expect offsets as inputs, which in a number of cases are zero. A good example is the return data parameters of `CALLs`, which are set to zeroes in case the contract prefers using `RETURNDATA*`. This is only one example, but there are many other reasons why a contract would need to push a zero value. They can achieve that today by `PUSH1 0`, which costs 3 gas at runtime, and is encoded as two bytes which means `2 * 200` gas deployment cost. + +Because of the overall cost many try to use various other instructions to achieve the same effect. Common examples include `PC`, `MSIZE`, `CALLDATASIZE`, `RETURNDATASIZE`, `CODESIZE`, `CALLVALUE`, and `SELFBALANCE`. Some of these cost only 2 gas and are a single byte long, but their value can depend on the context. + +We have conducted an analysis on Mainnet (block ranges 8,567,259…8,582,058 and 12,205,970…12,817,405), and ~11.5% of all the `PUSH*` instructions executed push a value of zero. + +The main motivations for this change include: +1. Reducing contract code size. +2. Reducing the risk of contracts (mis)using various instructions as an optimisation measure. Repricing/changing those instructions can be more risky. +3. Reduce the need to use `DUP` instructions for duplicating zeroes. + +To put the "waste" into perspective, across existing accounts 340,557,331 bytes are wasted on `PUSH1 00` instructions, which means 68,111,466,200 gas was spent to deploy them. In practice a lot of these accounts share identical bytecode with others, so their total stored size in clients is lower, however the deploy time cost must have been paid nevertheless. + +An example for 2) is changing the behaviour of `RETURNDATASIZE` such that it may not be guaranteed to be zero at the beginning of the call frame. + +## Specification + +The instruction `PUSH0` is introduced at `0x5f`. It has no immediate data, pops no items from the stack, and places a single item with the value 0 onto the stack. The cost of this instruction is 2 gas (aka `base`). + +## Rationale + +### Gas cost + +The `base` gas cost is used for instructions which place constant values onto the stack, such as `ADDRESS`, `ORIGIN`, and so forth. + +### Opcode + +`0x5f` means it is in a "contiguous" space with the rest of the `PUSH` implementations and potentially could share the implementation. + +## Backwards Compatibility + +This EIP introduces a new opcode which did not exist previously. Already deployed contracts using this opcode could change their behaviour after this EIP. + +## Test Cases + +- `5F` -- successful execution, stack consist of a single item, set to zero +- `5F5F..5F` (1024 times) -- successful execution, stack consists of 1024 items, all set to zero +- `5F5F..5F` (1025 times) -- execution aborts due to out of stack + +## Security Considerations + +The authors are not aware of any impact on security. Note that jumpdest-analysis is unaffected, as `PUSH0` has no immediate data bytes. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3860.md b/EIPS/eip-3860.md new file mode 100644 index 00000000000000..9ee005834d488e --- /dev/null +++ b/EIPS/eip-3860.md @@ -0,0 +1,124 @@ +--- +eip: 3860 +title: Limit and meter initcode +description: Limit the maximum size of initcode to 49152 and apply extra gas cost of 2 for every 32-byte chunk of initcode +author: Martin Holst Swende (@holiman), Paweł Bylica (@chfast), Alex Beregszaszi (@axic), Andrei Maiboroda (@gumb0) +discussions-to: https://ethereum-magicians.org/t/eip-3860-limit-and-meter-initcode/7018 +status: Final +type: Standards Track +category: Core +created: 2021-07-16 +requires: 170 +--- + +## Abstract + +We extend [EIP-170](./eip-170.md) by introducing a maximum size limit for `initcode` (`MAX_INITCODE_SIZE = 2 * MAX_CODE_SIZE = 49152`). + +Furthermore, we introduce a charge of `2` gas for every 32-byte chunk of `initcode` to represent the cost of jumpdest-analysis. + +Lastly, the size limit results in the nice-to-have property that EVM code size, code offset (`PC`), and jump offset fits a 16-bit value. + +## Motivation + +During contract creation the client has to perform jumpdest-analysis on the `initcode` prior to execution. The work performed scales linearly with the size of the `initcode`. This work currently is not metered, nor is there a protocol enforced upper bound for the size. + +There are three costs charged today: + +1. Cost for calldata aka `initcode`: 4 gas for a byte with the value of zero, and 16 gas otherwise. +2. Cost for the resulting deployed code: 200 gas per byte. +3. Cost of address calculation (hashing of code) in case of `CREATE2` only: 6 gas per word. + +Only the first cost applies to `initcode`, but only in the case of contract creation transactions. For the case of `CREATE`/`CREATE2` there is no such cost, and it is possible to programmatically generate variations of `initcode` in a relatively cheap manner. In the past it was possible to craft malicious `initcode` due to a vulnerability fixed in 2017 by geth 1.6.5. + +Furthermore, the lack of a limit has caused lengthy discussions for some EVM proposals, influencing the design, or even causing a delay or cancellation of a feature. + +We are motivated by three reasons: + +1. Ensuring `initcode` is fairly charged (most importantly cost is proportional to `initcode`'s length) to minimize the risks for the future. +2. To have a cost system which is extendable in the future. +3. To simplify EVM engines by the explicit limits (code size, code offsets (`PC`), and jump offsets fit 16-bits). + +## Specification + +### Parameters + +| Constant | Value | +| -------------------- | ------------------- | +| `INITCODE_WORD_COST` | `2` | +| `MAX_INITCODE_SIZE` | `2 * MAX_CODE_SIZE` | + +Where `MAX_CODE_SIZE` is defined by [EIP-170](./eip-170.md) as `24576`. + +We define `initcode_cost(initcode)` to equal `INITCODE_WORD_COST * ceil(len(initcode) / 32)`. + +### Rules + +1. If length of transaction data (`initcode`) in a create transaction exceeds `MAX_INITCODE_SIZE`, transaction is invalid. (*Note that this is similar to transactions considered invalid for not meeting the intrinsic gas cost requirement.*) +2. For a create transaction, extend the transaction data cost formula to include `initcode_cost(initcode)`. (*Note that this is included in transaction intrinsic cost, i.e. transaction with not enough gas to cover initcode cost is invalid.*) +3. If length of `initcode` to `CREATE` or `CREATE2` instructions exceeds `MAX_INITCODE_SIZE`, instruction execution exceptionally aborts (as if it runs out of gas). +4. For the `CREATE` and `CREATE2` instructions charge an extra gas cost equaling to `initcode_cost(initcode)`. This cost is deducted before the calculation of the resulting contract address and the execution of `initcode`. (*Note that this means before or at the same time as the hashing cost is applied in `CREATE2`.*) + +## Rationale + +### Gas cost constant + +The value of `INITCODE_WORD_COST` is selected based on performance benchmarks of differing worst-cases per implementation. The baseline for the benchmarks is the performance of `KECCAK256` hashing in geth 1.10.9, which matches the 70 Mgas/s gas limit target on a 4.0 GHz x86_64 CPU. + +| EVM | version | MB/s | B/CPUcycle | CPUcycle/B | cost of 1 B | cost of 32 B | +| --------------- | ------- | ---- | ---- | ---- | ---- | ---- | +| geth/KECCAK256 | 1.10.9 | 357 | 1.8 | 0.6 | 0.2 | 6.0 | +| geth | 1.10.9 | 1091 | 5.5 | 0.2 | 0.1 | 2.0 | +| evmone/Baseline | 0.8.2 | 727 | 3.7 | 0.3 | 0.1 | 2.9 | +| evmone/Advanced | 0.8.2 | 155 | 0.8 | 1.3 | 0.4 | 13.8 | + +### Gas cost per word (32-byte chunk) + +We have chosen the cost of 2 gas per word based on Geth's implementation and comparing with `KECCAK256` performance. This means the per byte cost is `0.0625`. While fractional gas costs are not permitted in the EVM, we can approximate it by charging per-word. + +Moreover, calculating gas per word is compatible with the calculation of `CREATE2`'s *hashcost* of [EIP-1014](./eip-1014.md). Therefore, the same implementation may be used for `CREATE` and `CREATE2` with different cost constants: before activation `0` for `CREATE` and `6` for `CREATE2`, after activation `2` for `CREATE` and `6 + 2` for `CREATE2`. + +### Reason for size limit of initcode + +Estimating and creating worst case scenarios is easier with an upper bound in place, given one parameter for the search is greatly reduced. This allows for selecting a much more optimistic gas per byte. + +Should there be no upper bound, the cost would need to be higher accounting for unknown unknowns. Given most *initcode* (*TODO: state maximum initcode size resulting in deployment seen on mainnet here*) does not exceed the proposed limit, penalising contracts by overly conservative costs seems unnecessary. + +### Effect of size limit of initcode + +In most, if not all cases when a new contract is being created, the resulting runtime code is copied from the initcode itself. For the basic case the `2 * MAX_CODE_SIZE` limit allows `MAX_CODE_SIZE` for runtime code and another `MAX_CODE_SIZE` for contract constructor code. However, the limit may have practical implications for cases where multiple contracts are deployed in a single create transaction. + +### Initcode cost for create transaction + +The initcode cost for create transaction data (0.0625 gas per byte) is negligible compared to the transaction data cost (4 or 16 gas per byte). Despite that, we decided to include it in the specification for consistency, and more importantly for forward compatibility. + +### How to report initcode limit violation? + +We specified that initcode size limit violation for `CREATE`/`CREATE2` results in exceptional abort of the execution. This places it in the group of early out-of-gas checks, including: stack underflow, memory expansion, static call violation, initcode hashing cost, and initcode cost introduced by this EIP. They precede the later "light" checks: call depth and balance. The choice gives consistency to the order of checks and lowers implementation complexity (out-of-gas checks can be performed in any order). + +## Backwards Compatibility + +This EIP requires a "network upgrade", since it modifies consensus rules. + +Already deployed contracts should not be affected, but certain transactions (with `initcode` beyond the proposed limit) would still be includable in a block, but result in an exceptional abort. + +## Test Cases + +Tests should include the following cases: + +- Creation transaction with gas limit enough to cover initcode cost +- Creation transaction with gas limit enough to cover intrinsic cost except initcode cost +- `CREATE`/`CREATE2`/creation transaction with `len(initcode)` at `MAX_INITCODE_SIZE` +- `CREATE`/`CREATE2`/creation transaction with `len(initcode)` at `MAX_INITCODE_SIZE+1` + +## Security Considerations + +For client implementations, this EIP makes attacks based on jumpdest-analysis less problematic, so should increase the robustness of clients. + +For layer 2, this EIP introduces failure-modes where there previously were none. There *could* exist factory-contracts which deploy multi-level contract hierarchies, such that the code for multiple contracts are included in the initcode of the first contract. The author(s) of this EIP are not aware of any such contracts. + +Currently, on London, with `30M` gas limit, it would be possible to trigger jumpdest-analysis of a total `~1.3GB` of initcode. With this EIP, the cost for such an attack would increase by roughly `80M` gas. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3978.md b/EIPS/eip-3978.md new file mode 100644 index 00000000000000..18d167195826e2 --- /dev/null +++ b/EIPS/eip-3978.md @@ -0,0 +1,86 @@ +--- +eip: 3978 +title: Gas refunds on reverts +description: Reprice reverted SSTORE/CREATE/SELFDESTRUCT/LOGX operations gas via gas refund mechanism +author: Anton Bukov (@k06a), Mikhail Melnik (@ZumZoom) +discussions-to: https://ethereum-magicians.org/t/eip-3978-gas-refunds-on-reverts/7071/ +status: Stagnant +type: Standards Track +category: Core +created: 2021-09-16 +updated: 2022-02-14 +requires: 2929 +--- + +## Abstract + +For reverted state modification operations, keep access cost, but refund modification cost. + +## Motivation + +Reverting a transaction, or any of its sub-calls, drops any state modifications that happened inside. +But now, users are being charged for the dropped modifications as if they persisted. + +Since [EIP-3298](./eip-3298.md), the gas refund mechanism works for storage restores only inside the same transaction. But on revert, the gas refund is not increased; it is completely erased. +It can even be cheaper to transfer tokens back at the end of a transaction instead of reverting, to keep the existing gas refund. +This should be changed. + +- Reverted SSTORE deserves to be repriced to SLOAD gas (100 gas) +- Reverted LOG0, LOG1, LOG2, LOG3 and LOG4 deserve to be repriced to 100 gas +- Reverted CALL with value (`positive_value_cost` = 9,000 gas) deserves to be repriced to 100 gas +- Reverted CALL with value and account creation (`value_to_empty_account_cost` = 25,000 gas) deserves to be repriced to 100 gas +- Reverted CREATE and CREATE2 (32,000 gas) deserve to be repriced to 100 gas +- Reverted SELFDESTRUCT (5,000 or 25,000 gas) deserves to be repriced to 100 gas + +Moreover, it seems fair to charge CREATE and CREATE2 operations 32,000 fix price conditionally only if returned bytecode is not empty. + + +## Specification +For each callframe, track `revert_gas_refund`, initially 0. + +The set of operations that modify `revert_gas_refund` are: +- SSTORE +- LOG0, LOG1, LOG2, LOG3, LOG4 +- CALL +- CREATE, CREATE2 +- SELFDESTRUCT + +They increase `revert_gas_refund` as follows: +```javascript +call.revert_gas_refund += operation.gas - WARM_STORAGE_READ_COST +``` + +And in case of revert let's use this value instead of just erasing `gas_refund`: +```javascript +if (call.reverted) { + // existing behavior + tx.gas_refund -= call.gas_refund; + + // New behavior added to existing according to the EIP-3978 + tx.gas_refund += call.revert_gas_refund; +} +``` + +## Rationale + +Gas should reflect the cost of use. +The revert cost reflects the cost of access during execution, but not the cost of modification. + +## Backwards Compatibility + +No known backward incompatibilities. + +## Test Cases + +TBD + +## Reference Implementation + +TBD + +## Security Considerations + +TBD + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4.md b/EIPS/eip-4.md index ad647ac5206bec..f3e3535f3f282e 100644 --- a/EIPS/eip-4.md +++ b/EIPS/eip-4.md @@ -2,7 +2,7 @@ eip: 4 title: EIP Classification author: Joseph Chow (@ethers) -status: Draft +status: Final type: Meta created: 2015-11-17 --- @@ -17,7 +17,7 @@ The specification defines the layers and sets forth specific criteria for decidi # Motivation -Ethereum is a system involving a number of different standards. Some standards are absolute requirements for interoperability while others can be considered optional, giving implementors a choice of whether to support them. +Ethereum is a system involving a number of different standards. Some standards are absolute requirements for interoperability while others can be considered optional, giving implementers a choice of whether to support them. In order to have a EIP process which more closely reflects the interoperability requirements, it is necessary to categorize EIPs accordingly. Lower layers present considerably greater challenges in getting standards accepted and deployed. @@ -48,7 +48,7 @@ In a hard fork, structures that were invalid under the old rules become valid un # 2. Networking Layer -The networking layer specifies the Ethereum wire protocol (eth) and the Light Ethereum Subprotocol (les). RLPx is excluded and tracked in the [https://github.com/ethereum/devp2p devp2p repository]. +The networking layer specifies the Ethereum wire protocol (eth) and the Light Ethereum Subprotocol (les). RLPx is excluded and tracked in the [devp2p repository](https://github.com/ethereum/devp2p). Only a subset of subprotocols are required for basic node interoperability. Nodes can support further optional extensions. diff --git a/EIPS/eip-4200.md b/EIPS/eip-4200.md new file mode 100644 index 00000000000000..ac4578dbd2fcb8 --- /dev/null +++ b/EIPS/eip-4200.md @@ -0,0 +1,168 @@ +--- +eip: 4200 +title: EOF - Static relative jumps +description: RJUMP, RJUMPI and RJUMPV instructions with a signed immediate encoding the jump destination +author: Alex Beregszaszi (@axic), Andrei Maiboroda (@gumb0), Paweł Bylica (@chfast) +discussions-to: https://ethereum-magicians.org/t/eip-4200-static-relative-jumps/7108 +status: Stagnant +type: Standards Track +category: Core +created: 2021-07-16 +requires: 3540, 3670 +--- + +## Abstract + +Three new EVM jump instructions are introduced (`RJUMP`, `RJUMPI` and `RJUMPV`) which encode destinations as signed immediate values. These can be useful in the majority of (but not all) use cases and offer a cost reduction. + +## Motivation + +A recurring discussion topic is that EVM only has a mechanism for dynamic jumps. They provide a very flexible architecture with only 2 (!) instructions. This flexibility comes at a cost however: it makes analysis of code more complicated and it also (partially) resulted in the need to have the `JUMPDEST` marker. + +In a great many cases control flow is actually static and there is no need for any dynamic behaviour, though not every use case can be solved by static jumps. + +There are various ways to reduce the need for dynamic jumps, some examples: + +1. With native support for functions / subroutines +2. A "return to caller" instruction +3. A "switch-case" table with dynamic indexing + +This change does not attempt to solve these, but instead introduces a minimal feature set to allow compilers to decide which is the most adequate option for a given use case. It is expected that compilers will use `RJUMP`/`RJUMPI` almost exclusively, with the exception of returning to the caller continuing to use `JUMP`. + +This functionality does not preclude the EVM from introducing other forms of control flow later on. `RJUMP`/`RJUMPI` can efficiently co-exists with a higher-level declaration of functions, where static relative jumps should be used for intra-function control flow. + +The main benefit of these instruction is reduced gas cost (both at deploy and execution time) and better analysis properties. + +## Specification + +We introduce three new instructions on the same block number [EIP-3540](./eip-3540.md) is activated on: + +1. `RJUMP` (0xe0) - relative jump +2. `RJUMPI` (0xe1) - conditional relative jump +3. `RJUMPV` (0xe2) - relative jump via jump table + +If the code is legacy bytecode, all of these instructions result in an *exceptional halt*. (*Note: This means no change to behaviour.*) + +If the code is valid EOF1: + +1. `RJUMP relative_offset` sets the `PC` to `PC_post_instruction + relative_offset`. +2. `RJUMPI relative_offset` pops a value (`condition`) from the stack, and sets the `PC` to `PC_post_instruction + ((condition == 0) ? 0 : relative_offset)`. +3. `RJUMPV max_index relative_offset+` pops a value (`case`) from the stack, and sets the `PC` to `PC_post_instruction + ((case > max_index) ? 0 : relative_offset[case])`. + +The immediate argument `relative_offset` is encoded as a 16-bit **signed** (two's-complement) big-endian value. Under `PC_post_instruction` we mean the `PC` position after the entire immediate value. + +The immediate encoding of `RJUMPV` is more special: the unsigned 8-bit `max_index` value determines the maximum index in the jump table. The number of `relative_offset` values following is `max_index+1`. This allows table sizes up to 256. The encoding of `RJUMPV` must have at least one `relative_offset` and thus it will take at minimum 4 bytes. Furthermore, the `case > max_index` condition falling through means that in many use cases, one would place the *default* path following the `RJUMPV` instruction. An interesting feature is that `RJUMPV 0 relative_offset` is an inverted-`RJUMPI`, which can be used in many cases instead of `ISZERO RJUMPI relative_offset`. + +We also extend the validation algorithm of [EIP-3670](./eip-3670.md) to verify that each `RJUMP`/`RJUMPI`/`RJUMPV` has a `relative_offset` pointing to an instruction. This means it cannot point to an immediate data of `PUSHn`/`RJUMP`/`RJUMPI`/`RJUMPV`. It cannot point outside of code bounds. It is allowed to point to a `JUMPDEST`, but is not required to. + +Because the destinations are validated upfront, the cost of these instructions are less than their dynamic counterparts: `RJUMP` should cost 2, and `RJUMPI` and `RJUMPV` should cost 4. + +## Rationale + +### Relative addressing + +We chose relative addressing in order to support code which is relocatable. This also means a code snippet can be injected. A technique seen used prior to this EIP to achieve the same goal was to inject code like `PUSHn PC ADD JUMPI`. + +We do not see any significant downside to relative addressing and it allows us to also deprecate the `PC` instruction. + +### Immediate size + +The signed 16-bit immediate means that the largest jump distance possible is 32767. In the case the bytecode at `PC=0` starts with an `RJUMP`, it will be possible to jump as far as `PC=32770`. + +Given `MAX_CODE_SIZE = 24576` (in [EIP-170](./eip-170.md)) and `MAX_INITCODE_SIZE = 49152` (in [EIP-3860](./eip-3860.md)), we think the 16-bit immediate is large enough. + +A version with an 8-bit immediate would only allow moving `PC` backward by 125 or forward by 127 bytes. While that seems to be a good enough distance for many for-loops, it is likely not good enough for cross-function jumps, and since the 16-bit immediate is the same size as what a dynamic jump would take in such cases (3 bytes: `JUMP PUSH1 n`), we think having less instructions is better. + +Should there be a need to have immediate encodings of other size (such as 8-bits, 24-bits or 32-bits), it would be possible to introduce new opcodes, similarly to how multiple `PUSH` instructions exist. + +### `PUSHn JUMP` sequences + +If we chose absolute addressing, then `RJUMP` could be viewed similar to the sequence `PUSHn JUMP` (and `RJUMPI` similar to `PUSHn JUMPI`). In that case one could argue that instead of introducing a new instruction, such sequences should get a discount, because EVMs could optimise them. + +We think this is a bad direction to go: + +1. It further complicates the already complex rules of gas calculation. +2. And it either requires a consensus defined internal representation for EVM code, or forces EVM implementations to do optimisations on their own. + +Both of these are risky. Furthermore we think that EVM implementations should be free to chose what optimisations they apply, and the savings do not need to be passed down at all cost. + +Additionally it requires a potentially significant change to the current implementations which depend on a streaming one-by-one execution without a lookahead. + +### Relation to dynamic jumps + +The goal was not to completely replace the current control flow system of the EVM, but to augment it. There are many cases where dynamic jumps are useful, such as returning to the caller. + +It is possible to introduce a new mechanism for having a pre-defined table of valid jump destinations, and dynamically supplying the index within this table to accomplish some form of dynamic jumps. This is very useful for efficiently encoding a form of "switch-cases" statements. It could also be used for "return to caller" cases, however it is likely inefficient or awkward. + +### Lack of `JUMPDEST` + +`JUMPDEST` serves two purposes: + +1. To efficiently partition code -- this can be useful for pre-calculating total gas usage for a given *block* (i.e. instructions between `JUMPDEST`s), and for JIT/AOT translation. +2. To explicitly show valid locations (otherwise any non-data location would be valid). + +This functionality is not needed for static jumps, as the analysers can easily tell destinations from the static jump immediates during jumpdest-analysis. + +There are two benefits here: + +1. Not wasting a byte for a `JUMPDEST` also means a saving of 200 gas during deployment, for each jump destination. +2. Saving an extra 1 gas per jump during execution, given `JUMPDEST` itself cost 1 gas and is "executed" during jumping. + +### `RJUMPV` fallback case + +If no match is found (i.e. the *default* case) in the `RJUMPV` instruction execution will continue without branching. This allows for gaps in the arguments to be filled with `0`s, and a choice of implementation by the programmer. Alternate options would include exceptional aborts in case of no match. + +## Backwards Compatibility + +This change poses no risk to backwards compatibility, as it is introduced at the same time EIP-3540 is. The new instructions are not introduced for legacy bytecode (code which is not EOF formatted). + +## Test Cases + +### Validation + +#### Valid cases + +- `RJUMP`/`RJUMPI`/`RJUMPV` with `JUMPDEST` as target + - `relative_offset` is positive/negative/`0` +- `RJUMP`/`RJUMPI`/`RJUMPV` with instruction other than `JUMPDEST` as target + - `relative_offset` is positive/negative/`0` +- `RJUMPV` with various valid table sizes from 1 to 256 +- `RJUMP` as a final instruction in code section + +#### Invalid cases + +- `RJUMP`/`RJUMPI`/`RJUMPV` with truncated immediate +- `RJUMPI`/`RJUMPV` as a final instruction in code section +- `RJUMP`/`RJUMPI`/`RJUMPV` target outside of code section bounds +- `RJUMP`/`RJUMPI`/`RJUMPV` target push data +- `RJUMP`/`RJUMPI`/`RJUMPV` target another `RJUMP`/`RJUMPI`/`RJUMPV` immediate argument + +### Execution + +- `RJUMP`/`RJUMPI`/`RJUMPV` in legacy code aborts execution +- `RJUMP` + - `relative_offset` is positive/negative/`0` +- `RJUMPI` + - `relative_offset` is positive/negative/`0` + - `condition` equals `0` + - `condition` does not equal `0` +- `RJUMPV 0 relative_offset` + - `case` equals `0` + - `case` does not equal `0` +- `RJUMPV` with table containing positive, negative, `0` offsets + - `case` equals `0` + - `case` does not equal `0` + - `case` outside of table bounds (`case > max_index`, fallback case) + - `case` > 255 + +## Security Considerations + +Adding new instructions with immediate arguments should be carefully considered when implementing the EOF container validation algorithm. + +Static relative jump execution does not require runtime check of the jump destination. It greatly reduces execution cost. Therefore the gas cost of the new instructions can also be significantly reduced. + +The `RJUMPV` instruction relative offset table can have up to 256 one-byte entries, so reading an offset cannot be a potential attack surface. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4337.md b/EIPS/eip-4337.md new file mode 100644 index 00000000000000..37b25643cd879b --- /dev/null +++ b/EIPS/eip-4337.md @@ -0,0 +1,7 @@ +--- +eip: 4337 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4337.md diff --git a/EIPS/eip-4341.md b/EIPS/eip-4341.md new file mode 100644 index 00000000000000..1f0417528a9494 --- /dev/null +++ b/EIPS/eip-4341.md @@ -0,0 +1,7 @@ +--- +eip: 4341 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4341.md diff --git a/EIPS/eip-4345.md b/EIPS/eip-4345.md new file mode 100644 index 00000000000000..34cb5bb8904f3b --- /dev/null +++ b/EIPS/eip-4345.md @@ -0,0 +1,60 @@ +--- +eip: 4345 +title: Difficulty Bomb Delay to June 2022 +description: Delays the difficulty bomb to be noticeable in June 2022. +author: Tim Beiko (@timbeiko), James Hancock (@MadeOfTin), Thomas Jay Rush (@tjayrush) +discussions-to: https://ethereum-magicians.org/t/eip-4345-difficulty-bomb-delay-to-may-2022/7209 +status: Final +type: Standards Track +category: Core +created: 2021-10-05 +--- + +## Abstract +Starting with `FORK_BLOCK_NUMBER` the client will calculate the difficulty based on a fake block number suggesting to the client that the difficulty bomb is adjusting 10,700,000 blocks later than the actual block number. + +## Motivation +Targeting for The Merge to occur before June 2022. If it is not ready by then, the bomb can be delayed further. + +## Specification +#### Relax Difficulty with Fake Block Number +For the purposes of `calc_difficulty`, simply replace the use of `block.number`, as used in the exponential ice age component, with the formula: +```py + fake_block_number = max(0, block.number - 10_700_000) if block.number >= FORK_BLOCK_NUMBER else block.number +``` +## Rationale + +The following script predicts a ~0.1 second delay to block time by June 2022 and a ~0.5 second delay by July 2022. This gives reason to address because the effect will be seen, but not so much urgency we don't have space to work around if needed. + +```python +def predict_diff_bomb_effect(current_blknum, current_difficulty, block_adjustment, months): + ''' + Predicts the effect on block time (as a ratio) in a specified amount of months in the future. + Vars used for predictions: + current_blknum = 13423376 # Oct 15, 2021 + current_difficulty = 9545154427582720 + block adjustment = 10700000 + months = 7.5 # June 2022 + months = 8.5 # July 2022 + ''' + blocks_per_month = (86400 * 30) // 13.3 + future_blknum = current_blknum + blocks_per_month * months + diff_adjustment = 2 ** ((future_blknum - block_adjustment) // 100000 - 2) + diff_adjust_coeff = diff_adjustment / current_difficulty * 2048 + return diff_adjust_coeff + + +diff_adjust_coeff = predict_diff_bomb_effect(13423376,9545154427582720,10700000,7.5) +diff_adjust_coeff = predict_diff_bomb_effect(13423376,9545154427582720,10700000,8.5) +``` + +## Backwards Compatibility +No known backward compatibility issues. + +## Security Considerations +Misjudging the effects of the difficulty can mean longer blocktimes than anticipated until a hardfork is released. Wild shifts in difficulty can affect this number severely. Also, gradual changes in blocktimes due to longer-term adjustments in difficulty can affect the timing of difficulty bomb epochs. This affects the usability of the network but unlikely to have security ramifications. + +In this specific instance, it is possible that the network hashrate drops considerably before The Merge, which could accelerate the timeline by which the bomb is felt in block times. The offset value chosen aimed to take this into account. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4353.md b/EIPS/eip-4353.md new file mode 100644 index 00000000000000..0d79c1e41536b4 --- /dev/null +++ b/EIPS/eip-4353.md @@ -0,0 +1,7 @@ +--- +eip: 4353 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4353.md diff --git a/EIPS/eip-4361.md b/EIPS/eip-4361.md new file mode 100644 index 00000000000000..02043a16b4dabe --- /dev/null +++ b/EIPS/eip-4361.md @@ -0,0 +1,7 @@ +--- +eip: 4361 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4361.md diff --git a/EIPS/eip-4393.md b/EIPS/eip-4393.md new file mode 100644 index 00000000000000..2f9b3257d678eb --- /dev/null +++ b/EIPS/eip-4393.md @@ -0,0 +1,7 @@ +--- +eip: 4393 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4393.md diff --git a/EIPS/eip-4396.md b/EIPS/eip-4396.md new file mode 100644 index 00000000000000..533c3143355677 --- /dev/null +++ b/EIPS/eip-4396.md @@ -0,0 +1,158 @@ +--- +eip: 4396 +title: Time-Aware Base Fee Calculation +description: Accounts for block time in the base fee calculation to target a stable throughput by time instead of by block. +author: Ansgar Dietrichs (@adietrichs) +discussions-to: https://ethereum-magicians.org/t/eip-4396-time-aware-base-fee-calculation/7363 +status: Stagnant +type: Standards Track +category: Core +created: 2021-10-28 +--- + +## Abstract +This EIP proposes accounting for time between blocks in the base fee calculation to target a stable throughput by time, instead of by block. Aiming to minimize changes to the calculation, it only introduces a variable block gas target proportional to the block time. The EIP can, in principle, be applied to either a Proof-of-Work or a Proof-of-Stake chain, however the security implications for the Proof-of-Work case remain unexplored. + +## Motivation + +The current base fee calculation chooses the gas usage of a block as the signal to determine whether demand for block space is too low (indicating that the base fee should be lowered) or too high (indicating that the base fee should be increased). While simple, this choice of signal has drawbacks: it does not take the block time into account. Assuming a relatively constant demand, a proposer constructing a block after 20 seconds will have transactions available with twice the gas of a proposer constructing a block after 10 seconds. Using the same gas target for both is accordingly sub-optimal. In practice, there are several undesirable consequences of this flawed signal: + +### Base Fee Volatility Under Proof-of-Work + +Under Proof-of-Work (PoW), block times are stochastic, and for that reason there exists large block time variability. This variability contributes to the base fee volatility, where the base fee can be expected to oscillate around the equilibrium value even under perfectly stable demand. + +### Missed Slots + +Under Proof-of-Stake (PoS), block times are ideally uniform (always 12s), but missed slots lead to individual blocks with increased block time (24s, 36s, ...). Such missed slots will result in the next block being overfull, and with the current update rule, signal a fake demand spike and thus cause a small unwarranted base fee spike. + +More importantly, these missed slots directly reduce the overall throughput of the execution chain by the gas target of one block. While the next block can be expected to include the "delayed" transactions of the missed slot, the resulting base fee spike then results in some number of under-full blocks. In the end the block space of the missed slot is lost for the chain. + +This is particularly problematic because a Denial-of-Service (DoS) attack on block proposers can cause them to miss slots, and compromises the overall chain performance. + +### Throughput Degradation During Consensus Issues + +A more severe version of individual missed slots can be caused by consensus issues that prevent a significant portion of block proposers from continuing to create blocks. This can be due to block proposers forking off (and creating blocks on their own fork), being unable to keep up with the current chain head for another reason, or simply being unable to create valid blocks. + +In all these situations, average block times go up significantly, causing chain throughput to fall by the same fraction. While this effect is already present under PoW, the self-healing mechanism of difficulty adjustments is relatively quick to kick in and restore normal block times. On the other hand, under PoS the automatic self-healing mechanism can be extremely slow: potentially several months to return to normal with up to a third of slots missed, or several weeks if more than a third of slots are missed. + +For all these reasons, it would be desirable to target a stable throughput per time instead of per block, by taking block time into account during the base fee calculation. + +To maximize the chance of this EIP being included in the merge fork, the adjustments are kept to a minimum, with more involved changes discussed in the rationale section. + +## Specification +Using the pseudocode language of [EIP-1559](./eip-1559.md), the updated base fee calculation becomes: + +```python +... + +BASE_FEE_MAX_CHANGE_DENOMINATOR = 8 +BLOCK_TIME_TARGET = 12 +MAX_GAS_TARGET_PERCENT = 95 + +class World(ABC): + def validate_block(self, block: Block) -> None: + parent_gas_limit = self.parent(block).gas_limit + parent_block_time = self.parent(block).timestamp - self.parent(self.parent(block)).timestamp + parent_base_gas_target = parent_gas_limit // ELASTICITY_MULTIPLIER + parent_adjusted_gas_target = min(parent_base_gas_target * parent_block_time // BLOCK_TIME_TARGET, parent_gas_limit * MAX_GAS_TARGET_PERCENT // 100) + parent_base_fee_per_gas = self.parent(block).base_fee_per_gas + parent_gas_used = self.parent(block).gas_used + + ... + + if parent_gas_used == parent_adjusted_gas_target: + expected_base_fee_per_gas = parent_base_fee_per_gas + elif parent_gas_used > parent_adjusted_gas_target: + gas_used_delta = parent_gas_used - parent_adjusted_gas_target + base_fee_per_gas_delta = max(parent_base_fee_per_gas * gas_used_delta // parent_base_gas_target // BASE_FEE_MAX_CHANGE_DENOMINATOR, 1) + expected_base_fee_per_gas = parent_base_fee_per_gas + base_fee_per_gas_delta + else: + gas_used_delta = parent_adjusted_gas_target - parent_gas_used + base_fee_per_gas_delta = parent_base_fee_per_gas * gas_used_delta // parent_base_gas_target // BASE_FEE_MAX_CHANGE_DENOMINATOR + expected_base_fee_per_gas = parent_base_fee_per_gas - base_fee_per_gas_delta + + ... + + ... +``` + +## Rationale + +### Mechanism + +The proposed new base fee calculation only adjusts the block gas target by scaling it with the block time, capped at a maximum percent of the overall block gas limit: + +#### Current Base Fee Calculation + +![](../assets/eip-4396/old_formula.png) + +#### Proposed Base Fee Calculation + +![](../assets/eip-4396/new_formula.png) + +This new calculation thus targets a stable throughput per time instead of per block. + +### Limitations + +Under PoS, block time increases always come in multiples of full blocks (e.g. a single missed slot = 24s instead of 12s block time). Accounting for this already requires doubling the block gas target, even for a single missed slot. However, with the block elasticity currently set to 2, this target would be equal to the block gas limit. Having the new target equal to the block gas limit is less than ideal, and thus is reduced slightly, according to the `MAX_GAS_TARGET_PERCENT` parameter. The reason for the existence of this parameter is twofold: + +- Ensure that the signal remains meaningful: A target equal to or greater than the gas limit could never be reached, so the base fee would always be reduced after a missed slot. +- Ensure that the base fee can still react to genuine demand increases: During times of many offline block proposers (and thus many missed slots), genuine demand increases still need a way to eventually result in a base fee increase, to avoid a fallback to a first-price priority fee auction. + +However, this means that even a single missed slot cannot be fully compensated. Even worse, any second or further sequential missed slot cannot be compensated for at all, as the gas target is already at its max. This effect becomes more pronounced as the share of offline validators increases: + +![](../assets/eip-4396/degradation.png) + +As can be observed, while this EIP does indeed increase the robustness of the network throughput in cases of offline validators, it does so imperfectly. Furthermore, there is a tradeoff effected by the `MAX_GAS_TARGET_PERCENT` parameter, with a higher value resulting in a higher network robustness, but a more impaired base fee adjustment mechanism during times of frequent missed slots. + +### Possible Extensions + +These limitations directly result from the design goal of a minimal change, to maximize chances of being included in the merge. There are natural ways of extending the EIP design to more effectively handle offline validators, at the expense of somewhat more extensive changes: + +#### Persistent Multi-Slot Buffer + +To be able to compensate multiple consecutive missed slots, a gas buffer could be introduced, that would allow the gas beyond the block elasticity to be carried forward to future blocks. To avoid long-run buffer accumulation that would delay a return to normal operations once block proposers are back online, a cap on the buffer would be added. Even for a relatively small buffer cap, the throughput robustness is significantly improved: + +![](../assets/eip-4396/degradation_buffers.png) + +With an elasticity still at 2, there is no way of avoiding the eventual breakdown for more than 50% offline block proposers. + +The main implementation complexity for this approach comes from the introduction of the buffer as a new persistent field. To retain the ability for calculating base fees only based on headers, it would have to be added to the block header. + +#### Increased Block Elasticity + +In addition to the introduction of a buffer, increasing the block elasticity is another tool for increasing throughput robustness. The following diagram shows the effect of different elasticity levels, both in the presence and absence of a persistent buffer: + +![](../assets/eip-4396/degradation_elasticity.png) + +Again, a clear positive effect can be observed. + +The main additional complexity here would come from the increased peak load (networking, compute & disk access) of multiple sequential overfull blocks. Note though that PoS with its minimum block time of 12s significantly reduces worst case peak stress as compared to PoW. + +## Backwards Compatibility + +The EIP has minimal impact on backwards compatibility, only requiring updates to existing base fee calculation tooling. + +## Test Cases +tbd + +## Reference Implementation +tbd + +## Security Considerations + +### Timestamp Manipulation + +Under PoW, miners are in control over the timestamp field of their blocks. While there are some enforced limits to valid timestamps, implications regarding potential timestamp manipulation are nontrivial and remain unexplored for this EIP. + +Under PoS, each slot has a [fixed assigned timestamp](https://github.com/ethereum/consensus-specs/blob/v1.1.3/specs/merge/beacon-chain.md#process_execution_payload), rendering any timestamp manipulation by block proposers impossible. + +### Suppressing Base Fee Increases +As discussed in the rationale, a high value for `MAX_GAS_TARGET_PERCENT` during times of many offline block proposers results in a small remaining signal space for genuine demand increases that should result in base fee increases. This in turn decreases the cost for block proposers for suppresing these base fee increases, instead forcing the fallback to a first-price priority fee auction. + +While the arguments of incentive incompatibility for base fee suppression of the base EIP-1559 case still apply here, with a decreasing cost of this individually irrational behavior the risk for overriding psychological factors becomes more significant. + +Even in such a case the system degradation would however be graceful, as it would only temporarily suspend the base fee burn. As soon as the missing block proposers would come back online, the system would return to its ordinary EIP-1559 equilibrium. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4399.md b/EIPS/eip-4399.md new file mode 100644 index 00000000000000..eb7d731fa68ab1 --- /dev/null +++ b/EIPS/eip-4399.md @@ -0,0 +1,155 @@ +--- +eip: 4399 +title: Supplant DIFFICULTY opcode with PREVRANDAO +description: Expose beacon chain randomness in the EVM by supplanting DIFFICULTY opcode semantics +author: Mikhail Kalinin (@mkalinin), Danny Ryan (@djrtwo) +discussions-to: https://ethereum-magicians.org/t/eip-4399-supplant-difficulty-opcode-with-random/7368 +status: Final +type: Standards Track +category: Core +created: 2021-10-30 +requires: 3675 +--- + +## Abstract + +This EIP supplants the semantics of the return value of existing `DIFFICULTY (0x44)` opcode and renames the opcode to `PREVRANDAO (0x44)`. + +The return value of the `DIFFICULTY (0x44)` instruction after this change is the output of the randomness beacon provided by the beacon chain. + + +## Motivation + +Applications may benefit from using the randomness accumulated by the beacon chain. Thus, randomness outputs produced by the beacon chain should be accessible in the EVM. + +At the point of `TRANSITION_BLOCK` of the Proof-of-Stake (PoS) upgrade described in [EIP-3675](./eip-3675.md), the `difficulty` block field **MUST** be `0` thereafter because there is no longer any Proof-of-Work (PoW) seal on the block. This means that the `DIFFICULTY (0x44)` instruction no longer has it's previous semantic meaning, nor a clear "correct" value to return. + +Given prior analysis on the usage of `DIFFICULTY`, the value returned by the instruction mixed with other values is a common pattern used by smart contracts to obtain randomness. The instruction with the same number as the `DIFFICULTY` opcode returning outputs of the beacon chain RANDAO implementation makes the upgrade to PoS backwards compatible for existing smart contracts obtaining randomness from the `DIFFICULTY` instruction. + +Additionally, changes proposed by this EIP allow for smart contracts to determine whether the upgrade to the PoS has already happened. This can be done by analyzing the return value of the `DIFFICULTY` instruction. A value greater than `2**64` indicates that the transaction is being executed in the PoS block. Decompilers and other similar tooling may also use this trick to discern the new semantics of the instruction if data of the block including the transaction in question is available. + + +## Specification + +### Definitions + +* **`TRANSITION_BLOCK`** The definition of this block can be found in the Definitions section of [EIP-3675](./eip-3675.md#definitions). + +### Block structure + +Beginning with `TRANSITION_BLOCK`, client software **MUST** set the value of the `mixHash`, i.e. the field with the number `13` (0-indexed) in a block header, to the latest RANDAO mix of the post beacon state of the previous block. + +### EVM + +Beginning with `TRANSITION_BLOCK`, the `DIFFICULTY (0x44)` instruction **MUST** return the value of the `mixHash` field. + +*Note*: The gas cost of the `DIFFICULTY (0x44)` opcode remains unchanged. + +### Renaming + +The `mixHash` field **SHOULD** further be renamed to `prevRandao`. + +The `DIFFICULTY (0x44)` opcode **SHOULD** further be renamed to `PREVRANDAO (0x44)`. + + +## Rationale + +### Including RANDAO output in the block header + +Including a RANDAO output in the block header provides a straightforward method of accessing it from inside of the EVM as block header data is already available in the EVM context. + +Additionally, this ensures that the execution layer can be fully executed with the block alone rather than requiring extra inputs from the PoS consensus layer. + +Mixing the randomness into a block header may contribute to uniqueness of the block hash in the case when values of other fields of the block header match the corresponding values of the header of another block. + +### Using `mixHash` field instead of `difficulty` + +The `mixHash` header field is used instead of `difficulty` to avoid a class of hidden forkchoice bugs after the PoS upgrade. + +Client software implementing pre-EIP-3675 logic heavily depends on the `difficulty` value as total difficulty computation is the basis of the PoW fork choice rule. Setting the `difficulty` field to `0` at the PoS upgrade aims to reduce the surface of bugs related to the total difficulty value growing after the upgrade. + +Additionally, any latent total difficulty computation after the PoS upgrade would become overflow prone if the randomness output supplanted the value of the `difficulty` field. + +### Reusing existing field instead of appending a new one + +The `mixHash` field is deprecated at the PoS upgrade and set to zero bytes array thereafter. Reusing an existing field as a place for the randomness output saves 32 bytes per block and effectively removes the deprecation of one of the fields induced by the upgrade. + +### Reusing the `DIFFICULTY` opcode instead of introducing a new one + +See the [Motivation](#motivation). + +### Renaming the field and the opcode + +The renaming should be done to make the field and the opcode names semantically sound. + +### Using `TRANSITION_BLOCK` rather than a block or slot number + +By utilizing `TRANSITION_BLOCK` to trigger the change in logic defined in this EIP rather than a block or slot number, this EIP is tightly coupled to the PoS upgrade defined by [EIP-3675](./eip-3675.md). + +By tightly coupling to the PoS upgrade, we ensure that there is no discontinuity for the usecase of this opcode for randomness -- the primary [motivation](#motivation) for re-using `DIFFICULTY` rather than creating a new opcode. + +### Using `2**64` threshold to determine PoS blocks + +The probability of RANDAO value to fall into the range between `0` and `2**64` and, thus, to be mixed with PoW difficulty values, is drastically low. Though, proposed threshold might seem to have insufficient distance from difficulty values on Ethereum Mainnet (they are currently around `2**54`), it requires a thousand times increase of the hashrate to make this threshold insecure. Such an increase is considered impossible to occur before the upcoming consensus upgrade. + + +## Backwards Compatibility + +This EIP introduces backward incompatible changes to the execution and validation of EVM state transitions. As written, this EIP utilizes `TRANSITION_BLOCK` and is thus tightly coupled with the PoS upgrade introduced in [EIP-3675](./eip-3675.md). If this EIP is to be adopted, it **MUST** be scheduled at the same time as EIP-3675. + +Additionally, the changes proposed might be backward incompatible for the following categories of applications: +* Applications that use the value returned by the `DIFFICULTY` opcode as the PoW `difficulty` parameter +* Applications with logic that depends on the `DIFFICULTY` opcode returning a relatively small number with respect to the full 256-bit size of the field. + +The first category is already affected by switching the consensus mechanism to PoS and no additional breaking changes are introduced by this specification. + +The second category is comprised of applications that use the return value of the `DIFFICULTY` opcode in operations that might cause either overflow or underflow errors. While it is theoretically possible to author an application where a change in the range of possible values this opcode may return could lead to a security vulnerability, the chances of that are negligible. + + +## Test Cases + +* In one of ancestors of `TRANSITION_BLOCK` deploy a contract that stores return value of `DIFFICULTY (0x44)` to the state +* Check that value returned by `DIFFICULTY (0x44)` in transaction executed within the parent of `TRANSITION_BLOCK` equals `difficulty` field value +* Check that value returned by `PREVRANDAO (0x44)` in transaction executed within `TRANSITION_BLOCK` equals `prevRandao` field value + + +## Security Considerations + +The `PREVRANDAO (0x44)` opcode in PoS Ethereum (based on the beacon chain RANDAO implementation) is a source of randomness with different properties to the randomness supplied by `BLOCKHASH (0x40)` or `DIFFICULTY (0x44)` opcodes in the PoW network. + +### Biasability + +The beacon chain RANDAO implementation gives every block proposer 1 bit of influence power per slot. Proposer may deliberately refuse to propose a block on the opportunity cost of proposer and transaction fees to prevent beacon chain randomness (a RANDAO mix) from being updated in a particular slot. + +An effect of proposer's influence power is limited in time and lasts until the first honest RANDAO reveal is made afterwards. This limitation does also exist in the case when proposers of `n` consecutive slots are colluding to get `n` bits of influence power. Simply speaking, one honest block proposal is enough to unbias the RANDAO even if it was biased during several slots in a row. + +Additionally, semantics of the `PREVRANDAO (0x44)` instruction gives proposers another way to gain 1 bit of influence power on applications. Biased proposer may censor a rolling the dice transaction to force it to be included into the next block, thus, force it to use a RANDAO mix that the proposer knows in advance. The opportunity cost in this case would be negligible. + +### Predictability + +Obviously, historical randomness provided by any decentralized oracle is 100% predictable. On the contrary, the randomness that is revealed in the future is predictable up to a limited extent. + +A list of inputs influencing future randomness on the beacon chain consists of but is not limited to the following items: +* **Accumulated randomness.** A RANDAO mix produced by the beacon chain in the last slot of epoch `N` is the main input to the function defining block proposers in each slot of epoch `N + MIN_SEED_LOOKAHEAD + 1`, i.e. it is the main factor defining future RANDAO revealers. +* **Number of active validators.** A number of active validators throughout an epoch is another input to the block proposer function. +* **Effective balance.** All else being equal, the lower the effective balance of a validator the lower the chance this validator has to be designated as a proposer in a slot. +* **Accidentally missed proposals.** Network conditions and other factors that are resulting in accidentally missed proposals is a source of highly qualitative entropy that impacts RANDAO mixes. Usual rate of missed proposals on the Mainnet is about `1%`. + +These inputs may be predictable and malleable on a short range of slots but the longer the attempted lookahead the more entropy is accumulated by the beacon chain. + +### Tips for application developers + +The following tips attempt to reduce predictability and biasability of randomness outputs returned by `PREVRANDAO (0x44)`: + +1. Make your applications rely on the future randomness with a reasonably high lookahead. For example, an application stops accepting bids at the end of epoch `K` and uses a RANDAO mix produced in slot `K + N + ε` to roll the dice, where `N` is a lookahead in epochs and `ε` is a few slots into epoch `N + 1`. +2. At least four epochs of lookahead results in the following outcome: + * A proposer set of epoch `N + 1` isn't known at the end of epoch `K` breaking a direct link between bidders and dice rollers + * A number of active validators is updated at the end of each epoch affecting a set of proposers of next epochs, thus, impacting a RANDAO mix used by the application to roll the dice + * Due to Mainnet statistics, there is about a `100%` chance for the network to accidentally miss a proposal during this period of time which reduces predictability of a RANDAO mix used to roll the dice. +3. Setting `ε` to a small number, e.g. 2 or 4 slots, gives a third party a little time to gain influence power on the future randomness that is being used to roll the dice. This amount of time is defined by `MIN_SEED_LOOKAHEAD` parameter and is about 6 minutes on the Mainnet. + +A reasonably high distance between bidding and rolling the dice attempts to leave low chance for bidders controlling a subset of validators to directly exploit their influence power. Ultimately, this chance depends on the type of the game and on a number of controlled validators. For instance, a chance of a single validator to affect a one-time game is negligible, and becomes bigger for multiple validators in a repeated game scenario. + + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4400.md b/EIPS/eip-4400.md new file mode 100644 index 00000000000000..aa065c239a8db7 --- /dev/null +++ b/EIPS/eip-4400.md @@ -0,0 +1,7 @@ +--- +eip: 4400 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4400.md diff --git a/EIPS/eip-4430.md b/EIPS/eip-4430.md new file mode 100644 index 00000000000000..e8a6481a1cf3f5 --- /dev/null +++ b/EIPS/eip-4430.md @@ -0,0 +1,7 @@ +--- +eip: 4430 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4430.md diff --git a/EIPS/eip-4444.md b/EIPS/eip-4444.md new file mode 100644 index 00000000000000..3a071bc94ed204 --- /dev/null +++ b/EIPS/eip-4444.md @@ -0,0 +1,105 @@ +--- +eip: 4444 +title: Bound Historical Data in Execution Clients +description: Prune historical data in clients older than one year +author: George Kadianakis (@asn-d6), lightclient (@lightclient), Alex Stokes (@ralexstokes) +discussions-to: https://ethereum-magicians.org/t/eip-4444-bound-historical-data-in-execution-clients/7450 +status: Stagnant +type: Standards Track +category: Networking +created: 2021-11-02 +--- + +## Abstract + +Clients must stop serving historical headers, bodies, and receipts older than one year on the p2p layer. Clients may locally prune this historical data. + +## Motivation + +Historical blocks and receipts currently occupy more than 400GB of disk space (and growing!). Therefore, to validate the chain, users must typically have a 1TB disk. + +Historical data is not necessary for validating new blocks, so once a client has synced the tip of the chain, historical data is only retrieved when requested explicitly over the JSON-RPC or when a peer attempts to sync the chain. By pruning the history, this proposal reduces the disk requirements for users. Pruning history also allows clients to remove code that processes historical blocks. This means that execution clients don't need to maintain code paths that deal with each upgrade's compounding changes. + +Finally, this change will result in less bandwidth usage on the network as clients adopt more lightweight sync strategies based on the PoS weak subjectivity assumption. + +## Specification + +| Parameter | Value | Description | +| - | - | - | +| `HISTORY_PRUNE_EPOCHS` | 82125 | A year in beacon chain epochs | + +Clients SHOULD NOT serve headers, block bodies, and receipts that are older than `HISTORY_PRUNE_EPOCHS` epochs on the p2p network. + +Clients MAY locally prune headers, block bodies, and receipts that are older than `HISTORY_PRUNE_EPOCHS` epochs. + +#### Bootstrapping and syncing + +This EIP impacts the way clients bootstrap and sync. Clients will not be able to full sync using devp2p since historical data will no longer be served. + +Clients MUST use a valid Weak Subjectivity Checkpoint to bootstrap from a more recent view of the chain. For the purpose of syncing, clients treat weak subjectivity checkpoints as the genesis block. We call this method "checkpoint sync". + +For the purposes of this proposal, we assume clients always start with a configured and valid weak subjectivity checkpoint. The way this is achieved is out-of-scope for this proposal. + +## Rationale + +This proposal forces clients to stop serving old historical data over p2p. We make this explicit to force clients to seek historical data from other sources, instead of relying on the optional behavior of some clients which would result in quality degradation. + +### Why a year? + +This proposal sets `HISTORY_PRUNE_EPOCHS` to 82125 epochs (one earth year). This constant is large enough to provide sufficient room for the Weak Subjectivity Period to grow, and it's also small enough so as to not occupy too much disk space. + +## Backwards Compatibility + +### Preserving historical data + +This proposal impacts nodes that make use of historical data (e.g. web3 applications that display history of blocks, transactions or accounts). Preserving the history of Ethereum is fundamental and we believe there are various out-of-band ways to achieve this. + +Historical data can be packaged and shared via torrent magnet links or over networks like IPFS. Furthermore, systems like the Portal Network or The Graph can be used to acquire historical data. + +Clients should allow importing and exporting of historical data. Clients can provide scripts that fetch/verify data and automatically import them. + +### Full syncing from genesis + +Full syncing will no longer be possible over the p2p network. However, we do want to allow interested parties to do so on their own. + +We suggest that a specialized "full sync" client is built. The client is a shim that pieces together different releases of execution engines and can import historical blocks to validate the entire Ethereum chain from genesis and generate all other historical data. + +It's important to also note that although archive nodes with "state sync" functionality are in development, full sync is currently the only reliable way to bootstrap them. Clients that wish to continue providing archive support would need the ability to import historical blocks retrieved out-of-band and retain support for each historical upgrade of the network. + +### User experience + +This proposal impacts the UX for setting up applications that use historical data. Hence we suggest that clients introduce this change in two phases: + +In the first phase, clients don't prune historical data by default. They introduce a command line option similar to geth's `--txlookuplimit` that users can use if they want to prune historical data. + +In the second phase, history is pruned by default and the command line option is removed. Clients assume that users will find and import data in an out-of-band way. + +### JSON-RPC changes + +After this proposal is implemented, certain JSON-RPC endpoints (e.g. like `getBlockByHash`) won't be able to tell whether a given hash is invalid or just outdated. Other endpoints like `getLogs` will simply no longer have the data the user is requesting. The way this regression should be handled by applications or clients is out-of-scope for this proposal. + +## Security Considerations + +### Relying on weak subjectivity + +With the move to PoS, it's essential for security to use valid weak subjectivity checkpoints because of long-range attacks. + +This proposal relies on the weak subjectivity assumption and assumes that clients will not bootstrap with an invalid or old WS checkpoint. + +This proposal also assumes that the weak subjectivity period will never be longer than `HISTORY_PRUNE_EPOCHS`. If that were to happen, clients with an old weak subjectivity checkpoint would never be able to "checkpoint sync" since the p2p network would not be able to provide the required data. + +### Centralization/censorship risk + +There are censorship/availability risks if there is a lack of incentives to keep historical data. + +It's important that Ethereum historical data are preserved and seeded by independent organizations, and their availability should be checked frequently. We consider these mechanisms as out-of-scope for this proposal. + +Furthermore, there is a risk that more dapps will rely on centralized services for acquiring historical data because it will be harder to setup a full node. + +### Confusion with other proposals + +Because there are a number of alternative proposals for reducing the execution client's footprint on disk, we've decided to enforce a specific pronunciation of the EIP. When pronouncing the EIP number, it **MUST** be pronounced EIP "four fours". All other pronunciation are incorrect. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-4488.md b/EIPS/eip-4488.md new file mode 100644 index 00000000000000..0ac03550238d92 --- /dev/null +++ b/EIPS/eip-4488.md @@ -0,0 +1,71 @@ +--- +eip: 4488 +title: Transaction calldata gas cost reduction with total calldata limit +description: Greatly decreases the gas cost of transaction calldata and simultaneously caps total transaction calldata in a block +author: Vitalik Buterin (@vbuterin), Ansgar Dietrichs (@adietrichs) +discussions-to: https://ethereum-magicians.org/t/eip-4488-transaction-calldata-gas-cost-reduction-with-total-calldata-limit/7555 +type: Standards Track +category: Core +status: Stagnant +created: 2021-11-23 +--- + +## Abstract + +Decrease transaction calldata gas cost, and add a limit of how much total transaction calldata can be in a block. + +## Motivation + +Rollups are in the short and medium term, and possibly the long term, the only trustless scaling solution for Ethereum. Transaction fees on L1 have been very high for months and there is greater urgency in doing anything required to help facilitate an ecosystem-wide move to rollups. Rollups are significantly reducing fees for many Ethereum users: Optimism and Arbitrum frequently provide fees that are ~3-8x lower than the Ethereum base layer itself, and ZK rollups, which have better data compression and can avoid including signatures, have fees ~40-100x lower than the base layer. + +However, even these fees are too expensive for many users. The long-term solution to the long-term inadequacy of rollups by themselves has always been [data sharding](https://github.com/ethereum/consensus-specs#sharding), which would add ~1-2 MB/sec of dedicated data space for rollups to the chain. However, data sharding will still take a considerable amount of time to finish implementing and deploying. Hence, a short-term solution to further cut costs for rollups, and to incentivize an ecosystem-wide transition to a rollup-centric Ethereum, is desired. + +This EIP presents a quick-to-implement short-term solution that also mitigates security risks. + +## Specification + +| Parameter | Value | +| - | - | +| `NEW_CALLDATA_GAS_COST` | `3` | +| `BASE_MAX_CALLDATA_PER_BLOCK` | `1,048,576` | +| `CALLDATA_PER_TX_STIPEND` | `300` | + +Reduce the gas cost of transaction calldata to `NEW_CALLDATA_GAS_COST` per byte, regardless of whether the byte is zero or nonzero. + +Add a rule that a block is only valid if `sum(len(tx.calldata) for tx in block.txs) <= BASE_MAX_CALLDATA_PER_BLOCK + len(block.txs) * CALLDATA_PER_TX_STIPEND`. + +## Rationale + +A natural alternative proposal is to decrease `NEW_CALLDATA_GAS_COST` without adding a limit. However, this presents a security concern: today, the average block size [is 60-90 kB](https://etherscan.io/chart/blocksize), but the _maximum_ block size is `30M / 16 = 1,875,000` bytes (plus about a kilobyte of block and tx overhead). Simply decreasing the calldata gas cost from 16 to 3 would increase the maximum block size to 10M bytes. This would push the Ethereum p2p networking layer to unprecedented levels of strain and risk breaking the network; some previous live tests of ~500 kB blocks a few years ago had already taken down a few bootstrap nodes. + +The decrease-cost-and-cap proposal achieves most of the benefits of the decrease, as rollups are unlikely to _dominate_ Ethereum block space in the short term future and so 1.5 MB will be sufficient, while preventing most of the security risk. + +Historically, the Ethereum protocol community has been suspicious of multi-dimensional resource limit rules (in this case, gas and calldata) because such rules greatly increase the complexity of the block packing problem that proposers (today miners, post-merge validators) need to solve. Today, proposers can generate blocks with near-optimal fee revenue by simply choosing transactions in highest-to-lowest order of priority fee. In a multi-dimensional world, proposers would have to deal with multi-dimensional constraints. Multi-dimensional knapsack problems are much more complicated than the single-dimensional equivalent, and well-optimized proprietary implementations built by pools may well outperform default open source implementations. + +Today, there are two key reasons why this is less of a problem than before: + +1. [EIP-1559](./eip-1559.md) means that, at least most of the time, the problem that block proposers are solving is _not_ a knapsack problem. Rather, block proposers are simply including all the transactions they can find with sufficient base fee and priority fee. Hence, naive algorithms will also frequently generate close-to-optimal results. +2. The existence of sophisticated proprietary strategies for miner extractable value (MEV) extraction means that decentralized optimal block production is already in the medium and long term a lost cause. Research is instead going into solutions that separate away the specialization-friendly task of block body generation from the role of a validator ("proposer/builder separation"). Instead of being a fundamental change, two-dimensional knapsack problems today would be merely "yet another" MEV opportunity. + +Hence, it's worth rethinking the historical opposition to multi-dimensional resource limits and considering them as a pragmatic way to simultaneously achieve moderate scalability gains while retaining security. + +Additionally, the stipend mechanism makes the two-dimensional optimization problem even less of an issue in practice. 90% of all transactions ([sample](../assets/eip-4488/gas_and_calldata_sample.csv) taken from blocks `13500000, 13501000 ... 13529000`) have <300 bytes of calldata. Hence, if a naive transaction selection algorithm overfills the calldata of a block that the proposer is creating, the proposer will still be able to keep adding transactions from 90% of their mempool. + +## Backwards Compatibility + +This is a backwards incompatible gas repricing that requires a scheduled network upgrade. + +Users will be able to continue operating with no changes. + +Miners will be able to continue operating with no changes except for a rule to stop adding new transactions into a block when the total calldata size reaches the maximum. However, there are pragmatic heuristics that they could add to achieve closer-to-optimal returns in such cases: for example, if a block fills up to the size limit, they could repeatedly remove the last data-heavy transaction and replace it with as many data-light transactions as possible, until doing so is no longer profitable. + +## Security Considerations + +The _burst_ data capacity of the chain does not increase as a result of this proposal (in fact, it slightly decreases). However, the _average_ data capacity will increase. This means that the storage requirements of history-storing will go up. A worst-case scenario would be a theoretical long-run maximum of ~1,262,861 bytes per 12 sec slot, or ~3.0 TB per year. + +We recommend [EIP-4444](./eip-4444.md) or some similar history expiry proposal be implemented either at the same time or soon after this EIP to mitigate this risk. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-4494.md b/EIPS/eip-4494.md new file mode 100644 index 00000000000000..520bdfdceb4fb0 --- /dev/null +++ b/EIPS/eip-4494.md @@ -0,0 +1,7 @@ +--- +eip: 4494 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4494.md diff --git a/EIPS/eip-4519.md b/EIPS/eip-4519.md new file mode 100644 index 00000000000000..75822b42b22c49 --- /dev/null +++ b/EIPS/eip-4519.md @@ -0,0 +1,7 @@ +--- +eip: 4519 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4519.md diff --git a/EIPS/eip-4520.md b/EIPS/eip-4520.md new file mode 100644 index 00000000000000..45b73f24ee7662 --- /dev/null +++ b/EIPS/eip-4520.md @@ -0,0 +1,36 @@ +--- +eip: 4520 +title: Multi-byte opcodes prefixed by EB and EC. +description: Reserve `0xEB` and `0xEC` for usage as extended opcode space. +author: Brayton Goodall (@Spore-Druid-Bray), Mihir Faujdar (@uink45) +discussions-to: https://ethereum-magicians.org/t/multi-byte-opcodes/7681 +status: Stagnant +type: Standards Track +category: Core +created: 2021-12-01 +--- + +## Abstract +Reserve `0xEB` and `0xEC` for usage as extended opcode space. + +## Motivation +It would be convenient to introduce new opcodes that are likely to be infrequently used, whilst also being able to have greater than 256 opcodes in total. As a single byte opcode is half the size of a double byte opcode, the greatest efficiency in code sizes will be one where frequently used opcodes are single bytes. Two prefix bytes are used to accommodate up to 510 double byte opcodes. + +## Specification +For example, a new arithmetic opcode may be allocated to `0xEC 01`(`ADD`), and a novel opcode may be introduced at `0xEB F4`(`DELEGATECALL`). + +Triple byte opcodes may be doubly-prefixed by `0xEB EB`, `0xEC EC`, `0xEB EC` and `0xEC EB`. It is possible to allocate experimental opcodes to this triple-byte space initially, and if they prove safe and useful, they could later be allocated a location in double-byte or single-byte space. + +Only `0xEB EB`, `0xEC EC`, `0xEC EC`, and `0xEB EC` may be interpreted as further extensions of the opcode space. `0xEB` and `0xEC` do not themselves affect the stack or memory, however opcodes specified by further bytes may. If a multi-byte opcode is yet to be defined, it is to be treated as `INVALID` rather than as a `NOP`, as per usual for undefined opcodes. + +## Rationale +It was considered that two prefix bytes rather than one would be adequate for reservation as extension addresses. Both `0xEB` and `0xEC` were chosen to be part of the E-series of opcodes. For example, the `0xEF` byte is reserved for contracts conforming to the Ethereum Object Format. By having unassigned opcodes for extending the opcode space, there will be a lower risk of breaking the functionalities of deployed contracts compared to choosing assigned opcodes. + +## Backwards Compatibility +Previous usage of `0xEB` and `0xEC` may result in unexpected behaviour and broken code. + +## Security Considerations +There are no known security considerations. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4521.md b/EIPS/eip-4521.md new file mode 100644 index 00000000000000..f9b8533ed65f63 --- /dev/null +++ b/EIPS/eip-4521.md @@ -0,0 +1,7 @@ +--- +eip: 4521 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4521.md diff --git a/EIPS/eip-4524.md b/EIPS/eip-4524.md new file mode 100644 index 00000000000000..bf966b0c5f3543 --- /dev/null +++ b/EIPS/eip-4524.md @@ -0,0 +1,7 @@ +--- +eip: 4524 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4524.md diff --git a/EIPS/eip-4527.md b/EIPS/eip-4527.md new file mode 100644 index 00000000000000..237429150b71ca --- /dev/null +++ b/EIPS/eip-4527.md @@ -0,0 +1,7 @@ +--- +eip: 4527 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4527.md diff --git a/EIPS/eip-4546.md b/EIPS/eip-4546.md new file mode 100644 index 00000000000000..3dcbfa7ce06799 --- /dev/null +++ b/EIPS/eip-4546.md @@ -0,0 +1,7 @@ +--- +eip: 4546 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4546.md diff --git a/EIPS/eip-4573.md b/EIPS/eip-4573.md new file mode 100644 index 00000000000000..9015b073a0a867 --- /dev/null +++ b/EIPS/eip-4573.md @@ -0,0 +1,195 @@ +--- +eip: 4573 +title: Procedures for the EVM +description: Introduces support for EVM Procedures. +status: Stagnant +type: Standards Track +category: Core +author: Greg Colvin (@gcolvin), Greg Colvin +discussions-to: https://ethereum-magicians.org/t/eip-4573-named-procedures-for-evm-code-sections/7776 +created: 2021-12-16 +requires: 2315, 3540, 3670, 3779, 4200 +--- + +## Abstract + +Five EVM instructions are introduced to define, call, and return from named EVM _procedures_ and access their _call frames_ in memory - `ENTERPROC`, `LEAVEPROC`, `CALLPROC`, `RETURNPROC`, and `FRAMEADDRESS`. + +## Motivation + +Currently, Ethereum bytecode has no syntactic structure, and _subroutines_ have no defined interfaces. + +We propose to add _procedures_ -- delimited blocks of code that can be entered only by calling into them via defined interfaces. + +Also, the EVM currently has no automatic management of memory for _procedures_. So we also propose to automatically reserve call frames on an in-memory stack. + +Constraints on the use of _procedures_ must be validated at contract initialization time to maintain the safety properties of [EIP-3779](./eip-3779.md): Valid programs will not halt with an exception unless they run out of gas or recursively overflow stack. + +### Prior Art + +The terminology is not well-defined, but we will follow Intel in calling the low-level concept _subroutines_ and the higher level concept _procedures_. The distinction is that _subroutines_ are little more than a jump that knows where it came from, whereas procedures have a defined interface and manage memory as a stack. [EIP-2315](./eip-2315.md) introduces _subroutines_, and this EIP introduces _procedures_. + +## Specification + +### Instructions + +#### ENTERPROC (0x??) dest_section: uint8, dest_offset: uint8, n_inputs: uint16, n_outputs: uint16, n_locals: uint16 +``` +frame_stack.push(FP) +FP -= n_locals * 32 +PC +- +``` +Marks the entry point to a procedure +* at offset `dest_offset` from the beginning of the `dest_section`. +* taking `n_inputs` arguments from the data stack, +* returning `n_outputs` values on the `data stack`, and +* reserving `n_locals` words of data in memory on the `frame stack`. + +Procedures can only be entered via a `CALLPROC` to their entry point. + +#### LEAVEPROC (0x??) + +``` + FP = frame_stack.pop() + asm RETURNSUB +``` +> Pop the `frame stack` and return to the calling procedure using `RETURNSUB`. + +Marks the end of a procedure. Each `ENTERPROC` requires a closing `LEAVEPROC`. + +*Note: Attempts to jump into a procedure (including its `LEAVEPROC`) from outside of the procedure or to jump or step to `ENTERPROC` at all must be prevented at validation time. `CALLPROC` is the only valid way to enter a procedure.* + +#### CALLPROC (0x??) dest_section: uint16, dest_proc: uint16 + ``` + FP -= n_locals + asm JUMPSUB + +``` +> Allocate a *stack frame* and transfer control and `JUMPSUB` to the Nth (N=*dest_proc*) _procedure_ in the Mth(M=*dest_section*) _section_ of the code. _Section 0_ is the current code section, any other code sections are indexed starting at _1_. + +*Note: That the procedure is defined and the required `n_inputs` words are available on the `data stack` must be shown at validation time.* + +#### RETURNPROC (0x??) +``` + FP += n_locals + asm RETURNSUB +``` +> Pop the `frame stack` and return control to the calling procedure using `RETURNSUB`. + +*Note: That the promised `n_outputs` words are available on the `data stack` must be shown at validation time.* + +#### FRAMEADDRESS (0x??) offset: int16 +``` +asm PUSH2 FP + offset +``` +> Push the address `FP + offset` onto the data stack. + +Call frame data is addressed at an immediate `offset` relative to `FP`. + +Typical usage includes storing data on a call frame +``` +PUSH 0xdada +FRAMEADDRESS 32 +MSTORE +``` +and loading data from a call frame +``` +FRAMEADDRESS 32 +MLOAD +``` + +### Memory Costs + +Presently,`MSTORE` is defined as +``` + memory[stack[0]...stack[0]+31] = stack[1] + memory_size = max(memory_size,floor((stack[0]+32)÷32) +``` +* where `memory_size` is the number of active words of memory above _0_. + +We propose to treat memory addresses as signed, so the formula needs to be +``` + memory[stack[0]...stack[0]+31] = stack[1] + if (stack[0])+32)÷32) < 0 + negative_memory_size = max(negative_memory_size,floor((stack[0]+32)÷32)) + else + positive_memory_size = max(positive_memory_size,floor((stack[0]+32)÷32)) + memory_size = positive_memory_size + negative_memory_size +``` +* where `negative_memory_size` is the number of active words of memory below _0_ and +* where `positive_memory_size` is the number of active words of memory at or above _0_. + +### Call Frame Stack + +These instructions make use of a `frame stack` to allocate and free frames of local data for _procedures_ in memory. Frame memory begins at address 0 in memory and grows downwards, towards more negative addresses. A frame is allocated for each procedure when it is called, and freed when it returns. + +Memory can be addressed relative to the frame pointer `FP` or by absolute address. `FP` starts at 0, and moves downward towards more negative addresses to point to the frame for each `CALLPROC` and moving upward towards less negative addresses to point to the previous frame for the corresponding `RETURNPROC`. + +Equivalently, in the EVM's twos-complement arithmetic, `FP` moves from the highest address down, as is common in many calling conventions. + +For example, after an initial `CALLPROC` to a procedure needing two words of data the `frame stack` might look like this + +``` + 0-> ........ + ........ + FP-> +``` +Then, after a further `CALLPROC` to a procedure needing three words of data the `frame stack` would like this + +``` + 0-> ........ + ........ + -64-> ........ + ........ + ........ + FP-> +``` +After a `RETURNPROC` from that procedure the `frame stack` would look like this +``` + 0-> ........ + ........ + FP-> ........ + ........ + ........ +``` +and after a final `RETURNPROC`, like this +``` + FP-> ........ + ........ + ........ + ........ + ........ +``` + +## Rationale + +There is actually not much new here. It amounts to [EIP-615](./eip-615.md), refined and refactored into bite-sized pieces, along lines common to other machines. + +This proposal uses the [EIP-2315](./eip-2315.md) return stack to manage calls and returns, and steals ideas from [EIP-615](./eip-615.md), [EIP-3336](./eip-3336.md), and [EIP-4200](./eip-4200.md). `ENTERPROC` corresponds to `BEGINSUB` from EIP-615. Like EIP-615 it uses a frame stack to track call-frame addresses with `FP` as _procedures_ are entered and left, but like EIP-3336 and EIP-3337 it moves call frames from the data stack to memory. + +Aliasing call frames with ordinary memory supports addressing call-frame data with ordinary stores and loads. This is generally useful, especially for languages like C that provide pointers to variables on the stack. + +The design model here is the _subroutines_ and _procedures_ of the Intel x86 architecture. +* `JUMPSUB` and `RETURNSUB` (from [EIP-2315](./eip-2315.md) -- like `CALL` and `RET` -- jump to and return from _subroutines_. +* `ENTERPROC` -- like `ENTER` -- sets up the stack frame for a _procedure_. +* `CALLPROC` amounts to a `JUMPSUB` to an `ENTERPROC`. +* `RETURNPROC` amounts to an early `LEAVEPROC`. +* `LEAVEPROC` -- like `LEAVE` -- takes down the stack frame for a _procedure_. It then executes a `RETURNSUB`. + +## Backwards Compatibility + +This proposal adds new EVM opcodes. It doesn't remove or change the semantics of any existing opcodes, so there should be no backwards compatibility issues. + +## Security + +Safe use of these constructs must be checked completely at validation time -- per EIP-3779 -- so there should be no security issues at runtime. + +`ENTERPROC` and `LEAVEPROC` must follow the same safety rules as for `JUMPSUB` and `RETURNSUB` in EIP-2315. In addition, the following constraints must be validated: + +* Every`ENTERPROC` must be followed by a `LEAVEPROC` to delimit the bodies of _procedures_. +* There can be no nested _procedures_. +* There can be no jump into the body of a procedure (including its `LEAVEPROC`) from outside of that body. +* There can be no jump or step to `BEGINPROC` at all -- only `CALLPROC`. +* The specified `n_inputs` and `n_outputs` must be on the stack. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4626.md b/EIPS/eip-4626.md new file mode 100644 index 00000000000000..be8961ad67107a --- /dev/null +++ b/EIPS/eip-4626.md @@ -0,0 +1,7 @@ +--- +eip: 4626 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4626.md diff --git a/EIPS/eip-4671.md b/EIPS/eip-4671.md new file mode 100644 index 00000000000000..8362070fa3fda9 --- /dev/null +++ b/EIPS/eip-4671.md @@ -0,0 +1,7 @@ +--- +eip: 4671 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4671.md diff --git a/EIPS/eip-4675.md b/EIPS/eip-4675.md new file mode 100644 index 00000000000000..07210894d9c9cc --- /dev/null +++ b/EIPS/eip-4675.md @@ -0,0 +1,7 @@ +--- +eip: 4675 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4675.md diff --git a/EIPS/eip-4736.md b/EIPS/eip-4736.md new file mode 100644 index 00000000000000..3266787337e5d9 --- /dev/null +++ b/EIPS/eip-4736.md @@ -0,0 +1,157 @@ +--- +eip: 4736 +title: Consensus Layer Withdrawal Protection +description: Additional security for BLSToExecutionChange operation when a consensus layer mnemonic may be compromised, without changing consensus +author: Benjamin Chodroff (@benjaminchodroff), Jim McDonald (@mcdee) +discussions-to: https://ethereum-magicians.org/t/consensus-layer-withdrawal-protection/8161 +status: Final +type: Standards Track +category: Interface +created: 2022-01-30 +--- + +## Abstract + +If a consensus layer mnemonic phrase is compromised, it is impossible for the consensus layer network to differentiate the legitimate holder of the key from an illegitimate holder. However, there are signals that can be considered in a wider sense without changing core Ethereum consensus. This proposal outlines ways in which on chain evidence such as the execution layer deposit address and list of signed messages could create a social consensus that would significantly favor but not guarantee legitimate mnemonic holders would win a race condition against an attacker. + +## Motivation + +The consensus layer `BLSToExecutionChange` message is secure for a single user who has certainty their keys and mnemonic have not been compromised. However, as validator withdrawals on the consensus layer are not possible until the Capella hard fork, no user can have absolute certainty that their keys are not compromised until the `BLSToExecutionChange` is on chain, and by then too late to change. All legitimate mnemonic phrase holders were originally in control of the execution layer deposit address. Beacon node clients and node operators may optionally load a list of verifiable `BLSToExecutionChange` messages to broadcasts that may create a social consensus for legitimate holders to successfully win a race condition against an attacker. If attackers compromise a significant number of consensus layer nodes, it would pose risks to the entire Ethereum community. + +Setting a withdrawal address to an execution layer address was not supported by the eth2.0-deposit-cli until v1.1.1 on March 23, 2021, leaving early adopters wishing they could force set their execution layer address to a deposit address earlier. Forcing this change is not something that can be enforced in-protocol, partly due to lack of information on the beacon chain about the execution layer deposit address and partly due to the fact that this was never listed as a requirement. It is also possible that the execution layer deposit address is no longer under the control of the legitimate holder of the withdrawal private key. + +However, it is possible for individual nodes to locally restrict the changes they wish to include in blocks they propose, and which they propagate around the network, in a way that does not change consensus. It is also possible for client nodes to help broadcast signed `BLSToExecutionChange` requests to ensure as many nodes witness this message as soon as possible in a fair manner. Further, such `BLSToExecutionChange` signed messages can be preloaded into clients in advance to further help nodes filter attacking requests. + +This proposal provides purely optional additional protection. It aims to request nodes set a priority on withdrawal credential claims that favour a verifiable execution layer deposit address in the event of two conflicting `BLSToExecutionChange` messages. It also establishes a list of `BLSToExecutionChange` signed messages to help broadcast "as soon as possible" when the network supports it, and encourage client teams to help use these lists to honour filter and prioritize accepting requests by REST and transmitting them via P2P. This will not change consensus, but may help prevent propagating an attack where a withdrawal key has been knowingly or unknowingly compromised. + +It is critical to understand that this proposal is not a consensus change. Nothing in this proposal restricts the validity of withdrawal credential operations within the protocol. It is a voluntary change by client teams to build this functionality in to their beacon nodes, and a voluntary change by node operators to accept any or all of the restrictions and broadcasting capabilities suggested by end users. + +Because of the above, even if fully implemented, it will be down to chance as to which validators propose blocks, and which voluntary restrictions those validators’ beacon nodes are running. Node operators can do what they will to help the community prevent attacks on any compromised consensus layer keys, but there are no guarantees of success this will prevent a successful attack. + +## Specification + +The Consensus Layer `BLSToExecutionChange` operation has the following fields: + +* Validator index +* Current withdrawal BLS public key +* Proposed execution layer withdrawal address +* Signature by withdrawal private key over the prior fields + +This proposal describes OPTIONAL and RECOMMENDED mechanisms which a client beacon node MAY implement, and end users are RECOMMENDED to use in their beacon node operation. + +### `BLSToExecutionChange` Broadcast File + +Beacon node clients MAY support an OPTIONAL file of lines specifying "validator index" , "current withdrawal BLS public key" , "proposed execution layer withdrawal address", and "signature" which, if implemented and if provided, SHALL instruct nodes to automatically submit a one-time `BLSToExecutionChange` broadcast message for each valid signature at the Capella hard fork. This file SHALL give all node operators an OPTIONAL opportunity to ensure any valid `BLSToExecutionChange` messages are broadcast, heard, and shared by nodes at the Capella hard fork. This OPTIONAL file SHALL also instruct nodes to perpetually prefer accepting and repeating signatures matching the signature in the file, and SHALL reject accepting or rebroadcasting messages which do not match a signature for a given withdrawal credential. + +### `BLSToExecutionChange` Handling + +Beacon node clients are RECOMMENDED to allow accepting "`BLSToExecutionChange` Broadcast" file of verifiable signatures, and then MAY fallback to accept a "first request" via P2P. All of this proposal is OPTIONAL for beacon nodes to implement or use, but all client teams are RECOMMENDED to allow a "`BLSToExecutionChange` Broadcast File" to be loaded locally before the Capella hard fork. This OPTIONAL protection will allow a user to attempt to set a withdrawal address message as soon as the network supports it without any change to consensus. + +## Rationale + +This proposal is intended to protect legitimate validator mnemonic holders where it was knowingly or unknowingly compromised. As there is no safe way to transfer ownership of a validator without exiting, it can safely be assumed that all validator holders intend to set to a withdrawal address they specify. Using the deposit address in the execution layer to determine the legitimate holder is not possible to consider in consensus as it may be far back in history and place an overwhelming burden to maintain such a list. As such, this proposal outlines optional mechanism which protect legitimate original mnemonic holders and does so in a way that does not place any mandatory burden on client node software or operators. + +## Backwards Compatibility + +As there is no existing `BLSToExecutionChange` operation prior to Capella, there is no documented backwards compatibility. As all of the proposal is OPTIONAL in both implementation and operation, it is expected that client beacon nodes that do not implement this functionality would still remain fully backwards compatible with any or all clients that do implement part or all of the functionality described in this proposal. Additionally, while users are RECOMMENDED to enable these OPTIONAL features, if they decide to either disable or ignore some or all of the features, or even purposefully load content contrary to the intended purpose, the beacon node client will continue to execute fully compatible with the rest of the network as none of the proposal will change core Ethereum consensus. + +## Reference Implementation + +### `BLSToExecutionChange` Broadcast File + +A "change-operations.json" file intended to be preloaded with all consensus layer withdrawal credential signatures and verifiable execution layer deposit addresses. This file may be generated by a script and able to be independently verified by community members using the consensus layer node, and intended to be included by all clients, enabled by default. Client nodes are encouraged to enable packaging this independently verifiable list with the client software, and enable it by default to help further protect the community from unsuspected attacks. + +The change-operations.json format is the "`BLSToExecutionChange` File - Claim" combined into a single JSON array. + +### `BLSToExecutionChange` Broadcast File - Claim + +A community collected and independently verifiable list of "`BLSToExecutionChange` Broadcasts" containing verifiable claims will be collected. Node operators may verify these claims independently and are suggested to load claims in compatible beacon node clients. + +To make a verifiable claim, users MAY upload a claim to any public repository in a text file "[chain]/validatorIndex.json" such as "mainnet/123456.json". + +123456.json: + +``` +[{"message":{"validator_index":"123456","from_bls_pubkey":"0x977cc21a067003e848eb3924bcf41bd0e820fbbce026a0ff8e9c3b6b92f1fea968ca2e73b55b3908507b4df89eae6bfb","to_execution_address":"0x08f2e9Ce74d5e787428d261E01b437dC579a5164"},"signature":"0x872935e0724b31b2f0209ac408b673e6fe2f35b640971eb2e3b429a8d46be007c005431ef46e9eb11a3937f920cafe610c797820ca088543c6baa0b33797f0a38f6db3ac68ffc4fd03290e35ffa085f0bfd56b571d7b2f13c03f7b6ce141c283"}] +``` + +#### Claim Acceptance + +In order for a submission to be merged into public repository, the submission must have: + +1. Valid filename in the format validatorIndex.json +2. Valid validator index which is active on the consensus layer +3. Verifiable signature +5. A single change operation for a single validator, with all required fields in the file with no other content present + +All merge requests that fail will be provided a reason from above which must be addressed prior to merge. Any future verifiable amendments to accepted claims must be proposed by the same submitter, or it will be treated as a contention. + +#### `BLSToExecutionChange` Broadcast + +Anyone in the community will be able to independently verify the files from the claims provided using the Capella spec and command line clients such as "ethdo" which support the specification. + +A claim will be considered contested if a claim arrives where the verifiable consensus layer signatures differ between two or more submissions, where neither party has proven ownership of the execution layer deposit address. If a contested but verified "`BLSToExecutionChange` Broadcast" request arrives to a repository, all parties can be notified, and may try to convince the wider community by providing any publicly verifiable on chain evidence or off chain evidence supporting their claim to then include their claim in nodes. Node operators may decide which verifiable claims they wish to include based on social consensus. + +## Security Considerations + +### 1: Attacker lacks EL deposit key, uncontested claim + +* User A: Controls the CL keys and the EL key used for the deposit +* User B: Controls the CL keys, but does not control the EL key for the deposit + +User A signs and submits a claim to the CLWP repository, clients load User A message into the "`BLSToExecutionChange` Broadcast" file. At the time of the first epoch support `BLSToExecutionChange`, many (not all) nodes begin to broadcast the message. User B also tries to submit a different but valid `BLSToExecutionChange` to an address that does not match the signature in the claim. This message is successfully received via REST API, but some (not all) nodes begin to silently drop this message as the signature does not match the signature in the "`BLSToExecutionChange` Broadcast" file. As such, these nodes do not replicate this message via P2P. + +### 2: Attacker has both EL deposit key and CL keys, uncontested claim + +* User A: Controls the CL key/mnemonic and the EL key used for the deposit, and submits a claim to move to a new address +* User B: Controls the CL and EL key/mnemonic used for the EL deposit, but fails to submit a claim + +It is possible/likely that User A would notice that all their funds in the EL deposit address had been stolen. This may signal that their CL key is compromised as well, so they decide to pick a new address for the withdrawal. The story will play out the same as Scenario 1 as the claim is uncontested. + +### 3: Same as #2, but the attacker submits a contested claim + +* User A: Controls the CL keys/mnemonic and the EL key used for the deposit, and submits a claim to move to a new address +* User B: Controls the CL keys/mnemonic and the EL key used for the deposit, and submits a claim to move to a new address + +This is a contested claim and as such there is no way to prove who is in control using on chain data. Instead, either user may try to persuade the community they are the rightful owner (identity verification, social media, etc.) in an attempt to get node operators to load their contested claim into their "`BLSToExecutionChange` Broadcast" file. However, there is no way to fully prove it. + +### 4: A user has lost either their CL key and/or mnemonic (no withdrawal key) + +* User A: Lacks the CL keys and mnemonic + +There is no way to recover this scenario with this proposal as we cannot prove a user has lost their keys, and the mnemonic is required to generate the withdrawal key. + +### 5: End game - attacker + +* User A: Controls EL and CL key/mnemonic, successfully achieves a set address withdrawal +* User B: Controls CL key, decides to attack + +Upon noticing User A has submitted a successful set address withdrawal, User B may run a validator and attempt to get User A slashed. Users who suspect their validator key or seed phrase is compromised should take action to exit their validator as early as possible. + +### 6: Compromised key, but not vulnerable to withdrawal + +* User A: Controls EL and CL key/mnemonic, but has a vulnerability which leaks their CL key but NOT their CL mnemonic +* User B: Controls the CL key, but lacks the CL mnemonic + +User A may generate the withdrawal key (requires the mnemonic). User B can attack User A by getting them slashed, but will be unable to generate the withdrawal key. + +### 7: Attacker loads a malicious `BLSToExecutionChange` Broadcast file into one or multiple nodes, User A submits claim + +* User A: Submits a valid uncontested claim which is broadcast out as soon as possible by many nodes +* User B: Submits no claim, but broadcasts a valid malicious claim out through their `BLSToExecutionChange` Broadcast list, and blocks User A's claim from their node. + +User B's claim will make it into many nodes, but when it hits nodes that have adopted User A's signature they will be dropped and not rebroadcast. Statistically, User B will have a harder time achieving consensus among the entire community, but it will be down to chance. + +### 8: Same as #7, but User A submits no claim + +The attacker will statistically likely win as they will be first to have their message broadcast to many nodes and, unless User A submits a request exactly at the time of support, it is unlikely to be heard by enough nodes to gain consensus. All users are encouraged to submit claims for this reason because nobody can be certain their mnemonic has not been compromised until it is too late. + +### Second Order Effects + +1. A user who participates in the "`BLSToExecutionChange` Broadcast" may cause the attacker to give up early and instead start to slash. For some users, the thought of getting slashed is preferable to giving an adversary any funds. As the proposal is voluntary, users may choose not to participate if they fear this scenario. +2. The attacker may set up their own `BLSToExecutionChange` Broadcast to reject signatures not matching their attack. This is possible with or without this proposal. +3. The attacker may be the one collecting "`BLSToExecutionChange` Broadcast" claims for this proposal and may purposefully reject legitimate requests. Anyone is free to set up their own community claim collection and gather their own community support using the same mechanisms described in this proposal to form an alternative social consensus. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4747.md b/EIPS/eip-4747.md new file mode 100644 index 00000000000000..2a710d36ad68ba --- /dev/null +++ b/EIPS/eip-4747.md @@ -0,0 +1,312 @@ +--- +eip: 4747 +title: Simplify EIP-161 +description: Simplify EIP-161 and retroactively deprecate unused aspects of it +author: Peter Davies (@petertdavies) +discussions-to: https://ethereum-magicians.org/t/eip-4747-simplify-eip-161/8246 +status: Stagnant +type: Standards Track +category: Core +created: 2022-02-02 +requires: 161 +--- + + +## Abstract + +Simplify the definition of [EIP-161](./eip-161.md), removing the requirement for implementors to support edge cases that are impossible on Ethereum Mainnet. + +## Motivation + +EIP-161 is overly complex and has a number of edge cases that are poorly documented and tested. This EIP takes advantage of the complete removal of all remaining empty accounts in block 14049881 (tx `0xf955834bfa097458a9cf6b719705a443d32e7f43f20b9b0294098c205b4bcc3d`) to clarify it, and allows implementors to not implement various edge cases that never occurred and are not possible in the future. + +In particular, this EIP permits implementors who do not wish to support historical blocks to not implement state clearing at all. + +## Specification +The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. + +Retroactively replace EIP-161, starting from its introduction in block 2675000, with the following rules: + +a. When creating an account, set it's nonce to `1` prior to executing initcode. + +b. When performing EVM execution treat all empty accounts as if they do not exist. Any operation that would create an empty account instead leaves it non-existent. + +c. If one of the following events happens to an empty account `X`, it is deleted: + +1. `X` receives a zero value `CALL`. +2. `X` is the recipient of a zero value transaction. +3. `X` is the beneficiary of a `SELFDESTRUCT` with zero value. + +If the transaction, `CALL` or `SELFDESTRUCT` is reverted, then the state clearing is also reverted. As a special case on Ethereum Mainnet, in block 2675119 (tx `0xcf416c536ec1a19ed1fb89e4ec7ffb3cf73aa413b3aa9b77d60e4fd81a4296ba`), an empty call is made to an empty account at `RIPEMD160` (precompile `0x3`), the call fails out of gas, but the empty account is removed anyway. + +The deletion MAY happen immediately or be processed at the end of the transaction. A client may assume that `STATICCALL`s to empty accounts never occur and that `CALL`s to empty accounts in `STATICCALL` contexts never occur. + +On Ethereum Mainnet, the only state clearing events after the start of Byzantium are the two listed below. Clients MAY implement post Byzantium state clearing by hardcoding those events. + +* In block 4457731 (tx `0x63791f962e13e6b01ec13d38a8ab66c87c2f5a1768276f866300d900cca808fe`), `0xd29DFe5aE95B5C067a91F472Dac0d9be6700A4A9` receives a zero value `SELFDESTRUCT` and is cleared. + +* In block 14049881 (tx `0xf955834bfa097458a9cf6b719705a443d32e7f43f20b9b0294098c205b4bcc3d`), the following accounts receive zero value calls and are cleared. +
+ Accounts cleared + + ``` + 0x01a3dd7d158e3b4c9d8d2af0ddcf3df0f5e14463 + 0x0366c731dd7c095dc08896806765a649c6c0885a + 0x056c68da52395f1d42c5ba15c4fb956146a4f2c1 + 0x070ba92497cd4b88a8a9a60795ca7d7f7de0faa3 + 0x07a1648ce2bed6721a5d25de3c228a296d03fd52 + 0x07b14ba68f474529cc0bd6a9bffee2bc4090d185 + 0x07ea32232e37d44134a3071319d228bdab249a60 + 0x096b7382500fa11c22c54c0422c5e38899a2e933 + 0x09f3200441bd60522bcf28f3666f8e8dbd19fb62 + 0x0ad0f3c60696adece09367a9a11c968fb88560bb + 0x0af6181e1db22071f38fc162e1610e29d288de04 + 0x0cdc7fef8f8d0ee77360060930aada1263b26ff7 + 0x0dac3d571eb5b884a2550db2791d5ac1efca306b + 0x0ec857faba49392080b68dd5074d85f34724d04a + 0x0f5054f9c674b37d15915ca8925f231edb3afa8c + 0x0f78d535e1faad9a982dca2a76d16da4649f7021 + 0x104c5b235166f26df54f52666d5e77d9e03e353e + 0x106b47175965b6d607008544267c91490672a54f + 0x1223d5c03b4d52ebed43f781251098c9138c3dd7 + 0x1251d13cde439378349f039379e83c2641b6269f + 0x12c814cebee6bb08a5d1b9d009332bf8b536d645 + 0x150c63df3da35e590a6d2f7accf2e6f241ea5f1a + 0x15ddf20e4eb8b53b823bc45c9bad2670aad907dd + 0x1712b1c428f89bc695b1871abfff6b5097350150 + 0x178df2e27b781f024e90ab0abe9cff7e2f66a5fc + 0x1c2bd83dc29095173c4bcc14927811f5141c1373 + 0x1d12f2fad3603ea871fcb13ac3e30674f9ad903f + 0x1f7391b6881b6f025aef25cff737ff3fcb9d7660 + 0x219a3d724f596a4b75656e9b1569289c71782804 + 0x21a7fd9228c46ec72f926978f791fc8bfcd277fa + 0x23acb760cebd01fe7c92361274a4077d37b59f4c + 0x23b249eeeeedd86bc40349f8bb8e2df34bd28f78 + 0x28d006b1a2309e957005ee575f422af8034f93df + 0x28ef72d5614b2833d645aecf8ef7add075eb21e2 + 0x292966802ffedb6f34f2c8c59df35c9d8f612c24 + 0x2c2661ddd320017138075aba06999440a902695f + 0x2c632be2dc2f47affd07bfce91bd4a27c02f4563 + 0x2f86de22ced85a7dd0d680fc4266929a72775e27 + 0x2fa04f15123025ab487dce71668f5265649d0598 + 0x30f78fd12c17855453e0db166fecf684bb239b8c + 0x31534e95353323209cd18ad35c22c2528db6d164 + 0x336e0e1a14e0136c02bf8dcf0a9a3fe408548262 + 0x340399588bba5b843883d1ad7afd771a3651447a + 0x341d2b82d0924ef42d75ce053654295d34839459 + 0x34c2b8975b47e13818f496cf80b40566798cf968 + 0x370e67f45db9c18d6551000e6c0918bc8d346ebf + 0x37149dae898296173d309f1de6981922ec1dc495 + 0x377cb0d3427af7f06df47d2ab420458834bed1fc + 0x3d473af3e6ce45183c781b414e8a9edcb8b26f72 + 0x42794c1d807079e16735e47e193825cec80ee28c + 0x45603aa97b67965b42b38ddc8884373edbcf2d56 + 0x465cb9df2f6d3c8a1c1ce3f2338823f0638fefa5 + 0x49fbe69c2897bce0340b5983a0f719213a8c6e6f + 0x4a84cbd3ef642e301aa59bedf4fa4d28e24e6204 + 0x4d4d551bd6244b854e732572902f19f4ccaa6996 + 0x4f62af4ec150ea121859b3368e6a61fb7bcf9002 + 0x4fd1c530f73ddfff5c609a4a8b25af6ca489d1fd + 0x50010a4f0e429b398c66876dea7694d5f8b1a639 + 0x522c9f65bc77ad9eed6bcdc3ec220236451c9583 + 0x52b30ca3c2f8656e2c022e896bef7fad9a0449ca + 0x537a7030ecd9d159e8231ce31b0c2e83b4f9ed75 + 0x5483a4c5583d5ba3db23676a3db346f47ba357e1 + 0x55ec1a78a1187428dc0c67cbb77ae9fbdd61cc2a + 0x56cc1c0aadc2b8beb71f1ac61f03645483abe165 + 0x58bea8cea61fad5c453731aaeed377f3d77a04cc + 0x58f632327fbc4f449bda3bd51e13f590e67a8627 + 0x59d122afcbd68c731de85c2597004c6ddafbc7ed + 0x5da0228024cc084b9475470a7b7ae1d478d51bb7 + 0x5e51d6621883afcbd4e999b93180a96909bdc766 + 0x5e9a0a1bdfdd868706f4554aae21bb2c46da32c2 + 0x5f3f0d3215db85faa693d99acfb03cca66556671 + 0x5f6aa25f22edb2347b464312e2508cbc4c6e0162 + 0x6006f79e4104850ab7c9b0f75918c1e2cf6311df + 0x60f5da58bccb716f58b5759a06fc2167fe237c26 + 0x62d3a444d0af59f9de79f8abeb5c942fcfbfbef5 + 0x630ea66c8c5dc205d45a978573fa86df5af1fe7a + 0x6464f0f96a29934087a955c67a6b53d5ed852e49 + 0x6653cedb0b7f51c4b0c44079eb45c514df24ecfd + 0x66d69ac12b573299f36b108792be75a1e2ccdfdc + 0x690ed837d25b46dbf46727fcda7392d997c2bc97 + 0x696eecbc97189c5b2a8245a8e32517db9960c171 + 0x69aaff0b7babe85e0a95adfc540e689399db7f24 + 0x6b71d2ceab5678b607aa1e69b6781f5c7abc9aaf + 0x6e03d9cce9d60f3e9f2597e13cd4c54c55330cfd + 0x6e278cfecfe96fa5e6d5411ba6eeb765dff4f118 + 0x6e557f01c9dcb573b03909c9a5b3528aec263472 + 0x6ec268f8bef9c685d7e04d5cdb61fbb544869a9f + 0x6f2ba051b3ce06a90705c22e0241c2b7e32c1af0 + 0x7063732ced55cfa08aea520f3fe200c39b3df0f5 + 0x7073a17a0172dfb1e46a62f054d11a775aeac32e + 0x71d3718cfa0f9ee8173688fe52bb499e1f36534b + 0x74e20aec156674945894d404f8dea602570e62f5 + 0x783e45c2989e675ffc9d067914d7de3ff68aee58 + 0x7a5f843f884bb15d070806e1ff59b6c6f74bbe2d + 0x7c6b1706c86ea76a0e232324f249e1508ca2dfda + 0x7d23a23584c83c1f6636124255cfd8e9cfc0e529 + 0x7e8b5df0dec9168741c93d52d7045aca7ea632d3 + 0x7ec5da0f1036750688084252b802befe41551205 + 0x82c9fcef4dd2d374b000063d4899a38a7219cdc7 + 0x82fa2ab30a566ceeac987eb5510485be9382f130 + 0x83d927aca3266f94e8163eaa32700c70e9b76e6e + 0x8476f7e193c930f21e88dae84888e0d8bfaf3ed8 + 0x85ec166cb81f5010b4a8d365821473dac0c0aa88 + 0x8883c55943d5caf06b6484de9c1d73da8307cd82 + 0x8c07456cffd4254c89aaaa9d4e95c8b3e36c2a3b + 0x8fef965e5db6f7f1a165008499e8b7901cd766b2 + 0x9018e2967c15e1faed9b5d6439522f075535a683 + 0x903f1d8a086c6af1afe24648b6409aade83c4340 + 0x9127c398827d8db6b6d5f17b71f5db69d06e8b74 + 0x917b5be6e3acd96d40a33c13e6748e4a88576c6d + 0x91edfd05112f0bc9d6cd43b65361713a50e9eb7f + 0x93026a2c4a0bc69de31515070bf086e0c1f789e5 + 0x94863bbbc12ec5be148f60a7020fd49236fc1937 + 0x94befc001e203f141462f16bde60873bcefae401 + 0x94c408cf5934f241d4fdd55ff3825131635c6af2 + 0x94cfdec548de92301735dc0b82d8e1f79404ff94 + 0x96527f3311f44340887c926acc16f0997eb3b955 + 0x974117faf194885c01513e8d87b38a2291083ed5 + 0x993424827a5fb2fa97818814ea4027e28150f187 + 0x9a6f30a5cb46840076edd780da2dbb4bc7c39f24 + 0x9a74a096b0bb82adfd28494107f2c07f4545723e + 0x9af82ec46185641c0ea44679aac8a7e7570be202 + 0x9e2287a60ed85f6bd80c62c1b7b4130ea1b521dd + 0x9fee5b81ee0cbf34c18c52061f1b257d4ccb2702 + 0xa017226377e775af8e56450301cc035ae72267f8 + 0xa1b423e024daf925f25296ea2efcf009cc328873 + 0xa23c0cbfe59e8650277ffa635c59f287cece9087 + 0xa340b7625eec76b372f2c317fe08a7733f05d09c + 0xa4cb6be13c2eace6c0f1157553e3c446f7b38b10 + 0xa54326267784fae3ffd6800af38099753bb7f470 + 0xa580086125d040fddd3af9d563285bd0ec4d13e3 + 0xa88fc7a34ca36b952aa45d94c1e13155042b5e7d + 0xac8f4ce2e4eff39c738bf1941350b3b57e8eec4f + 0xacb17dca110db022b1aceb5399acba1e9bf577e3 + 0xae0b03c8d8bf9cf71eda758e9e8b59c70a3b4580 + 0xae365ff4b0c64413baf6f7dfdb5cd3fb65ad1376 + 0xaf7e60d02b425b54730b7281a97d1640233704b0 + 0xaf9846f8098656e7c2f0e53e9ff7d38ec7b7f679 + 0xb2784c0a95e9b6b865aca13556fb32e2f37cb775 + 0xb385fa211cd08326ff84b0d4f37cc8c3735aa3aa + 0xb3fb883cbbccb0551daf1507f87426fd38da087e + 0xb6515cfb82fa877fbadae5a87006a8d3deeeb7c9 + 0xb78c4f0b8c9ec0b3058724eca65292d0d65586b9 + 0xba25f341e16ee81ab80ea246d45bdead7cc339e5 + 0xbab14024437285c2e3b3c521abff96b0ef2e919f + 0xbaf0996297cc70fca1bee30162eabcd892f0574a + 0xbb01ea95321a94242c89479995b7e3f264cb46a0 + 0xc1b37a3b7f76947e24cc2470e0e948aab0181346 + 0xc24431c1a1147456414355b1f1769de450e524da + 0xc467b893e29277f9b62b4ed6c9ba054bd8225bff + 0xc4bc101a168ea2228973a65564a7d40a68528dd2 + 0xc784626571c2c25cd2cfe24192a149cad86d40d8 + 0xc7acf90a9f442855b8f291288bb5fb612536ed9b + 0xc9956593dbfb46cfd24686a365b34051a55abce6 + 0xca2eb2af7dd7a90777c8c6456efcc00fe56dbd6f + 0xcb4bb078edaae9393c8da27b809aa9c0f4c920b7 + 0xcc8f68e8e2d8196e2ecd0caf2f35b1611739a21f + 0xcd67903318a805d63fe79bf9b8401c1b79c6babf + 0xcd7a2fe9cb80c95b03950daf5b6d476bec9ac24d + 0xd09476f5ee7979becca8ffe6dc22a72565fc3cea + 0xd1c4bd2b583f445354d1b644ea4b8353f2d23048 + 0xd32bb8bceafc89ff59ba43ce8b6cd65bb06dd7b0 + 0xd49e9fa792db9d9398c57eabf94ba1b2c709ace7 + 0xd6b862cf0d009bde0f020ab9d8f96e475069c5c6 + 0xd747c05d9c8057db608ef7aedabf07e4db0bbe97 + 0xdb9b40d1b691ced3680e539261b6bc195388b3c0 + 0xdbcc502093cadd0feb709708c633e2427aeb9c2d + 0xdc53001181ddc6a279deea6419443ea0ac0aec9c + 0xde3b38cb1050e7b5db39b4cbb2b2b63a1e32cbf6 + 0xdf1b687a99216ad4ebf9176983bf165be7b25bbe + 0xe000662c02a02d8b40aabfcd661594312992311d + 0xe30c59e4dc19d7c9ed6eb10d734d4d7ef28403ac + 0xe415114089b4b4933e542a5c79af4b6e6cd7abc9 + 0xe47f0a0e93241d390fe9b99de852682522e847bc + 0xe54abbd51e324bf8cf349b6b31c01b043d1ee0e4 + 0xe57838f777b11fdc428d9e7e67f1187d6251ba1f + 0xe5e4b26325d0fbf551367f2cf3b5d01caed6abcf + 0xe6655208bd812d833238b560e847014b0aab3b51 + 0xe6e16a1023af4a8fe54669f3fce7c406801bb333 + 0xe727bba699fbe82a731dad9476b5234d0038cfa1 + 0xec361d34a55e24e2f77de7121ae2b7bf11ed0d65 + 0xed3bf94976eb11d55b955d1369a478620872b57c + 0xee93ad447fe6a0e2bbac4952e651b21c0175acad + 0xefc5d9cabc0bda8124e1b821e8c86c7e7bf1e4bc + 0xf272f72a00f166f491d994642c8243099b72d2cd + 0xf45f642034bbce869e31b05d1da919125c7331ee + 0xf4883b21724405b19e240f3309a64d16dd89adc7 + 0xf5cb2a87ff1095f6d93e7b4bfc1bc47542380550 + 0xf6ddd386c4f7f0b460032c8055d7f9c3503d7140 + 0xf72093096c81b3e9e991f5b737baec9570a56927 + 0xf7412232a7a731bca2e5554c8ee051274373c17c + 0xfc2321dc32c2e6e96a0e41c911fb73a7b278d5c8 + 0xfc4dc782bf7e81a2ed5cc0519f80de36e7931bd9 + 0xfcde1c261eb257e14491b4e7cb1949a7623c00c5 + 0xfd17a22fd80075f2716e93268aa01bcdd7d70b22 + ``` +
+ + +## Rationale + +EIP-161 provides that empty accounts (accounts that have zero nonce, zero balance and no code, but that might have storage) can no longer be created and provides mechanism to remove old empty accounts. The last empty accounts were removed in block 14049881 (tx `0xf955834bfa097458a9cf6b719705a443d32e7f43f20b9b0294098c205b4bcc3d`). + +The complete removal of all empty accounts ensures that certain edgecases of EIP-161 can never occur on Ethereum Mainnet. Continuing to define and test those cases as part of the Ethereum Specification burdens future client implementors with unnecessary technical debt. This EIP declares those cases undefined and leaves clients free to assume they will not occur. + +## Backwards Compatibility + +This EIP is identical to EIP-161 except for the following differences, none of which affect Ethereum Mainnet. The differences are: + +### "Potentially state-changing operations" + +EIP-161 specifies 11 "potentially state-changing operations" that trigger state clearing. All but the 3 listed in this EIP are irrelevant, for the following reasons: + +#### Impossible + +* Receiving zero value mining reward/fees (this would become possible after the merge). + +#### Cannot happen to an empty account + +* Being the source of a `CREATE`. +* Being the source of a `CALL`. +* Being refunded by a `SELFDESTRUCT` + +#### Causes the account to become non-empty + +* Being the sender of a message call transaction. +* Being the sender of a contract creation transaction. +* Being created by a `CREATE`. +* Being created by a contract creation transaction. + +### Interaction with `STATICCALL` + +The interaction between `STATICCALL` and account clearing has never been specified in an EIP. The Ethereum currently testsuite requires that `STATICCALL` triggers state clearing. + +This EIP formally undefines all interactions between `STATICCALL` and state clearing as it has never happened on Ethereum Mainnet and cannot happen in future. + +### "At the end of the transaction" + +This only makes a difference if an account is deleted and later recreated in the same transaction. This never happens on Ethereum Mainnet. + +### Test Cases + +All test cases involving empty accounts in the Ethereum execution layer test suite shall be removed unless they relate to the Spurious Dragon Hardfork. If a Spurious Dragon test relates involved deprecated edgecase the test must be removed or reworked. + +### Other networks + +Ropsten had empty accounts seeded at genesis. They appear to have been cleared early in Ropsten's history before the Byzantium hardfork. Ropsten has never been checked for edgecases occurring. All other Ethereum testnets have had EIP-161 from genesis. + +As a security precaution all empty accounts on Ethereum Classic have been cleared, but no checks for edgecases occurring have been done. Due to EIP-161's age the vast majority of EVM compatible networks have supported it from genesis. + +## Security considerations + +This EIP is only equivalent to EIP-161 on Ethereum Mainnet if the following facts are true: + +1. No empty accounts are ever touched and then reinstated in the same transaction. +2. The transactions in the Appendix are the only state clearing transactions on Ethereum Mainnet after block 4370000 (start of Byzantium). +3. All empty accounts have been removed on Ethereum Mainnet. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4750.md b/EIPS/eip-4750.md new file mode 100644 index 00000000000000..02c9f6558fc09a --- /dev/null +++ b/EIPS/eip-4750.md @@ -0,0 +1,173 @@ +--- +eip: 4750 +title: EOF - Functions +description: Individual sections for functions with `CALLF` and `RETF` instructions +author: Andrei Maiboroda (@gumb0), Alex Beregszaszi (@axic), Paweł Bylica (@chfast) +discussions-to: https://ethereum-magicians.org/t/eip-4750-eof-functions/8195 +status: Stagnant +type: Standards Track +category: Core +created: 2022-01-10 +requires: 3540, 3670, 5450 +--- + +## Abstract + +Introduce the ability to have several code sections in EOF-formatted ([EIP-3540](./eip-3540.md)) bytecode, each one representing a separate subroutine/function. Two new opcodes,`CALLF` and `RETF`, are introduced to call and return from such a function. Dynamic jump instructions are disallowed. + +## Motivation + +Currently, in the EVM everything is a dynamic jump. Languages like Solidity generate most jumps in a static manner (i.e. the destination is pushed to the stack right before, `PUSHn .. JUMP`). Unfortunately however this cannot be used by most EVM interpreters, because of added requirement of validation/analysis. This also restricts them from making optimisations and potentially reducing the cost of jumps. + +[EIP-4200](./eip-4200.md) introduces static jump instructions, which remove the need for *most* dynamic jump use cases, but not everything can be solved with them. + +This EIP aims to remove the need and disallow dynamic jumps as it offers the most important feature those are used for: calling into and returning from functions. + +Furthermore, it aims to improve analysis opportunities by encoding the number of inputs and outputs for each given function, and isolating the stack of each function (i.e. a function cannot read the stack of the caller/callee). + +## Specification + +### Type Section + +The type section of EOF containers must adhere to following requirements: + +1. The section is a list of metadata where the metadata index in the type section corresponds to a code section index. Therefore, the type section size MUST be `n * 4` bytes, where `n` is the number of code sections. +2. Each metadata item has 3 attributes: a uint8 `inputs`, a uint8 `outputs`, and a uint16 `max_stack_increase`. *Note:* This implies that there is a limit of 255 stack for the input and in the output. This is further restricted to 127 stack items, because the upper bit of both the input and output bytes are reserved for future use (`outputs == 0x80` is already used in EOF1 to denote non-returning functions, as introduced in a separate EIP). `max_stack_increase` is further defined in [EIP-5450](./eip-5450.md). +3. The 0th code section MUST have 0 inputs and be non-returning. + +Refer to [EIP-3540](./eip-3540.md) to see the full structure of a well-formed EOF bytecode. + +### New execution state in EVM + +A return stack is introduced, separate from the operand stack. It is a stack of items representing execution state to return to after function execution is finished. Each item is comprised of code section index and offset in the code section (PC value). + +Note: Implementations are free to choose particular encoding for a stack item. In the specification below we assume that representation is two unsigned integers: `code_section_index`, `offset`. + +The return stack is limited to a maximum of `1024` items. + +Additionally, EVM keeps track of the index of currently executing section - `current_section_index`. + +### New instructions + +We introduce two new instructions: + +1. `CALLF` (`0xe3`) - call a function +2. `RETF` (`0xe4`) - return from a function + +If the code is legacy bytecode, any of these instructions results in an *exceptional halt*. (*Note: This means no change to behaviour.*) + +First we define several helper values: + +- `type[i].inputs = type_section_contents[i * 4]` - number of inputs of ith code section +- `type[i].outputs = type_section_contents[i * 4 + 1]` - number of outputs of ith code section +- `type[i].max_stack_increase = type_section_contents[i * 4 + 2:i * 4 + 4]` - maximum operand stack height increase of ith code section + +If the code is valid EOF1, the following execution rules apply: + +#### `CALLF` + +1. Has one immediate argument,`target_section_index`, encoded as a 16-bit unsigned big-endian value. +2. *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees that operand stack has enough items to use as callee's inputs. +3. If operand stack size exceeds `1024 - type[target_section_index].max_stack_increase` (i.e. if the called function may exceed the global stack height limit), execution results in exceptional halt. This also guarantees that the stack height after the call is within the limits. +4. If return stack already has `1024` items, execution results in exceptional halt. +5. Charges `5` gas. +6. Pops nothing and pushes nothing to operand stack. +7. Pushes to return stack an item: + + ``` + (code_section_index = current_section_index, + offset = PC_post_instruction) + ``` + + Under `PC_post_instruction` we mean the PC position after the entire immediate argument of `CALLF`. + + *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees there is always an instruction following `CALLF` (since terminating instruction or unconditional jump is required to be final one in the section), therefore `PC_post_instruction` always points to an instruction inside section bounds. +8. Sets `current_section_index` to `target_section_index` and `PC` to `0`, and execution continues in the called section. + +#### `RETF` + +1. Does not have immediate arguments. +2. *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees that operand stack has exact number of items to use as outputs. +3. Charges `3` gas. +4. Pops nothing and pushes nothing to operand stack. +5. Pops an item from return stack and sets `current_section_index` and `PC` to values from this item. + +*Note:* EOF validation requirement for 0th code section to be non-returning (non-returning sections introduced in a separate EIP) guarantees that return stack cannot be empty before `RETF`. + +### Code Validation + +In addition to container format validation rules above, we extend code section validation rules (as defined in [EIP-3670](./eip-3670.md)). + +1. Code validation rules of [EIP-3670](./eip-3670.md) are applied to every code section. +2. Code section is invalid in case an immediate argument of any `CALLF` is greater than or equal to the total number of code sections. +3. `RJUMP`, `RJUMPI` and `RJUMPV` immediate argument value (jump destination relative offset) validation: + 1. Code section is invalid in case offset points to a position outside of section bounds. + 2. Code section is invalid in case offset points to one of two bytes directly following `CALLF` instruction. +5. No unreachable code sections are allowed, i.e. every code section can be reached from the 0th code section with a series of `CALLF` / `JUMPF` (`JUMPF` introduced in a separate EIP) instructions (0th code section is always reachable). + +### Disallowed instructions + +Dynamic jump instructions `JUMP` (`0x56`) and `JUMPI` (`0x57`) are invalid and their opcodes are undefined. + +`JUMPDEST` (`0x5b`) instruction is renamed to `NOP` ("no operation") without the change in behaviour: it pops nothing and pushes nothing to operand stack and has no other effects except for `PC` increment and charging 1 gas. + +`PC` (0x58) instruction becomes invalid and its opcode is undefined. + +*Note:* This change implies that JUMPDEST analysis is no longer required for EOF code. + +### Execution + +1. Execution starts at the first byte of the 0th code section, and `PC` is set to `0`. +2. Return stack is initialized empty. +3. Stack underflow check is not performed anymore. *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees that it cannot happen at run-time. +3. Stack overflow check is not performed anymore, except during `CALLF` as specified above. + +## Rationale + +### `RETF` in the top frame ends execution vs exceptionally halts vs is not allowed during validation + +Alternative logic for `RETF` in the top frame could be to allow it during code validation and make it either: + +- end execution if the return stack is emptied by the `RETF` or +- exceptionally halt if the return stack is empty before the `RETF`. + +This has been superseded with the validation rule of top frame (0th code section) being non-returning (non-returning sections introduced in a separate EIP), because validating non-returning status of functions is valuable by itself for other reasons. Therefore all considerations of runtime behavior of `RETF` in the top frame were obsoleted. + +### "Minimal" function type + +Let's consider a trivial function with single instruction `RETF`. +Such function have the "minimal" type of `inputs = 0, outputs = 0`. +However, any other type like `inputs = k, outputs = k` is also valid for such function. +It has been considered to enforce usage of the "minimal" type for all functions. +This requires additional validation rule that checks if any instruction in the function accesses the bottom stack operand. +This rule can be obeyed by compilers, but causes quite significant annoyance. +On the other hand, it provides close to zero benefits for the EVM implementations. +In the end, it has been decided that this is not enforced. + +### Code section limit and instruction size + +The number of code sections is limited to 1024. This requires 2-byte immediate for `CALLF` and leaves room for increasing the limit in the future. The 256 limit (1-byte immediate) was discussed and concerns were raised that it might not be sufficient. + +### `NOP` instruction + +Instead of deprecating `JUMPDEST` we repurpose it as `NOP` instruction, because `JUMPDEST` effectively was a "no-operation" instruction and was already used as such in various contexts. It can be useful for some off-chain tooling, e.g. benchmarking EVM implementations (performance of `NOP` instruction is performance of EVM interpreter loop), as a padding to force code alignment, as a placeholder in dynamic code composition. + +### Deprecating `JUMPDEST` analysis + +The purpose of `JUMPDEST` analysis was to find in code the valid `JUMPDEST` bytes that do not happen to be inside `PUSH` immediate data. Only dynamic jump instructions (`JUMP`, `JUMPI`) required destination to be `JUMPDEST` instruction. Relative static jumps (`RJUMP`, `RJUMPI` and `RJUMPV`) do not have this requirement and are validated once at deploy-time during EOF instructions validation. Therefore, without dynamic jump instructions, `JUMPDEST` analysis is not required. + +## Backwards Compatibility + +This change poses no risk to backwards compatibility, as it is introduced only for EOF1 contracts, for which deploying undefined instructions is not allowed, therefore there are no existing contracts using these instructions. The new instructions are not introduced for legacy bytecode (code which is not EOF formatted). + +The new execution state and multi-section control flow pose no risk to backwards compatibility, because it is a generalization of executing a single code section. Executing existing contracts (both legacy and EOF1) has no user-observable changes. + +## Security Considerations + +The gas cost of introduced instructions reflects the need to manipulate return stack entries and jumping to proper code section offset in memory when interpreting the bytecode. + +These new instructions need to be carefully considered during implementation of the EOF container validation algorithm. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4758.md b/EIPS/eip-4758.md new file mode 100644 index 00000000000000..df7433a9a0f56d --- /dev/null +++ b/EIPS/eip-4758.md @@ -0,0 +1,50 @@ +--- +eip: 4758 +title: Deactivate SELFDESTRUCT +description: Deactivate SELFDESTRUCT by changing it to SENDALL, which does recover all funds to the caller but does not delete any code or storage. +author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad) +discussions-to: https://ethereum-magicians.org/t/eip-4758-deactivate-selfdestruct/8710 +status: Stagnant +type: Standards Track +category: Core +created: 2022-02-03 +--- + +## Abstract + +This EIP renames the `SELFDESTRUCT` opcode to `SENDALL`, and replaces its functionality. The new functionality will be only to send all Ether in the account to the caller. + +## Motivation + +The `SELFDESTRUCT` opcode requires large changes to the state of an account, in particular removing all code and storage. This will not be possible in the future with Verkle trees: Each account will be stored in many different account keys, which will not be obviously connected to the root account. + +This EIP implements this change. Applications that only use `SELFDESTRUCT` to retrieve funds will still work. + +## Specification + + * The `SELFDESTRUCT` opcode is renamed to `SENDALL`, and now only immediately moves all ETH in the account to the target; it no longer destroys code or storage or alters the nonce + * All refunds related to `SELFDESTRUCT` are removed + +## Rationale + +Getting rid of the `SELFDESTRUCT` opcode has been considered in the past, and there are currently no strong reasons to use it. Disabling it will be a requirement for statelessness. + +## Backwards Compatibility + +This EIP requires a hard fork, since it modifies consensus rules. + +Few applications are affected by this change. The only use that breaks is where a contract is re-created at the same address using `CREATE2` (after a `SELFDESTRUCT`). + +## Security Considerations + +The following applications of `SELFDESTRUCT` will be broken and applications that use it in this way are not safe anymore: + +1. Any use where `SELFDESTRUCT` is used to burn non-ETH token balances, such as [EIP-20](./eip-20.md)), inside a contract. We do not know of any such use (since it can easily be done by sending to a burn address this seems an unlikely way to use `SELFDESTRUCT`) +2. Where `CREATE2` is used to redeploy a contract in the same place. There are two ways in which this can fail: + * The destruction prevents the contract from being used outside of a certain context. For example, the contract allows anyone to withdraw funds, but `SELFDESTRUCT` is used at the end of an operation to prevent others from doing this. This type of operation can easily be modified to not depend on `SELFDESTRUCT`. + * The `SELFDESTRUCT` operation is used in order to make a contract upgradable. This is not supported anymore and delegates should be used. + + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4760.md b/EIPS/eip-4760.md new file mode 100644 index 00000000000000..2a8e779082cb92 --- /dev/null +++ b/EIPS/eip-4760.md @@ -0,0 +1,65 @@ +--- +eip: 4760 +title: SELFDESTRUCT bomb +description: Deactivate SELFDESTRUCT by changing it to SENDALL and stage this via a stage of exponential gas cost increases. +author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad) +discussions-to: https://ethereum-magicians.org/t/eip-4760-selfdestruct-bomb/8713 +status: Stagnant +type: Standards Track +category: Core +created: 2022-02-03 +--- +## Abstract + +This EIP renames the `SELFDESTRUCT` opcode to `SENDALL`, and replaces its functionality. The new functionality will be only to send all Ether in the account to the caller. + +In order to give apps more warning even if their developers are completely unaware of the EIP process, this version will exponentially increase the gas costs of the opcode, so any developer has time to see this change and react by implementing a version of their contract that does not rely on `SELFDESTRUCT` . + +## Motivation + +The `SELFDESTRUCT` opcode requires large changes to the state of an account, in particular removing all code and storage. This will not be possible in the future with Verkle trees: Each account will be stored in many different account keys, which will not be obviously connected to the root account. + +This EIP implements this change. Applications that only use `SELFDESTRUCT` to retrieve funds will still work. + +## Specification + +### Constants + +| Name | Value | Comment | +|------|-------|---------| +| `OLD_SELFDESTRUCT_COST` | 5000 | Current gas cost of `SELFDESTRUCT` opcode | +| `HARD_FORK_BLOCK` | TBD | (Shanghai HF block height) | +| `DOUBLING_SLOTS` | `2**16` | (Time for gas price to double, ca. 9 days) | +| `DOUBLINGS_BEFORE_SENDALL` | `13` | `SELFDESTRUCT` will be converted to `SENDALL` at `HARD_FORK_BLOCK + DOUBLING_SLOTS * DOUBLINGS_BEFORE_SENDALL` | + + * If `HARD_FORK_BLOCK <= slot < HARD_FORK_BLOCK + DOUBLING_SLOTS * DOUBLINGS_BEFORE_SENDALL` + * `SELFDESTRUCT` functionality remains unchanged + * `SELFDESTRUCT` gas cost is now `OLD_SELFDESTRUCT_COST * 2 ** ((slot - HARD_FORK_BLOCK) // DOUBLING_SLOTS)` + * For `slot >= HARD_FORK_BLOCK + DOUBLING_SLOTS * DOUBLINGS_BEFORE_SENDALL` + * The cost reverts back to `OLD_SELFDESTRUCT_COST` + * The `SELFDESTRUCT` opcode is renamed to `SENDALL`, and now only immediately moves all ETH in the account to the target; it no longer destroys code or storage or alters the nonce + * All refunds related to `SELFDESTRUCT` are removed + +## Rationale + +The idea behind this EIP is to disable `SELFDESTRUCT` in a way that gives ample warning to Dapp developers. Many developers do not watch the EIP process closely and can therefore be caught by surprise when an opcode is deactivated and does not fulfill its original purpose anymore. However, at least if the smart contract has regular use, then users will notice the price of the operation going up tremendously. The period over which this is happening (`HARD_FORK_BLOCK + DOUBLING_SLOTS * DOUBLINGS_BEFORE_SENDALL`) is chosen to be long enough (ca. 4 months) such that it gives developers time to react to this change and prepare their application. + +## Backward Compatibility + +This EIP requires a hard fork, since it modifies consensus rules. + +Few applications are affected by this change. The only use that breaks is where a contract is re-created at the same address using `CREATE2` (after a `SELFDESTRUCT`). The only application that is significantly affected (and where code can be analyzed) is able to switch to a different model, and should have ample time to do so. + +## Security Considerations + +The following applications of `SELFDESTRUCT` will be broken and applications that use it in this way are not safe anymore: + +1. Any use where `SELFDESTRUCT` is used to burn non-ETH token balances, such as ERC20, inside a contract. We do not know of any such use (since it can easily be done by sending to a burn address this seems an unlikely way to use `SELFDESTRUCT`) +2. Where `CREATE2` is used to redeploy a contract in the same place. There are two ways in which this can fail: + + * The destruction prevents the contract from being used outside of a certain context. For example, the contract allows anyone to withdraw funds, but `SELFDESTRUCT` is used at the end of an operation to prevent others from doing this. This type of operation can easily be modified to not depend on `SELFDESTRUCT`. + * The `SELFDESTRUCT` operation is used in order to make a contract upgradable. This is not supported anymore and delegates should be used. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4762.md b/EIPS/eip-4762.md new file mode 100644 index 00000000000000..fde0a6550d308f --- /dev/null +++ b/EIPS/eip-4762.md @@ -0,0 +1,297 @@ +--- +eip: 4762 +title: Statelessness gas cost changes +description: Changes the gas schedule to reflect the costs of creating a witness by requiring clients update their database layout to match. +author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad), Ignacio Hagopian (@jsign), Tanishq Jasoria (@tanishqjasoria), Gajinder Singh (@g11tech) +discussions-to: https://ethereum-magicians.org/t/eip-4762-statelessness-gas-cost-changes/8714 +status: Draft +type: Standards Track +category: Core +created: 2022-02-03 +--- +## Abstract + +This EIP introduces changes in the gas schedule to reflect the costs of creating a witness. It requires clients to update their database layout to match this, so as to avoid potential DoS attacks. + +## Motivation + +The introduction of Verkle trees into Ethereum requires fundamental changes and as a preparation, this EIP is targeting the fork coming right before the verkle tree fork, in order to incentivize Dapp developers to adopt the new storage model, and ample time to adjust to it. It also incentivizes client developers to migrate their database format ahead of the verkle fork. + +## Specification + +### Helper functions + +```python +def get_storage_slot_tree_keys(storage_key: int) -> [int, int]: + if storage_key < (CODE_OFFSET - HEADER_STORAGE_OFFSET): + pos = HEADER_STORAGE_OFFSET + storage_key + else: + pos = MAIN_STORAGE_OFFSET + storage_key + return ( + pos // 256, + pos % 256 + ) +``` + +### Access events + +Whenever the state is read, one or more of the access events of the form `(address, sub_key, leaf_key)` take place, determining what data is being accessed. We define access events as follows: + +#### Access events for account headers + +When: + + 1. a non-precompile which is also not a system contract is the target of a `*CALL`, `CALLCODE`, `SELFDESTRUCT`, `EXTCODESIZE`, or `EXTCODECOPY` opcode, + 2. a non-precompile which is also not a system contract is the target address of a contract creation whose initcode starts execution, + 3. any address is the target of the `BALANCE` opcode + 4. a _deployed_ contract calls `CODECOPY` + +process this access event: + +``` +(address, 0, BASIC_DATA_LEAF_KEY) +``` + +Note: a non-value-bearing `SELFDESTRUCT`, `*CALL` or `CALLCODE`, targeting a precompile or a system contract, will not cause the `BASIC_DATA_LEAF_KEY` to be added to the witness. + +If a `*CALL`, `CALLCODE` or `SELFDESTRUCT` is value-bearing (ie. it transfers nonzero wei), whether or not the `callee` is a precompile or a system contract, process this additional access event: + +``` +(caller, 0, BASIC_DATA_LEAF_KEY) +``` + +Note: when checking for the existence of the `callee`, the existence check is done by validating that there is an extension-and-suffix tree at the corresponding stem, and does not rely on `CODEHASH_LEAF_KEY`. + +When calling `EXTCODEHASH`, process the access event: + +``` +(address, 0, CODEHASH_LEAF_KEY) +``` + +Note that precompiles and system contracts are excluded, as their hashes are known to the client. + +When a contract is created, process these access events: + +``` +(contract_address, 0, BASIC_DATA_LEAF_KEY) +(contract_address, 0, CODEHASH_LEAF_KEY) +``` + +#### Access events for storage + +`SLOAD` and `SSTORE` opcodes with a given address and key process an access event of the form + +``` +(address, tree_key, sub_key) +``` + +Where `tree_key` and `sub_key` are computed as `tree_key, sub_key = get_storage_slot_tree_keys(key)` + +#### Access events for code + +In the conditions below, “chunk chunk_id is accessed” is understood to mean an access event of the form + +``` +(address, (chunk_id + 128) // 256, (chunk_id + 128) % 256) +``` + + * At each step of EVM execution, if and only if `PC < len(code)`, chunk `PC // CHUNK_SIZE` (where `PC` is the current program counter) of the callee is accessed. In particular, note the following corner cases: + * The destination of a `JUMP` (or positively evaluated `JUMPI`) is considered to be accessed, even if the destination is not a jumpdest or is inside pushdata + * The destination of a `JUMPI` is not considered to be accessed if the jump conditional is `false`. + * The destination of a jump is not considered to be accessed if the execution gets to the jump opcode but does not have enough gas to pay for the gas cost of executing the `JUMP` opcode (including chunk access cost if the `JUMP` is the first opcode in a not-yet-accessed chunk) + * The destination of a jump is not considered to be accessed if it is beyond the code (`destination >= len(code)`) + * If code stops execution by walking past the end of the code, `PC = len(code)` is not considered to be accessed + * If the current step of EVM execution is a `PUSH{n}`, all chunks `(PC // CHUNK_SIZE) <= chunk_index <= ((PC + n) // CHUNK_SIZE)` of the callee are accessed. + * If a nonzero-read-size `CODECOPY` or `EXTCODECOPY` read bytes `x...y` inclusive, all chunks `(x // CHUNK_SIZE) <= chunk_index <= (min(y, code_size - 1) // CHUNK_SIZE)` of the accessed contract are accessed. + * Example 1: for a `CODECOPY` with start position 100, read size 50, `code_size = 200`, `x = 100` and `y = 149` + * Example 2: for a `CODECOPY` with start position 600, read size 0, no chunks are accessed + * Example 3: for a `CODECOPY` with start position 1500, read size 2000, `code_size = 3100`, `x = 1500` and `y = 3099` + * `CODESIZE`, `EXTCODESIZE` and `EXTCODEHASH` do NOT access any chunks. + When a contract is created, access chunks `0 ... (len(code)+30)//31` + +### Write Events + +We define **write events** as follows. Note that when a write takes place, an access event also takes place (so the definition below should be a subset of the definition of access events). A write event is of the form `(address, sub_key, leaf_key)`, determining what data is being written to. + +#### Write events for account headers + +When a nonzero-balance-sending `CALL`, `CALLCODE` or `SELFDESTRUCT` with a given sender and recipient takes place, process these write events: + +``` +(caller, 0, BASIC_DATA_LEAF_KEY) +(callee, 0, BASIC_DATA_LEAF_KEY) +``` + +if no account exists at `callee_address`, also process: + +``` +(callee, 0, CODEHASH_LEAF_KEY) +``` + +When a contract creation is initialized, process these write events: + +``` +(contract_address, 0, BASIC_DATA_LEAF_KEY) +(contract_address, 0, CODEHASH_LEAF_KEY) +``` + +#### Write events for storage + +`SSTORE` opcodes with a given `address` and `key` process a write event of the form + +``` +(address, tree_key, sub_key) +``` + +Where `tree_key` and `sub_key` are computed as `tree_key, sub_key = get_storage_slot_tree_keys(key)` + +#### Write events for code + +When a contract is created, process the write events: + +```python +( + address, + (CODE_OFFSET + i) // VERKLE_NODE_WIDTH, + (CODE_OFFSET + i) % VERKLE_NODE_WIDTH +) +``` + +For `i` in `0 ... (len(code)+30)//31`. + +Note: since no access list existed for code up until this EIP, note that no warm costs are charged for code accesses. + +### Transaction + +#### Access events + +For a transaction, make these access events: + +``` +(tx.origin, 0, BASIC_DATA_LEAF_KEY) +(tx.origin, 0, CODEHASH_LEAF_KEY) +(tx.target, 0, BASIC_DATA_LEAF_KEY) +(tx.target, 0, CODEHASH_LEAF_KEY) +``` + +#### Write events + +``` +(tx.origin, 0, BASIC_DATA_LEAF_KEY) +``` + +If `value` is non-zero: + +``` +(tx.target, 0, BASIC_DATA_LEAF_KEY) +``` + +### Witness gas costs + +Remove the following gas costs: + + * Increased gas cost of `CALL` if it is nonzero-value-sending + * [EIP-2200](./eip-2200.md) `SSTORE` gas costs except for the `SLOAD_GAS` + * 200 per byte contract code cost + * All `CALLCODE` costs related to nonzero-value-sending + +Reduce gas cost: + + * `CREATE`/`CREATE2` to 1000 + +| Constant | Value | +| --------------------- | ----- | +| `WITNESS_BRANCH_COST` | 1900 | +| `WITNESS_CHUNK_COST` | 200 | +| `SUBTREE_EDIT_COST` | 3000 | +| `CHUNK_EDIT_COST` | 500 | +| `CHUNK_FILL_COST` | 6200 | + +When executing a transaction, maintain four sets: + + * `accessed_subtrees: Set[Tuple[address, int]]` + * `accessed_leaves: Set[Tuple[address, int, int]]` + * `edited_subtrees: Set[Tuple[address, int]]` + * `edited_leaves: Set[Tuple[address, int, int]]` + +When an **access** event of `(address, sub_key, leaf_key)` occurs, perform the following checks: + + * Perform the following steps unless event is a _Transaction access event_; + * If `(address, sub_key)` is not in `accessed_subtrees`, charge `WITNESS_BRANCH_COST` gas and add that tuple to `accessed_subtrees`. + * If `leaf_key` is not `None` and `(address, sub_key, leaf_key)` is not in `accessed_leaves`, charge `WITNESS_CHUNK_COST` gas and add it to `accessed_leaves` + +When a **write** event of `(address, sub_key, leaf_key)` occurs, perform the following checks: + + * If event is _Transaction write event_, skip the following steps. + * If `(address, sub_key)` is not in `edited_subtrees`, charge `SUBTREE_EDIT_COST` gas and add that tuple to `edited_subtrees`. + * If `leaf_key` is not `None` and `(address, sub_key, leaf_key)` is not in `edited_leaves`, charge `CHUNK_EDIT_COST` gas and add it to `edited_leaves` + * Additionally, if there was no value stored at `(address, sub_key, leaf_key)` (ie. the state held `None` at that position), charge `CHUNK_FILL_COST` + +Note that tree keys can no longer be emptied: only the values `0...2**256-1` can be written to a tree key, and 0 is distinct from `None`. Once a tree key is changed from `None` to not-`None`, it can never go back to `None`. + +Note that values should only be added to the witness if there is sufficient gas to cover their associated event costs. If there is not enough gas to cover the event costs, all the remaining gas should be consumed. + +`CREATE*` and `*CALL` reserve 1/64th of the gas before the nested execution. In order to match the behavior of this charge with the pre-fork behavior of access lists: + + * this minimum 1/64th gas reservation is checked **AFTER** charging the witness costs when performing a `CALL`, `CALLCODE`, `DELEGATECALL` or `STATICCALL` + * this 1/64th of the gas is subtracted **BEFORE** charging the witness costs when performing a `CREATE` or `CREATE2` + +### Block-level operations + +None of: + +* Precompile accounts, system contract accounts and slots of a system contract that are accessed during a system call, +* The coinbase account +* Withdrawal accounts + +are warm at the start of a transaction. + +### System contracts + +When (and only when) calling a system contract either + + * _via a system call_ or + * _to resolve a precompile/opcode_, + + the system contract's _code chunks_ and _account headers_ accesses should not appear in the witness as these should be known/cached in the clients. However any other accesses and all writes should appear in the witness. + +Also corresponding witness costs need to be charged for _precompile/opcode resolution_ but are not charged in the _system call_. + +### Account abstraction + +TODO : still waiting on a final decision between 7702 and 3074 + +## Rationale + +### Gas reform + +Gas costs for reading storage and code are reformed to more closely reflect the gas costs under the new Verkle tree design. `WITNESS_CHUNK_COST` is set to charge 6.25 gas per byte for chunks, and `WITNESS_BRANCH_COST` is set to charge ~13,2 gas per byte for branches on average (assuming 144 byte branch length) and ~2.5 gas per byte in the worst case if an attacker fills the tree with keys deliberately computed to maximize proof length. + +The main differences from gas costs in Berlin are: + + * 200 gas charged per 31 byte chunk of code. This has been estimated to increase average gas usage by ~6-12% (suggesting 10-20% gas usage increases at a 350 gas per chunk level). + * Cost for accessing adjacent storage slots (`key1 // 256 == key2 // 256`) decreases from 2100 to 200 for all slots after the first in the group, + * Cost for accessing storage slots 0…63 decreases from 2100 to 200, including the first storage slot. This is likely to significantly improve performance of many existing contracts, which use those storage slots for single persistent variables. + +Gains from the latter two properties have not yet been analyzed, but are likely to significantly offset the losses from the first property. It’s likely that once compilers adapt to these rules, efficiency will increase further. + +The precise specification of when access events take place, which makes up most of the complexity of the gas repricing, is necessary to clearly specify when data needs to be saved to the period 1 tree. + +## Backwards Compatibility + +This EIP requires a hard fork, since it modifies consensus rules. + +The main backwards-compatibility-breaking change is the gas costs for code chunk access making some applications less economically viable. It can be mitigated by increasing the gas limit at the same time as implementing this EIP, reducing the risk that applications will no longer work at all due to transaction gas usage rising above the block gas limit. + +## Security Considerations + +This EIP will mean that certain operations, mostly reading and writing several elements in the same suffix tree, become cheaper. If clients retain the same database structure as they have now, this would result in a DOS vector. + +So some adaptation of the database is required in order to make this work: + + * In all possible futures, it is important to logically separate the commitment scheme from data storage. In particular, no traversal of the commitment scheme tree should be necessary to find any given state element + * In order to make accesses to the same stem cheap as required for this EIP, the best way is probably to store each stem in the same location in the database. Basically the 256 leaves of 32 bytes each would be stored in an 8kB BLOB. The overhead of reading/writing this BLOB is small because most of the cost of disk access is seeking and not the amount transferred. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4788.md b/EIPS/eip-4788.md new file mode 100644 index 00000000000000..efcac43ef9aadd --- /dev/null +++ b/EIPS/eip-4788.md @@ -0,0 +1,300 @@ +--- +eip: 4788 +title: Beacon block root in the EVM +description: Expose beacon chain roots in the EVM +author: Alex Stokes (@ralexstokes), Ansgar Dietrichs (@adietrichs), Danny Ryan (@djrtwo), Martin Holst Swende (@holiman), lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-4788-beacon-root-in-evm/8281 +status: Final +type: Standards Track +category: Core +created: 2022-02-10 +requires: 1559 +--- + +## Abstract + +Commit to the hash tree root of each beacon chain block in the corresponding execution payload header. + +Store each of these roots in a smart contract. + +## Motivation + +Roots of the beacon chain blocks are cryptographic accumulators that allow proofs of arbitrary consensus state. +Exposing these roots inside the EVM allows for trust-minimized access to the consensus layer. +This functionality supports a wide variety of use cases that improve trust assumptions of staking pools, +restaking constructions, smart contract bridges, MEV mitigations and more. + +## Specification + +| constants | value | +|--- |--- | +| `FORK_TIMESTAMP` | `1710338135` | +| `HISTORY_BUFFER_LENGTH` | `8191` | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | +| `BEACON_ROOTS_ADDRESS` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | + +### Background + +The high-level idea is that each execution block contains the parent beacon block's root. Even in the event of missed slots since the previous block root does not change, +we only need a constant amount of space to represent this "oracle" in each execution block. To improve the usability of this oracle, a small history of block roots +are stored in the contract. + +To bound the amount of storage this construction consumes, a ring buffer is used that mirrors a block root accumulator on the consensus layer. + +### Block structure and validity + +Beginning at the execution timestamp `FORK_TIMESTAMP`, execution clients **MUST** extend the header schema with an additional field: the `parent_beacon_block_root`. +This root consumes 32 bytes and is exactly the [hash tree root](https://github.com/ethereum/consensus-specs/blob/fa09d896484bbe240334fa21ffaa454bafe5842e/ssz/simple-serialize.md#merkleization) of the parent beacon block for the given execution block. + +The resulting RLP encoding of the header is therefore: + +```python +rlp([ + parent_hash, + 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, # ommers hash + coinbase, + state_root, + txs_root, + receipts_root, + logs_bloom, + 0, # difficulty + number, + gas_limit, + gas_used, + timestamp, + extradata, + prev_randao, + 0x0000000000000000, # nonce + base_fee_per_gas, + withdrawals_root, + blob_gas_used, + excess_blob_gas, + parent_beacon_block_root, +]) +``` + +Validity of the parent beacon block root is guaranteed from the consensus layer, much like how withdrawals are handled. + +When verifying a block, execution clients **MUST** ensure the root value in the block header matches the one provided by the consensus client. + +For a genesis block with no existing parent beacon block root the 32 zero bytes are used as a root placeholder. + +#### Beacon roots contract + +The beacon roots contract has two operations: `get` and `set`. The input itself is not used to determine which function to execute, for that the result of `caller` is used. If `caller` is equal to `SYSTEM_ADDRESS` then the operation to perform is `set`. Otherwise, `get`. + +##### `get` + +* Callers provide the `timestamp` they are querying encoded as 32 bytes in big-endian format. +* If the input is not exactly 32 bytes, the contract must revert. +* If the input is equal to 0, the contract must revert. +* Given `timestamp`, the contract computes the storage index in which the timestamp is stored by computing the modulo `timestamp % HISTORY_BUFFER_LENGTH` and reads the value. +* If the `timestamp` does not match, the contract must revert. +* Finally, the beacon root associated with the timestamp is returned to the user. It is stored at `timestamp % HISTORY_BUFFER_LENGTH + HISTORY_BUFFER_LENGTH`. + +##### `set` + +* Caller provides the parent beacon block root as calldata to the contract. +* Set the storage value at `header.timestamp % HISTORY_BUFFER_LENGTH` to be `header.timestamp` +* Set the storage value at `header.timestamp % HISTORY_BUFFER_LENGTH + HISTORY_BUFFER_LENGTH` to be `calldata[0:32]` + +##### Pseudocode + +```python +if evm.caller == SYSTEM_ADDRESS: + set() +else: + get() + +def get(): + if len(evm.calldata) != 32: + evm.revert() + + if to_uint256_be(evm.calldata) == 0: + evm.revert() + + timestamp_idx = to_uint256_be(evm.calldata) % HISTORY_BUFFER_LENGTH + timestamp = storage.get(timestamp_idx) + + if timestamp != evm.calldata: + evm.revert() + + root_idx = timestamp_idx + HISTORY_BUFFER_LENGTH + root = storage.get(root_idx) + + evm.return(root) + +def set(): + timestamp_idx = to_uint256_be(evm.timestamp) % HISTORY_BUFFER_LENGTH + root_idx = timestamp_idx + HISTORY_BUFFER_LENGTH + + storage.set(timestamp_idx, evm.timestamp) + storage.set(root_idx, evm.calldata) +``` + +##### Bytecode + +The exact contract bytecode is shared below. + +```asm +caller +push20 0xfffffffffffffffffffffffffffffffffffffffe +eq +push1 0x4d +jumpi + +push1 0x20 +calldatasize +eq +push1 0x24 +jumpi + +push0 +push0 +revert + +jumpdest +push0 +calldataload +dup1 +iszero +push1 0x49 +jumpi + +push3 0x001fff +dup2 +mod +swap1 +dup2 +sload +eq +push1 0x3c +jumpi + +push0 +push0 +revert + +jumpdest +push3 0x001fff +add +sload +push0 +mstore +push1 0x20 +push0 +return + +jumpdest +push0 +push0 +revert + +jumpdest +push3 0x001fff +timestamp +mod +timestamp +dup2 +sstore +push0 +calldataload +swap1 +push3 0x001fff +add +sstore +stop +``` + +#### Deployment + +The beacon roots contract is deployed like any other smart contract. A special synthetic address is generated +by working backwards from the desired deployment transaction: + +```json +{ + "type": "0x0", + "nonce": "0x0", + "to": null, + "gas": "0x3d090", + "gasPrice": "0xe8d4a51000", + "maxPriorityFeePerGas": null, + "maxFeePerGas": null, + "value": "0x0", + "input": "0x60618060095f395ff33373fffffffffffffffffffffffffffffffffffffffe14604d57602036146024575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f5260205ff35b5f5ffd5b62001fff42064281555f359062001fff015500", + "v": "0x1b", + "r": "0x539", + "s": "0x1b9b6eb1f0", + "hash": "0xdf52c2d3bbe38820fff7b5eaab3db1b91f8e1412b56497d88388fb5d4ea1fde0" +} +``` + +Note, the input in the transaction has a simple constructor prefixing the desired runtime code. + +The sender of the transaction can be calculated as `0x0B799C86a49DEeb90402691F1041aa3AF2d3C875`. The address of the first contract deployed from the account is `rlp([sender, 0])` which equals `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02`. This is how `BEACON_ROOTS_ADDRESS` is determined. Although this style of contract creation is not tied to any specific initcode like create2 is, the synthetic address is cryptographically bound to the input data of the transaction (e.g. the initcode). + +### Block processing + +At the start of processing any execution block where `block.timestamp >= FORK_TIMESTAMP` (i.e. before processing any transactions), call `BEACON_ROOTS_ADDRESS` as `SYSTEM_ADDRESS` with the 32-byte input of `header.parent_beacon_block_root`, a gas limit of `30_000_000`, and `0` value. This will trigger the `set()` routine of the beacon roots contract. This is a system operation and therefore: + +* the call must execute to completion +* the call does not count against the block's gas limit +* the call does not follow the [EIP-1559](./eip-1559.md) burn semantics - no value should be transferred as part of the call +* if no code exists at `BEACON_ROOTS_ADDRESS`, the call must fail silently + +Clients may decide to omit an explicit EVM call and directly set the storage values. Note: While this is a valid optimization for Ethereum mainnet, it could be problematic on non-mainnet situations in case a different contract is used. + +If this EIP is active in a genesis block, the genesis header's `parent_beacon_block_root` must be `0x0` and no system transaction may occur. + +## Rationale + +### Why not repurpose `BLOCKHASH`? + +The `BLOCKHASH` opcode could be repurposed to provide the beacon root instead of some execution block hash. +To minimize code change, avoid breaking changes to smart contracts, and simplify deployment to mainnet, this EIP suggests leaving `BLOCKHASH` alone and adding new +functionality with the desired semantics. + +### Beacon block root instead of state root + +Block roots are preferred over state roots so there is a constant amount of work to do with each new execution block. Otherwise, skipped slots would require +a linear amount of work with each new payload. While skipped slots are quite rare on mainnet, it is best to not add additional load under what would already +be nonfavorable conditions. + +Use of block root over state root does mean proofs will require a few additional nodes but this cost is negligible (and could be amortized across all consumers, +e.g. with a singleton state root contract that caches the proof per slot). + +### Why two ring buffers? + +The first ring buffer only tracks `HISTORY_BUFFER_LENGTH` worth of roots and so for all possible timestamp values would consume a constant amount of storage. +However, this design opens the contract to an attack where a skipped slot that has the same value modulo the ring buffer length would return an old root value, +rather than the most recent one. + +To nullify this attack while retaining a fixed memory footprint, this EIP keeps track of the pair of data `(parent_beacon_block_root, timestamp)` for each index into the +ring buffer and verifies the timestamp matches the one originally used to write the root data when being read. Given the fixed size of storage slots (only 32 bytes), the requirement +to store a pair of values necessitates two ring buffers, rather than just one. + +### Size of ring buffers + +The ring buffer data structures are sized to hold 8191 roots from the consensus layer. Using a prime number as the ring buffer size ensures that no value is overwritten until the entire ring buffer has been saturated and thereafter, each value will be updated once per iteration. This also means that even if the slot times were to change, we would continue to use at most 8191 storage slots. + +Given the current mainnet values, 8191 roots provides about a day of coverage. This gives users plenty of time to make a transaction with a verification against a specific root and get the transaction included on-chain. + +## Backwards Compatibility + +No issues. + +## Test Cases + +N/A + +## Reference Implementation + +N/A + +## Security Considerations + +N/A + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4799.md b/EIPS/eip-4799.md new file mode 100644 index 00000000000000..7de60257d4d049 --- /dev/null +++ b/EIPS/eip-4799.md @@ -0,0 +1,7 @@ +--- +eip: 4799 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4799.md diff --git a/EIPS/eip-4803.md b/EIPS/eip-4803.md new file mode 100644 index 00000000000000..2d2245e89e0fef --- /dev/null +++ b/EIPS/eip-4803.md @@ -0,0 +1,51 @@ +--- +eip: 4803 +title: Limit transaction gas to a maximum of 2^63-1 +description: Valid transactions must have a reasonable gas limit +author: Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-4803-limit-transaction-gas-to-a-maximum-of-2-63-1/8296 +status: Stagnant +type: Standards Track +category: Core +created: 2022-02-02 +--- + +## Abstract + +Limit transaction gas to be between `0` and `2^63-1`. + +## Motivation + +The gas limit field in the transaction is specified to be an arbitrary long unsigned integer, but various clients put limits on this value. This EIP brings a reasonable limit into consensus. + +## Specification + +Introduce one new restriction retroactively from genesis: any transaction is invalid and not includeable in a block, where the gas limit exceeds `2^63-1`. + +## Rationale + +### `2^63-1` vs `2^64-1` + +`2^63-1` is chosen because it allows representing the gas value as a signed integer, and so the out of gas check can be done as a simple "less than zero" check after subtraction. + +### Consider `2^31-1` + +An alternative is considering a lower limit, because this can be handled easily in Javascript, since it handles numbers as floating point (the actual upper bound is `2^53-1`). + +### Current limit + +Due to the nature of RLP encoding, there is no fixed upper bound for the value, but most implementations limit it to 256-bits. Furthermore, most client implementations (such as geth) internally handle gas as a 64-bit value. + +## Backwards Compatibility + +While this is a breaking change, no actual effect should be visible. + +Before [EIP-1559](./eip-1559.md) it was possible to include transactions with `gasPrice = 0` and thus the `gasLimit * gasPrice <= accountBalance` calculation could have allowed for arbitrarily large values of `gasLimit`. However, the rule that the transaction list cannot exceed the block gas limit, and the strict rules about how the block gas limit can change, prevented arbitrarily large values of `gasLimit` to be in the historical state. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4804.md b/EIPS/eip-4804.md new file mode 100644 index 00000000000000..6617a0fe57da75 --- /dev/null +++ b/EIPS/eip-4804.md @@ -0,0 +1,7 @@ +--- +eip: 4804 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4804.md diff --git a/EIPS/eip-4824.md b/EIPS/eip-4824.md new file mode 100644 index 00000000000000..8c9fde03f38948 --- /dev/null +++ b/EIPS/eip-4824.md @@ -0,0 +1,7 @@ +--- +eip: 4824 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4824.md diff --git a/EIPS/eip-4834.md b/EIPS/eip-4834.md new file mode 100644 index 00000000000000..c68ab4e15bbdea --- /dev/null +++ b/EIPS/eip-4834.md @@ -0,0 +1,7 @@ +--- +eip: 4834 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4834.md diff --git a/EIPS/eip-4844.md b/EIPS/eip-4844.md new file mode 100644 index 00000000000000..de2e4a46ad93fc --- /dev/null +++ b/EIPS/eip-4844.md @@ -0,0 +1,438 @@ +--- +eip: 4844 +title: Shard Blob Transactions +description: Shard Blob Transactions scale data-availability of Ethereum in a simple, forwards-compatible manner. +author: Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad), Diederik Loerakker (@protolambda), George Kadianakis (@asn-d6), Matt Garnett (@lightclient), Mofi Taiwo (@Inphi), Ansgar Dietrichs (@adietrichs) +discussions-to: https://ethereum-magicians.org/t/eip-4844-shard-blob-transactions/8430 +status: Final +type: Standards Track +category: Core +created: 2022-02-25 +requires: 1559, 2718, 2930, 4895 +--- + +## Abstract + +Introduce a new transaction format for "blob-carrying transactions" which contain a large amount of data that cannot be +accessed by EVM execution, but whose commitment can be accessed. +The format is intended to be fully compatible with the format that will be used in full sharding. + +## Motivation + +Rollups are in the short and medium term, and possibly in the long term, the only trustless scaling solution for Ethereum. +Transaction fees on L1 have been very high for months and there is greater urgency in doing anything required to help facilitate an ecosystem-wide move to rollups. +Rollups are significantly reducing fees for many Ethereum users: Optimism and Arbitrum frequently provide fees that are ~3-8x lower than the Ethereum base layer itself, +and ZK rollups, which have better data compression and can avoid including signatures, have fees ~40-100x lower than the base layer. + +However, even these fees are too expensive for many users. The long-term solution to the long-term inadequacy of rollups +by themselves has always been data sharding, which would add ~16 MB per block of dedicated data space to the chain that rollups could use. +However, data sharding will still take a considerable amount of time to finish implementing and deploying. + +This EIP provides a stop-gap solution until that point by implementing the _transaction format_ that would be used in sharding, +but not actually sharding those transactions. Instead, the data from this transaction format is simply part of the beacon chain and is fully downloaded +by all consensus nodes (but can be deleted after only a relatively short delay). +Compared to full data sharding, this EIP has a reduced cap on the number of these transactions that can be included, corresponding to a target of ~0.375 MB per block and a limit of ~0.75 MB. + +## Specification + +### Parameters + +| Constant | Value | +| - | - | +| `BLOB_TX_TYPE` | `Bytes1(0x03)` | +| `BYTES_PER_FIELD_ELEMENT` | `32` | +| `FIELD_ELEMENTS_PER_BLOB` | `4096` | +| `BLS_MODULUS` | `52435875175126190479447740508185965837690552500527637822603658699938581184513` | +| `VERSIONED_HASH_VERSION_KZG` | `Bytes1(0x01)` | +| `POINT_EVALUATION_PRECOMPILE_ADDRESS` | `Bytes20(0x0A)` | +| `POINT_EVALUATION_PRECOMPILE_GAS` | `50000` | +| `MAX_BLOB_GAS_PER_BLOCK` | `786432` | +| `TARGET_BLOB_GAS_PER_BLOCK` | `393216` | +| `MIN_BASE_FEE_PER_BLOB_GAS` | `1` | +| `BLOB_BASE_FEE_UPDATE_FRACTION` | `3338477` | +| `GAS_PER_BLOB` | `2**17` | +| `HASH_OPCODE_BYTE` | `Bytes1(0x49)` | +| `HASH_OPCODE_GAS` | `3` | +| [`MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS`](https://github.com/ethereum/consensus-specs/blob/4de1d156c78b555421b72d6067c73b614ab55584/configs/mainnet.yaml#L148) | `4096` | + +### Type aliases + +| Type | Base type | Additional checks | +| - | - | - | +| `Blob` | `ByteVector[BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB]` | | +| `VersionedHash` | `Bytes32` | | +| `KZGCommitment` | `Bytes48` | Perform IETF BLS signature "KeyValidate" check but do allow the identity point | +| `KZGProof` | `Bytes48` | Same as for `KZGCommitment` | + +### Cryptographic Helpers + +Throughout this proposal we use cryptographic methods and classes defined in the corresponding [consensus 4844 specs](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb). + +Specifically, we use the following methods from [`polynomial-commitments.md`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md): + +- [`verify_kzg_proof()`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md#verify_kzg_proof) +- [`verify_blob_kzg_proof_batch()`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md#verify_blob_kzg_proof_batch) + +### Helpers + +```python +def kzg_to_versioned_hash(commitment: KZGCommitment) -> VersionedHash: + return VERSIONED_HASH_VERSION_KZG + sha256(commitment)[1:] +``` + +Approximates `factor * e ** (numerator / denominator)` using Taylor expansion: + +```python +def fake_exponential(factor: int, numerator: int, denominator: int) -> int: + i = 1 + output = 0 + numerator_accum = factor * denominator + while numerator_accum > 0: + output += numerator_accum + numerator_accum = (numerator_accum * numerator) // (denominator * i) + i += 1 + return output // denominator +``` + +### Blob transaction + +We introduce a new type of [EIP-2718](./eip-2718.md) transaction, "blob transaction", where the `TransactionType` is `BLOB_TX_TYPE` and the `TransactionPayload` is the RLP serialization of the following `TransactionPayloadBody`: + +``` +[chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, max_fee_per_blob_gas, blob_versioned_hashes, y_parity, r, s] +``` + +The fields `chain_id`, `nonce`, `max_priority_fee_per_gas`, `max_fee_per_gas`, `gas_limit`, `value`, `data`, and `access_list` follow the same semantics as [EIP-1559](./eip-1559.md). + +The field `to` deviates slightly from the semantics with the exception that it MUST NOT be `nil` and therefore must always represent a 20-byte address. This means that blob transactions cannot have the form of a create transaction. + +The field `max_fee_per_blob_gas` is a `uint256` and the field `blob_versioned_hashes` represents a list of hash outputs from `kzg_to_versioned_hash`. + +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. + +#### Signature + +The signature values `y_parity`, `r`, and `s` are calculated by constructing a secp256k1 signature over the following digest: + +`keccak256(BLOB_TX_TYPE || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, max_fee_per_blob_gas, blob_versioned_hashes]))`. + +### Header extension + +The current header encoding is extended with two new 64-bit unsigned integer fields: + +- `blob_gas_used` is the total amount of blob gas consumed by the transactions within the block. +- `excess_blob_gas` is a running total of blob gas consumed in excess of the target, prior to the block. Blocks with above-target blob gas consumption increase this value, blocks with below-target blob gas consumption decrease it (bounded at 0). + +The resulting RLP encoding of the header is therefore: + +``` +rlp([ + parent_hash, + 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, # ommers hash + coinbase, + state_root, + txs_root, + receipts_root, + logs_bloom, + 0, # difficulty + number, + gas_limit, + gas_used, + timestamp, + extradata, + prev_randao, + 0x0000000000000000, # nonce + base_fee_per_gas, + withdrawals_root, + blob_gas_used, + excess_blob_gas, +]) +``` + +The value of `excess_blob_gas` can be calculated using the parent header. + +```python +def calc_excess_blob_gas(parent: Header) -> int: + if parent.excess_blob_gas + parent.blob_gas_used < TARGET_BLOB_GAS_PER_BLOCK: + return 0 + else: + return parent.excess_blob_gas + parent.blob_gas_used - TARGET_BLOB_GAS_PER_BLOCK +``` + +For the first post-fork block, both `parent.blob_gas_used` and `parent.excess_blob_gas` are evaluated as `0`. + +### Gas accounting + +We introduce blob gas as a new type of gas. It is independent of normal gas and follows its own targeting rule, similar to EIP-1559. +We use the `excess_blob_gas` header field to store persistent data needed to compute the blob gas base fee. For now, only blobs are priced in blob gas. + +```python +def calc_blob_fee(header: Header, tx: Transaction) -> int: + return get_total_blob_gas(tx) * get_base_fee_per_blob_gas(header) + +def get_total_blob_gas(tx: Transaction) -> int: + return GAS_PER_BLOB * len(tx.blob_versioned_hashes) + +def get_base_fee_per_blob_gas(header: Header) -> int: + return fake_exponential( + MIN_BASE_FEE_PER_BLOB_GAS, + header.excess_blob_gas, + BLOB_BASE_FEE_UPDATE_FRACTION + ) +``` + +The block validity conditions are modified to include blob gas checks (see the [Execution layer validation](#execution-layer-validation) section below). + +The actual `blob_fee` as calculated via `calc_blob_fee` is deducted from the sender balance before transaction execution and burned, and is not refunded in case of transaction failure. + +### Opcode to get versioned hashes + +We add an instruction `BLOBHASH` (with opcode `HASH_OPCODE_BYTE`) which reads `index` from the top of the stack +as big-endian `uint256`, and replaces it on the stack with `tx.blob_versioned_hashes[index]` +if `index < len(tx.blob_versioned_hashes)`, and otherwise with a zeroed `bytes32` value. +The opcode has a gas cost of `HASH_OPCODE_GAS`. + +### Point evaluation precompile + +Add a precompile at `POINT_EVALUATION_PRECOMPILE_ADDRESS` that verifies a KZG proof which claims that a blob +(represented by a commitment) evaluates to a given value at a given point. + +The precompile costs `POINT_EVALUATION_PRECOMPILE_GAS` and executes the following logic: + +```python +def point_evaluation_precompile(input: Bytes) -> Bytes: + """ + Verify p(z) = y given commitment that corresponds to the polynomial p(x) and a KZG proof. + Also verify that the provided commitment matches the provided versioned_hash. + """ + # The data is encoded as follows: versioned_hash | z | y | commitment | proof | with z and y being padded 32 byte big endian values + assert len(input) == 192 + versioned_hash = input[:32] + z = input[32:64] + y = input[64:96] + commitment = input[96:144] + proof = input[144:192] + + # Verify commitment matches versioned_hash + assert kzg_to_versioned_hash(commitment) == versioned_hash + + # Verify KZG proof with z and y in big endian format + assert verify_kzg_proof(commitment, z, y, proof) + + # Return FIELD_ELEMENTS_PER_BLOB and BLS_MODULUS as padded 32 byte big endian values + return Bytes(U256(FIELD_ELEMENTS_PER_BLOB).to_be_bytes32() + U256(BLS_MODULUS).to_be_bytes32()) +``` + +The precompile MUST reject non-canonical field elements (i.e. provided field elements MUST be strictly less than `BLS_MODULUS`). + +### Consensus layer validation + +On the consensus layer the blobs are referenced, but not fully encoded, in the beacon block body. +Instead of embedding the full contents in the body, the blobs are propagated separately, as "sidecars". + +This "sidecar" design provides forward compatibility for further data increases by black-boxing `is_data_available()`: +with full sharding `is_data_available()` can be replaced by data-availability-sampling (DAS) thus avoiding all blobs being downloaded by all beacon nodes on the network. + +Note that the consensus layer is tasked with persisting the blobs for data availability, the execution layer is not. + +The `ethereum/consensus-specs` repository defines the following consensus layer changes involved in this EIP: + +- Beacon chain: process updated beacon blocks and ensure blobs are available. +- P2P network: gossip and sync updated beacon block types and new blob sidecars. +- Honest validator: produce beacon blocks with blobs; sign and publish the associated blob sidecars. + +### Execution layer validation + +On the execution layer, the block validity conditions are extended as follows: + +```python +def validate_block(block: Block) -> None: + ... + + # check that the excess blob gas was updated correctly + assert block.header.excess_blob_gas == calc_excess_blob_gas(block.parent.header) + + blob_gas_used = 0 + + for tx in block.transactions: + ... + + # modify the check for sufficient balance + max_total_fee = tx.gas * tx.max_fee_per_gas + if get_tx_type(tx) == BLOB_TX_TYPE: + max_total_fee += get_total_blob_gas(tx) * tx.max_fee_per_blob_gas + assert signer(tx).balance >= max_total_fee + + ... + + # add validity logic specific to blob txs + if get_tx_type(tx) == BLOB_TX_TYPE: + # there must be at least one blob + assert len(tx.blob_versioned_hashes) > 0 + + # all versioned blob hashes must start with VERSIONED_HASH_VERSION_KZG + for h in tx.blob_versioned_hashes: + assert h[0] == VERSIONED_HASH_VERSION_KZG + + # ensure that the user was willing to at least pay the current blob base fee + assert tx.max_fee_per_blob_gas >= get_base_fee_per_blob_gas(block.header) + + # keep track of total blob gas spent in the block + blob_gas_used += get_total_blob_gas(tx) + + # ensure the total blob gas spent is at most equal to the limit + assert blob_gas_used <= MAX_BLOB_GAS_PER_BLOCK + + # ensure blob_gas_used matches header + assert block.header.blob_gas_used == blob_gas_used + +``` + +### Networking + +Blob transactions have two network representations. During transaction gossip responses (`PooledTransactions`), the EIP-2718 `TransactionPayload` of the blob transaction is wrapped to become: + +``` +rlp([tx_payload_body, blobs, commitments, proofs]) +``` + +Each of these elements are defined as follows: + +- `tx_payload_body` - is the `TransactionPayloadBody` of standard EIP-2718 [blob transaction](#blob-transaction) +- `blobs` - list of `Blob` items +- `commitments` - list of `KZGCommitment` of the corresponding `blobs` +- `proofs` - list of `KZGProof` of the corresponding `blobs` and `commitments` + +The node MUST validate `tx_payload_body` and verify the wrapped data against it. To do so, ensure that: + +- There are an equal number of `tx_payload_body.blob_versioned_hashes`, `blobs`, `commitments`, and `proofs`. +- The KZG `commitments` hash to the versioned hashes, i.e. `kzg_to_versioned_hash(commitments[i]) == tx_payload_body.blob_versioned_hashes[i]` +- The KZG `commitments` match the corresponding `blobs` and `proofs`. (Note: this can be optimized using `verify_blob_kzg_proof_batch`, with a proof for a + random evaluation at a point derived from the commitment and blob data for each blob) + +For body retrieval responses (`BlockBodies`), the standard EIP-2718 blob transaction `TransactionPayload` is used. + +Nodes MUST NOT automatically broadcast blob transactions to their peers. +Instead, those transactions are only announced using `NewPooledTransactionHashes` messages, and can then be manually requested via `GetPooledTransactions`. + +## Rationale + +### On the path to sharding + +This EIP introduces blob transactions in the same format in which they are expected to exist in the final sharding specification. +This provides a temporary but significant scaling relief for rollups by allowing them to initially scale to 0.375 MB per slot, +with a separate fee market allowing fees to be very low while usage of this system is limited. + +The core goal of rollup scaling stopgaps is to provide temporary scaling relief, +without imposing extra development burdens on rollups to take advantage of this relief. +Today, rollups use calldata. In the future, rollups will have no choice but to use sharded data (also called "blobs") +because sharded data will be much cheaper. +Hence, rollups cannot avoid making a large upgrade to how they process data at least once along the way. +But what we _can_ do is ensure that rollups need to _only_ upgrade once. +This immediately implies that there are exactly two possibilities for a stopgap: (i) reducing the gas costs of existing calldata, +and (ii) bringing forward the format that will be used for sharded data, but not yet actually sharding it. +Previous EIPs were all a solution of category (i); this EIP is a solution of category (ii). + +The main tradeoff in designing this EIP is that of implementing more now versus having to implement more later: +do we implement 25% of the work on the way to full sharding, or 50%, or 75%? + +The work that is already done in this EIP includes: + +- A new transaction type, of the exact same format that will need to exist in "full sharding" +- _All_ of the execution-layer logic required for full sharding +- _All_ of the execution / consensus cross-verification logic required for full sharding +- Layer separation between `BeaconBlock` verification and data availability sampling blobs +- Most of the `BeaconBlock` logic required for full sharding +- A self-adjusting independent base fee for blobs + +The work that remains to be done to get to full sharding includes: + +- A low-degree extension of the `commitments` in the consensus layer to allow 2D sampling +- An actual implementation of data availability sampling +- PBS (proposer/builder separation), to avoid requiring individual validators to process 32 MB of data in one slot +- Proof of custody or similar in-protocol requirement for each validator to verify a particular part of the sharded data in each block + +This EIP also sets the stage for longer-term protocol cleanups. For example, its (cleaner) gas base fee update rule could be applied to the primary basefee calculation. + +### How rollups would function + +Instead of putting rollup block data in transaction calldata, rollups would expect rollup block submitters +to put the data into blobs. This guarantees availability (which is what rollups need) but would be much cheaper than calldata. +Rollups need data to be available once, long enough to ensure honest actors can construct the rollup state, but not forever. + +Optimistic rollups only need to actually provide the underlying data when fraud proofs are being submitted. +The fraud proof can verify the transition in smaller steps, loading at most a few values of the blob at a time through calldata. +For each value it would provide a KZG proof and use the point evaluation precompile to verify the value against the versioned hash that was submitted before, +and then perform the fraud proof verification on that data as is done today. + +ZK rollups would provide two commitments to their transaction or state delta data: +the blob commitment (which the protocol ensures points to available data) and the ZK rollup's own commitment using whatever proof system the rollup uses internally. +They would use a proof of equivalence protocol, using the point evaluation precompile, +to prove that the two commitments refer to the same data. + +### Versioned hashes & precompile return data + +We use versioned hashes (rather than commitments) as references to blobs in the execution layer to ensure forward compatibility with future changes. +For example, if we need to switch to Merkle trees + STARKs for quantum-safety reasons, then we would add a new version, +allowing the point evaluation precompile to work with the new format. +Rollups would not have to make any EVM-level changes to how they work; +sequencers would simply have to switch over to using a new transaction type at the appropriate time. + +However, the point evaluation happens inside a finite field, and it is only well defined if the field modulus is known. Smart contracts could contain a table mapping the commitment version to a modulus, but this would not allow smart contract to take into account future upgrades to a modulus that is not known yet. By allowing access to the modulus inside the EVM, the smart contract can be built so that it can use future commitments and proofs, without ever needing an upgrade. + +In the interest of not adding another precompile, we return the modulus and the polynomial degree directly from the point evaluation precompile. It can then be used by the caller. It is also "free" in that the caller can just ignore this part of the return value without incurring an extra cost -- systems that remain upgradable for the foreseeable future will likely use this route for now. + +### Base fee per blob gas update rule + +The base fee per blob gas update rule is intended to approximate the formula `base_fee_per_blob_gas = MIN_BASE_FEE_PER_BLOB_GAS * e**(excess_blob_gas / BLOB_BASE_FEE_UPDATE_FRACTION)`, +where `excess_blob_gas` is the total "extra" amount of blob gas that the chain has consumed relative to the "targeted" number (`TARGET_BLOB_GAS_PER_BLOCK` per block). +Like EIP-1559, it's a self-correcting formula: as the excess goes higher, the `base_fee_per_blob_gas` increases exponentially, reducing usage and eventually forcing the excess back down. + +The block-by-block behavior is roughly as follows. +If block `N` consumes `X` blob gas, then in block `N+1` `excess_blob_gas` increases by `X - TARGET_BLOB_GAS_PER_BLOCK`, +and so the `base_fee_per_blob_gas` of block `N+1` increases by a factor of `e**((X - TARGET_BLOB_GAS_PER_BLOCK) / BLOB_BASE_FEE_UPDATE_FRACTION)`. +Hence, it has a similar effect to the existing EIP-1559, but is more "stable" in the sense that it responds in the same way to the same total usage regardless of how it's distributed. + +The parameter `BLOB_BASE_FEE_UPDATE_FRACTION` controls the maximum rate of change of the base fee per blob gas. It is chosen to target a maximum change rate of `e**(TARGET_BLOB_GAS_PER_BLOCK / BLOB_BASE_FEE_UPDATE_FRACTION) ≈ 1.125` per block. + +### Throughput + +The values for `TARGET_BLOB_GAS_PER_BLOCK` and `MAX_BLOB_GAS_PER_BLOCK` are chosen to correspond to a target of 3 blobs (0.375 MB) and maximum of 6 blobs (0.75 MB) per block. These small initial limits are intended to minimize the strain on the network created by this EIP and are expected to be increased in future upgrades as the network demonstrates reliability under larger blocks. + +## Backwards Compatibility + +### Blob non-accessibility + +This EIP introduces a transaction type that has a distinct mempool version and execution-payload version, +with only one-way convertibility between the two. The blobs are in the network representation and not in the consensus representation; +instead, they are coupled with the beacon block. This means that there is now a part of a transaction that will not be accessible from the web3 API. + +### Mempool issues + +Blob transactions have a large data size at the mempool layer, which poses a mempool DoS risk, +though not an unprecedented one as this also applies to transactions with large amounts of calldata. + +By only broadcasting announcements for blob transactions, receiving nodes will have control over which and how many transactions to receive, +allowing them to throttle throughput to an acceptable level. +[EIP-5793](./eip-5793.md) will give further fine-grained control to nodes by extending the `NewPooledTransactionHashes` announcement messages to include the transaction type and size. + +In addition, we recommend including a 1.1x base fee per blob gas bump requirement to the mempool transaction replacement rules. + +## Test Cases + +Execution layer test cases for this EIP can be found in the [`eip4844_blobs`](https://github.com/ethereum/execution-spec-tests/tree/1983444bbe1a471886ef7c0e82253ffe2a4053e1/tests/cancun/eip4844_blobs) of the `ethereum/execution-spec-tests` repository. Consensus layer test cases can be found [here](https://github.com/ethereum/consensus-specs/tree/2297c09b7e457a13f7b2261a28cb45777be82f83/tests/core/pyspec/eth2spec/test/deneb). + +## Security Considerations + +This EIP increases the bandwidth requirements per beacon block by a maximum of ~0.75 MB. +This is 40% larger than the theoretical maximum size of a block today (30M gas / 16 gas per calldata byte = 1.875M bytes), and so it will not greatly increase worst-case bandwidth. +Post-merge, block times are static rather than an unpredictable Poisson distribution, giving a guaranteed period of time for large blocks to propagate. + +The _sustained_ load of this EIP is much lower than alternatives that reduce calldata costs, even if the calldata is limited, +because there is no expectation that the blobs need to be stored for as long as an execution payload. +This makes it possible to implement a policy that these blobs must be kept for at least a certain period. The specific value chosen is `MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS` epochs, which is around 18 days, +a much shorter delay compared to proposed (but yet to be implemented) one-year rotation times for execution payload history. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4863.md b/EIPS/eip-4863.md new file mode 100644 index 00000000000000..869b9a9dde4d00 --- /dev/null +++ b/EIPS/eip-4863.md @@ -0,0 +1,107 @@ +--- +eip: 4863 +title: Beacon chain push withdrawals +description: Support validator withdrawals from the beacon chain to the EVM via a new "push-style" transaction type. +author: Alex Stokes (@ralexstokes), Danny Ryan (@djrtwo) +discussions-to: https://ethereum-magicians.org/t/eip-4863-beacon-chain-push-withdrawals/8465 +status: Stagnant +type: Standards Track +category: Core +created: 2022-02-28 +--- + +## Abstract + +Introduce a new [EIP-2718 transaction type](./eip-2718.md) to support validator withdrawals that are "pushed" from the beacon chain to the EVM. + +Add block validations to ensure the withdrawal transactions are sound with respect to withdrawal processing on the beacon chain. + +## Motivation + +This EIP provides a way for validator withdrawals made on the beacon chain to enter into the EVM. +The architecture is "push"-based, rather than "pull"-based, where withdrawals are required to be processed in the execution block as soon as they are dequeued from the beacon chain. + +This approach is more involved than "pull"-based alternatives (e.g. [EIP-4788](./eip-4788.md) + user-space withdrawal contract) with respect to the core protocol (by providing a new transaction type with special semantics) but does provide tighter integration of a critical feature into the protocol itself. + +## Specification + +| constants | value | units +|--- |--- |--- +| `FORK_TIMESTAMP` | TBD | +| `WITHDRAWAL_TX_TYPE` | `0x3` | byte + +Beginning with the execution timestamp `FORK_TIMESTAMP`, execution clients **MUST** introduce the following extensions to transaction processing and block validation: + +### New transaction type + +Define a new [EIP-2718](./eip-2718.md) transaction type with `TransactionType` `WITHDRAWAL_TX_TYPE`. + +The `TransactionPayload` is an RLP-encoded list `RLP([index, address, amount])` where the `index` is a 64-bit value uniquely labeling a specific withdrawal, the `address` refers to an execution layer account and the `amount` refers to an ether value given in units of wei. + +These values are provided by the consensus layer. + +### Block validity + +If a block contains *any* transactions with `WITHDRAWAL_TX_TYPE` type, they **MUST** come after **ALL** other transactions in the block. + +If the execution client receives a block where this is not the case, it **MUST** consider the block invalid. + +### Transaction processing + +When processing a transaction with `WITHDRAWAL_TX_TYPE` type, the implementation should increase the balance of the `address` specified by +the `WithdrawalTransaction` by the `amount` of wei specified. + +This balance change is unconditional and **MUST** not fail. + +This transaction type has no associated gas costs. + +TODO: add logs? + +## Rationale + +### Push vs pull approach + +This push approach gives validators a small subsidy with respect to processing, in lieu of needing to buy gas via normal EVM processing that would be required for a pull-based approach. + +This style also happens automatically when the requisite conditions are met on the beacon chain which is nicer UX for validators. + +### Why a new transaction type? + +This EIP suggests a new transaction type as it has special semantics different from other existing types of EVM transactions. + +An entirely new transaction type firewalls off generic EVM execution from this type of processing to simplify testing and security review of withdrawals. + +### Why no (gas) costs for new transaction type? + +The maximum number of this transaction type that can reach the execution layer at a given time is bounded (enforced by the consensus layer) and this limit is kept small so that +any execution layer operational costs are negligible in the context of the broader block execution. + +### Why only balance updates? No general EVM execution? + +More general processing introduces the risk of failures, which complicates accounting on the beacon chain. + +This EIP suggests a route for withdrawals that provides most of the benefits for a minimum of the (complexity) cost. + +### Why new block validations? + +The beacon chain must be able to efficiently validate that the withdrawal transactions in a given execution block are +the ones expected based on its own internal scheduling logic to maintain the soundness of the withdrawal mechanism. + +By requiring all withdrawal transactions to be at the back of every block where they are applicable, the algorithm to +check consistency becomes a straightforward linear walk from the start of the set until a known, bounded (small) number. + +Having a simple ordering scheme like this facilitates optimizations clients may do with respect to withdrawal processing, which +would be hampered if withdrawal transactions could be placed in the block freely. + +## Backwards Compatibility + +No issues. + +## Security Considerations + +Consensus-layer validation of withdrawal transactions is critical to ensure that the proper amount of ETH is withdrawn back into the execution layer. +This consensus-layer to execution-layer ETH transfer does not have a current analog in the EVM and thus deserves very high security scrutiny. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4881.md b/EIPS/eip-4881.md new file mode 100644 index 00000000000000..5d02f92261e8d1 --- /dev/null +++ b/EIPS/eip-4881.md @@ -0,0 +1,320 @@ +--- +eip: 4881 +title: Deposit Contract Snapshot Interface +description: Establishing the format and endpoint for transmitting a snapshot of the deposit Merkle tree +author: Mark Mackey (@ethDreamer) +discussions-to: https://ethereum-magicians.org/t/eip-4881-deposit-contract-snapshot-interface/8554 +status: Final +type: Standards Track +category: Interface +created: 2021-01-29 +--- + +## Abstract + +This EIP defines a standard format for transmitting the deposit contract Merkle tree in a compressed form during weak subjectivity sync. This allows newly syncing consensus clients to reconstruct the deposit tree much faster than downloading all historical deposits. The format proposed also allows clients to prune deposits that are no longer needed to participate fully in consensus (see [Deposit Finalization Flow](#deposit-finalization-flow)). + +## Motivation + +To reconstruct the deposit Merkle tree, most client implementations require beacon nodes to download and store every deposit log since the launch of the deposit contract. However, this approach requires beacon nodes to store far more deposits than necessary to participate in consensus. Additionally, this leads to increased sync times for new nodes, which is particularly evident during weak subjectivity sync. This simplistic approach also prevents historical contract logs from being pruned from full nodes, a prospect frequently discussed in the context of limiting state growth. + +## Specification + +Consensus clients MAY continue to implement the deposit Merkle tree however they choose. However, when transmitting the tree to newly syncing nodes, clients MUST use the following format: + +```python +class DepositTreeSnapshot: + finalized: List[Hash32, DEPOSIT_CONTRACT_DEPTH] + deposit_root: Hash32 + deposit_count: uint64 + execution_block_hash: Hash32 + execution_block_height: uint64 +``` + +Where `finalized` is a variable-length list (of maximum size `DEPOSIT_CONTRACT_DEPTH`) containing the hashes defined in the [Deposit Finalization Flow](#deposit-finalization-flow) section below. The fields `deposit_root`, `deposit_count`, and `execution_block_hash` store the same information as the [`Eth1Data`](https://github.com/ethereum/consensus-specs/blob/2b45496fe48fa75450ad29a05bdd48866f86528a/specs/phase0/beacon-chain.md#eth1data) object that corresponds to the snapshot, and `execution_block_height` is the height of the execution block with hash `execution_block_hash`. Consensus clients MUST make this structure available via the Beacon Node API endpoint: + +``` +/eth/v1/beacon/deposit_snapshot +``` + +### Deposit Finalization Flow + +During deposit processing, the beacon chain requires deposits to be submitted along with a Merkle path to the deposit root. This is required exactly once for each deposit. When a deposit has been processed by the beacon chain and the [deposit finalization conditions](#deposit-finalization-conditions) have been met, many of the hashes along the path to the deposit root will never be required again to construct Merkle proofs on chain. These unnecessary hashes MAY be pruned to save space. The image below illustrates the evolution of the deposit Merkle tree under this process alongside the corresponding `DepositTreeSnapshot` as new deposits are added and older deposits become finalized: + +![deposit tree evolution](../assets/eip-4881/deposit_tree_evolution.svg) + +## Rationale + +The format in this specification was chosen to achieve several goals simultaneously: + +1. Enable reconstruction of the deposit contract Merkle tree without requiring full nodes to store all historical contract logs +2. Avoid requiring consensus nodes to retain more deposits than necessary to fully participate in consensus +3. Simplicity of implementation (see [Reference Implementation](#reference-implementation) section) +4. Increase speed of weak subjectivity sync +5. Compatibility with existing implementations of this mechanism (see discussion) + +The proposed `DepositTreeSnapshot` structure includes both `execution_block_hash` and `execution_block_height` for convenience to consensus node implementors. While only one of these fields is strictly necessary, different clients may have already designed their block cache logic around one or the other. Sending only one of these would force some consensus clients to query the execution engine for the other information, but as this is happening in the context of a newly syncing consensus node, it is very likely that the execution engine will not be synced, especially post-merge. The `deposit_root` field is also not strictly necessary, but by including it, newly syncing consensus nodes can cheaply validate any received snapshot against itself (see the `calculate_root()` method in the [Reference Implementation](#reference-implementation)). + +### Why not Reconstruct the Tree Directly from the Deposit Contract? + +The deposit contract can only provide the tree at the head of the chain. Because the beacon chain's view of the deposit contract lags behind the execution chain by `ETH1_FOLLOW_DISTANCE`, there are almost always deposits which haven't yet been included in the chain that need proofs constructed from an earlier version of the tree than exists at the head. + +### Why not Reconstruct the Tree from a Deposit in the Beacon Chain? + +In principle, a node could scan backwards through the chain starting from the weak subjectivity checkpoint to locate a suitable [`Deposit`](https://github.com/ethereum/consensus-specs/blob/2b45496fe48fa75450ad29a05bdd48866f86528a/specs/phase0/beacon-chain.md#deposit), and then extract the rightmost branch of the tree from that. The node would also need to extract the `execution_block_hash` from which to start syncing new deposits from the `Eth1Data` in the corresponding `BeaconState`. This approach is less desirable for a few reasons: + +* More difficult to implement due to the edge cases involved in finding a suitable deposit to anchor to (the rightmost branch of the latest not-yet-included deposit is required) +* This would make backfilling beacon blocks a requirement for reconstructing the deposit tree and therefore a requirement for block production +* This is inherently slower than getting this information from the weak subjectivity checkpoint + +## Backwards Compatibility + +This proposal is fully backwards compatible. + +## Test Cases + +Test cases are included in [test_cases.yaml](../assets/eip-4881/test_cases.yaml). Each case is structured as follows: + +```python +class DepositTestCase: + deposit_data: DepositData # These are all the inputs to the deposit contract's deposit() function + deposit_data_root: Hash32 # The tree hash root of this deposit (calculated for convenience) + eth1_data: Eth1Data # An Eth1Data object that can be used to finalize the tree after pushing this deposit + block_height: uint64 # The height of the execution block with this Eth1Data + snapshot: DepositTreeSnapshot # The resulting DepositTreeSnapshot object if the tree were finalized after this deposit +``` + +This EIP also includes other files for testing: + +* [deposit_snapshot.py](../assets/eip-4881/deposit_snapshot.py) contains the same code as the [Reference Implementation](#reference-implementation) +* [eip_4881.py](../assets/eip-4881/eip_4881.py) contains boilerplate declarations +* [test_deposit_snapshot.py](../assets/eip-4881/test_deposit_snapshot.py) includes code for running test cases against the reference implementation + +If these files are downloaded to the same directory, the test cases can be run by executing `pytest` in that directory. + +## Reference Implementation + +This implementation lacks full error checking and is optimized for readability over efficiency. If `tree` is a `DepositTree`, then the `DepositTreeSnapshot` can be obtained by calling `tree.get_snapshot()` and a new instance of the tree can be recovered from the snapshot by calling `DepositTree.from_snapshot()`. See the [Deposit Finalization Conditions](#deposit-finalization-conditions) section for discussion on when the tree can be pruned by calling `tree.finalize()`. + +Generating proofs for deposits against an earlier version of the tree is relatively fast in this implementation; just create a copy of the finalized tree with `copy = DepositTree.from_snapshot(tree.get_snapshot())` and then append the remaining deposits to the desired count with `copy.push_leaf(deposit)`. Proofs can then be obtained with `copy.get_proof(index)`. + +```python +from __future__ import annotations +from typing import List, Optional, Tuple +from dataclasses import dataclass +from abc import ABC,abstractmethod +from eip_4881 import DEPOSIT_CONTRACT_DEPTH,Hash32,sha256,to_le_bytes,zerohashes + +@dataclass +class DepositTreeSnapshot: + finalized: List[Hash32, DEPOSIT_CONTRACT_DEPTH] + deposit_root: Hash32 + deposit_count: uint64 + execution_block_hash: Hash32 + execution_block_height: uint64 + + def calculate_root(self) -> Hash32: + size = self.deposit_count + index = len(self.finalized) + root = zerohashes[0] + for level in range(0, DEPOSIT_CONTRACT_DEPTH): + if (size & 1) == 1: + index -= 1 + root = sha256(self.finalized[index] + root) + else: + root = sha256(root + zerohashes[level]) + size >>= 1 + return sha256(root + to_le_bytes(self.deposit_count)) + def from_tree_parts(finalized: List[Hash32], + deposit_count: uint64, + execution_block: Tuple[Hash32, uint64]) -> DepositTreeSnapshot: + snapshot = DepositTreeSnapshot( + finalized, zerohashes[0], deposit_count, execution_block[0], execution_block[1]) + # A real implementation should store the deposit_root from the eth1_data passed to + # DepositTree.finalize() instead of relying on calculate_root() here. This allows + # the snapshot to be validated using calculate_root(). + snapshot.deposit_root = snapshot.calculate_root() + return snapshot + +@dataclass +class DepositTree: + tree: MerkleTree + mix_in_length: uint + finalized_execution_block: Optional[Tuple[Hash32, uint64]] + def new() -> DepositTree: + merkle = MerkleTree.create([], DEPOSIT_CONTRACT_DEPTH) + return DepositTree(merkle, 0, None) + def get_snapshot(self) -> DepositTreeSnapshot: + assert(self.finalized_execution_block is not None) + finalized = [] + deposit_count = self.tree.get_finalized(finalized) + return DepositTreeSnapshot.from_tree_parts( + finalized, deposit_count, self.finalized_execution_block) + def from_snapshot(snapshot: DepositTreeSnapshot) -> DepositTree: + # decent validation check on the snapshot + assert(snapshot.deposit_root == snapshot.calculate_root()) + finalized_execution_block = (snapshot.execution_block_hash, snapshot.execution_block_height) + tree = MerkleTree.from_snapshot_parts( + snapshot.finalized, snapshot.deposit_count, DEPOSIT_CONTRACT_DEPTH) + return DepositTree(tree, snapshot.deposit_count, finalized_execution_block) + def finalize(self, eth1_data: Eth1Data, execution_block_height: uint64): + self.finalized_execution_block = (eth1_data.block_hash, execution_block_height) + self.tree.finalize(eth1_data.deposit_count, DEPOSIT_CONTRACT_DEPTH) + def get_proof(self, index: uint) -> Tuple[Hash32, List[Hash32]]: + assert(self.mix_in_length > 0) + # ensure index > finalized deposit index + assert(index > self.tree.get_finalized([]) - 1) + leaf, proof = self.tree.generate_proof(index, DEPOSIT_CONTRACT_DEPTH) + proof.append(to_le_bytes(self.mix_in_length)) + return leaf, proof + def get_root(self) -> Hash32: + return sha256(self.tree.get_root() + to_le_bytes(self.mix_in_length)) + def push_leaf(self, leaf: Hash32): + self.mix_in_length += 1 + self.tree = self.tree.push_leaf(leaf, DEPOSIT_CONTRACT_DEPTH) + +class MerkleTree(): + @abstractmethod + def get_root(self) -> Hash32: + pass + @abstractmethod + def is_full(self) -> bool: + pass + @abstractmethod + def push_leaf(self, leaf: Hash32, level: uint) -> MerkleTree: + pass + @abstractmethod + def finalize(self, deposits_to_finalize: uint, level: uint) -> MerkleTree: + pass + @abstractmethod + def get_finalized(self, result: List[Hash32]) -> uint: + # returns the number of finalized deposits in the tree + # while populating result with the finalized hashes + pass + def create(leaves: List[Hash32], depth: uint) -> MerkleTree: + if not(leaves): + return Zero(depth) + if not(depth): + return Leaf(leaves[0]) + split = min(2**(depth - 1), len(leaves)) + left = MerkleTree.create(leaves[0:split], depth - 1) + right = MerkleTree.create(leaves[split:], depth - 1) + return Node(left, right) + def from_snapshot_parts(finalized: List[Hash32], deposits: uint, level: uint) -> MerkleTree: + if not(finalized) or not(deposits): + # empty tree + return Zero(level) + if deposits == 2**level: + return Finalized(deposits, finalized[0]) + left_subtree = 2**(level - 1) + if deposits <= left_subtree: + left = MerkleTree.from_snapshot_parts(finalized, deposits, level - 1) + right = Zero(level - 1) + return Node(left, right) + else: + left = Finalized(left_subtree, finalized[0]) + right = MerkleTree.from_snapshot_parts(finalized[1:], deposits - left_subtree, level - 1) + return Node(left, right) + def generate_proof(self, index: uint, depth: uint) -> Tuple[Hash32, List[Hash32]]: + proof = [] + node = self + while depth > 0: + ith_bit = (index >> (depth - 1)) & 0x1 + if ith_bit == 1: + proof.append(node.left.get_root()) + node = node.right + else: + proof.append(node.right.get_root()) + node = node.left + depth -= 1 + proof.reverse() + return node.get_root(), proof + +@dataclass +class Finalized(MerkleTree): + deposit_count: uint + hash: Hash32 + def get_root(self) -> Hash32: + return self.hash + def is_full(self) -> bool: + return True + def finalize(self, deposits_to_finalize: uint, level: uint) -> MerkleTree: + return self + def get_finalized(self, result: List[Hash32]) -> uint: + result.append(self.hash) + return self.deposit_count + +@dataclass +class Leaf(MerkleTree): + hash: Hash32 + def get_root(self) -> Hash32: + return self.hash + def is_full(self) -> bool: + return True + def finalize(self, deposits_to_finalize: uint, level: uint) -> MerkleTree: + return Finalized(1, self.hash) + def get_finalized(self, result: List[Hash32]) -> uint: + return 0 + +@dataclass +class Node(MerkleTree): + left: MerkleTree + right: MerkleTree + def get_root(self) -> Hash32: + return sha256(self.left.get_root() + self.right.get_root()) + def is_full(self) -> bool: + return self.right.is_full() + def push_leaf(self, leaf: Hash32, level: uint) -> MerkleTree: + if not(self.left.is_full()): + self.left = self.left.push_leaf(leaf, level - 1) + else: + self.right = self.right.push_leaf(leaf, level - 1) + return self + def finalize(self, deposits_to_finalize: uint, level: uint) -> MerkleTree: + deposits = 2**level + if deposits <= deposits_to_finalize: + return Finalized(deposits, self.get_root()) + self.left = self.left.finalize(deposits_to_finalize, level - 1) + if deposits_to_finalize > deposits / 2: + remaining = deposits_to_finalize - deposits / 2 + self.right = self.right.finalize(remaining, level - 1) + return self + def get_finalized(self, result: List[Hash32]) -> uint: + return self.left.get_finalized(result) + self.right.get_finalized(result) + +@dataclass +class Zero(MerkleTree): + n: uint64 + def get_root(self) -> Hash32: + if self.n == DEPOSIT_CONTRACT_DEPTH: + # Handle the entirely empty tree case. This is included for + # consistency/clarity as the zerohashes array is typically + # only defined from 0 to DEPOSIT_CONTRACT_DEPTH - 1. + return sha256(zerohashes[self.n - 1] + zerohashes[self.n - 1]) + return zerohashes[self.n] + def is_full(self) -> bool: + return False + def push_leaf(self, leaf: Hash32, level: uint) -> MerkleTree: + return MerkleTree.create([leaf], level) + def get_finalized(self, result: List[Hash32]) -> uint: + return 0 +``` + +## Security Considerations + +### Relying on Weak Subjectivity Sync + +The upcoming switch to PoS will require newly synced nodes to rely on valid weak subjectivity checkpoints because of long-range attacks. This proposal relies on the weak subjectivity assumption that clients will not bootstrap with an invalid WS checkpoint. + +### Deposit Finalization Conditions + +Care must be taken not to send a snapshot which includes deposits that haven't been fully included in the finalized checkpoint. Let `state` be the [`BeaconState`](https://github.com/ethereum/consensus-specs/blob/2b45496fe48fa75450ad29a05bdd48866f86528a/specs/phase0/beacon-chain.md#beaconstate) at a given block in the chain. Under normal operation, the [`Eth1Data`](https://github.com/ethereum/consensus-specs/blob/2b45496fe48fa75450ad29a05bdd48866f86528a/specs/phase0/beacon-chain.md#eth1data) stored in `state.eth1_data` is replaced every `EPOCHS_PER_ETH1_VOTING_PERIOD` epochs. Thus, finalization of the deposit tree proceeds with increments of `state.eth1_data`. Let `eth1data` be some `Eth1Data`. Both of the following conditions MUST be met to consider `eth1data` finalized: + +1. A finalized checkpoint exists where the corresponding `state` has `state.eth1_data == eth1data` +2. A finalized checkpoint exists where the corresponding `state` has `state.eth1_deposit_index >= eth1data.deposit_count` + +When these conditions are met, the tree can be pruned in the [reference implementation](#reference-implementation) by calling `tree.finalize(eth1data, execution_block_height)` + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4883.md b/EIPS/eip-4883.md new file mode 100644 index 00000000000000..ccaf2633e9c6c6 --- /dev/null +++ b/EIPS/eip-4883.md @@ -0,0 +1,7 @@ +--- +eip: 4883 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4883.md diff --git a/EIPS/eip-4885.md b/EIPS/eip-4885.md new file mode 100644 index 00000000000000..4893c605f95460 --- /dev/null +++ b/EIPS/eip-4885.md @@ -0,0 +1,7 @@ +--- +eip: 4885 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4885.md diff --git a/EIPS/eip-4886.md b/EIPS/eip-4886.md new file mode 100644 index 00000000000000..9bf28952e4beb5 --- /dev/null +++ b/EIPS/eip-4886.md @@ -0,0 +1,7 @@ +--- +eip: 4886 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4886.md diff --git a/EIPS/eip-4895.md b/EIPS/eip-4895.md new file mode 100644 index 00000000000000..81af3b60b632bc --- /dev/null +++ b/EIPS/eip-4895.md @@ -0,0 +1,173 @@ +--- +eip: 4895 +title: Beacon chain push withdrawals as operations +description: Support validator withdrawals from the beacon chain to the EVM via a new "system-level" operation type. +author: Alex Stokes (@ralexstokes), Danny Ryan (@djrtwo) +discussions-to: https://ethereum-magicians.org/t/eip-4895-beacon-chain-withdrawals-as-system-level-operations/8568 +status: Final +type: Standards Track +category: Core +created: 2022-03-10 +--- + +## Abstract + +Introduce a system-level "operation" to support validator withdrawals that are "pushed" from the beacon chain to the EVM. + +These operations create unconditional balance increases to the specified recipients. + +## Motivation + +This EIP provides a way for validator withdrawals made on the beacon chain to enter into the EVM. +The architecture is "push"-based, rather than "pull"-based, where withdrawals are required to be processed in the execution layer as soon as they are dequeued from the consensus layer. + +Withdrawals are represented as a new type of object in the execution payload -- an "operation" -- that separates the withdrawals feature from user-level transactions. +This approach is more involved than the prior approach introducing a new transaction type but it cleanly separates this "system-level" operation from regular transactions. +The separation simplifies testing (so facilitates security) by reducing interaction effects generated by mixing this system-level concern with user data. + +Moreover, this approach is more complex than "pull"-based alternatives with respect to the core protocol but does provide tighter integration of a critical feature into the protocol itself. + +## Specification + +| constants | value | units +|--- |--- |--- +| `FORK_TIMESTAMP` | 1681338455 | + +Beginning with the execution timestamp `FORK_TIMESTAMP`, execution clients **MUST** introduce the following extensions to payload validation and processing: + +### System-level operation: withdrawal + +Define a new payload-level object called a `withdrawal` that describes withdrawals that have been validated at the consensus layer. +`Withdrawal`s are syntactically similar to a user-level transaction but live in a different domain than user-level transactions. + +`Withdrawal`s provide key information from the consensus layer: + +1. a monotonically increasing `index`, starting from 0, as a `uint64` value that increments by 1 per withdrawal to uniquely identify each withdrawal +2. the `validator_index` of the validator, as a `uint64` value, on the consensus layer the withdrawal corresponds to +3. a recipient for the withdrawn ether `address` as a 20-byte value +4. a nonzero `amount` of ether given in Gwei (1e9 wei) as a `uint64` value. + +*NOTE*: the `index` for each withdrawal is a global counter spanning the entire sequence of withdrawals. + +`Withdrawal` objects are serialized as a RLP list according to the schema: `[index, validator_index, address, amount]`. + +### New field in the execution payload: withdrawals + +The execution payload gains a new field for the `withdrawals` which is an RLP list of `Withdrawal` data. + +For example: + +```python +withdrawal_0 = [index_0, validator_index_0, address_0, amount_0] +withdrawal_1 = [index_1, validator_index_1, address_1, amount_1] +withdrawals = [withdrawal_0, withdrawal_1] +``` + +This new field is encoded after the existing fields in the execution payload structure and is considered part of the execution payload's body. + +```python +execution_payload_rlp = RLP([header, transactions, [], withdrawals]) + +execution_payload_body_rlp = RLP([transactions, [], withdrawals]) +``` + +NOTE: the empty list in this schema is due to [EIP-3675](./eip-3675.md) that sets the `ommers` value to a fixed constant. + +### New field in the execution payload header: withdrawals root + +The execution payload header gains a new field committing to the `withdrawals` in the execution payload. + +This commitment is constructed identically to the transactions root in the existing execution payload header by inserting +each withdrawal into a Merkle-Patricia trie keyed by index in the list of `withdrawals`. + +```python +def compute_trie_root_from_indexed_data(data): + trie = Trie.from([(i, obj) for i, obj in enumerate(data)]) + return trie.root + +execution_payload_header.withdrawals_root = compute_trie_root_from_indexed_data(execution_payload.withdrawals) +``` + +The execution payload header is extended with a new field containing the 32 byte root of the trie committing to the list of withdrawals provided in a given execution payload. + +To illustrate: + +```python +execution_payload_header_rlp = RLP([ + parent_hash, + 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, # ommers hash + coinbase, + state_root, + txs_root, + receipts_root, + logs_bloom, + 0, # difficulty + number, + gas_limit, + gas_used, + timestamp, + extradata, + prev_randao, + 0x0000000000000000, # nonce + base_fee_per_gas, + withdrawals_root, +]) +``` + +NOTE: field names and constant value in this example reflect [EIP-3675](./eip-3675.md) and [EIP-4399](./eip-4399.md). Refer to those EIPs for further information. + +### Execution payload validity + +Assuming the execution payload is well-formatted, the execution client has an additional payload validation to ensure that the `withdrawals_root` matches the expected value given the list in the payload. + +```python +assert execution_payload_header.withdrawals_root == compute_trie_root_from_indexed_data(execution_payload.withdrawals) +``` + +### State transition + +The `withdrawals` in an execution payload are processed **after** any user-level transactions are applied. + +For each `withdrawal` in the list of `execution_payload.withdrawals`, the implementation increases the balance of the `address` specified by the `amount` given. + +Recall that the `amount` is given in units of Gwei so a conversion to units of wei must be performed when working with account balances in the execution state. + +This balance change is unconditional and **MUST** not fail. + +This operation has no associated gas costs. + +## Rationale + +### Why not a new transaction type? + +This EIP suggests a new type of object -- the "withdrawal operation" -- as it has special semantics different from other existing types of EVM transactions. + +Operations are initiated by the overall system, rather than originating from end users like typical transactions. + +An entirely new type of object firewalls off generic EVM execution from this type of processing to simplify testing and security review of withdrawals. + +### Why no (gas) costs for the withdrawal type? + +The maximum number of withdrawals that can reach the execution layer at a given time is bounded (enforced by the consensus layer) and this limit has been chosen so that +any execution layer operational costs are negligible in the context of the broader payload execution. + +This bound applies to both computational cost (only a few balance updates in the state) and storage/networking cost as the additional payload footprint is kept small (current parameterizations put the additional overhead at ~1% of current average payload size). + +### Why only balance updates? No general EVM execution? + +More general processing introduces the risk of failures, which complicates accounting on the beacon chain. + +This EIP suggests a route for withdrawals that provides most of the benefits for a minimum of the (complexity) cost. + +## Backwards Compatibility + +No issues. + +## Security Considerations + +Consensus-layer validation of withdrawal transactions is critical to ensure that the proper amount of ETH is withdrawn back into the execution layer. +This consensus-layer to execution-layer ETH transfer does not have a current analog in the EVM and thus deserves very high security scrutiny. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4906.md b/EIPS/eip-4906.md new file mode 100644 index 00000000000000..8cd9b57407120c --- /dev/null +++ b/EIPS/eip-4906.md @@ -0,0 +1,7 @@ +--- +eip: 4906 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4906.md diff --git a/EIPS/eip-4907.md b/EIPS/eip-4907.md new file mode 100644 index 00000000000000..59a08349daa26a --- /dev/null +++ b/EIPS/eip-4907.md @@ -0,0 +1,7 @@ +--- +eip: 4907 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4907.md diff --git a/EIPS/eip-4910.md b/EIPS/eip-4910.md new file mode 100644 index 00000000000000..df0a7cb9a97ff1 --- /dev/null +++ b/EIPS/eip-4910.md @@ -0,0 +1,7 @@ +--- +eip: 4910 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4910.md diff --git a/EIPS/eip-4931.md b/EIPS/eip-4931.md new file mode 100644 index 00000000000000..479459fd3765bd --- /dev/null +++ b/EIPS/eip-4931.md @@ -0,0 +1,7 @@ +--- +eip: 4931 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4931.md diff --git a/EIPS/eip-4938.md b/EIPS/eip-4938.md new file mode 100644 index 00000000000000..fed17608d31f8a --- /dev/null +++ b/EIPS/eip-4938.md @@ -0,0 +1,52 @@ +--- +eip: 4938 +title: "eth/67 - Removal of GetNodeData" +description: "Remove GetNodeData and NodeData messages from the wire protocol" +author: Marius van der Wijden (@MariusVanDerWijden), Felix Lange , Gary Rong +discussions-to: https://ethereum-magicians.org/t/eip-4938-removal-of-getnodedata/8893 +status: Final +type: Standards Track +category: Networking +created: 2022-03-23 +requires: 2464, 2481 +--- + +## Abstract + +The [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md) defines request and response messages for exchanging data between clients. The `GetNodeData` request retrieves a set of trie nodes or contract code from the state trie by hash. We propose to remove the `GetNodeData` and `NodeData` messages from the wire protocol. + +## Motivation + +`GetNodeData` and `NodeData` were introduced in protocol version `eth/63` to allow for a sync mode called "fast sync", which downloads the Ethereum state without executing all blocks. The sync algorithm works by requesting all state trie nodes and contract codes by their hash. + +Serving `GetNodeData` requests requires clients to store state as a mapping of hashes to trie nodes. Avoiding the need to store such a mapping in the database is the main motivation for removing this request type. + +At this time, some client implementations cannot serve `GetNodeData` requests because they do not store the state in a compatible way. The Ethereum Wire Protocol should accurately reflect the capabilities of clients, and should not contain messages which are impossible to implement in some clients. + +## Specification + +Remove the following message types from the `eth` protocol: + +* `GetNodeData (0x0d)` + * **(eth/66)**: `[request_id: P, [hash_0: B_32, hash_1: B_32, ...]]` +* `NodeData (0x0e)` + * **(eth/66)**: `[request_id: P, [value_0: B, value_1: B, ...]]` + +## Rationale + +A replacement for `GetNodeData` is available in the [snap protocol](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/snap.md). Specifically, clients can use the [GetByteCodes](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/snap.md#getbytecodes-0x04) and [GetTrieNodes](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/snap.md#gettrienodes-0x06) messages instead of `GetNodeData`. The snap protocol can be used to implement the "fast sync" algorithm, though it is recommended to use it for "snap sync". + +## Backwards Compatibility + +This EIP changes the `eth` protocol and requires rolling out a new version, `eth/67`. Supporting multiple versions of a wire protocol is possible. Rolling out a new version does not break older clients immediately, since they can keep using protocol version `eth/66`. + +This EIP does not change consensus rules of the EVM and does not require a hard fork. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-4944.md b/EIPS/eip-4944.md new file mode 100644 index 00000000000000..54629461207dba --- /dev/null +++ b/EIPS/eip-4944.md @@ -0,0 +1,7 @@ +--- +eip: 4944 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4944.md diff --git a/EIPS/eip-4950.md b/EIPS/eip-4950.md new file mode 100644 index 00000000000000..4ea0a1fe066128 --- /dev/null +++ b/EIPS/eip-4950.md @@ -0,0 +1,7 @@ +--- +eip: 4950 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4950.md diff --git a/EIPS/eip-4955.md b/EIPS/eip-4955.md new file mode 100644 index 00000000000000..c1b433ff16912c --- /dev/null +++ b/EIPS/eip-4955.md @@ -0,0 +1,7 @@ +--- +eip: 4955 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4955.md diff --git a/EIPS/eip-4972.md b/EIPS/eip-4972.md new file mode 100644 index 00000000000000..4a7501934239cb --- /dev/null +++ b/EIPS/eip-4972.md @@ -0,0 +1,7 @@ +--- +eip: 4972 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4972.md diff --git a/EIPS/eip-4973.md b/EIPS/eip-4973.md new file mode 100644 index 00000000000000..47684e3c3913ee --- /dev/null +++ b/EIPS/eip-4973.md @@ -0,0 +1,7 @@ +--- +eip: 4973 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4973.md diff --git a/EIPS/eip-4974.md b/EIPS/eip-4974.md new file mode 100644 index 00000000000000..44ce64e47e8efe --- /dev/null +++ b/EIPS/eip-4974.md @@ -0,0 +1,7 @@ +--- +eip: 4974 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4974.md diff --git a/EIPS/eip-4987.md b/EIPS/eip-4987.md new file mode 100644 index 00000000000000..1677e968b51ebb --- /dev/null +++ b/EIPS/eip-4987.md @@ -0,0 +1,7 @@ +--- +eip: 4987 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4987.md diff --git a/EIPS/eip-5.md b/EIPS/eip-5.md index bb47fbe6d93009..8d3a8990b13726 100644 --- a/EIPS/eip-5.md +++ b/EIPS/eip-5.md @@ -2,11 +2,10 @@ eip: 5 title: Gas Usage for `RETURN` and `CALL*` author: Christian Reitwiessner -status: Superseded +status: Final type: Standards Track category: Core created: 2015-11-22 -superseded-by: 211 --- ### Abstract @@ -40,7 +39,7 @@ After the call, the `MSIZE` opcode should return the size the memory was actuall ### Motivation -In general, it is good practise to reserve a certain memory area for the output of a call, +In general, it is good practice to reserve a certain memory area for the output of a call, because letting a subroutine write to arbitrary areas in memory might be dangerous. On the other hand, it is often hard to know the output size of a call prior to performing the call: The data could be in the storage of another contract which is generally inaccessible and @@ -101,10 +100,10 @@ The change in semantics affects existing contracts in two ways: 1. Overlaps in allocated memory. By using `CALL`, a contract might have wanted to allocate a certain slice of memory, even if that is not written to by the called contract. Subsequent uses of `MSIZE` to allocate memory might overlap with this slice that is - now smaller than before the change. It is though unlikely that such contracts exist. + now smaller than before the change. It is, though, unlikely that such contracts exist. 2. Memory addresses change. Rather general, if memory is allocated using `MSIZE`, the - addresses of objects in memory will be different after the change. Contract should + addresses of objects in memory will be different after the change. Contracts should all be written in a way, though, such that objects in memory are _relocatable_, i.e. their absolute position in memory and their relative position to other objects does not matter. This is of course not the case for arrays, but they diff --git a/EIPS/eip-5000.md b/EIPS/eip-5000.md new file mode 100644 index 00000000000000..5a87df3a007544 --- /dev/null +++ b/EIPS/eip-5000.md @@ -0,0 +1,117 @@ +--- +eip: 5000 +title: MULDIV instruction +description: Introduce a new instruction to perform x * y / z in 512-bit precision +author: Harikrishnan Mulackal (@hrkrshnn), Alex Beregszaszi (@axic), Paweł Bylica (@chfast) +discussions-to: https://ethereum-magicians.org/t/muldiv-instruction/9930 +status: Stagnant +type: Standards Track +category: Core +created: 2022-03-14 +--- + +## Abstract + +Introduce a new instruction, `MULDIV(x, y, z)`, to perform `((x * y) / z) % 2**256` in 512-bit precision. `z = 0` is a special case for `(x * y) / 2**256`. + +## Motivation + +Fixed point operations in high level languages are very commonly used on Ethereum, especially in the domain of financial applications. + +While fixed point addition and subtraction can be done with merely `add` and `sub` respectively, being able to efficiently do fixedpoint multiplication and division is a very sought after feature. A commonly used workaround relies on a `mulmod`-based, rather complex implementation (taking around 50 instructions, excluding stack manipulation). This instruction reduces that to a single opcode. + +A secondary use case is likely in cryptographic applications, where the `muldiv` instruction allows full precision 256x256->512 multiplication. `mul(x y)` (or `muldiv(x, y, 1)`) computes the lower order 256 bits and `muldiv(x, y, 0)` computes the higher order 256 bits. + +Finally we aimed to provide an instruction which can be efficiently used both in *checked* and *unchecked arithmetic* use cases. By *checked* we mean to abort on conditions including division-by-zero and wrapping behaviour. + +## Specification + +A new instruction is introduced: `MULDIV` (`0x1e`). + +- Pops 3 values from the stack, first `x`, then `y` and `z`. +- If `z == 0`, `r = (uint512(x) * y) / 2**256`. +- Otherwise `r = (uint512(x) * y / z) % 2**256`, where the intermediate calculation is performed with 512-bit precision. +- Pushes `r` on the stack. + +```python +# operations `*` and `//` are done in 512 bit precision +def muldiv(x, y, z): + if z == 0: + return (x * y) // (2**256) + else: + return ((x * y) // z) % (2**256) +``` + +The cost of the instruction is 8 gas (aka `mid`), the same as for `addmod` and `mulmod`. + +## Rationale + +### The special 0 case + +All the arithmetic instructions in EVM handle division or modulo 0 specially: the instructions return 0. We have decided to break consistency in order to provide a flexible opcode, which can be used to detect wrapping behaviour. + +Alternate options include: + +- Returning a flag for wrapping +- Returning two stack items, higher and lower order bits +- Compute the higher order 256 bits in EVM: + +```solidity +/// Returns `hi` such that `x × y = hi × 2**256 + mul(x, y)` +function hob(uint x, uint y) returns (uint hi) { + uint uint_max = type(uint).max; + assembly { + let lo := mul(x, y) + let mm := mulmod(x, y, uint_max) + hi := sub(sub(mm, lo), lt(mm, lo)) + } +} +``` + +While this feature is clever and useful, callers must be aware that unlike other EVM instructions, passing 0 will have a vastly different behaviour. + +### Argument ordering + +The order of arguments matches `addmod` and `mulmod`. + +## Backwards Compatibility + +This is a new instruction not present prior. + +## Test Cases + +``` +PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +MULDIV +--- +0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +``` + + +``` +PUSH 0x0000000000000000000000000000000000000000000000000000000000000000 +PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +MULDIV +--- +0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe +``` + +``` +PUSH 0x0000000000000000000000000000000000000000000000000de0b6b3a7640000 +PUSH 0x000000000000000000000000000000000000000000000000016345785d8a0000 +PUSH 0x00000000000000000000000000000000000000000000d3c21bcecceda1000000 +MULDIV +--- +0x00000000000000000000000000000000000000000000152d02c7e14af6800000 +``` + +## Security Considerations + +TBA + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5003.md b/EIPS/eip-5003.md new file mode 100644 index 00000000000000..995c4a235a4c68 --- /dev/null +++ b/EIPS/eip-5003.md @@ -0,0 +1,89 @@ +--- +eip: 5003 +title: Insert Code into EOAs with AUTHUSURP +description: Allow migrating away from ECDSA by deploying code in place of an externally owned account. +author: Dan Finlay (@danfinlay), Sam Wilson (@SamWilsn) +discussions-to: https://ethereum-magicians.org/t/eip-5003-auth-usurp-publishing-code-at-an-eoa-address/8979 +status: Withdrawn +type: Standards Track +category: Core +created: 2022-03-26 +requires: 3074, 3607 +withdrawal-reason: Superseded by EIP-7702. +--- + +## Abstract + +This EIP introduces a new opcode, `AUTHUSURP`, which deploys code at an [EIP-3074](./eip-3074.md) authorized address. For externally owned accounts (EOAs), together with [EIP-3607](./eip-3607.md), this effectively revokes the original signing key's authority. + +## Motivation + +EOAs currently hold a significant amount of user-controlled value on Ethereum blockchains, but are limited by the protocol in a variety of critical ways. These accounts do not support rotating keys for security, batching to save gas, or sponsored transactions to reduce the need to hold ether yourself. There are countless other benefits that come from having a contract account or account abstraction, like choosing one's own authentication algorithm, setting spending limits, enabling social recovery, allowing key rotation, arbitrarily and transitively delegating capabilities, and just about anything else we can imagine. + +New users have access to these benefits using smart contract wallets, and new contracts can adopt recent standards to enable app-layer account abstraction (like [EIP-4337](./eip-4337.md)), but these would neglect the vast majority of existing Ethereum users' accounts. These users exist today, and they also need a path to achieving their security goals. + +Those added benefits would mostly come along with EIP-3074 itself, but with one significant shortcoming: the original signing key has ultimate authority for the account. While an EOA could delegate its authority to some _additional_ contract, the key itself would linger, continuing to provide an attack vector, and a constantly horrifying question lingering: have I been leaked? In other words, EIP-3074 can only grant authority to additional actors, but never revoke it. + +Today's EOAs have no option to rotate their keys. A leaked private key (either through phishing, or accidental access) cannot be revoked. A prudent user concerned about their key security might migrate to a new secret recovery phrase but at best this requires a transaction per asset (making it extremely expensive), and at worst, some powers (like hard-coded owners in a smart contract) might not be transferable at all. + +We know that EOAs cannot provide ideal user experience or safety, and there is a desire in the community to change the norm to contract-based accounts, but if that transition is designed without regard for the vast majority of users today—for whom Ethereum has always meant EOAs—we will be continually struggling against the need to support both of these userbases. This EIP provides a path not to enshrine EOAs, but to provide a migration path off of them, once and for all. + +This proposal combines well with, but is distinct from, [EIP-3074](./eip-3074.md), which provides opcodes that could enable any externally owned account (EOA) to delegate its signing authority to an arbitrary smart contract. It allows an EOA to authorize a contract account to act on its behalf _without forgoing its own powers_, while this EIP provides a final migration path off the EOA's original signing key. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. + +### Conventions + + - **`top - N`** - the `N`th most recently pushed value on the EVM stack, where `top - 0` is the most recent. + - **invalid execution** - execution that is invalid and must exit the current execution frame immediately, consuming all remaining gas (in the same way as a stack underflow or invalid jump). + - **empty account** - account where its balance is 0, its nonce is 0, and it has no code. + +### `AUTHUSURP` (`0xf8`) + +A new opcode `AUTHUSURP` shall be created at `0xf8`. It shall take two stack elements and return one stack element. + +#### Input + +| Stack | Value | +| --------- | ------------ | +| `top - 0` | `offset` | +| `top - 1` | `length` | + +#### Output + +| Stack | Value | +| ---------- | --------- | +| `top - 0` | `address` | + +#### Behavior + +`AUTHUSURP` behaves identically to `CREATE` (`0xf0`), except as described below: + + - If `authorized` (as defined in EIP-3074) is unset, execution is invalid. + - If `authorized` points to an empty account, then `static_gas` remains 32,000. Otherwise, `static_gas` shall be 7,000. + - `AUTHUSURP` does not check the nonce of the `authorized` account. + - The initcode runs at the address `authorized`. + - If the initcode returns no bytes, its execution frame must be reverted, and `AUTHUSURP` returns zero. + - After executing the initcode, but before the returned code is deployed, if the account's code is non-empty, the initcode's execution frame must be reverted, and `AUTHUSURP` returns zero. + - The code is deployed into the account with the address `authorized`. + +## Rationale + +`AUTHUSURP` does not check the nonce of the `authorized` account because it must work with accounts that have previously sent transactions. + +When using `AUTHUSURP`, if the initcode were to deploy a zero-length contract, there would be no way to prevent using `AUTHUSURP` again later. + +The account's code must be checked immediately before deploying to catch the situation where the initcode attempts to `AUTHUSURP` at the same address. This is unnecessary with other deployment instructions because they increment and check the account's nonce. + +## Backwards Compatibility + +`AUTHUSURP` with EIP-3607 revokes the authority of the original ECDSA signature to send transactions from the account. This is completely new behavior, although it is somewhat similar to the `CREATE2` opcode. + +## Security Considerations + +Contracts using ECDSA signatures outside of transactions will not be aware that the usurped account is no longer controlled by a private key. This means that, for example, the private key will _always_ have access to the `permit` function on token contracts. This can—and should—be mitigated by modifying the `ecrecover` pre-compiled contract. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5005.md b/EIPS/eip-5005.md new file mode 100644 index 00000000000000..7accb63abae1da --- /dev/null +++ b/EIPS/eip-5005.md @@ -0,0 +1,7 @@ +--- +eip: 5005 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5005.md diff --git a/EIPS/eip-5006.md b/EIPS/eip-5006.md new file mode 100644 index 00000000000000..7780c11e3eacce --- /dev/null +++ b/EIPS/eip-5006.md @@ -0,0 +1,7 @@ +--- +eip: 5006 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5006.md diff --git a/EIPS/eip-5007.md b/EIPS/eip-5007.md new file mode 100644 index 00000000000000..f3125d18516401 --- /dev/null +++ b/EIPS/eip-5007.md @@ -0,0 +1,7 @@ +--- +eip: 5007 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5007.md diff --git a/EIPS/eip-5008.md b/EIPS/eip-5008.md new file mode 100644 index 00000000000000..8d6d0347cf4b45 --- /dev/null +++ b/EIPS/eip-5008.md @@ -0,0 +1,7 @@ +--- +eip: 5008 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5008.md diff --git a/EIPS/eip-5018.md b/EIPS/eip-5018.md new file mode 100644 index 00000000000000..603e39911cd48a --- /dev/null +++ b/EIPS/eip-5018.md @@ -0,0 +1,7 @@ +--- +eip: 5018 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5018.md diff --git a/EIPS/eip-5022.md b/EIPS/eip-5022.md new file mode 100644 index 00000000000000..da2180c4e28622 --- /dev/null +++ b/EIPS/eip-5022.md @@ -0,0 +1,67 @@ +--- +eip: 5022 +title: Increase price of SSTORE from zero to non-zero to 40k gas +author: Green (@greenlucid) +status: Stagnant +type: Standards Track +category: Core +created: 2022-04-20 +discussions-to: https://ethereum-magicians.org/t/eip-proposal-increase-cost-of-sstore-from-20k-to-x-when-creating-new-storage/7614 +--- + +### Abstract + +Increase the price of the SSTORE opcode from `20_000` gas to `40_000` gas when the original slot is zero and the resultant slot is non-zero. + +### Motivation + +The cost of creating a piece of new state increases as state is larger. However, the price for creating every new storage slot has not increased. +All resources are merged into the same pricing mechanism. If the price for creating new storage slots is fixed, then it needs to be manually changed. + +One of the main reasons for not increasing gas limit is the increase of state. In that regard, because the cost of creating storage is higher than its price, all the users of all the other opcodes are subsidizing the creation of state. If state creation was more precisely priced, raising gas limit would be more feasible, and would benefit the users. + +## Rationale + +### Why not also raise the cost of non-zero to non-zero? + +Rewriting storage does not affect state growth, which is the main issue this EIP is addressing. Rewriting storage may also be underpriced. +Increasing the price of state growth will, at least, incentivize developers to reuse storage instead. + +### Why not also increase the gas refund from setting non-zero to zero? + +More discussion is needed on this. + +### Why not a better state solution? + +Whereas solutions like state rent, or state expiry have been researched for a long time, they will not be ready on the short to medium term. So, it is desirable to patch pricing for the short term. Opcode repricing has been done before, so it should not impose a large development time investment for clients. + +### Why was that specific amount chosen? + +The current pricing was made off a naive approach of benchmarking opcodes in a laptop. Not only it did not consider the long term problem of having the same price for a resource that costs more over time, the benchmark itself was wrong. This price is closer to what the naive original benchmark should have been. It could go higher, but that may be too disruptive. + +### Is this too disruptive? + +This change will severely impact the gas cost of many applications. The network does not have to subsidize state growth at the expense of more expensive regular transactions, so even if it is too disruptive, it will increase the health of the network. + +### Specification + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | TBD | +| `NEW_STORAGE_PRICE` | `40_000` + +For blocks where `block.number >= FORK_BLOCK`, a new gas schedule applies. Make `SSTORE_SET_GAS`, the price when a slot is set from zero to non-zero, equal `NEW_STORAGE_PRICE`. All other costs remain the same. + +### Backwards compatibility + +Contracts that depend on hardcoded gas costs will break if they create state. + +It is a gas schedule change, so transactions from an epoch before FORK_BLOCK should be treated with previous gas costs. + +## Implementation + +https://github.com/ethereum/go-ethereum/pull/24725 + +## Security considerations + +TODO diff --git a/EIPS/eip-5023.md b/EIPS/eip-5023.md new file mode 100644 index 00000000000000..5f6ade7fc343bd --- /dev/null +++ b/EIPS/eip-5023.md @@ -0,0 +1,7 @@ +--- +eip: 5023 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5023.md diff --git a/EIPS/eip-5027.md b/EIPS/eip-5027.md new file mode 100644 index 00000000000000..279c8f7f8bd2cb --- /dev/null +++ b/EIPS/eip-5027.md @@ -0,0 +1,94 @@ +--- +eip: 5027 +title: Remove the limit on contract code size +description: Change the limit on contract size from 24576 to infinity +author: Qi Zhou (@qizhou) +discussions-to: https://ethereum-magicians.org/t/eip-5027-unlimit-contract-code-size/9010 +status: Stagnant +type: Standards Track +category: Core +created: 2022-04-21 +requires: 170, 2929, 2930 +--- + + +## Abstract + +Remove the limit on the contract code size, i.e., only limit the contract code size by block gas limit, with minimal changes to existing code and proper gas metering adjustment to avoid possible attacks. + + +## Motivation + +The motivation is to remove the limit on the code size so that users can deploy a large-code contract without worrying about splitting the contract into several sub-contracts. + +With the dramatic growth of dApplications, the functionalities of smart contracts are becoming more and more complicated, and thus, the sizes of newly developed contracts are steadily increasing. As a result, we are facing more and more issues with the 24576-bytes contract size limit. Although several techniques such as splitting a large contract into several sub-contracts can alleviate the issue, these techniques inevitably increase the burden of developing/deploying/maintaining smart contracts. + +The proposal implements a solution to remove the existing 24576-bytes limit of the code size. Further, the proposal aims to minimize the changes in the client implementation (e.g., Geth) with +- proper gas metering to avoid abusing the node resources for contract-related opcodes, i.e, `CODESIZE (0x38)/CODECOPY (0x39)/EXTCODESIZE (0x3B)/EXTCODECOPY (0x3C)/EXTCODEHASH (0x3F)/DELEGATECALL (0xF4)/CALL (0xF1)/CALLCODE (0xF2)/STATICCALL (0xFA)/CREATE (0xF0)/CREATE2 (0xF5)`; and +- no change to the existing structure of the Ethereum state. + + +## Specification + +### Parameters + +| Constant | Value | +| ------------------------- | ---------------- | +| `FORK_BLKNUM` | TBD | +| `CODE_SIZE_UNIT` | 24576 | +| `COLD_ACCOUNT_CODE_ACCESS_COST_PER_UNIT` | 2600 | +| `CREATE_DATA_GAS` | 200 | + +If `block.number >= FORK_BLKNUM`, the contract creation initialization can return data with any length, but the contract-related opcodes will take extra gas as defined below: + +- For `CODESIZE/CODECOPY/EXTCODESIZE/EXTCODEHASH`, the gas is unchanged. + +- For CREATE/CREATE2, if the newly created contract size > `CODE_SIZE_UNIT`, the opcodes will take extra write gas as + +`(CODE_SIZE - CODE_SIZE_UNIT) * CREATE_DATA_GAS`. + +- For `EXTCODECOPY/CALL/CALLCODE/DELEGATECALL/STATICCALL`, if the contract code size > `CODE_SIZE_UNIT`, then the opcodes will take extra gas as + +``` +(CODE_SIZE - 1) // CODE_SIZE_UNIT * COLD_ACCOUNT_CODE_ACCESS_COST_PER_UNIT +``` + +if the contract is not in `accessed_code_in_addresses` or `0` if the contract is in `accessed_code_in_addresses`, where `//` is the integer divide operator, and `accessed_code_in_addresses: Set[Address]` is a transaction-context-wide set similar to `access_addresses` and `accessed_storage_keys`. + +When a transaction execution begins, `accessed_code_in_addresses` will include `tx.sender`, `tx.to`, and all precompiles. + +When `CREATE/CREATE2/EXTCODECOPY/CALL/CALLCODE/DELEGATECALL/STATICCALL` is called, immediately add the address to `accessed_code_in_addresses`. + +## Rationale + +### Gas Metering +The goal is to measure the CPU/IO cost of the contract read/write operations reusing existing gas metering so that the resources will not be abused. + +- For code-size-related opcodes (`CODESIZE`/`EXTCODESIZE`), we would expect the client to implement a mapping from the hash of code to the size, so reading the code size of a large contract should still be O(1). + +- For `CODECOPY`, the data is already loaded in memory (as part of `CALL/CALLCODE/DELEGATECALL/STATICCALL`), so we do not charge extra gas. + +- For `EXTCODEHASH`, the value is already in the account, so we do not charge extra gas. + +- For `EXTCODECOPY/CALL/CALLCODE/DELEGATECALL/STATICCALL`, since it will read extra data from the database, we will additionally charge `COLD_ACCOUNT_CODE_ACCESS_COST_PER_UNIT` per extra `CODE_SIZE_UNIT`. + +- For `CREATE/CREATE2`, since it will create extra data to the database, we will additionally charge `CREATE_DATA_GAS` per extra bytes. + + +## Backwards Compatibility + +All existing contracts will not be impacted by the proposal. + +Only contracts deployed before [EIP-170](./eip-170.md) could possibly be longer than the current max code size, and the reference implementation was able to successfully import all blocks before that fork. + +## Reference Implementation + +The reference implementation on Geth is available at [0001-unlimit-code-size.patch](../assets/eip-5027/0001-unlimit-code-size.patch). + +## Security Considerations +TBD + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). + + diff --git a/EIPS/eip-5050.md b/EIPS/eip-5050.md new file mode 100644 index 00000000000000..677c5c3223f3c7 --- /dev/null +++ b/EIPS/eip-5050.md @@ -0,0 +1,7 @@ +--- +eip: 5050 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5050.md diff --git a/EIPS/eip-5058.md b/EIPS/eip-5058.md new file mode 100644 index 00000000000000..568d58249c290d --- /dev/null +++ b/EIPS/eip-5058.md @@ -0,0 +1,7 @@ +--- +eip: 5058 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5058.md diff --git a/EIPS/eip-5065.md b/EIPS/eip-5065.md new file mode 100644 index 00000000000000..9aab276bd2b6ac --- /dev/null +++ b/EIPS/eip-5065.md @@ -0,0 +1,53 @@ +--- +eip: 5065 +title: Instruction for transferring ether +description: Instruction for just transferring ether without transferring the flow of execution +author: Mudit Gupta (@maxsam4) +discussions-to: https://ethereum-magicians.org/t/eip-5065-instruction-for-transferring-ether/9107 +status: Stagnant +type: Standards Track +category: Core +created: 2022-04-30 +requires: 2929 +--- + +## Abstract +Add a new instruction that transfers ether to a destination address without handing over the flow of execution to it. It should work similarly to how `SELFDESTRUCT (0xFF)` transfers ether to the destination without making a call to it. + +## Motivation +From an architectural point of view, execution flow should never be handed over to an untrusted contract. Ethereum currently does not have any ideal way to transfer ether without transferring the flow of execution. People have come up with reentrancy guards and similar solutions to prevent some types of attacks but it's not an ideal solution. The only way to transfer ether from smart contracts without triggering a call is to create a dummy contract, send the precise amount of ether to it and then call `SELFDESTRUCT (0xFF)` from it. + +## Specification +Introduce a new instruction, `AIRDROP` (`0xFG`) that transfers ether to the destination without making a call to it. + +### Stack input +address: the account to send ether to. +value: value in wei to send to the account. + +### Gas + +The total gas cost should be the sum of a static cost + address_access_cost + value_to_empty_account_cost. + - Static cost: 6700 + - Dynamic cost: + 1. address_access_cost: If the target is not in `accessed_addresses`, charge `COLD_ACCOUNT_ACCESS_COST` gas, and add the address to `accessed_addresses`. Otherwise, charge `WARM_STORAGE_READ_COST` gas. Currently, `COLD_ACCOUNT_ACCESS_COST` is 2600 while `WARM_STORAGE_READ_COST` is 100. + 2. value_to_empty_account_cost: If value is not 0 and the address given points to an empty account, then value_to_empty_account_cost is the account creation gas cost which currently is 25000. An account is empty if its balance is 0, its nonce is 0 and it has no code. + + +## Rationale +This behavior is already possible by deploying a new contract that does `SELFDESTRUCT (0xFF)` but it is prohibitively expensive. In most scenarios, the contract author only wants to transfer ether rather than transferring control of the execution. ERC20 can be used as a case study for this where most users transfer funds without a post-transfer hook. + +This instruction allows contracts to safely pass ether to an untrusted address without worrying about reentrancy or other malicious things an untrusted contract can do on. + +The static gas cost is derived by subtracting the gas stipend (2300) from the positive_value_cost of `CALL (0xF1)` opcode which is currently set to 9000. + +## Backwards Compatibility +No known issues as this is a new instruction that does not affect any old instructions and does not break any valid assumptions since it make not anything impossible possible. + +## Test Cases +TODO + +## Security Considerations +No known security risks. + +## Copyright +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/EIPS/eip-5069.md b/EIPS/eip-5069.md new file mode 100644 index 00000000000000..0e37f8f230d25c --- /dev/null +++ b/EIPS/eip-5069.md @@ -0,0 +1,119 @@ +--- +eip: 5069 +title: EIP Editor Handbook +description: Organizational structure, decision making process, and other EIP Editor odds and ends. +author: Pooja Ranjan (@poojaranjan), Gavin John (@Pandapip1), Sam Wilson (@SamWilsn), et al. +discussions-to: https://ethereum-magicians.org/t/pr-5069-eip-editor-handbook/9137 +status: Living +type: Meta +created: 2022-05-02 +requires: 1 +--- + +## Introduction + +We, the Ethereum Improvement Proposal (EIP) Editors, maintain a repository of documents related to the Ethereum protocol and its ecosystem. Consider us both _archivists_ making sure the community as a whole does not lose its history, and a _publisher_ making sure interested parties can stay up-to-date with the latest proposals. + +## Mission + +### What we Do + +Our mission is to serve the broad Ethereum community, both present and future, by: + + - **Publishing Proposals**: Making proposals, including their history and associated discussions available over the long term at no cost. + + By doing so, we foster transparency and ensure that valuable insights from past proposals are accessible for future decision-making and learning. + - **Facilitating Discussion**: Providing a forum for discussing proposals open to anyone who wants to participate civilly. + + By encouraging open dialogue and collaboration, we aim to harness the collective knowledge and expertise of the Ethereum community in shaping proposals. + - **Upholding Quality**: Upholding a measure of minimally-subjective quality for each proposal as defined by its target audience. + + By adhering to defined criteria, we promote the development of high-quality and relevant proposals that drive the evolution of Ethereum. + +### What we Don't + +On the other hand, we do _not_: + + - **Decide Winners**: If there are multiple competing proposals, we will publish all of them. We are not in the business of deciding what is the right path for Ethereum, nor do we believe that there is One True Way to satisfy a need. + + - **Assert Correctness**: While we might offer technical feedback from time to time, we are not experts nor do we vet every proposal in depth. Publishing a proposal is not an endorsement or a statement of technical soundness. + + - **Manage**: We do not track implementation status, schedule work, or set fork dates or contents. + + - **Track Registries**: We want all proposals to eventually become immutable, but a registry will never get there if anyone can keep adding items. To be clear, exhaustive and/or static lists are fine. + - **Provide Legal Advice**: Trademarks, copyrights, patents, prior art, and other legal matters are the responsibility of authors and implementers, not EIP Editors. We are not lawyers, and while we may occasionally make comments touching on these areas, we cannot guarantee any measure of correctness. + +Documenting all of the things we would not do is impossible, and the above are just a few examples. We reserve the right to do less work whenever possible! + +## Structure + +### EIP Editors + +We, the Editors, consist of some number of EIP Editors and one Keeper of Consensus (or just Keeper for short) elected by and from the EIP Editors. + +EIP Editors are responsible for governing the EIP process itself, electing a Keeper, and stewarding proposals. + +The Keeper's two responsibilities (on top of their EIP Editor duties) are: to determine when rough consensus has been reached on a matter, and determine when/if it is appropriate to re-open an already settled matter. + +## Membership + +Anyone may apply to join as an EIP Editor. Specific eligibility requirements are left to individual current EIP Editors, but the general requirements are: + + - A strong belief in the above mission; + - Proficiency with English (both written and spoken); + - Reading and critiquing EIPs; + - Participation in governance. + +EIP Editors are expected to meet these requirements throughout their tenure, and not doing so is grounds for removal. Any member may delegate some or all of their responsibilities/powers to tools and/or to other people. + +## Making Decisions + +### Informally + +For decisions that are unlikely to be controversial—especially for decisions affecting a single proposal—an EIP Editor may choose whatever option they deem appropriate in accordance with our mission. + +### Formally + +Electing a Keeper, adding/removing EIP Editors, and any possibly-controversial decisions must all be made using variations of this formal process. + +#### Preparation + +##### Call for Input + +For any matter requiring a decision, a call for input must be published in writing to the usual channels frequented by EIP Editors. + +##### Quorum + +Within thirty days of the call for input, to establish a valid quorum, all EIP Editors must express their opinion, vote (where appropriate), or lack thereof on the matter under consideration. + +After thirty days from the call for input, if not all EIP Editors have responded, the quorum is reduced to the Editors that have responded. This deadline may be extended in exceptional situations. + +#### Deciding + +##### Electing a Keeper of Consensus + +Any EIP Editor can call for an election for Keeper. Business continues as usual while the election is running. The EIP Editor with the most votes once quorum is met is named Keeper until the next election completes. If there is a tie, we'll randomly choose between the EIP Editors with the most votes, using a fair and agreed upon method (for example, a coin toss over a video call or a commit/reveal game of rock paper scissors.) + +##### Adding an EIP Editor + +An EIP Editor is added once quorum is met, provided the candidate consents and no current EIP Editor objects. + +##### Removing an EIP Editor + +An EIP Editor is involuntarily retired once quorum is met, provided no current EIP Editor (aside from the one being removed) objects. An EIP Editor may voluntarily leave their position at any time. + +If the departing Editor was also the Keeper, an election for a new Keeper begins immediately. + +##### Other Decisions + +All other decisions are made through a "rough consensus" process. This does not require all EIP Editors to agree, although this is preferred. In general, the dominant view of the Editors shall prevail. Dominance, in this process, is not determined by persistence or volume but rather a more general sense of agreement. Note that 51% does not mean "rough consensus" has been reached, and 99% is better than rough. It is up to the Keeper to determine if rough consensus has been reached. Every EIP Editor is entitled to have their opinion heard and understood before the Keeper makes that determination. + +No one, not the EIP Editors and certainly not the Keeper, holds veto powers (except when adding/removing an Editor as defined above.) It is imperative that the EIP process evolve, albeit cautiously. + +_This section has been adapted from [RFC 2418]._ + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + +[RFC 2418]: https://www.rfc-editor.org/rfc/rfc2418 diff --git a/EIPS/eip-5081.md b/EIPS/eip-5081.md new file mode 100644 index 00000000000000..bbf80e25ca63ec --- /dev/null +++ b/EIPS/eip-5081.md @@ -0,0 +1,91 @@ +--- +eip: 5081 +title: Expirable Transaction +description: This EIP adds a new transaction type of that includes expiration with a blocknum +author: Zainan Victor Zhou (@xinbenlv), Nick Johnson (@Arachnid), Konrad Feldmeier +discussions-to: https://ethereum-magicians.org/t/eip-5081-expirable-transaction/9208 +status: Stagnant +type: Standards Track +category: Core +created: 2022-05-06 +requires: 155, 1559, 2718, 2929, 2930 +--- + +## Abstract +This EIP adds a new transaction type of that includes expiration with a blocknum. + +## Motivation + +When a user sends a transaction `tx0` with a low gas price, sometimes it might not be high enough to be executed. +A common resolution is for the user to submit the transaction again with the same nonce and higher gas price. + +That previous `tx0` can theoretically be included in any time in the future unless a `tx` with the exact same nonce is already executed. + +When network is congested, gas price are high, for critical transactions user might try gas price that is much higher than an average day. +This cause the `tx0` choice might be very easy to executed in the average day. + +If user already uses a `tx1` with different nonce or from another account to execute the intended transaction, +there is currently no clean way to cancel it, +except for signing a new `tx0'` that shares the same nonce but with higher gas fee hoping that it will execute to *preempt*- than `tx0`. + +Given `tx0` was already high gas price, the current way of *preempting* `tx0` could be both unreliable and very costly. + +TODO(@xinbenlv): to include in the motivation: + +- Expiring transactions are transactions that have low time preference, but can easily become invalid in the future. For example, you may want to do a swap on an AMM but you don't want to pay a very high fee for it so you set the max fee to a low number. However, your transaction will almost certainly fail if it takes longer than a couple minutes to be mined. In this scenario, you would rather fail cheaply if your transaction doesn't get included quickly. + +- Similarly, there are situations where there is a limited window of availability of some asset and if your transaction doesn't mine within that period you know with certainty that it will fail. In these cases, it would be nice to be able to express that to the system and not waste unnecessary resources just to have the transaction fail. + +## Specification +The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. + +### Parameters +- `FORK_BLKNUM` = `TBD` +- `CHAIN_ID` = `TBD` +- `TX_TYPE` = TBD, > 0x02 ([EIP-1559](./eip-1559.md)) + + +As of `FORK_BLOCK_NUMBER`, a new [EIP-2718](./eip-2718.md) transaction is introduced with `TransactionType` = `TX_TYPE(TBD)`. + +The intrinsic cost of the new transaction is inherited from [EIP-2930](./eip-2930.md), specifically `21000 + 16 * non-zero calldata bytes + 4 * zero calldata bytes + 1900 * access list storage key count + 2400 * access list address count`. + +The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is + +``` +rlp([chain_id, expire_by, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list, signature_y_parity, signature_r, signature_s]) +``` + +The definition of `expire_by` is a block number the latest possible block to +execute this transaction. Any block with a block number `block_num > expire_by` MUST NOT execute this transaction. + +The definitions of all other fields share the same meaning with [EIP-1559](./eip-1559.md) + +The `signature_y_parity, signature_r, signature_s` elements of this transaction represent a secp256k1 signature over `keccak256(0x02 || rlp([chain_id, expire_by, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list]))`. + +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. + + +## Rationale +TODO + +## Backwards Compatibility +TODO + +## Security Considerations + +1. If `current_block_num` is available, client MUST drop and stop propagating/broadcasting any transactions that has a +`transaction_type == TX_TYPE` AND `current_block_num > expire_by` + +2. It is suggested but not required that a `currentBlockNum` SHOULD be made available to client. Any client doing PoW calculation on blocks expire tx or propagating such are essentially penalized for wasting of work, mitigating possible denial of service attack. + +3. It is suggested but not required that client SHOULD introduce a +`gossip_ttl` in unit of block_num as a safe net so that it only propagate +a tx if `current_block_num + gossip_ttl <= expire_by`. Backward compatibility: +for nodes that doesn't have `current_block_num` or `gossip_ttl` available, +they should be presumed to be `0`. + +4. It is suggested by not required that any propagating client SHOULD properly deduct the `gossip_ttl` +based on the network environment it sees fit. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5094.md b/EIPS/eip-5094.md new file mode 100644 index 00000000000000..3bbbc02603efb5 --- /dev/null +++ b/EIPS/eip-5094.md @@ -0,0 +1,7 @@ +--- +eip: 5094 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5094.md diff --git a/EIPS/eip-5095.md b/EIPS/eip-5095.md new file mode 100644 index 00000000000000..6fc5b3ca5361b7 --- /dev/null +++ b/EIPS/eip-5095.md @@ -0,0 +1,7 @@ +--- +eip: 5095 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5095.md diff --git a/EIPS/eip-5114.md b/EIPS/eip-5114.md new file mode 100644 index 00000000000000..79c5a50e50faa7 --- /dev/null +++ b/EIPS/eip-5114.md @@ -0,0 +1,7 @@ +--- +eip: 5114 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5114.md diff --git a/EIPS/eip-5115.md b/EIPS/eip-5115.md new file mode 100644 index 00000000000000..bf95b31278dc77 --- /dev/null +++ b/EIPS/eip-5115.md @@ -0,0 +1,7 @@ +--- +eip: 5115 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5115.md diff --git a/EIPS/eip-5131.md b/EIPS/eip-5131.md new file mode 100644 index 00000000000000..b6e1f6590301a3 --- /dev/null +++ b/EIPS/eip-5131.md @@ -0,0 +1,7 @@ +--- +eip: 5131 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5131.md diff --git a/EIPS/eip-5133.md b/EIPS/eip-5133.md new file mode 100644 index 00000000000000..ffc3e7f4cc48b8 --- /dev/null +++ b/EIPS/eip-5133.md @@ -0,0 +1,59 @@ +--- +eip: 5133 +title: Delaying Difficulty Bomb to mid-September 2022 +description: Delays the difficulty bomb by a further 700000 blocks, to the middle of September 2022. +author: Tomasz Kajetan Stanczak (@tkstanczak), Eric Marti Haynes (@ericmartihaynes), Josh Klopfenstein (@joshklop), Abhimanyu Nag (@AbhiMan1601) +discussions-to: https://ethereum-magicians.org/t/eip-5133-delaying-difficulty-bomb-to-mid-september-2022/9622 +status: Final +type: Standards Track +category: Core +created: 2022-06-01 +--- + +## Abstract +Starting with `FORK_BLOCK_NUMBER` the client will calculate the difficulty based on a fake block number suggesting to the client that the difficulty bomb is adjusting 11,400,000 blocks later than the actual block number. + +## Motivation +To avoid network degradation due to a premature activation of the difficulty bomb. + +## Specification +#### Relax Difficulty with Fake Block Number +For the purposes of `calc_difficulty`, simply replace the use of `block.number`, as used in the exponential ice age component, with the formula: +```py +fake_block_number = max(0, block.number - 11_400_000) if block.number >= FORK_BLOCK_NUMBER else block.number +``` +## Rationale + +The following script predicts the bomb will go off at block 15530314, which is expected to be mined around mid-September. + +```python +import math +def predict_bomb_block(current_difficulty, diff_adjust_coeff, block_adjustment): + ''' + Predicts the block number at which the difficulty bomb will become noticeable. + + current_difficulty: the current difficulty + diff_adjust_coeff: intuitively, the percent increase in work that miners have to exert to find a PoW + block_adjustment: the number of blocks to delay the bomb by + ''' + return round(block_adjustment + 100000 * (2 + math.log2(diff_adjust_coeff * current_difficulty // 2048))) + +# current_difficulty = 13891609586928851 (Jun 01, 2022) +# diff_adjust_coeff = 0.1 (historically, the bomb is noticeable when the coefficient is >= 0.1) +# block_adjustment = 11400000 +print(predict_bomb_block(13891609586928851, 0.1, 11400000)) +``` + +Precise increases in block times are very difficult to predict (especially after the bomb is noticeable). +However, based on past manifestations of the bomb, we can anticipate 0.1s delays by mid-September and 0.6-1.2s delays by early October. + +## Backwards Compatibility +No known backward compatibility issues. + +## Security Considerations +Misjudging the effects of the difficulty can mean longer blocktimes than anticipated until a hardfork is released. Wild shifts in difficulty can affect this number severely. Also, gradual changes in blocktimes due to longer-term adjustments in difficulty can affect the timing of difficulty bomb epochs. This affects the usability of the network but unlikely to have security ramifications. + +In this specific instance, it is possible that the network hashrate drops considerably before The Merge, which could accelerate the timeline by which the bomb is felt in block times. The offset value chosen aims to take this into account. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5139.md b/EIPS/eip-5139.md new file mode 100644 index 00000000000000..986243b12e3e38 --- /dev/null +++ b/EIPS/eip-5139.md @@ -0,0 +1,7 @@ +--- +eip: 5139 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5139.md diff --git a/EIPS/eip-5143.md b/EIPS/eip-5143.md new file mode 100644 index 00000000000000..4801b06b35ff4c --- /dev/null +++ b/EIPS/eip-5143.md @@ -0,0 +1,7 @@ +--- +eip: 5143 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5143.md diff --git a/EIPS/eip-5164.md b/EIPS/eip-5164.md new file mode 100644 index 00000000000000..90463ae650de76 --- /dev/null +++ b/EIPS/eip-5164.md @@ -0,0 +1,7 @@ +--- +eip: 5164 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5164.md diff --git a/EIPS/eip-5169.md b/EIPS/eip-5169.md new file mode 100644 index 00000000000000..a2b2997a9ed3b6 --- /dev/null +++ b/EIPS/eip-5169.md @@ -0,0 +1,7 @@ +--- +eip: 5169 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5169.md diff --git a/EIPS/eip-5173.md b/EIPS/eip-5173.md new file mode 100644 index 00000000000000..0320897356e19a --- /dev/null +++ b/EIPS/eip-5173.md @@ -0,0 +1,7 @@ +--- +eip: 5173 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5173.md diff --git a/EIPS/eip-5185.md b/EIPS/eip-5185.md new file mode 100644 index 00000000000000..525124d9400dcc --- /dev/null +++ b/EIPS/eip-5185.md @@ -0,0 +1,7 @@ +--- +eip: 5185 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5185.md diff --git a/EIPS/eip-5187.md b/EIPS/eip-5187.md new file mode 100644 index 00000000000000..d4905de87b3a80 --- /dev/null +++ b/EIPS/eip-5187.md @@ -0,0 +1,7 @@ +--- +eip: 5187 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5187.md diff --git a/EIPS/eip-5189.md b/EIPS/eip-5189.md new file mode 100644 index 00000000000000..c077cfb4fe7f38 --- /dev/null +++ b/EIPS/eip-5189.md @@ -0,0 +1,7 @@ +--- +eip: 5189 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5189.md diff --git a/EIPS/eip-5192.md b/EIPS/eip-5192.md new file mode 100644 index 00000000000000..d359d2343d5c6f --- /dev/null +++ b/EIPS/eip-5192.md @@ -0,0 +1,7 @@ +--- +eip: 5192 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5192.md diff --git a/EIPS/eip-5202.md b/EIPS/eip-5202.md new file mode 100644 index 00000000000000..a91ed535bbce97 --- /dev/null +++ b/EIPS/eip-5202.md @@ -0,0 +1,7 @@ +--- +eip: 5202 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5202.md diff --git a/EIPS/eip-5216.md b/EIPS/eip-5216.md new file mode 100644 index 00000000000000..70a3f279d40a93 --- /dev/null +++ b/EIPS/eip-5216.md @@ -0,0 +1,7 @@ +--- +eip: 5216 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5216.md diff --git a/EIPS/eip-5218.md b/EIPS/eip-5218.md new file mode 100644 index 00000000000000..20c14cd8a73e6c --- /dev/null +++ b/EIPS/eip-5218.md @@ -0,0 +1,7 @@ +--- +eip: 5218 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5218.md diff --git a/EIPS/eip-5219.md b/EIPS/eip-5219.md new file mode 100644 index 00000000000000..0fc809df47fd20 --- /dev/null +++ b/EIPS/eip-5219.md @@ -0,0 +1,7 @@ +--- +eip: 5219 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5219.md diff --git a/EIPS/eip-5247.md b/EIPS/eip-5247.md new file mode 100644 index 00000000000000..b16f5d4602a906 --- /dev/null +++ b/EIPS/eip-5247.md @@ -0,0 +1,7 @@ +--- +eip: 5247 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5247.md diff --git a/EIPS/eip-5252.md b/EIPS/eip-5252.md new file mode 100644 index 00000000000000..c2eaacf9529487 --- /dev/null +++ b/EIPS/eip-5252.md @@ -0,0 +1,7 @@ +--- +eip: 5252 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5252.md diff --git a/EIPS/eip-5267.md b/EIPS/eip-5267.md new file mode 100644 index 00000000000000..44c2f824c79f7f --- /dev/null +++ b/EIPS/eip-5267.md @@ -0,0 +1,7 @@ +--- +eip: 5267 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5267.md diff --git a/EIPS/eip-5269.md b/EIPS/eip-5269.md new file mode 100644 index 00000000000000..2dc062e47ebe50 --- /dev/null +++ b/EIPS/eip-5269.md @@ -0,0 +1,7 @@ +--- +eip: 5269 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5269.md diff --git a/EIPS/eip-5283.md b/EIPS/eip-5283.md new file mode 100644 index 00000000000000..d8c5a14dbcb5da --- /dev/null +++ b/EIPS/eip-5283.md @@ -0,0 +1,108 @@ +--- +eip: 5283 +title: Semaphore for Reentrancy Protection +description: A Precompile-based parallelizable reentrancy protection using the call stack +author: Sergio D. Lerner (@SergioDemianLerner) +discussions-to: https://ethereum-magicians.org/t/eip-5283-a-semaphore-for-parallelizable-reentrancy-protection/10236 +status: Stagnant +type: Standards Track +category: Core +created: 2022-07-17 +requires: 20, 1283, 1352 +--- + +## Abstract + +This EIP proposes adding a precompiled contract that provides a semaphore function for creating a new type of reentrancy protection guard (RPG). This function aims to replace the typical RPG based on modifying a contract storage cell. The benefit is that the precompile-based RPG does not write to storage, and therefore it enables contracts to be forward-compatible with all designs that provide fine-grained (i.e. cell level) parallelization for the multi-threaded execution of EVM transactions. + +## Motivation + +The typical smart contract RPG uses a contract storage cell. The algorithm is simple: the code checks that a storage cell is 0 (or any other predefined constant) on entry, aborting if not, and then sets it to 1. After executing the required code, it resets the cell back to 0 before exiting. This is the algorithm implemented in OpenZeppelin's ReentrancyGuard. The algorithm results in a read-write pattern on the RPG's storage cell. This pattern prevents the parallelization of the execution of the smart contract for all known designs that try to provide fine-grained parallelization (detecting conflicts at the storage cell level). + +Several EVM-based blockchains have successfully tested designs for the parallelization of the EVM. The best results have been obtained with fine-grained parallelization where conflicts are detected by tracking writes and reads of individual storage cells. The designs based on tracking the use of accounts or contracts provide only minor benefits because most transactions use the same [EIP-20](./eip-20.md) contracts. + +To summarize, the only available RPG construction today is based on using a contract storage cell. This construction is clean but it is not forward-compatible with transaction execution parallelization. + +## Specification + +Starting from an activation block (TBD) a new precompiled contract `Semaphore` is created at address `0x0A`. When `Semaphore` is called, if the caller address is present more than once in the call stack, the contract behaves as if the first instruction had been a `REVERT`, therefore the CALL returns 0. Otherwise, it executes no code and returns 1. The gas cost of the contract execution is set to 100, which is consumed independently of the call result. + +## Rationale + +The address `0x0A` is the next one available within the range defined by [EIP-1352](./eip-1352). + +### Sample usage + +```solidity +pragma solidity ^0.8.0; + +abstract contract ReentrancyGuard2 { + + uint8 constant SemaphoreAddress = 0x0A; + /** + * @dev Prevents a contract from calling itself, directly or indirectly. + * Calling a `nonReentrant` function from another `nonReentrant` + * function is supported. + */ + modifier nonReentrant() { + _nonReentrantBefore(); + _; + } + + function _nonReentrantBefore() private { + assembly { + if iszero(staticcall(1000,SemaphoreAddress, 0, 0, 0, 0)) { + revert(0, 0) + } + } + } +} +``` + +### Parallelizable storage-based RPGs + +The only way to parallelize preexistent contracts that are using the storage RPG construction is that the VM automatically detects that a storage variable is used for the RPG, and proves that it works as required. This requires static code analysis. This is difficult to implement in consensus for two reasons. First, the CPU cost of detection and/or proving may be high. Second, some contract functions may not be protected by the RPG, meaning that some execution paths do not alter the RPG, which may complicate proving. Therefore this proposal aims to protect future contracts and let them be parallelizable, rather than to parallelize already deployed ones. + +### Alternatives + +There are alternative designs to implement RPGs on the EVM: + +1. Transient storage opcodes (`TLOAD`/`TSTORE`) provide contract state that is kept between calls in the same transaction but it is not committed to the world state afterward. These opcodes also enable fine-grained parallelization. +2. An opcode `SSTORE_COUNT` that retrieves the number of `SSTORE` instructions executed. It enables also fine-grained execution parallelization, but `SSTORE_COUNT` is much more complex to use correctly as it returns the number `SSTORE` opcodes executed, not the number of reentrant calls. Reentrancy must be deducted from this value. +3. A new `LOCKCALL` opcode that works similar to `STATICALL` but only blocks storage writes in the caller contract. This results in cheaper RPG, but it doesn't allow some contract functions to be free of the RPG. + +All these alternative proposals have the downside that they create new opcodes, and this is discouraged if the same functionality can be implemented with the same gas cost using precompiles. A new opcode requires modifying compilers, debuggers and static analysis tools. + +### Gas cost + +A gas cost of 100 represents a worst-case resource consumption, which occurs when the stack is almost full (approximately 400 addresses) and it is fully scanned. As the stack is always present in RAM, the scanning is fast. + +Note: Once code is implemented in geth, it can be benchmarked and the cost can be re-evaluated, as it may result to be lower in practice. As a precompile call currently costs 700 gas, the cost of stack scanning has a low impact on the total cost of the precompile call (800 gas in total). + +The storage-based RPG currently costs 200 gas (because of the savings introduced in [EIP-1283](./eip-1283.md). Using the `Semaphore` precompile as a reentrancy check would currently cost 800 gas (a single call from one of the function modifiers). While this cost is higher than the traditional RPG cost and therefore discourages its use, it is still much lower than the pre-EIP-1283 cost. If a reduction in precompile call cost is implemented, then the cost of using the `Semaphore` precompile will be reduced to approximately 140 gas, below the current 200 gas consumed by a storage-based RPG. To encourage to use of the precompile-based RPG, it is suggested that this EIP is implemented together with a reduction in precompile calls cost. + +## Backwards Compatibility + +This change requires a hard fork and therefore all full nodes must be updated. + +## Test Cases + +```solidity +contract Test is ReentrancyGuard2 { + function second() external nonReentrant { + } + function first() external nonReentrant { + this.second(); + } +} +``` + +A call to `second()` directly from a transaction does not revert, but a call to `first()` does revert. + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5289.md b/EIPS/eip-5289.md new file mode 100644 index 00000000000000..107a94c17e94f4 --- /dev/null +++ b/EIPS/eip-5289.md @@ -0,0 +1,7 @@ +--- +eip: 5289 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5289.md diff --git a/EIPS/eip-5298.md b/EIPS/eip-5298.md new file mode 100644 index 00000000000000..7f515627047102 --- /dev/null +++ b/EIPS/eip-5298.md @@ -0,0 +1,7 @@ +--- +eip: 5298 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5298.md diff --git a/EIPS/eip-5313.md b/EIPS/eip-5313.md new file mode 100644 index 00000000000000..e6756e76569dfb --- /dev/null +++ b/EIPS/eip-5313.md @@ -0,0 +1,7 @@ +--- +eip: 5313 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5313.md diff --git a/EIPS/eip-5334.md b/EIPS/eip-5334.md new file mode 100644 index 00000000000000..a87552359aa2c8 --- /dev/null +++ b/EIPS/eip-5334.md @@ -0,0 +1,7 @@ +--- +eip: 5334 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5334.md diff --git a/EIPS/eip-5345.md b/EIPS/eip-5345.md new file mode 100644 index 00000000000000..68bc9fffeb1f63 --- /dev/null +++ b/EIPS/eip-5345.md @@ -0,0 +1,126 @@ +--- +eip: 5345 +title: Silent Signing Extension for JSON-RPC +description: Temporary transaction signing without user interaction +author: Stanley Wu (@fruit37), Mücahit Büyükyılmaz (@anndro), Muhammed Emin Aydın (@muhammedea) +discussions-to: https://ethereum-magicians.org/t/walletconnect-silent-signing-extension/10137 +status: Stagnant +type: Standards Track +category: Interface +created: 2022-07-26 +--- + +## Abstract + +Mobile applications supporting lots of transactions might become a source of bad user experience due to uncontrolled switching between the wallet's and application's UI. By this proposal, we would like to introduce the means to sign and send wallet transactions without the need for user participation. This feature can be implemented by providing user consent for a specific time duration. We call the feature Silent Signing. + +## Motivation + +Some blockchain applications interact with a blockchain much more frequently than others. It is especially true for gaming applications having their own sidechains. Interrupting the gaming process and switching to the wallet to perform a transaction drastically affect the user experience. + +## Specification + +To remedy the situation, we'd like to introduce new RPC methods for the ethereum JSON-RPC. Those methods help enable wallets to implement the Silent Signing feature. + +### Silent Signing User Flow + +The Silent Signing process has the following structure: + +1. First, the application requests the wallet to use Silent Signing via the RPC's `wallet_requestSilentSign` method. +2. Second, the wallet prompts the user to confirm enabling the Silent Singing functionality for a specific time duration. +3. If the user does not confirm Silent Signing or the RPC method is not allowed, the application will continue using the regular methods. +4. If the user confirms Silent Signing, then each subsequent transaction will be sent using the `wallet_silentSendTransaction` method for the time duration specified. + +### Implementation + +The implementation introduces new RPC methods and flow for application and wallet side. + +### New RPC Methods + +#### `wallet_requestSilentSign` + +This RPC method opens the wallet and prompts the user to enable automatic signing for a specific time duration. This function grants the application to call the following methods until the timestamp expires. Standard methods like `eth_signTrancaction` remain untouched. + +```shell +Parameters + Object: request object + until: NUMBER - unix timesptamp, the end time the permission will be valid + chainId: NUMBER - the chain id that the contract located in + contractAddress: ADDRESS - address of the contract to be allowed + allowedFunctions: STRING ARRAY - allowed function signatures + Ex: ["equip(address,uint256)", "unequip(address,uint256)"] + description: STRING - extra description that can be shown to user by the wallet + +Returns + DATA, 20 Bytes: permissionSecret - a secret key for silent-signing requests (randomly generated) +``` + +#### `wallet_silentSignTransaction` + +This RPC method creates a transaction and sends its data to the wallet for signing. The wallet signs the data in the background, interfering with no processes the user is involved in. Afterward, the application sends the signed transaction to the blockchain using Nethereum's or other libraries' `sendRawTransaction` method. + +```shell +Parameters + DATA, 20 Bytes: permissionSecret - secret key obtained from `wallet_requestSilentSign` method + Object - The transaction object + from: DATA, 20 Bytes - The address the transaction is sent from. + to: DATA, 20 Bytes - (optional when creating new contract) The address the transaction is directed to. + gas: QUANTITY - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas. + gasPrice: QUANTITY - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas, in Wei. + value: QUANTITY - (optional) Integer of the value sent with this transaction, in Wei. + data: DATA - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. + nonce: QUANTITY - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. + +Returns + DATA, The signed transaction object. +``` + +#### `wallet_silentSendTransaction` + +This RPC method creates a transaction and sends it to the blockchain without interfering with the process the user is involved in. + +```shell +Parameters + DATA, 20 Bytes: permissionSecret - secret key obtained from `wallet_requestSilentSign` method + Object - The transaction object + from: DATA, 20 Bytes - The address the transaction is sent from. + to: DATA, 20 Bytes - (optional when creating new contract) The address the transaction is directed to. + gas: QUANTITY - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas. + gasPrice: QUANTITY - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas. + value: QUANTITY - (optional) Integer of the value sent with this transaction. + data: DATA - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. + nonce: QUANTITY - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. + +Returns + DATA, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available. +``` + +### Application and Wallet Communication + +Sending RPC requests between application and wallet can be as usual. For example browser extension wallets can use these new methods easily. Even hardware wallets can implement this too. But for mobile wallets extra communication techniques should be considered. Because mobile wallets can be inactive when it is not in use. + +Mobile wallets mostly use Walletconnect protocol. The application closed or active in the background can't connect to the Bridge server via WebSocket. Therefore, we have to trigger the wallet to connect to the Bridge and to start waiting for requests. For this purpose, push notifications are to be used. That means that only the wallets supporting push notifications can implement the feature. + +![](../assets/eip-5345/walletconnect-flow.png) + +Whenever the wallet receives a push notification, it connects to the Bridge server and gets access to the pending requests. If there are `wallet_silenSignTransaction` or `wallet_silentSendTransaction` silent signing requests pending and the interaction with the requesting client has been confirmed for this particular time duration, then the wallet executes the request without interfering with the ongoing user activity. + +## Rationale + +Games and Metaverse applications imply lots of cases when the user interacts with the wallet, switching to it and approving transactions. This switching aspect might interfere with gaming per se and create a bad user experience. That is why such applications can benefit if the wallets can support the Silent Signing functionality allowing transactions to be signed with no user interaction. + +## Backwards Compatibility + +These new RPC methods don't interfere with the current ones, and for mobile wallets the push notifications API is currently a part of the `WalletConnect` specification. Implementing the proposal's functionality changes nothing for other applications and wallets. + +## Security Considerations + +The proposed feature aims to improve the user experience and can only be enabled with user consent. Users might freely choose to use the application as usual. + +Silent Signing permission has restrictions that makes it more secure. +* Permission granted only for a specified time duration +* Permission granted only for specific contract in a specific chain and restricted to specified functions. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5375.md b/EIPS/eip-5375.md new file mode 100644 index 00000000000000..75cedb8e50b7f6 --- /dev/null +++ b/EIPS/eip-5375.md @@ -0,0 +1,7 @@ +--- +eip: 5375 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5375.md diff --git a/EIPS/eip-5380.md b/EIPS/eip-5380.md new file mode 100644 index 00000000000000..0802cb770cf3f4 --- /dev/null +++ b/EIPS/eip-5380.md @@ -0,0 +1,7 @@ +--- +eip: 5380 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5380.md diff --git a/EIPS/eip-5409.md b/EIPS/eip-5409.md new file mode 100644 index 00000000000000..b26426d298c975 --- /dev/null +++ b/EIPS/eip-5409.md @@ -0,0 +1,7 @@ +--- +eip: 5409 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5409.md diff --git a/EIPS/eip-5437.md b/EIPS/eip-5437.md new file mode 100644 index 00000000000000..3b3f19a0d0f546 --- /dev/null +++ b/EIPS/eip-5437.md @@ -0,0 +1,7 @@ +--- +eip: 5437 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5437.md diff --git a/EIPS/eip-5450.md b/EIPS/eip-5450.md new file mode 100644 index 00000000000000..b61f2501801a98 --- /dev/null +++ b/EIPS/eip-5450.md @@ -0,0 +1,170 @@ +--- +eip: 5450 +title: EOF - Stack Validation +description: Deploy-time validation of stack usage for EOF functions. +author: Andrei Maiboroda (@gumb0), Paweł Bylica (@chfast), Alex Beregszaszi (@axic), Danno Ferrin (@shemnon) +discussions-to: https://ethereum-magicians.org/t/eip-5450-eof-stack-validation/10410 +status: Stagnant +type: Standards Track +category: Core +created: 2022-08-12 +requires: 3540, 3670, 4200, 4750 +--- + +## Abstract + +Introduce extended validation of EOF code sections to guarantee that neither stack underflow nor overflow can happen during execution of validated contracts. + +## Motivation + +The current EVM performs a number of validity checks for each executed instruction, such as checking +for instruction being defined, stack overflow and underflow, and enough amount of gas remaining. + +This EIP minimizes the number of such checks required at run-time +by verifying that no exceptional conditions can happen +and preventing the execution and deployment of any invalid code. + +The operand stack validation provides several benefits: + +- removes the run-time stack underflow check for all instructions, +- removes the run-time stack overflow check for all instructions except `CALLF` and `JUMPF` (`JUMPF` introduced in a separate EIP) , +- ensures that execution terminates with one of the terminating instructions, +- prevents deployment of code with unreachable instructions, thereby discouraging the use of code sections for data storage. + +It also has some disadvantages: + +- adds constraints to the code structure (similar to JVM, CPython bytecode, WebAssembly, SPIR-V and others); however, these constraints can be lifted in a backward-compatible manner if they are shown to be user-unfriendly, +- it is natural to implement stack validation as a second validation pass; however, it is not strictly required and validation's computational and space complexity remains linear in any implementation variant. + +The guarantees created by these validation rules also improve the feasibility of Ahead-Of-Time and Just-In-Time compilation of EVM code. Single pass transpilation passes can be safely executed with the code validation and advanced stack/register handling can be applied with the stack height validations. While not as impactful to a Mainnet validator node that is bound mostly by storage state sizes, these can significantly speed up witness validation and other non-Mainnet use cases. + +## Specification + +### Code validation + +*Remark:* We rely on the notions of *operand stack* and *type section* as defined by [EIP-4750](./eip-4750.md). + +Each code section is validated independently. + +#### Instructions validation + +In the first validation phase defined in [EIP-3670](./eip-3670.md) (and extended by [EIP-4200](./eip-4200.md) and [EIP-4750](./eip-4750.md)) instructions are inspected independently to check if their opcodes and immediate values are valid. + +#### Operand stack validation + +In the second validation phase control-flow analysis is performed on the code. + +*Operand stack height* here refers to the number of stack values accessible by this function, i.e. it does not take into account values of caller functions' frames (but does include this function's inputs). Note that validation procedure does not require actual operand stack implementation, but only to keep track of its height. + +*Terminating instructions* refers to the instructions either: + +- ending function execution: `RETF`, `JUMPF`, or +- ending call frame execution: `STOP`, `RETURN`, `RETURNCODE`, `REVERT`, `INVALID`. + +*note: `JUMPF` and `RETURNCODE` are introduced in separate EIPs.* + +*Forward jump* refers to any of `RJUMP`/`RJUMPI`/`RJUMPV` instruction with relative offset greater than or equal to 0. *Backwards jump* refers to any of `RJUMP`/`RJUMPI`/`RJUMPV` instruction with relative offset less than 0, including jumps to the same jump instruction. + +Instructions in the code are scanned in a single linear pass over the code. For each instruction the operand stack height bounds are recorded as `stack_height_min` and `stack_height_max`. + +The first instruction's recorded stack height bounds are initialized to be equal to the number of inputs to the function type matching the code (`stack_height_min = stack_height_max = type[code_section_index].inputs`). + +For each instruction: + +1. **Check** if this instruction has recorded stack height bounds. If it does not, it means it was neither referenced by previous forward jump, nor is part of sequential instruction flow, and this code fails validation. + - It is a prerequisite to validation algorithm, and code generators are required to order code basic blocks in a way that no block is referenced only by backwards jump. Any program can satisfy this requirement by ordering code basic blocks by the reverse postorder. +2. Determine the effect the instruction has on the operand stack: + 1. **Check** if the recorded stack height bounds satisfy the instruction requirements. Specifically: + - for `CALLF` instruction the recorded stack height lower bound must be at least the number of inputs of the called function according to its type defined in the type section, + - for `RETF` instruction both the recorded lower and upper bound must be equal and must be exactly the number of outputs of the function matching the code, + - for `JUMPF` into returning function both the recorded lower and upper bound must equal exactly `type[current_section_index].outputs + type[target_section_index].inputs - type[target_section_index].outputs`, + - for `JUMPF` into non-returning function the recorded stack height lower bound must be at least the number of inputs of the target function according to its type defined in the type section, + - for any other instruction the recorded stack height lower bound must be at least the number of inputs required by instruction, + - there is no additional check for terminating instructions other than `RETF` and `JUMPF`, this implies that extra items left on stack at instruction ending EVM execution are allowed. + 2. For `CALLF` and `JUMPF` **check** for possible stack overflow: if recorded stack height upper bound is greater than `1024 - types[target_section_index].max_stack_increase`, validation fails. + 3. Compute new stack height bounds after the instruction execution. Upper and lower bound are updated by the same value: + - after `CALLF` stack height bounds are adjusted by adding `types[target_section_index].outputs - types[target_section_index].inputs`, + - after any other non-terminating instruction stack height bounds are adjusted by subtracting the number of instruction inputs and adding the number of instruction outputs, + - terminating instructions do not need to update stack height bounds. +3. Determine the list of successor instructions that can follow the current instructions: + 1. The next instruction if the current instruction is not a terminating instruction nor unconditional jump (`RJUMP`). + 2. All the current instruction targets if the current instruction is a conditional (`RJUMPI` or `RJUMPV`) or unconditional jump (`RJUMP`). +4. For each successor instruction: + 1. **Check** if the instruction is present in the code (i.e. execution must not "fall off" the code). + 2. If the successor is reached via forwards jump or sequential flow from previous instruction: + 1. If the instruction does not have stack height bounds recorded (being visited for the first time), record the instruction stack height bound as the value computed in 2.3. + 2. Otherwise, instruction has been already visited (by previously seen forward jump). Update this instruction's recorded stack height bounds so that they contain the bounds computed in 2.3, i.e. `target_stack_min = min(target_stack_min, current_stack_min)` and `target_stack_max = max(target_stack_max, current_stack_max)`, where `(target_stack_min, target_stack_max)` are successor bounds and `(current_stack_min, current_stack_max)` are bounds computed in 2.3. + 3. If the successor is reached via backwards jump, **check** if the recorded stack height bounds equal the value computed in 2.3. Validation fails if they are not equal, i.e. we see backwards jump to a different stack height. + +After all instructions are visited, determine the function maximum operand stack height increase: + +1. Compute the maximum stack height `max_stack_height` as the maximum of all recorded stack height upper bounds. +2. Compute the maximum stack height increase `max_stack_increase` as `max_stack_height - type[current_section_index].inputs`. +3. **Check** if the maximum stack height increase `max_stack_increase` matches the value corresponding code section's within the type section: `types[current_section_index].max_stack_increase`. + +*Note: Although we check only that `max_stack_increase` matches the type section definition, which guarantees that it does not exceed 1023 by EOF header definition, it is also guaranteed that `max_stack_height` does not exceed 1024, because otherwise validation of `CALLF` and `JUMPF` into this section would fail at operand stack overflow check. Every section is required to have `CALLF` or `JUMPF` targeting it, except 0th section (non-reachable sections are not allowed). 0th section is required to have 0 inputs, which implies `max_stack_increase` equals `max_stack_height`.* + +The computational and space complexity of this pass is *O(len(code))*. Each instruction is visited at most once. + +### Execution + +Given the deploy-time validation guarantees, an EVM implementation is not required anymore to have run-time stack underflow nor overflow checks for each executed instruction. The exception is the `CALLF` and `JUMPF` performing operand stack overflow check for the entire called function. + +## Rationale + +### Properties of validated code + +Any code section validated according to operand stack validation has the following properties: + +1. There are no unreachable instructions +2. There are no instructions reachable only via backwards jump +3. Operand stack underflow cannot happen. +4. Operand stack overflow can only happen at `CALLF` or `JUMPF` instruction. +5. Multiple forward jump instructions executing at different stack heights may target the same instruction; the stack of target basic block is validated for all possible heights. +6. Any backwards jump instruction can only target an instruction that is executed with equal stack height; this prevents deployment of the loops with unbounded stack pushing or popping. +7. Final instruction in the code section is either terminating instruction or `RJUMP`. + +### Stack overflow check only in CALLF/JUMPF + +In this EIP, we provide a more efficient variant of the EVM where stack overflow check is performed only in `CALLF` and `JUMPF` instructions using the called function's `max_stack_height` information. This decreases flexibility of an EVM program because `max_stack_height` corresponds to the worst-case control-flow path in the function. + +### Unreachable code + +The operand stack validation algorithm rejects any code having any unreachable instructions. This check can be performed very cheaply. It prevents deploying degenerated code. Moreover, it enables combining instruction validation and operand stack validation into single pass. + +### Clean stack upon termination + +It is currently required that the operand stack is empty (in the current function context) after the `RETF` instruction. +Otherwise, the `RETF` semantic would be more complicated. For `n` function outputs and `s` the stack height at `RETF` the EVM would have to erase `s-n` non-top stack items and move the `n` stack items to the place of erased ones. Cost of such operation may be relatively cheap but is not constant. +However, lifting the requirement and modifying the `RETF` semantic as described above is backward +compatible and can be easily introduced in the future. + +### More restrictive stack validation + +Originally another variant of stack validation was proposed, where instead of linear scan of the code section, all code paths were examined by following the target(s) of every jump instruction in a breadth-first-search manner, tracking stack height for each visited instruction and checking that for every possible code path to a particular instruction its stack height remains constant. + +The advantage of this variant would be somewhat simpler algorithm (we would not need to track stack height bounds, but only a single stack height value for each instruction) and no extra requirement for ordering of code basic blocks (see below). + +However, compiler teams opposed to such restrictive stack height requirements. One prominent pattern used by compilers which wouldn't be possible is jumping to terminating helpers (code blocks ending with `RETURN` or `REVERT`) from different stack heights. This is common for example for a series of `assert` statements, each one compiled to a `RJUMPI` into a shared terminating helper. Enforcing constant stack requirement would mean that before jumping to such helper, extra items on the stack have to be popped, and this noticeably increases code size and consumed gas, and would defeat the purpose of extracting these common terminating sequences into a helper. + +### Ordering of basic blocks + +The prerequisite to stack validation algorithm is ordering of code basic blocks in a way that no block is referenced only by backwards jump. + +This is required to make it possible to examine each instruction in one linear pass over the code section. Forward pass over the code section allows for the algorithm to "expand" each forward jump target's stack height bounds and still keep the complexity linear. Trying to do jump target stack bounds expansion while scanning the code in the breadth-first-search manner would require to re-examine entire code path after its stack height bounds are expanded, which would result in quadratic complexity. + +This requirement is not unique to EOF but also present is some low-level IRs like SPIR-V and LLVM MIR. + +## Backwards Compatibility + +This change requires a "network upgrade," since it modifies consensus rules. + +It poses no risk to backwards compatibility, as it is introduced only for EOF1 contracts, for which deploying undefined instructions is not allowed, therefore there are no existing contracts using these instructions. The new instructions are not introduced for legacy bytecode (code which is not EOF formatted). + +## Security Considerations + +As mentioned above, the proposed validation algorithm has linear computational and space complexity and its cost is covered by the transaction data costs [EIP-2028](./eip-2028). + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5453.md b/EIPS/eip-5453.md new file mode 100644 index 00000000000000..9ab71ea0f96125 --- /dev/null +++ b/EIPS/eip-5453.md @@ -0,0 +1,7 @@ +--- +eip: 5453 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5453.md diff --git a/EIPS/eip-5478.md b/EIPS/eip-5478.md new file mode 100644 index 00000000000000..e190681c676a47 --- /dev/null +++ b/EIPS/eip-5478.md @@ -0,0 +1,49 @@ +--- +eip: 5478 +title: CREATE2COPY Opcode +description: Reducing the gas cost of contract creation with existing code +author: Qi Zhou (@qizhou) +discussions-to: https://ethereum-magicians.org/t/eip-5478-reducing-the-gas-cost-of-contract-creation-with-existing-code/10419 +status: Stagnant +type: Standards Track +category: Core +created: 2022-08-17 +requires: 1014, 2929 +--- + +## Abstract + +Adding a new opcode, `CREATE2COPY`, that is identical to `CREATE2` but with potentially much lower gas cost by accepting an additional argument `existing_contract_address` that already stored the code of the new contract. + +## Motivation + +This EIP aims to reduce the smart contract creation cost of account abstraction (AA) contracts that have identical code. + +The major cost of creating an AA contract is the contract creation cost, especially data gas. For example, creating an AA contract with 10,000 bytes will consume 2,000,000 data gas. Considering the code for each user's AA contract is the same, `CREATE2COPY` can reduce the data gas cost to 2600 (cold account) or even 100 (warm account) if the contract code already exists in the local storage. + +## Specification + +### Parameters + +| Constant | Value | +| ---------------------------- | ---------------- | +| `FORK_BLKNUM` | TBD | +| `CREATE_DATA_GAS_PER_BYTE` | 200 | +| `COLD_ACCOUNT_ACCESS_COST` | 2600 | +| `WARM_ACCOUNT_ACCESS_COST` | 100 | + +If `block.number >= FORK_BLKNUM`, a new opcode is added (`CREATE2COPY`) at `0xf6`, which takes 5 stack arguments: `endowment`, `memory_start`, `memory_length`, `salt`, `existing_contract_address`. `CREATE2COPY` behaves identically to `CREATE2` (`0xf5` as defined in [EIP-1014](./eip-1014.md)), except that the code hash of the creating contract MUST be the same as that of `existing_contract_address`. + +`CREATE2COPY` has the same `gas` schema as `CREATE2`, but replacing the data gas from `CREATE_DATA_GAS_PER_BYTE * CONTRACT_BYTES` to the gas cost of `EXTCODEHASH` opcode, which is `COLD_ACCOUNT_ACCESS_COST` if the `existing_contract_address` is first-time accessed in the transaction or `WARM_ACCOUNT_ACCESS_COST` if `existing_contract_address` is already in the access list according to [EIP-2929](./eip-2929.md). + +If the code of the contract returned from the init code differs from that of `existing_contract_address`, the creation fails with the error "mismatched contract creation code with existing code", and will burn all gas for the contract creation. +## Rationale + +TBD +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5484.md b/EIPS/eip-5484.md new file mode 100644 index 00000000000000..f199d2724ddde5 --- /dev/null +++ b/EIPS/eip-5484.md @@ -0,0 +1,7 @@ +--- +eip: 5484 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5484.md diff --git a/EIPS/eip-5485.md b/EIPS/eip-5485.md new file mode 100644 index 00000000000000..1511dbb63a03b5 --- /dev/null +++ b/EIPS/eip-5485.md @@ -0,0 +1,7 @@ +--- +eip: 5485 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5485.md diff --git a/EIPS/eip-5489.md b/EIPS/eip-5489.md new file mode 100644 index 00000000000000..dc67574085a2bc --- /dev/null +++ b/EIPS/eip-5489.md @@ -0,0 +1,7 @@ +--- +eip: 5489 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5489.md diff --git a/EIPS/eip-5496.md b/EIPS/eip-5496.md new file mode 100644 index 00000000000000..7b198b74d28fa5 --- /dev/null +++ b/EIPS/eip-5496.md @@ -0,0 +1,7 @@ +--- +eip: 5496 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5496.md diff --git a/EIPS/eip-55.md b/EIPS/eip-55.md index 3ef0eff3d1c5fd..f7016be98d9850 100644 --- a/EIPS/eip-55.md +++ b/EIPS/eip-55.md @@ -1,130 +1,7 @@ --- eip: 55 -title: Mixed-case checksum address encoding -author: Vitalik Buterin , Alex Van de Sande -type: Standards Track category: ERC -status: Final -created: 2016-01-14 +status: Moved --- -# Specification - -Code: - -``` python -from ethereum import utils - -def checksum_encode(addr): # Takes a 20-byte binary address as input - o = '' - v = utils.big_endian_to_int(utils.sha3(addr.hex())) - for i, c in enumerate(addr.hex()): - if c in '0123456789': - o += c - else: - o += c.upper() if (v & (2**(255 - 4*i))) else c.lower() - return '0x'+o - -def test(addrstr): - assert(addrstr == checksum_encode(bytes.fromhex(addrstr[2:]))) - -test('0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed') -test('0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359') -test('0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB') -test('0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb') - -``` - -In English, convert the address to hex, but if the `i`th digit is a letter (ie. it's one of `abcdef`) print it in uppercase if the `4*i`th bit of the hash of the lowercase hexadecimal address is 1 otherwise print it in lowercase. - -# Rationale - -Benefits: -- Backwards compatible with many hex parsers that accept mixed case, allowing it to be easily introduced over time -- Keeps the length at 40 characters -- On average there will be 15 check bits per address, and the net probability that a randomly generated address if mistyped will accidentally pass a check is 0.0247%. This is a ~50x improvement over ICAP, but not as good as a 4-byte check code. - -# Implementation - -In javascript: - -```js -const createKeccakHash = require('keccak') - -function toChecksumAddress (address) { - address = address.toLowerCase().replace('0x', '') - var hash = createKeccakHash('keccak256').update(address).digest('hex') - var ret = '0x' - - for (var i = 0; i < address.length; i++) { - if (parseInt(hash[i], 16) >= 8) { - ret += address[i].toUpperCase() - } else { - ret += address[i] - } - } - - return ret -} -``` - -``` -> toChecksumAddress('0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359') -'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359' -``` - -Note that the input to the Keccak256 hash is the lowercase hexadecimal string (i.e. the hex address encoded as ASCII): - -``` - var hash = createKeccakHash('keccak256').update(Buffer.from(address.toLowerCase(), 'ascii')).digest() -``` - -# Test Cases - -``` -# All caps -0x52908400098527886E0F7030069857D2E4169EE7 -0x8617E340B3D01FA5F11F306F4090FD50E238070D -# All Lower -0xde709f2102306220921060314715629080e2fb77 -0x27b1fdb04752bbc536007a920d24acb045561c26 -# Normal -0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed -0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359 -0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB -0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb -``` - -# Adoption - -| Wallet | displays checksummed addresses | rejects invalid mixed-case | rejects too short | rejects too long | -|--------------------------|--------------------------------|----------------------------|-------------------|------------------| -| Etherwall 2.0.1 | Yes | Yes | Yes | Yes | -| Jaxx 1.2.17 | No | Yes | Yes | Yes | -| MetaMask 3.7.8 | Yes | Yes | Yes | Yes | -| Mist 0.8.10 | Yes | Yes | Yes | Yes | -| MyEtherWallet v3.9.4 | Yes | Yes | Yes | Yes | -| Parity 1.6.6-beta (UI) | Yes | Yes | Yes | Yes | -| Jaxx Liberty 2.0.0 | Yes | Yes | Yes | Yes | -| Coinomi 1.10 | Yes | Yes | Yes | Yes | -| Trust Wallet | Yes | Yes | Yes | Yes | - -### Exchange support for mixed-case address checksums, as of 2017-05-27: - -| Exchange | displays checksummed deposit addresses | rejects invalid mixed-case | rejects too short | rejects too long | -|--------------|----------------------------------------|----------------------------|-------------------|------------------| -| Bitfinex | No | Yes | Yes | Yes | -| Coinbase | Yes | No | Yes | Yes | -| GDAX | Yes | Yes | Yes | Yes | -| Kraken | No | No | Yes | Yes | -| Poloniex | No | No | Yes | Yes | -| Shapeshift | No | No | Yes | Yes | - -# References - -1. EIP 55 issue and discussion https://github.com/ethereum/eips/issues/55 -2. Python example by @Recmo https://github.com/ethereum/eips/issues/55#issuecomment-261521584 -3. Python implementation in [`ethereum-utils`](https://github.com/pipermerriam/ethereum-utils#to_checksum_addressvalue---text) -4. Ethereumjs-util implementation https://github.com/ethereumjs/ethereumjs-util/blob/75f529458bc7dc84f85fd0446d0fac92d991c262/index.js#L452-L466 -5. Swift implementation in [`EthereumKit`](https://github.com/yuzushioh/EthereumKit/blob/master/EthereumKit/Helper/EIP55.swift) -6. Kotlin implementation in [`KEthereum`](https://github.com/walleth/kethereum/tree/master/erc55) +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-55.md diff --git a/EIPS/eip-5501.md b/EIPS/eip-5501.md new file mode 100644 index 00000000000000..5da15b925fb07a --- /dev/null +++ b/EIPS/eip-5501.md @@ -0,0 +1,7 @@ +--- +eip: 5501 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5501.md diff --git a/EIPS/eip-5505.md b/EIPS/eip-5505.md new file mode 100644 index 00000000000000..b37bfe663046e2 --- /dev/null +++ b/EIPS/eip-5505.md @@ -0,0 +1,7 @@ +--- +eip: 5505 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5505.md diff --git a/EIPS/eip-5507.md b/EIPS/eip-5507.md new file mode 100644 index 00000000000000..2fc8ba328eda85 --- /dev/null +++ b/EIPS/eip-5507.md @@ -0,0 +1,7 @@ +--- +eip: 5507 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5507.md diff --git a/EIPS/eip-5516.md b/EIPS/eip-5516.md new file mode 100644 index 00000000000000..3306e79fcae3c4 --- /dev/null +++ b/EIPS/eip-5516.md @@ -0,0 +1,7 @@ +--- +eip: 5516 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5516.md diff --git a/EIPS/eip-5521.md b/EIPS/eip-5521.md new file mode 100644 index 00000000000000..7abf4e216bf64c --- /dev/null +++ b/EIPS/eip-5521.md @@ -0,0 +1,7 @@ +--- +eip: 5521 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5521.md diff --git a/EIPS/eip-5528.md b/EIPS/eip-5528.md new file mode 100644 index 00000000000000..2573c467d35ce3 --- /dev/null +++ b/EIPS/eip-5528.md @@ -0,0 +1,7 @@ +--- +eip: 5528 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5528.md diff --git a/EIPS/eip-5539.md b/EIPS/eip-5539.md new file mode 100644 index 00000000000000..8b1d1b8823dbb4 --- /dev/null +++ b/EIPS/eip-5539.md @@ -0,0 +1,7 @@ +--- +eip: 5539 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5539.md diff --git a/EIPS/eip-5553.md b/EIPS/eip-5553.md new file mode 100644 index 00000000000000..65712704a35970 --- /dev/null +++ b/EIPS/eip-5553.md @@ -0,0 +1,7 @@ +--- +eip: 5553 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5553.md diff --git a/EIPS/eip-5554.md b/EIPS/eip-5554.md new file mode 100644 index 00000000000000..15be8c459edd63 --- /dev/null +++ b/EIPS/eip-5554.md @@ -0,0 +1,7 @@ +--- +eip: 5554 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5554.md diff --git a/EIPS/eip-5559.md b/EIPS/eip-5559.md new file mode 100644 index 00000000000000..8935eaa426be98 --- /dev/null +++ b/EIPS/eip-5559.md @@ -0,0 +1,7 @@ +--- +eip: 5559 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5559.md diff --git a/EIPS/eip-5560.md b/EIPS/eip-5560.md new file mode 100644 index 00000000000000..0c3abc9dc3ec23 --- /dev/null +++ b/EIPS/eip-5560.md @@ -0,0 +1,7 @@ +--- +eip: 5560 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5560.md diff --git a/EIPS/eip-5564.md b/EIPS/eip-5564.md new file mode 100644 index 00000000000000..7be889c69831b2 --- /dev/null +++ b/EIPS/eip-5564.md @@ -0,0 +1,7 @@ +--- +eip: 5564 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5564.md diff --git a/EIPS/eip-5568.md b/EIPS/eip-5568.md new file mode 100644 index 00000000000000..0c0502988e344c --- /dev/null +++ b/EIPS/eip-5568.md @@ -0,0 +1,7 @@ +--- +eip: 5568 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5568.md diff --git a/EIPS/eip-5570.md b/EIPS/eip-5570.md new file mode 100644 index 00000000000000..de758896830d33 --- /dev/null +++ b/EIPS/eip-5570.md @@ -0,0 +1,7 @@ +--- +eip: 5570 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5570.md diff --git a/EIPS/eip-5573.md b/EIPS/eip-5573.md new file mode 100644 index 00000000000000..5658cf8bf9e2dd --- /dev/null +++ b/EIPS/eip-5573.md @@ -0,0 +1,7 @@ +--- +eip: 5573 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5573.md diff --git a/EIPS/eip-5585.md b/EIPS/eip-5585.md new file mode 100644 index 00000000000000..bdbf243ee44f3f --- /dev/null +++ b/EIPS/eip-5585.md @@ -0,0 +1,7 @@ +--- +eip: 5585 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5585.md diff --git a/EIPS/eip-5593.md b/EIPS/eip-5593.md new file mode 100644 index 00000000000000..9b67df5cd02e08 --- /dev/null +++ b/EIPS/eip-5593.md @@ -0,0 +1,87 @@ +--- +eip: 5593 +title: Restrict Ethereum Provider API Injection +description: Wallet guidance for restricting Ethereum Provider API access to secure contexts for improved privacy and security for wallet users. +author: Yan Zhu (@diracdeltas), Brian R. Bondy (@bbondy), Andrea Brancaleoni (@thypon), Kyle Den Hartog (@kdenhartog) +discussions-to: https://ethereum-magicians.org/t/rfc-limiting-provider-object-injection-to-secure-contexts/10670 +status: Stagnant +type: Standards Track +category: Interface +created: 2022-09-05 +requires: 1193 +--- + +## Abstract + +Historically the web platform has had a notion of “powerful” APIs like those defined in W3C's Geolocation specification and W3C's Mediastreams specification, which are subject to additional security restrictions such as those defined by W3C's secure contexts specification. Since the Ethereum Provider APIs allow dApp websites to request access to sensitive user data and to request use of user funds, new Ethereum Provider APIs generally should align to the security considerations defined by W3C's Secure Context specification in order to better protect the users data and users funds managed via the web. + +### Author's Note + +Unfortunately, because of a difference in interpretations by EIP editors of RFC 2119 terminology around linking in [EIP-1](./eip-1.md), the authors cannot directly link to other W3C specifications which this EIP builds upon. The author's attempted to provide as much context as possible within the text while complying with the editor bot in order to get this merged. If this policy is updated or further clarified before this EIP reaches final call in the future this EIP will be updated with links. + +## Motivation + +Wallets are oftentimes maintaining security and safety of users' funds that can be equivalent to large portions of money. For this reason, it's a good idea to restrict access to the Ethereum Provider APIs to align it with other powerful APIs on the web platform. This will assist in reducing the surface area that attacks can be conducted to access users funds or data. Additionally, by adding in restrictions we're reducing the surface area that malicious web pages could fingerprint the user via the Ethereum Provider APIs providing some additional privacy benefits. An example of a specific attack that's avoided by this is one where a malicious advertisement is loaded on a legitimate dApp that attempts to interact with a users wallet to maliciously request the user to access funds. With this EIP implemented the advertisement frame would be considered a third-party iframe and therefore would not have the Ethereum Provider API injected into it's sub frame because it's not a secure context. + +## Specification + +The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. + +### Restrictions for providers + +The provider objects, e.g. `window.ethereum`, are expected to only inject the Ethereum Provider APIs in secure context when conforming with this specification. The following restrictions are REQUIRED for conformant wallets: + +- Provider objects MAY be accessible in private (incognito) windows. +- The origin MUST be a "potentially trustworthy origin" (defined in W3C's Secure Contexts specification in section 3.1) to have access to `window.ethereum`. This can be checked using `window.isSecureContext`, including inside iframes. + - Secure contexts include sites that are served from HTTPS but also HTTP `localhost`. + - The User Agent implementation MAY also support configured [potentially trustworthy origins] that would normally not be considered trustworthy if the user configures their User Agent to do so. See section 7.2 titled "Development Environments" of W3C's Secure Contexts specification for additional details. For example, in Chromium based User Agents this is done via the `chrome://flags/#unsafely-treat-insecure-origin-as-secure` flag. +- By default the Ethereum Provider APIs MUST NOT be exposed to third-party iframes. +- `window.ethereum` MUST be `undefined` in an iframe where `window.isSecureContext` returns `false` in that iframe. +- If the iframe is a third party to the top-level secure origin, it SHOULD be blocked. Some implementations MAY provide a mechanism (e.g., via the `allow` attribute and Permissions API) for pages to request access, subject to user approval. +- If the iframe is first-party to the top-level origin AND the `sandbox` attribute is set on the iframe, the provider object MUST be blocked. If the `sandbox` attribute is set to `sandbox="allow-same-origin"` it MUST be injected for a first party frame. + - Note `"allow-same-origin"` does nothing if the iframe is third-party. Third-party iframes SHOULD be blocked by default, but implementations MAY allow access through user-approved mechanisms such as the Permissions API. + +## Rationale + +By limiting the capabilities of where the Ethereum Provider APIs are being injected we can reduce the surface area of where attacks can be executed. Given the sensitivity of data that's passed to the Ethereum Provider APIs some basic levels of authentication and confidentiality should be met in order to ensure that request data is not being intercepted or tampered with. While there have been attempts to [limit request access via the wallet](./eip-2255.md) interface itself, there have not been limitations that have been set to where these Ethereum Provider APIs are expected to be or not be injected. Since the secure contexts web platform API is a well developed boundary that's been recommended by W3C and the fact that the Ethereum Provider APIs are extending the traditional web platform APIs, no other alternative solutions have been considered in order to extend current established prior art. + + +## Backwards Compatibility + +Wallet extensions SHOULD consider adding a "developer mode" toggle via a UX so that dApp developers have the capability to disable the insecure context (http) check for the `http://localhost:` origin only in the event that localhost does not return `true` for secure context. See section 5.2 of W3C's Secure Context specification for more details. This will allow dApp developers to be able to continue to host dApps on the localhost origin if a User Agent has chosen to not already consider localhost a secure context. All major User Agent implementations tested do consider localhost a secure context already. This toggle MUST be set to disabled by default. + +## Test Cases + +### Required Test Cases + +- Top level `http://a.com` -> blocked (insecure/top level) +- Top level `https://a.com` -> allowed +- Top level `https://a.com` with `