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 55% rename from ISSUE_TEMPLATE.md rename to .github/ISSUE_TEMPLATE.md index 61f357858bf11c..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-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](./eip-1.md): +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 83% rename from PULL_REQUEST_TEMPLATE.md rename to .github/PULL_REQUEST_TEMPLATE.md index 1a9b8b1e9a71c9..135008ace3ab1d 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,3 +1,7 @@ +**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: 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-merge-bot.yml b/.github/workflows/auto-merge-bot.yml deleted file mode 100644 index 51bc7c69df62ca..00000000000000 --- a/.github/workflows/auto-merge-bot.yml +++ /dev/null @@ -1,18 +0,0 @@ -on: [pull_request_target] -name: Auto-Merge Bot -jobs: - auto_merge_bot: - runs-on: ubuntu-latest - name: EIP Auto-Merge Bot - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup Node.js Environment - uses: actions/setup-node@v2 - with: - node-version: '14' - - name: auto-merge-bot - uses: alita-moore/EIP-Bot@c312303620a40e05554de582d2fd20366ca62e05 # tag 1.1.1 - id: auto-merge-bot - with: - GITHUB-TOKEN: ${{ secrets.TOKEN }} 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..45b815e390daeb --- /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@65d862660abb392b8c4a3d1195a2108db131dd05 + 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..7c50de8f79cc13 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,170 @@ +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@65d862660abb392b8c4a3d1195a2108db131dd05 + with: + name: pr_number + path: pr/ + + htmlproofer: + name: HTMLProofer + runs-on: ubuntu-20.04 + + steps: + - name: Checkout EIPs + uses: actions/checkout@v4 + with: + repository: ethereum/EIPs + path: '' + - name: Checkout ERCs + uses: actions/checkout@v4 + with: + repository: ethereum/ERCs + path: ERCs + - name: Merge Repos + 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 + - 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: 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 + + - 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/greetings.yml b/.github/workflows/greetings.yml deleted file mode 100644 index effc1d05ee0ad7..00000000000000 --- a/.github/workflows/greetings.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Greetings - -on: [pull_request, issues] - -jobs: - greeting: - runs-on: ubuntu-latest - steps: - - uses: actions/first-interaction@v1 - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - issue-message: 'Since this is your first issue, we kindly remind you to check out [EIP-1](https://eips.ethereum.org/EIPS/eip-1) for guidance.' - pr-message: 'Since this is your first pull request, we kindly remind you to check out [EIP-1](https://eips.ethereum.org/EIPS/eip-1) for guidance.' 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..490312887e3051 --- /dev/null +++ b/.github/workflows/jekyll.yml @@ -0,0 +1,87 @@ +# 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@v4 + with: + repository: ethereum/EIPs + path: '' + - name: Checkout ERCs + uses: actions/checkout@v4 + with: + repository: ethereum/ERCs + path: ERCs + - name: Merge Repos + 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 + - 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@v3 + - 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@v2 + + # 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@v2 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 index 6ea4c6afd1e422..f66a950b09ce8b 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -1,19 +1,35 @@ -name: "Mark stale PRs" +name: Mark stale PRs & Issues on: schedule: - # Run this every hour, so we are not spammed with changes at once. Later we could consider changing this to once a day. - - cron: "0 * * * *" + - 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@v3 + - uses: actions/stale@03af7c36d33f4905e618fac0a1bb7e6d05f0d41b with: + # General repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-pr-message: 'There has been no activity on this pull request for two months. It will be closed in a week if no further activity occurs. If you would like to move this EIP 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-stale: 60 - days-before-close: 7 - stale-pr-label: 'stale' + 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 bcebd7267ebdf9..8503a3cdadb0d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +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 0a3adfc9d57c97..00000000000000 --- a/.travis-ci.sh +++ /dev/null @@ -1,25 +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 - if [[ $(find . -maxdepth 1 -name 'eip-*' | wc -l) -ne 1 ]]; then - echo "only 'eip-template.md' should be in the root" - exit 1 - fi - eipv EIPS/ --ignore=title_max_length,missing_discussions_to --skip=eip-20-token-standard.md -elif [[ $TASK = 'codespell' ]]; then - codespell -q4 -I .codespell-whitelist -S ".git,Gemfile.lock,**/*.png,**/*.gif,**/*.jpg,**/*.svg,.codespell-whitelist,vendor,_site,_config.yml,style.css" -fi diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 78772718a5e3e1..00000000000000 --- a/.travis.yml +++ /dev/null @@ -1,51 +0,0 @@ -sudo: false - -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.6.0 - env: TASK='htmlproofer' - - rvm: 2.6.0 - env: TASK='htmlproofer-external' - - language: rust - cache: cargo - before_script: - - cargo install eipv --version=0.1.1 - 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.6.0 - 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 f0ae480de86254..d2bd33ab7bd224 100644 --- a/EIPS/eip-1.md +++ b/EIPS/eip-1.md @@ -21,10 +21,10 @@ For Ethereum implementers, EIPs are a convenient way to track the progress of th There are three types of EIP: -- 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]. Furthermore, Standards Track EIPs can be broken down into the following categories: +- 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] ([EIP-8](./eip-8.md)) 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 ([EIP-6](./eip-6.md)) 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. + - **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. @@ -38,6 +38,7 @@ An EIP must meet certain minimum criteria. It must be a clear and complete descr ### 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) ``` @@ -48,29 +49,29 @@ REVERT (0xfe) 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). -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] to do this, but you can also use [one of the Ethereum Gitter chat rooms], [the Ethereum subreddit] or [the Issues section of this repository]. +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. 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. ### 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. +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]. +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 serve 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. +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] thread for your EIP includes or links to as much of the community discussion as possible and that various stakeholders are well-represented. +: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.* +*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 +### EIP Process The following is the standardization process for all EIPs in all tracks: -![EIP Status Diagram](../assets/eip-1/EIP-process.png) +![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. @@ -78,76 +79,74 @@ The following is the standardization process for all EIPs in all tracks: **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 moving to `FINAL`. An EIP editor will assign `Last Call` status and set a review end date (review-period-end), typically 14 days later. +**Last Call** - This is the final review window for an EIP before moving to `Final`. An EIP editor will assign `Last Call` status and set a review end date (`last-call-deadline`), typically 14 days later. -If this period results in necessary normative changes it will revert the EIP to `REVIEW`. +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. -**Stagnant** - Any EIP in `DRAFT` or `REVIEW` 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`. +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. Any changes to these EIPs will move between `REVIEW` and `LIVING` states. +**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](./eip-1.md#eip-header-preamble) for details. -- Abstract - A short (~200 word) description of the technical issue being addressed. -- 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. 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. Tests should either be inlined in the EIP as data (such as input/expected output pairs, or included in `../assets/eip-###/`. -- Reference Implementation - An optional section that contains a reference/example implementation that people can use to assist in understanding or implementing this specification. +- 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. See the bottom of this EIP for an example copyright waiver. +- 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. There is a [template](https://github.com/ethereum/EIPs/blob/master/eip-template.md) to follow. +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. - -` eip:` *EIP number* (this is determined by the EIP editor) +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. -` title:` *EIP title* +`eip`: *EIP number* -` author:` *a list of the author's or authors' name(s) and/or username(s), or name(s) and email(s). Details are below.* +`title`: *The EIP title is a few words, not a complete sentence* -` * discussions-to:` *a url pointing to the official discussion thread* +`description`: *Description is one full (short) sentence* -` status:` *Draft, Review, Last Call, Final, Stagnant, Withdrawn, Living* +`author`: *The list of the author's or authors' name(s) and/or username(s), or name(s) and email(s). Details are below.* -`* review-period-end:` *date review period ends* +`discussions-to`: *The url pointing to the official discussion thread* -` type:` *Standards Track, Meta, or Informational* +`status`: *Draft, Review, Last Call, Final, Stagnant, Withdrawn, Living* -` * category:` *Core, Networking, Interface, or ERC* (fill out for Standards Track EIPs only) +`last-call-deadline`: *The date last call period ends on* (Optional field, only needed when status is `Last Call`) -` created:` *date created on* +`type`: *One of `Standards Track`, `Meta`, or `Informational`* -` * updated:` *comma separated list of dates* +`category`: *One of `Core`, `Networking`, `Interface`, or `ERC`* (Optional field, only needed for `Standards Track` EIPs) -` * requires:` *EIP number(s)* +`created`: *Date the EIP was created on* -` * replaces:` *EIP number(s)* +`requires`: *EIP number(s)* (Optional field) -` * superseded-by:` *EIP number(s)* - -` * resolution:` *a url pointing to the resolution of this EIP* +`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 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: @@ -157,55 +156,360 @@ or > Random J. User (@username) -if the email address or GitHub username is included, and - -> Random J. User +or -if the email address is not given. +> Random J. User (@username) <address@dom.ain> -It is not possible to use both an email and a GitHub username at the same time. If important to include both, one could include their name twice, once with the GitHub username, and once with the email. +if the email address and/or GitHub username is included, and -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. - -#### `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: -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. +[HTML](https://html.spec.whatwg.org/commit-snapshots/578def68a9735a1e36610a6789245ddfc13d24e0/) -#### `requires` header +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: -EIPs may have a `requires` header, indicating the EIP numbers that this EIP depends on. +```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\/.*$ +``` + +### Bitcoin Improvement Proposal + +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)$ +``` + +### 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) +``` -#### `superseded-by` and `replaces` headers +Which renders to: -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](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. ## 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 with `[EIP-1](./eip-1.md)`. +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 @@ -221,15 +525,25 @@ If you are interested in assuming ownership of an EIP, send a message asking to The current EIP editors are -- Nick Johnson (@arachnid) +- Matt Garnett (@lightclient) +- Sam Wilson (@SamWilsn) +- Zainan Victor Zhou (@xinbenlv) +- Gajinder Singh (@g11tech) + +Emeritus EIP editors are + +- Alex Beregszaszi (@axic) - Casey Detrio (@cdetrio) +- Gavin John (@Pandapip1) +- Greg Colvin (@gcolvin) - Hudson Jameson (@Souptacular) -- Vitalik Buterin (@vbuterin) -- Nick Savers (@nicksavers) - Martin Becze (@wanderer) -- Greg Colvin (@gcolvin) -- Alex Beregszaszi (@axic) - Micah Zoltu (@MicahZoltu) +- Nick Johnson (@arachnid) +- Nick Savers (@nicksavers) +- Vitalik Buterin (@vbuterin) + +If you would like to become an EIP editor, please check [EIP-5069](./eip-5069.md). ## EIP Editor Responsibilities @@ -243,10 +557,8 @@ If the EIP isn't ready, the editor will send it back to the author for revision, 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. @@ -255,32 +567,34 @@ The editors don't pass judgment on EIPs. We merely do the administrative & edito ## Style Guide -When referring to an EIP by number, it should be written in the hyphenated form `EIP-X` where `X` is the EIP's assigned number. +### 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. - -### Bibliography - -[devp2p]: https://github.com/ethereum/wiki/wiki/%C3%90%CE%9EVp2p-Wire-Protocol -[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 -[contract ABIs]: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI -[interfaces repo]: https://github.com/ethereum/interfaces -[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/ -[the Ethereum Magicians forum]: https://ethereum-magicians.org/ -[AllCoreDevs agenda GitHub Issue]: https://github.com/ethereum/pm/issues +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 3e3087b1f5e7b3..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,7 +395,7 @@ 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. @@ -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 ea3f55cb486425..0c7b04a82b7f54 100644 --- a/EIPS/eip-1013.md +++ b/EIPS/eip-1013.md @@ -17,7 +17,7 @@ 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 @@ -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-1015.md b/EIPS/eip-1015.md index e21c7f17201663..af447e242e1cc6 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: Draft +status: Stagnant type: Standards Track category: Core created: 2018-04-20 @@ -20,15 +20,15 @@ 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. -#### 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 @@ -54,9 +54,9 @@ It's not meant to be a general governance contract. The contract **should NOT be 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 @@ -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-1051.md b/EIPS/eip-1051.md index 309f4137743ae9..c6b1a7ef34afb6 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 @@ -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 6dc6015e16a40e..356404f1915b14 100644 --- a/EIPS/eip-1052.md +++ b/EIPS/eip-1052.md @@ -61,12 +61,12 @@ There are no backwards compatibility concerns. 1. The `EXTCODEHASH` of the account without code is `c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` what is the keccack256 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. @@ -75,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 index a600cb92fdc87a..12110c18a0d770 100644 --- a/EIPS/eip-1056.md +++ b/EIPS/eip-1056.md @@ -1,286 +1,7 @@ --- eip: 1056 -title: Ethereum Lightweight Identity -author: Pelle Braendgaard , Joel Torstensson -type: Standards Track category: ERC -discussions-to: https://github.com/ethereum/EIPs/issues/1056 -status: Draft -created: 2018-05-03 +status: Moved --- -## Simple Summary - -A registry for key and attribute management of lightweight blockchain identities. - -## Abstract - -This ERC describes a standard for creating and updating identities with a limited use of blockchain resources. An identity can have an unlimited number of `delegates` and `attributes` associated with it. Identity creation is as simple as creating a regular key pair ethereum account, which means that it's free (no gas costs) and all ethereum accounts are valid identities. Furthermore this ERC is fully [DID compliant](https://w3c-ccg.github.io/did-spec/). - -## Motivation - -As we have been developing identity systems for the last couple of years at uPort it has become apparent that the cost of identity creation is a large issue. The previous Identity proposal [ERC-725](./eip-725.md) faces this exact issue. Our requirements when creating this ERC is that identity creation should be free, and should be possible to do in an offline environment (e.g. refugee scenario). However it must also be possible to rotate keys without changing the primary identifier of the identity. The identity system should be fit to use off-chain as well as on-chain. - -## Definitions - -* `Identifier`: a piece of data that uniquely identifies the identity, an ethereum address - -* `delegate`: an address that is delegated for a specific time to perform some sort of function on behalf of an identity - -* `delegateType`: the type of a delegate, is determined by a protocol or application higher up - Examples: - - * `did-jwt` - * `raiden` - -* `attribute`: a piece of data associated with the identity - -## Specification - -This ERC specifies a contract called `EthereumDIDRegistry` that is deployed once and can then be commonly used by everyone. - -### Identity ownership - -By default an identity is owned by itself, meaning whoever controls the ethereum account with that address. The owner can be updated to a new key pair account or to a multisig account etc. - -#### identityOwner - -Returns the owner of the given identity. - -```js -function identityOwner(address identity) public view returns(address); -``` - -#### changeOwner - -Sets the owner of the given identity to another ethereum account. - -```js -function changeOwner(address identity, address newOwner) public; -``` - -#### changeOwnerSigned - -Same as above but with raw signature. - - -```js -function changeOwnerSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, address newOwner) public; -``` - -### Delegate management - -Delegates can be used both on- and off-chain. They all have a `delegateType` which can be used to specify the purpose of the delegate. - -#### validDelegate - -Returns true if the given `delegate` is a delegate with type `delegateType` of `identity`. - -```js -function validDelegate(address identity, bytes32 delegateType, address delegate) public view returns(bool); -``` - -#### addDelegate - -Adds a new delegate with the given type. `validity` indicates the number of seconds that the delegate will be valid for, after which it will no longer be a delegate of `identity`. - -```js -function addDelegate(address identity, bytes32 delegateType, address delegate, uint validity) public; -``` - - -#### addDelegateSigned - -Same as above but with raw signature. - - -```js -function addDelegateSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 delegateType, address delegate, uint validity) public; -``` - - -#### revokeDelegate - -Revokes the given `delegate` for the given `identity`. - - -```js -function revokeDelegate(address identity, bytes32 delegateType, address delegate) public; -``` - - -#### revokeDelegateSigned - -Same as above but with raw signature. - - -```js -function revokeDelegateSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 delegateType, address delegate) public; -``` - - -### Attribute management - -Attributes contain simple data about the identity. They can be managed only by the owner of the identity. - - -#### setAttribute - -Sets an attribute with the given `name` and `value`, valid for `validity` seconds. - - -```js -function setAttribute(address identity, bytes32 name, bytes value, uint validity) public; -``` - - -#### setAttributeSigned - -Same as above but with raw signature. - - -```js -function setAttributeSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 name, bytes value, uint validity) public; -``` - - -#### revokeAttrubte - -Revokes an attribute. - - -```js -function revokeAttribute(address identity, bytes32 name, bytes value) public; -``` - - -#### revokeAttributeSigned - -Same as above but with raw signature. - - -```js -function revokeAttributeSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 name, bytes value) public; -``` - - -### Events - -#### DIDOwnerChanged - -MUST be triggered when `changeOwner` or `changeOwnerSigned` was successfully called. - - -```js -event DIDOwnerChanged( - address indexed identity, - address owner, - uint previousChange -); -``` - - -#### DIDDelegateChanged - -MUST be triggered when a change to a delegate was successfully made. - - -```js -event DIDDelegateChanged( - address indexed identity, - bytes32 delegateType, - address delegate, - uint validTo, - uint previousChange -); -``` - - -#### DIDAttritueChanged - -MUST be triggered when a change to an attribute was successfully made. - - -```js -event DIDAttributeChanged( - address indexed identity, - bytes32 name, - bytes value, - uint validTo, - uint previousChange -); -``` - - -### Efficient lookup of events through linked identity events - -Contract Events are a useful feature for storing data from smart contracts exclusively for off-chain use. Unfortunately current ethereum implementations provide a very inefficient lookup mechanism. By using linked events that always link to the previous block with a change for the identity, we can solve this problem with much improved performance. Each identity has its previously changed block stored in the `changed` mapping. - - - -1. Lookup `previousChange` block for identity - -2. Lookup all events for given identity address using web3, but only for the `previousChange` block - -3. Do something with event - -4. Find `previousChange` from the event and repeat - - - -Example code: - - -```js -const history = [] -previousChange = await didReg.changed(identity) -while (previousChange) { - const filter = await didReg.allEvents({topics: [identity], fromBlock: previousChange, toBlock: previousChange}) - const events = await getLogs(filter) - previousChange = undefined - for (let event of events) { - history.unshift(event) - previousChange = event.args.previousChange - } -} -``` - - -### Building a DID document for an identity - -The primary owner key should be looked up using `identityOwner(identity)`. This should be the first of the publicKeys listed. Iterate through the `DIDDelegateChanged` events to build a list of additional keys and authentication sections as needed. The list of delegateTypes to include is still to be determined. Iterate through `DIDAttributeChanged` events for service entries, encryption public keys and other public names. The attribute names are still to be determined. - - -## Rationale - -For on-chain interactions Ethereum has a built in account abstraction that can be used regardless of whether the account is a smart contract or a key pair. Any transaction has a `msg.sender` as the verified send of the transaction. - - -Since each Ethereum transaction has to be funded, there is a growing trend of on-chain transactions that are authenticated via an externally created signature and not by the actual transaction originator. This allows 3rd party funding services or receiver pays without any fundamental changes to the underlying Ethereum architecture. These kinds of transactions have to be signed by an actual key pair and thus can not be used to represent smart contract based Ethereum accounts. - - -We propose a way of a Smart Contract or regular key pair delegating signing for various purposes to externally managed key pairs. This allows a smart contract to be represented both on-chain as well as off-chain or in payment channels through temporary or permanent delegates. - - -## Backwards Compatibility - -All ethereum accounts are valid identities (and DID compatible) using this standard. This means that any wallet provider that uses key pair accounts already supports the bare minimum of this standard, and can implement `delegate` and `attribute` functionality by simply using the `ethr-did` referenced below. As the **DID Auth** standard solidifies it also means that all of these wallets will be compatible with the [DID decentralized login system](https://github.com/decentralized-identity). - - -## Implementation - -[ethr-did-registry](https://github.com/uport-project/ethr-did-registry/blob/develop/contracts/EthereumDIDRegistry.sol) (`EthereumDIDRegistry` contract implementation) - -[ethr-did-resolver](https://github.com/uport-project/ethr-did-resolver) (DID compatible resolver) - -[ethr-did](https://github.com/uport-project/ethr-did) (javascript library for using the identity) - - -### Deployment - -The address for the `EthereumDIDRegistry` is `0xdca7ef03e98e0dc2b855be647c39abe984fcf21b` on Mainnet, Ropsten, Rinkeby and Kovan. - -## 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-1056.md diff --git a/EIPS/eip-1057.md b/EIPS/eip-1057.md index fa7a61f6602829..cccc97a29c040a 100644 --- a/EIPS/eip-1057.md +++ b/EIPS/eip-1057.md @@ -3,7 +3,7 @@ eip: 1057 title: ProgPoW, a Programmatic Proof-of-Work 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: Review +status: Stagnant type: Standards Track category: Core created: 2018-05-02 @@ -326,12 +326,12 @@ 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. @@ -568,8 +568,8 @@ Machine-readable test vectors (T.B.D) The reference ProgPoW mining implementation is located at [the @ifdefelse ProgPOW repository](https://github.com/ifdefelse/ProgPOW). -## License and Copyright +## 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 022467747dc0e0..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 : - -```solidity -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. - -```solidity -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 : - -```javascript -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) : - -```javascript -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 9f057326ec6833..f5cbc61ae0e4a7 100644 --- a/EIPS/eip-1066.md +++ b/EIPS/eip-1066.md @@ -1,598 +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 +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 [ERC-1444](./eip-1444.md) 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](./eip-658.md), 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](./eip-1444.md), 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 d6a79c2b53cf3e..c730bd4d3c084f 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). @@ -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). -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 3d37476ce9b424..470bf46b6f1727 100644 --- a/EIPS/eip-1077.md +++ b/EIPS/eip-1077.md @@ -1,229 +1,7 @@ --- eip: 1077 -title: Gas relay for contract calls -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: 20, 191, 1271, 1344 +status: Moved --- - -## Simple Summary - -A standard interface for gas abstraction in top of smart contracts. - -Allows users to offer [EIP-20] token for paying the gas used in a call. - -## Abstract - -A main barrier for adoption of DApps is the requirement of multiple tokens for executing in chain actions. Allowing users to sign messages to show intent of execution, but allowing a third party relayer to execute them can circumvent this problem, while ETH will always be required for ethereum transactions, it's possible for smart contract to take [EIP-191] signatures and forward a payment incentive to an untrusted party with ETH for executing the transaction. - -## Motivation - -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. - - -## Specification - -### Methods - -#### executeGasRelay - -Executes `_execData` with current `lastNonce()` and pays `msg.sender` the gas used in specified `_gasToken`. - -```solidity -function executeGasRelay(bytes calldata _execData, uint256 _gasPrice, uint256 _gasLimit, address _gasToken, address _gasRelayer, bytes calldata _signature) external; -``` - -### executeGasRelayMsg - -Returns the `executeGasRelay` message used for signing messages.. - -```solidity -function executeGasRelayMsg(uint256 _nonce, bytes memory _execData, uint256 _gasPrice, uint256 _gasLimit, address _gasToken, address _gasRelayer) public pure returns (bytes memory); -``` - -#### executeGasRelayERC191Msg - -Returns the [EIP-191] of `executeGasRelayMsg` used for signing messages and for verifying the execution. - -```solidity -function executeGasRelayERC191Msg(uint256 _nonce, bytes memory _execData, uint256 _gasPrice, uint256 _gasLimit, address _gasToken, address _gasRelayer) public view returns (bytes memory); -``` - -#### lastNonce - -Returns the current nonce for the gas relayed messages. - -```solidity -function lastNonce() public returns (uint nonce); -``` - -### Signed Message - -The signed message require the following fields: - -* Nonce: A nonce *or* a timestamp; -* Execute Data: the bytecode to be executed by the account contract; -* Gas Price: The gas price (paid in the selected token); -* Gas Limit: The gas reserved to the relayed execution; -* Gas Token: A token in which the gas will be paid (leave 0 for ether); -* Gas Relayer: the beneficiary of gas refund for this call (leave 0 for `block.coinbase`) . - -#### Signing the message - -The message **MUST** be signed as [EIP-191] standard, and the called contract **MUST** also implement [EIP-1271] which must validate the signed messages. - -Messages **MUST** be signed by the owner of the account contract executing. If the owner is a contract, it must implement [EIP-1271] interface and forward validation to it. - -In order to be compliant, the transaction **MUST** request to sign a "messageHash" that is a concatenation of multiple fields. - -The fields **MUST** be constructed as this method: - -The first and second fields are to make it [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 third being the validator address (the account contract address) according to version 0 of [EIP-191]. The remaining arguments being the application specific data for the gas relay: chainID as per [EIP-1344], execution nonce, execution data, agreed gas Price, gas limit of gas relayed call, gas token to pay back and gas relayer authorized to receive reward. - -The [EIP-191] message must be constructed as following: -```solidity -keccak256( - abi.encodePacked( - byte(0x19), //ERC-191 - the initial 0x19 byte - byte(0x0), //ERC-191 - the version byte - address(this), //ERC-191 - version data (validator address) - chainID, - bytes4( - keccak256("executeGasRelay(uint256,bytes,uint256,uint256,address,address)") - ), - _nonce, - _execData, - _gasPrice, - _gasLimit, - _gasToken, - _gasRelayer - ) -) -``` - -## Rationale - -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 account contract that holds funds, and multiple disposable ether-less keys that can sign on its behalf, solves many of these pain points. - -### Multiple signatures - -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. - -If multiple signatures are required, then all signatures should then be *ordered by account* and the account contract should implement signatures checks locally (`JUMP`) on [EIP-1271] interface which might forward (`STATIC_CALL`) the [EIP-1271] signature check to owner contract. - -### Keep track of nonces: - -Note that `executeGasRelay` function does not take a `_nonce` as parameter. The contract knows what is the current nonce, and can only execute the transactions in order, therefore there is no reason - -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 may accept transactions without nonce (nonce = 0). The contract then must keep the full hash of the transaction to prevent it from being replayed. This would 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 - -After signature validation, the evaluation of `_execBytes` is up to the account contract implementation, it's role of the wallet to properly use the account contract and it's gas relay method. -A common pattern is to expose an interface which can be only called by the contract itself. The `_execBytes` could entirely forward the call in this way, as example: `address(this).call.gas(_gasLimit)(_execData);` -Where `_execData` could call any method of the contract itself, for example: - -- `call(address to, uint256 value, bytes data)`: allow any type of ethereum call be performed; -- `create(uint256 value, bytes deployData)`: allows create contract -- `create2(uint256 value, bytes32 salt, bytes deployData)`: allows create contract with deterministic address -- `approveAndCall(address token, address to, uint256 value, bytes data)`: allows safe approve and call of an ERC20 token. -- `delegatecall(address codeBase, bytes data)`: allows executing code stored on other contract -- `changeOwner(address newOwner)`: Some account contracts might allow change of owner -- `foo(bytes bar)`: Some account contracts might have custom methods of any format. - -The standardization of account contracts is not scope of this ERC, and is presented here only for illustration on possible implementations. -Using a self call to evaluate `_execBytes` is not mandatory, depending on the account contract logic, the evaluation could be done locally. - -### 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 `_gasRelayer`, that is the account that deployed the message. - -If `_gasRelayer` is zero, then the funds **MUST** go to `block.coinbase`. - -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. - -### 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**. - -## Backwards Compatibility - -There is no issues with backwards compatibility, however for future upgrades, as `_execData` contains arbitrary data evaluated by the account contract, it's up to the contract to handle properly this data and therefore contracts can gas relay any behavior with the current interface. - -## Test Cases - -TBD - -## Implementation - -One initial implementation of such a contract can be found at [Status.im account-contracts repository](https://github.com/status-im/account-contracts/blob/develop/contracts/account/AccountGasAbstract.sol) - -Other version is implemented as Gnosis Safe variant in: https://github.com/status-im/safe-contracts - -### 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. - -## Security Considerations - -Deployers of transactions (relayers) should be able to call untrusted contracts, which provides no guarantees that the contract they are interacting with correctly implements the standard and they will be reimbursed for gas. To prevent being fooled by bad implementations, relayers must **estimate the outcome of a transaction**, and only include/sign transactions which have a desired outcome. - -Is also interest of relayers to maintaining a private reputation of contracts they interact with, as well as keep track of which tokens and for which `gasPrice` they’re willing to deploy transactions. - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -## References - -* [Universal Logins talk at UX Unconf, Toronto](https://www.youtube.com/watch?v=qF2lhJzngto) - -[EIP-20]: ./eip-20.md -[EIP-191]: ./eip-191.md -[EIP-1271]: ./eip-1271.md -[EIP-1344]: ./eip-1344.md +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 9c40dd81321361..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: 191, 681, 725, 1077 +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](./eip-681.md) 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 a60a52c976bd90..bc247bd4034492 100644 --- a/EIPS/eip-1080.md +++ b/EIPS/eip-1080.md @@ -1,184 +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 smart contract 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 754966e2a5d404..4c333bdccbb2f3 100644 --- a/EIPS/eip-1081.md +++ b/EIPS/eip-1081.md @@ -1,121 +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 fcf5cca50fd93d..5df422325d5d5c 100644 --- a/EIPS/eip-1087.md +++ b/EIPS/eip-1087.md @@ -3,7 +3,7 @@ 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 @@ -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 cf26f0006dfa3a..6e7e743c164f0a 100644 --- a/EIPS/eip-1102.md +++ b/EIPS/eip-1102.md @@ -3,7 +3,7 @@ eip: 1102 title: Opt-in account exposure 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 @@ -135,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 a1feaa7d00db0d..85bc480489800f 100644 --- a/EIPS/eip-1108.md +++ b/EIPS/eip-1108.md @@ -136,4 +136,4 @@ Both the Parity and Geth clients have already implemented cryptographic librarie @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 d666a5f2090641..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 @@ -47,7 +47,7 @@ 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` (`0xf1`). 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. @@ -84,4 +84,4 @@ Old contracts that call precompiled smart contracts with the `CALL` method, will 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 b0ea91705bde6a..41eb06e8f8005f 100644 --- a/EIPS/eip-1123.md +++ b/EIPS/eip-1123.md @@ -1,1883 +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: Withdrawn -type: Standards Track category: ERC -created: 2018-06-01 -replaces: 190 +status: Moved --- -This ERC has been abandoned in favor of the EthPM V3 smart contract packaging standard defined in [ERC-2678](./eip-2678.md) - -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](./eip-190.md)). -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](https://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](./eip-190.md), -[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 bce6407fb963d7..a9a2238c60965f 100644 --- a/EIPS/eip-1129.md +++ b/EIPS/eip-1129.md @@ -1,144 +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 d80c41c7332799..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 -```solidity -/** - * @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 -```solidity -/** - * @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 -```solidity -/** - * @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 -```solidity -/** - * @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 -```solidity -/** - * @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 -```solidity -/** - * @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 -```solidity -/** - * @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 -```solidity -/** - * @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 -```solidity -/** - * @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 e4668f5732ac7b..1eb863b534a5a3 100644 --- a/EIPS/eip-1153.md +++ b/EIPS/eip-1153.md @@ -1,75 +1,258 @@ --- 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`. + +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.) They use the same arguments on stack as `SLOAD` (`0x54`) and `SSTORE` (`0x55`). -`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. +`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 159bab8f2cc1f8..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: Withdrawn -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 5a509bfc7f1505..f7c6bc8c1c84ce 100644 --- a/EIPS/eip-1155.md +++ b/EIPS/eip-1155.md @@ -1,710 +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: Final -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 all of the functions in the `ERC1155` interface.** - -**Smart contracts implementing the ERC-1155 standard MUST implement the ERC-165 `supportsInterface` function and MUST return the constant value `true` if `0xd9b67a26` is passed through the `interfaceID` argument.** - -```solidity -pragma solidity ^0.5.9; - -/** - @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 to 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 all of the functions in the `ERC1155TokenReceiver` interface to accept transfers. See "Safe Transfer Rules" for further detail.** - -**Smart contracts MUST implement the ERC-165 `supportsInterface` function and signify support for the `ERC1155TokenReceiver` interface to accept transfers. See "ERC1155TokenReceiver ERC-165 rules" for further detail.** - -```solidity -pragma solidity ^0.5.9; - -/** - Note: The ERC-165 identifier for this interface is 0x4e2312e0. -*/ -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("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) 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("onERC1155Received(address,address,uint256,uint256,bytes)"))` - */ - 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("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) 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("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` - */ - function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); -} -``` - -### Safe Transfer Rules - -To be more explicit about how the standard `safeTransferFrom` and `safeBatchTransferFrom` functions 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 token(s) 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 "Backwards Compatibility" 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). -* The balances for the transfer MUST have been updated before the `ERC1155TokenReceiver` hook is called on a recipient contract. -* The transfer event MUST have been emitted to reflect the balance changes before the `ERC1155TokenReceiver` hook is called on the recipient contract. -* One of `onERC1155Received` or `onERC1155BatchReceived` MUST be called on the recipient contract. -* 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 balance transfers that are referenced in a call to an `ERC1155TokenReceiver` hook MUST be updated before the `ERC1155TokenReceiver` hook is called on the recipient contract. -* All transfer events MUST have been emitted to reflect current balance changes before an `ERC1155TokenReceiver` hook is called on the recipient contract. -* `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. - -**_Scenario#9 :_** You are transferring tokens via a non-standard API call i.e. an implementation specific API and NOT `safeTransferFrom` or `safeBatchTransferFrom`. -* In this scenario all balance updates and events output rules are the same as if a standard transfer function had been called. - - i.e. an external viewer MUST still be able to query the balance via a standard function and it MUST be identical to the balance as determined by `TransferSingle` and `TransferBatch` events alone. -* If the receiver is a contract the `ERC1155TokenReceiver` hooks still need to be called on it and the return values respected the same as if a standard transfer function had been called. - - However while the `safeTransferFrom` or `safeBatchTransferFrom` functions MUST revert if a receiving contract does not implement the `ERC1155TokenReceiver` interface, a non-standard function MAY proceed with the transfer. - - See "Implementation specific transfer API rules". - - -#### 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). See "Minting/creating and burning/destroying rules". - - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). See "Minting/creating and burning/destroying rules". -* `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). See "Minting/creating and burning/destroying rules". - - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). See "Minting/creating and burning/destroying rules". -* The total value transferred from address `0x0` minus the total value transferred to `0x0` observed via the `TransferSingle` and `TransferBatch` events MAY be used by clients and exchanges to determine 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("onERC1155Received(address,address,uint256,uint256,bytes)"))` - - If the return value is `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` 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 the recipient contract throws/reverts the transaction MUST be reverted. -* If the return value is anything other than `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` 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. -* A contract MAY skip calling the `onERC1155Received` hook function if the transfer operation is transferring the token to itself. - -**_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("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` - - If the return value is `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` 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 the recipient contract throws/reverts the transaction MUST be reverted. -* If the return value is anything other than `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` 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. -* A contract MAY skip calling the `onERC1155BatchReceived` hook function if the transfer operation is transferring the token(s) to itself. - -**_ERC1155TokenReceiver ERC-165 rules:_** -* The implementation of the ERC-165 `supportsInterface` function SHOULD be as follows: - ```solidity - function supportsInterface(bytes4 interfaceID) external view returns (bool) { - return interfaceID == 0x01ffc9a7 || // ERC-165 support (i.e. `bytes4(keccak256('supportsInterface(bytes4)'))`). - interfaceID == 0x4e2312e0; // ERC-1155 `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). - } - ``` -* The implementation MAY differ from the above but: - - It MUST return the constant value `true` if `0x01ffc9a7` is passed through the `interfaceID` argument. This signifies ERC-165 support. - - It MUST return the constant value `true` if `0x4e2312e0` is passed through the `interfaceID` argument. This signifies ERC-1155 `ERC1155TokenReceiver` support. - - It MUST NOT consume more than 10,000 gas. - - This keeps it below the ERC-165 requirement of 30,000 gas, reduces the gas reserve needs and minimises possible side-effects of gas exhaustion during the call. - -**_Implementation specific transfer API rules:_** -* If an implementation specific API function is used to transfer ERC-1155 token(s) to a contract, the `safeTransferFrom` or `safeBatchTransferFrom` (as appropriate) rules MUST still be followed if the receiver implements the `ERC1155TokenReceiver` interface. If it does not the non-standard implementation SHOULD revert but MAY proceed. -* An example: - 1. An approved user calls a function such as `function myTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values);`. - 2. `myTransferFrom` updates the balances for `_from` and `_to` addresses for all `_ids` and `_values`. - 3. `myTransferFrom` emits `TransferBatch` with the details of what was transferred from address `_from` to address `_to`. - 4. `myTransferFrom` checks if `_to` is a contract address and determines that it is so (if not, then the transfer can be considered successful). - 5. `myTransferFrom` calls `onERC1155BatchReceived` on `_to` and it reverts or returns an unknown value (if it had returned `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` the transfer can be considered successful). - 6. At this point `myTransferFrom` SHOULD revert the transaction immediately as receipt of the token(s) was not explicitly accepted by the `onERC1155BatchReceived` function. - 7. If however `myTransferFrom` wishes to continue it MUST call `supportsInterface(0x4e2312e0)` on `_to` and if it returns the constant value `true` the transaction MUST be reverted, as it is now known to be a valid receiver and the previous acceptance step failed. - - NOTE: You could have called `supportsInterface(0x4e2312e0)` at a previous step if you wanted to gather and act upon that information earlier, such as in a hybrid standards scenario. - 8. If the above call to `supportsInterface(0x4e2312e0)` on `_to` reverts or returns a value other than the constant value `true` the `myTransferFrom` function MAY consider this transfer successful. - - __NOTE__: this MAY result in unrecoverable tokens if sent to an address that does not expect to receive ERC-1155 tokens. -* The above example is not exhaustive but illustrates the major points (and shows that most are shared with `safeTransferFrom` and `safeBatchTransferFrom`): - - Balances that are updated MUST have equivalent transfer events emitted. - - A receiver address has to be checked if it is a contract and if so relevant `ERC1155TokenReceiver` hook function(s) have to be called on it. - - Balances (and events associated) that are referenced in a call to an `ERC1155TokenReceiver` hook MUST be updated (and emitted) before the `ERC1155TokenReceiver` hook is called. - - The return values of the `ERC1155TokenReceiver` hook functions that are called MUST be respected if they are implemented. - - Only non-standard transfer functions MAY allow tokens to be sent to a recipient contract that does NOT implement the necessary `ERC1155TokenReceiver` hook functions. `safeTransferFrom` and `safeBatchTransferFrom` MUST revert in that case (unless it is a hybrid standards implementation see "Backwards Compatibility"). - -**_Minting/creating and burning/destroying rules:_** -* A mint/create operation is essentially a specialized transfer and MUST follow these rules: - - 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. - - The "TransferSingle and TransferBatch event rules" MUST be followed as appropriate for the mint(s) (i.e. singles or batches) however the `_from` argument MUST be set to `0x0` (i.e. zero address) to flag the transfer as a mint to contract observers. - - __NOTE:__ This includes tokens that are given an initial balance in the contract. The balance of the contract MUST also be able to be determined by events alone meaning initial contract balances (for eg. in construction) MUST emit events to reflect those balances too. -* A burn/destroy operation is essentially a specialized transfer and MUST follow these rules: - - The "TransferSingle and TransferBatch event rules" MUST be followed as appropriate for the burn(s) (i.e. singles or batches) however the `_to` argument MUST be set to `0x0` (i.e. zero address) to flag the transfer as a burn to contract observers. - - When burning/destroying you do not have to actually transfer to `0x0` (that is impl specific), only the `_to` argument in the event MUST be set to `0x0` as above. -* The total value transferred from address `0x0` minus the total value transferred to `0x0` observed via the `TransferSingle` and `TransferBatch` events MAY be used by clients and exchanges to determine the "circulating supply" for a given token ID. -* As mentioned above mint/create and burn/destroy operations are specialized transfers and so will likely be accomplished with custom transfer functions rather than `safeTransferFrom` or `safeBatchTransferFrom`. If so the "Implementation specific transfer API rules" section would be appropriate. - - Even in a non-safe API and/or hybrid standards case the above event rules MUST still be adhered to when minting/creating or burning/destroying. -* A contract MAY skip calling the `ERC1155TokenReceiver` hook function(s) if the mint operation is transferring the token(s) to itself. In all other cases the `ERC1155TokenReceiver` rules MUST be followed as appropriate for the implementation (i.e. safe, custom and/or hybrid). - - -##### A solidity example of the keccak256 generated constants for the various magic values (these MAY be used by implementation): - -```solidity -bytes4 constant public ERC1155_ERC165 = 0xd9b67a26; // ERC-165 identifier for the main token standard. -bytes4 constant public ERC1155_ERC165_TOKENRECEIVER = 0x4e2312e0; // ERC-165 identifier for the `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). -bytes4 constant public ERC1155_ACCEPTED = 0xf23a6e61; // Return value from `onERC1155Received` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`). -bytes4 constant public ERC1155_BATCH_ACCEPTED = 0xbc197c81; // Return value from `onERC1155BatchReceived` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). -``` - -### 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 a large number of tokens to use the same on-chain string by defining a URI once, for that large number of tokens. - -* 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. - -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. - -#### Metadata Extensions - -The optional `ERC1155Metadata_URI` extension can be identified with the (ERC-165 Standard Interface Detection)[./eip-165.md]. - -If the optional `ERC1155Metadata_URI` extension is included: -* The ERC-165 `supportsInterface` function MUST return the constant value `true` if `0x0e89341c` is passed through the `interfaceID` argument. -* _Changes_ to the URI MUST emit the `URI` event if the change can be expressed with an event (i.e. it isn't dynamic/programmatic). - - An implementation MAY emit the `URI` event during a mint operation but it is NOT mandatory. An observer MAY fetch the metadata uri at mint time from the `uri` function if it was not emitted. -* The `uri` function SHOULD be used to retrieve values if no event was emitted. -* The `uri` function MUST return the same value as the latest event for an `_id` if it was emitted. -* The `uri` function MUST NOT be used to check for the existence of a token as it is possible for an implementation to return a valid string even if the token does not exist. - -```solidity -pragma solidity ^0.5.9; - -/** - 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 MUST 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. -* The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary. - -```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](./eip-1761.md) is suggested. -The counterpart `isApprovedForAll` provides introspection into any 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 [EIP-2535](./eip-2535.md). 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](./eip-1761.md) which is compatible with ERC-1155. - -## Backwards Compatibility - -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 revert 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 ERC-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 `supportsInterface(0x4e2312e0)` on the recipient contract, providing at least 10,000 gas. -2. If the function call succeeds and the return value is the constant value `true` the implementation proceeds as a regular ERC-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 the constant value `true` the implementation can assume the recipient contract 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 ERC-1155/ERC-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 *__ERC-1155 transfer events MUST still be emitted.__* This is so the balances can still be determined via events alone as per ERC-1155 standard rules. - -## 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`. - -It is RECOMMENDED that clients and wallets sort the token IDs and associated values (in ascending order) when posting a batch transfer, as some ERC-1155 implementations offer significant gas cost savings when IDs are sorted. See [Horizon Games - Multi-Token Standard](https://github.com/horizon-games/multi-token-standard) "packed balance" implementation for an example of this. - -### 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, transferred or destroyed. - -### Non-Fungible Tokens - -The following strategies are examples of how you MAY mix fungible and non-fungible tokens together in the same contract. The standard does NOT mandate how an implementation must do this. - -##### Split ID bits - -The top 128 bits of the uint256 `_id` parameter in any ERC-1155 function MAY represent the base token ID, while the bottom 128 bits MAY represent the index of the non-fungible to make it unique. - -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 a particular non-fungible within that set, `_id` could be passed as ``. - -To identify a non-fungible set/category as a whole (or a fungible) you COULD just pass in the base id via the `_id` argument as ``. If your implementation uses this technique this naturally means the index of a non-fungible SHOULD be 1-based. - -Inside the contract code the two pieces of data needed to access the individual non-fungible can be extracted with uint128(~0) and the same mask shifted by 128. - -```solidity -uint256 baseTokenNFT = 12345 << 128; -uint128 indexNFT = 50; - -uint256 baseTokenFT = 54321 << 128; - -balanceOf(baseTokenNFT, msg.sender); // Get balance of the base token for non-fungible set 12345 (this MAY be used to get balance of the user for all of this token set if the implementation wishes as a convenience). -balanceOf(baseTokenNFT + indexNFT, msg.sender); // Get balance of the token at index 50 for non-fungible set 12345 (should be 1 if user owns the individual non-fungible token or 0 if they do not). -balanceOf(baseTokenFT, msg.sender); // Get balance of the fungible base token 54321. -``` - -Note that 128 is an arbitrary number, an implementation MAY choose how they would like this split to occur as suitable for their use case. An observer of the contract would simply see events showing balance transfers and mints happening and MAY track the balances using that information alone. -For an observer to be able to determine type (non-fungible or fungible) from an ID alone they would have to know the split ID bits format on a implementation by implementation basis. - -The [ERC-1155 Reference Implementation](https://github.com/enjin/erc-1155) is an example of the split ID bits strategy. - -##### Natural Non-Fungible tokens - -Another simple way to represent non-fungibles is to allow a maximum value of 1 for each non-fungible token. This would naturally mirror the real world, where unique items have a quantity of 1 and fungible items have a quantity greater than 1. - -## References - -**Standards** -- [ERC-721 Non-Fungible Token Standard](./eip-721.md) -- [ERC-165 Standard Interface Detection](./eip-165.md) -- [ERC-1538 Transparent Contract Standard](./eip-1538.md) -- [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/) -- [ERC-1155: A new standard for The Sandbox](https://medium.com/sandbox-game/erc-1155-a-new-standard-for-the-sandbox-c95ee1e45072) - -## 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 b460151ea271cc..c8ce36929836ca 100644 --- a/EIPS/eip-1167.md +++ b/EIPS/eip-1167.md @@ -1,115 +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 6da0dc669e80bd..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](/assets/eip-1175/wallet.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](/assets/eip-1175/workflow.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 0bcf6814fc20fd..ce8fc9b21156bc 100644 --- a/EIPS/eip-1178.md +++ b/EIPS/eip-1178.md @@ -1,156 +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 88b9672799e43e..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 (@mcdee) -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 7443ea22ff54ef..13ed2e6f3899af 100644 --- a/EIPS/eip-1186.md +++ b/EIPS/eip-1186.md @@ -3,7 +3,7 @@ eip: 1186 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 @@ -52,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 @@ -135,4 +135,4 @@ Since this only adds a new Method there are no issues with Backwards Compatibili 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 c78b3f9c22fb15..9927c0a32159b5 100644 --- a/EIPS/eip-1191.md +++ b/EIPS/eip-1191.md @@ -1,127 +1,7 @@ --- eip: 1191 -title: Add chain id to mixed-case checksum address encoding -author: Juliano Rizzo (@juli) -status: Last Call -review-period-end: 2019-11-18 -type: Standards Track 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. - -## Abstract -The EIP-55 was created to prevent users from losing funds by sending them to invalid addresses. This EIP extends EIP-55 to protect users from losing funds by sending them to addresses that are valid but that where obtained from a client of another network.For example, if this EIP is implemented, a wallet can alert the user that is trying to send funds to an Ethereum Testnet address from an Ethereum Mainnet wallet. - -## Motivation -The motivation of this proposal is to provide a mechanism to allow software to distinguish addresses from different Ethereum based networks. This proposal is necessary because Ethereum addresses are hashes of public keys and do not include any metadata. By extending the EIP-55 checksum algorithm it is possible to achieve this objective. - -## 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 = [ -"0x27b1fdb04752bbc536007a920d24acb045561c26", -"0x3599689E6292b81B2d85451025146515070129Bb", -"0x42712D45473476b98452f434e72461577D686318", -"0x52908400098527886E0F7030069857D2E4169EE7", -"0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", -"0x6549f4939460DE12611948b3f82b88C3C8975323", -"0x66f9664f97F2b50F62D13eA064982f936dE76657", -"0x8617E340B3D01FA5F11F306F4090FD50E238070D", -"0x88021160C5C792225E4E5452585947470010289D", -"0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb", -"0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB", -"0xde709f2102306220921060314715629080e2fb77", -"0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359", -] -rsk_mainnet = [ -"0x27b1FdB04752BBc536007A920D24ACB045561c26", -"0x3599689E6292B81B2D85451025146515070129Bb", -"0x42712D45473476B98452f434E72461577d686318", -"0x52908400098527886E0F7030069857D2E4169ee7", -"0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD", -"0x6549F4939460DE12611948B3F82B88C3C8975323", -"0x66F9664f97f2B50F62d13EA064982F936de76657", -"0x8617E340b3D01Fa5f11f306f4090fd50E238070D", -"0x88021160c5C792225E4E5452585947470010289d", -"0xD1220A0Cf47c7B9BE7a2e6ba89F429762E7B9adB", -"0xDBF03B407c01E7CD3cBea99509D93F8Dddc8C6FB", -"0xDe709F2102306220921060314715629080e2FB77", -"0xFb6916095cA1Df60bb79ce92cE3EA74c37c5d359", -] -rsk_testnet = [ -"0x27B1FdB04752BbC536007a920D24acB045561C26", -"0x3599689e6292b81b2D85451025146515070129Bb", -"0x42712D45473476B98452F434E72461577D686318", -"0x52908400098527886E0F7030069857D2e4169EE7", -"0x5aAeb6053F3e94c9b9A09F33669435E7EF1BEaEd", -"0x6549f4939460dE12611948b3f82b88C3c8975323", -"0x66f9664F97F2b50f62d13eA064982F936DE76657", -"0x8617e340b3D01fa5F11f306F4090Fd50e238070d", -"0x88021160c5C792225E4E5452585947470010289d", -"0xd1220a0CF47c7B9Be7A2E6Ba89f429762E7b9adB", -"0xdbF03B407C01E7cd3cbEa99509D93f8dDDc8C6fB", -"0xDE709F2102306220921060314715629080e2Fb77", -"0xFb6916095CA1dF60bb79CE92ce3Ea74C37c5D359", -] -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 - -| Project | 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) | -| Web3.js | Yes | [JavaScript](https://github.com/ethereum/web3.js/blob/aaf26c8806bc9fb60cf6dcb6658104963c6c7fc7/packages/web3-utils/src/Utils.js#L140) | -| EthereumJS-util | Yes | [JavaScript](https://github.com/ethereumjs/ethereumjs-util/pull/204/commits/cdf0b3c996b05ac5b1f758f17ea9f9ed1847c1eb) | -| ENS address-encoder | Yes | [TypeScript](https://github.com/ensdomains/address-encoder/commit/5bf53b13fa014646ea28c9e5f937361dc9b40590) | - -## 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-1191.md diff --git a/EIPS/eip-1193.md b/EIPS/eip-1193.md index 890310376eb783..ea5377a8956e5d 100644 --- a/EIPS/eip-1193.md +++ b/EIPS/eip-1193.md @@ -1,7 +1,7 @@ --- eip: 1193 title: Ethereum Provider JavaScript API -author: Fabian Vogelsteller (@frozeman), Ryan Ghods (@ryanio), Victor Maia (@MaiaVictor), Marc Garreau (@marcgarreau), Erik Marks (@rekmarks) +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 @@ -323,7 +323,7 @@ Instead, Providers should support RPC methods for explicitly requesting account ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). ## Appendix I: Consumer-Facing API Documentation diff --git a/EIPS/eip-1202.md b/EIPS/eip-1202.md index f979466c18a804..2868fbb772b93b 100644 --- a/EIPS/eip-1202.md +++ b/EIPS/eip-1202.md @@ -1,147 +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 --- -## 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](./eip-20.md) or other new standards([EIP-777](./eip-777.md)) and item standard such as [EIP-721](./eip-721.md) -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](./eip-20.md) approach and later a [EIP-777](./eip-777.md) 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](./eip-721.md) -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 - -```solidity -pragma solidity ^0.5.8; - - -/** - * - Multiple issue - * - Multiple selection - * - Ordered multiple result - **/ -contract ERC1202 { - - // 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. - -## Backward Compatibility -There is no backward compatibility issue we are aware of. - -## 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) - -## Security Considerations - -EIP-1202 is a voting standard. We expect the voting standard to be used in connection with other contracts such as token distributions, conducting actions in consensus or on behalf of an entity, multi-signature wallets, etc. - -The major security consideration is to ensure only using the standard interface for performing downstream actions or receiving upstream input (vote casting). We expect future audit tool to be based on standard interfaces. - -It's also important to note as discussed in this standard that for the sake of simplicity, EIP-1202 is kept in the very basic form. It can be extended to support many different implementation variations. Such variations might contain different assumptions of the behavior and interpretation of actions. One example would be: What does it mean if someone votes multiple times through `vote`? - - Would that mean the voter is increasing their weight, or - - vote multiple options in the meanwhile, or - - Does the latter vote override the previous vote? - -Because of the flexible nature of voting, we expect many subsequent standards need to be created as an extension of EIP-1202. We suggest any extension or implementations of this standard be thoroughly audited before included in large scale or high asset volume applications. - -The third consideration is non-trivialness. Some voting applications assume ***anonymity***, ***randomness***, ***time-based deadline***, ***ordering***, etc, these requirements in Ethereum are known to be non-trivial to achieve. We suggest any applications or organizations rely on audited and time-proven shared libraries when these requirements need to be enforced in their applications. - -The fourth consideration is potential abuse. When voting is standardized and put on contract, it is possible to write another contract that rewards a voter to vote in a certain way. It creates potential issues of bribery and conflict of interest abuse that is previously hard to implement. - - -## Bibliography -### Related EIPs - - [EIP-20: ERC-20 Token Standard (a.k.a. ERC-20)](./eip-20.md) - - [EIP-165: Standard Interface Detection](./eip-165.md) - - [EIP-721: Non-Fungible Token Standard(a.k.a. ERC-721)](./eip-721.md) - - [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](./eip-777.md) - - [EIP-897: ERC DelegateProxy](./eip-897.md) - - [EIP-1155: Crypto Item Standard](./eip-1155.md) - - [EIP-1178: Multi-class Token Standard](./eip-1178.md) - - [EIP-1167: Minimal Proxy Contract](./eip-1167.md) - - [EIP-1203: Multi-class Token Standard(ERC-20 Extension)](./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) - - [Consensus/PLCR implementation](https://github.com/ConsenSys/PLCRVoting) - - [Aragon Voting App](https://wiki.aragon.org/dev/apps/voting/) - -## Acknowledgement -We appreciate Ansley, Andrew, Fred from Enigma, Fan and Raullen from IoTex for sharing us their use cases. we also appreciate the valuable input for designing an EIP from distinguished community members including: @frozeman, @fulldecent, @bingen, @aodhgan. - -## Work Directory -The drafting and revision of EIP-1202 is conducted at [GitHub/xinbenlv/eip-1202](https://github.com/xinbenlv/eip-1202) - -## 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 12ccfba22872df..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](./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. ./eip-20.md -- ERC-721 Non-Fungible Token Standard. ./eip-721.md -- ERC-1178 Multi-class Token Standard. ./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 be566ead875d12..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 @@ -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 c4363d36dbb59e..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_. @@ -58,4 +58,4 @@ Test cases shall be created once the specification is to be accepted by the deve 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 f20570a91fb2b1..e9c787cc4866f7 100644 --- a/EIPS/eip-1240.md +++ b/EIPS/eip-1240.md @@ -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 d8224f77635652..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 their day to day life. The protocol allows for the creation of software that puts everything all at one place. Their 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[] calldata 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[] calldata _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[] calldata _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[] memory); - - /// @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[] memory); - - /// @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() external view; - - /// @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. ./eip-20.md -1. ERC-165 Standard Interface Detection. ./eip-165.md -1. ERC-725/735 Claim Registry ./eip-725.md -1. ERC-173 Owned Standard. ./eip-173.md -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 8241665759def7..2a1649d5b0f11f 100644 --- a/EIPS/eip-1271.md +++ b/EIPS/eip-1271.md @@ -1,85 +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](./eip-725.md) & [ERC-1078](./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(bytes32,bytes)") - bytes4 constant internal MAGICVALUE = 0x1626ba7e; - - /** - * @dev Should return whether the signature provided is valid for the provided data - * @param _hash Hash of the data to be signed - * @param _signature Signature byte array associated with _data - * - * MUST return the bytes4 magic value 0x1626ba7e 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( - bytes32 _hash, - 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 : - -* ERC725 [implemented in the ERC725Account](https://github.com/ERC725Alliance/ERC725/blob/master/implementations/contracts/ERC725/ERC725Account.sol#L73-L90). -* 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 d5bcc711b3a4c0..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 --- @@ -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 e1ebfa6d43f9c0..cdc8d222b04013 100644 --- a/EIPS/eip-1283.md +++ b/EIPS/eip-1283.md @@ -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 16b5a992176d52..7d6d20525b5360 100644 --- a/EIPS/eip-1285.md +++ b/EIPS/eip-1285.md @@ -3,7 +3,7 @@ eip: 1285 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 @@ -39,4 +39,4 @@ This EIP requires a backwards incompatible change for the ``Gcallstipend`` gas p ## 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 33fb4a453c5097..4eb207482cdd5d 100644 --- a/EIPS/eip-1295.md +++ b/EIPS/eip-1295.md @@ -3,7 +3,7 @@ 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 @@ -86,4 +86,4 @@ Test cases shall be created once the specification is to be accepted by the deve 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 94991c0a9c877c..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 (@njgheorghita) -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](./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](./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](./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](./eip-165.md) and avail themselves of resources to publish more complex interfaces such as [EIP-926](./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 index 5db84b8bcaeb6a..8d201b25cb9b2f 100644 --- a/EIPS/eip-1337.md +++ b/EIPS/eip-1337.md @@ -1,247 +1,7 @@ --- eip: 1337 -title: Subscriptions on the blockchain -author: Kevin Owocki , Andrew Redden , Scott Burke , Kevin Seagraves , Luka Kacil , Štefan Šimec , Piotr Kosiński (@kosecki123), ankit raj , John Griffin , Nathan Creswell -discussions-to: https://ethereum-magicians.org/t/eip-1337-subscriptions-on-the-blockchain/4422 -type: Standards Track -status: Draft category: ERC -created: 2018-08-01 -requires: 20, 165 +status: Moved --- -## Simple Summary -Monthly subscriptions are a key monetization channel for legacy web, and arguably they are the most healthy monetization channel for businesses on the legacy web (especially when compared to ad/surveillance) based models. They are arguably more healthy than a token based economic system (depending upon the vesting model of the ICO) because - -##### For a user: - * you don't have to read a complex whitepaper to use a dapps utility (as opposed to utility tokens) -* you don't have to understand the founder's vesting schedules -* you can cancel anytime - -##### For a Service Provider: -* since you know your subscriber numbers, churn numbers, conversion rate, you get consistent cash flow, and accurate projections -* you get to focus on making your customers happy -* enables you to remove speculators from your ecosystem - -For these reasons, we think it's imperative to create a standard way to do 'subscriptions' on Ethereum. - -## Abstract -To enable replay-able transactions users sign a concatenated bytes hash that is composed of the input data needed to execute the transaction. This data is stored off chain by the recipient of the payment and is transmitted to the customers smart contract for execution alongside a provided signature. - -## Motivation -Recurring payments are the bedrock of SaSS and countless other businesses, a robust specification for defining this interaction will enable a broad spectrum of revenue generation and business models. - -## Specification -#### Enum Contract - -EIP-1337 Contracts should be compiled with a contract that references all the enumerations that are required for operation - -```SOLIDITY -/// @title Enum - Collection of enums -/// Original concept from Richard Meissner - Gnosis safe contracts -contract Enum { - enum Operation { - Call, - DelegateCall, - Create, - ERC20, - ERC20Approve - } - enum SubscriptionStatus { - ACTIVE, - PAUSED, - CANCELLED, - EXPIRED - } - - enum Period { - INIT, - DAY, - WEEK, - MONTH - } -} -``` - -#### EIP-165 - -EIP-1337 compliant contracts support EIP-165 announcing what interfaces they support - -```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); -} -``` - -#### Public View Functions - -###### isValidSubscription -```SOLIDITY - -/** @dev Checks if the subscription is valid. - * @param bytes subscriptionHash is the identifier of the customer's subscription with its relevant details. - * @return success is the result of whether the subscription is valid or not. - **/ - -function isValidSubscription( - uint256 subscriptionHash - ) - public - view - returns ( - bool success - ) -``` -###### getSubscriptionStatus -```SOLIDITY - -/** @dev returns the value of the subscription - * @param bytes subscriptionHash is the identifier of the customer's subscription with its relevant details. - * @return status is the enumerated status of the current subscription, 0 expired, 1 active, 2 paused, 3 cancelled - **/ -function getSubscriptionStatus( - uint256 subscriptionHash - ) - public - view - returns ( - uint256 status, - uint256 nextWithdraw - ) -``` - -###### getSubscriptionHash - -```SOLIDITY -/** @dev returns the hash of cocatenated inputs to the address of the contract holding the logic., - * the owner would sign this hash and then provide it to the party for execution at a later date, - * this could be viewed like a cheque, with the exception that unless you specifically - * capture the hash on chain a valid signature will be executable at a later date, capturing the hash lets you modify the status to cancel or expire it. - * @param address recipient the address of the person who is getting the funds. - * @param uint256 value the value of the transaction - * @param bytes data the data the user is agreeing to - * @param uint256 txGas the cost of executing one of these transactions in gas(probably safe to pad this) - * @param uint256 dataGas the cost of executing the data portion of the transaction(delegate calls etc) - * @param uint 256 gasPrice the agreed upon gas cost of Execution of this subscription(cost incurment is up to implementation, ie, sender or receiver) - * @param address gasToken address of the token in which gas will be compensated by, address(0) is ETH, only works in the case of an enscrow implementation) - * @param bytes meta dynamic bytes array with 4 slots, 2 required, 2 optional // address refundAddress / uint256 period / uint256 offChainID / uint256 expiration (uinx timestamp) - * @return bytes32, return the hash input arguments concatenated to the address of the contract that holds the logic. - **/ -function getSubscriptionHash( - address recipient, - uint256 value, - bytes data, - Enum.Operation operation, - uint256 txGas, - uint256 dataGas, - uint256 gasPrice, - address gasToken, - bytes meta - ) - public - view - returns ( - bytes32 subscriptionHash - ) -``` - - -###### getModifyStatusHash - -```SOLIDITY -/** @dev returns the hash of concatenated inputs that the owners user would sign with their public keys - * @param address recipient the address of the person who is getting the funds. - * @param uint256 value the value of the transaction - * @return bytes32 returns the hash of concatenated inputs with the address of the contract holding the subscription hash - **/ -function getModifyStatusHash( - bytes32 subscriptionHash - Enum.SubscriptionStatus status - ) - public - view - returns ( - bytes32 modifyStatusHash - ) -``` -#### Public Functions - -###### modifyStatus -```SOLIDITY - -/** @dev modifys the current subscription status - * @param uint256 subscriptionHash is the identifier of the customer's subscription with its relevant details. - * @param Enum.SubscriptionStatus status the new status of the subscription - * @param bytes signatures of the requested method being called - * @return success is the result of the subscription being paused - **/ -function modifyStatus( - uint256 subscriptionHash, - Enum.SubscriptionStatus status, - bytes signatures - ) - public - returns ( - bool success - ) -``` - -###### executeSubscription -```SOLIDITY - -/** @dev returns the hash of cocatenated inputs to the address of the contract holding the logic., - * the owner would sign this hash and then provide it to the party for execution at a later date, - * this could be viewed like a cheque, with the exception that unless you specifically - * capture the hash on chain a valid signature will be executable at a later date, capturing the hash lets you modify the status to cancel or expire it. - * @param address recipient the address of the person who is getting the funds. - * @param uint256 value the value of the transaction - * @param bytes data the data the user is agreeing to - * @param uint256 txGas the cost of executing one of these transactions in gas(probably safe to pad this) - * @param uint256 dataGas the cost of executing the data portion of the transaction(delegate calls etc) - * @param uint 256 gasPrice the agreed upon gas cost of Execution of this subscription(cost incurment is up to implementation, ie, sender or receiver) - * @param address gasToken address of the token in which gas will be compensated by, address(0) is ETH, only works in the case of an enscrow implementation) - * @param bytes meta dynamic bytes array with 4 slots, 2 required, 2 optional // address refundAddress / uint256 period / uint256 offChainID / uint256 expiration (uinx timestamp) - * @param bytes signatures signatures concatenated that have signed the inputs as proof of valid execution - * @return bool success something to note that a failed execution will still pay the issuer of the transaction for their gas costs. - **/ -function executeSubscription( - address to, - uint256 value, - bytes data, - Enum.Operation operation, - uint256 txGas, - uint256 dataGas, - uint256 gasPrice, - address gasToken, - bytes meta, - bytes signatures - ) - public - returns ( - bool success - ) -``` - -## Rationale -Merchants who accept credit-cards do so by storing a token that is retrieved from a third party processor(stripe, paypal, etc), this token is used to grant access to pull payment from the cx's credit card provider and move funds to the merchant account. -Having users sign input data acts in a similliar fashion and enables that merchant to store the signature of the concatenated bytes hash and input data used to generate the hash and pass them off to the contract holding the subscription logic, thus enabling a workflow that is similliar to what exists in the present day legacy web. - -## Backwards Compatibility -N/A - -## Test Cases -TBD - -## Implementation -TBD - -## 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-1337.md diff --git a/EIPS/eip-1344.md b/EIPS/eip-1344.md index f10106a0016d3d..02e46aebc80e6e 100644 --- a/EIPS/eip-1344.md +++ b/EIPS/eip-1344.md @@ -48,4 +48,4 @@ A reference implementation for the Trinity Python client is [here](https://githu 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-1363.md b/EIPS/eip-1363.md index 6175a7bcce8e5c..8c0100cab26161 100644 --- a/EIPS/eip-1363.md +++ b/EIPS/eip-1363.md @@ -1,208 +1,7 @@ --- eip: 1363 -title: ERC-1363 Payable Token -author: Vittorio Minacori (@vittominacori) -discussions-to: https://github.com/ethereum/eips/issues/1363 -status: Final -type: Standards Track category: ERC -created: 2020-01-31 -requires: 20, 165 +status: Moved --- -## Simple Summary -Defines a token interface for [ERC-20](./eip-20.md) tokens that supports executing recipient code after `transfer` or `transferFrom`, or spender code after `approve`. - -## Abstract -Standard functions a token contract and contracts working with tokens can implement to make a token Payable. - -`transferAndCall` and `transferFromAndCall` will call an `onTransferReceived` on a `ERC1363Receiver` contract. - -`approveAndCall` will call an `onApprovalReceived` on a `ERC1363Spender` contract. - -## Motivation -There is no way to execute code after a [ERC-20](./eip-20.md) transfer or approval (i.e. making a payment), so to make an action it is required to send another transaction and pay GAS twice. - -This proposal wants to make token payments easier and working without the use of any other listener. It allows to make a callback after a transfer or approval in a single transaction. - -There are many proposed uses of Ethereum smart contracts that can accept [ERC-20](./eip-20.md) payments. - -Examples could be -* to create a token payable crowdsale -* selling services for tokens -* paying invoices -* making subscriptions - -For these reasons it was named as **"Payable Token"**. - -Anyway you can use it for specific utilities or for any other purposes who require the execution of a callback after a transfer or approval received. - -This proposal has been inspired by the [ERC-721](./eip-721.md) `onERC721Received` and `ERC721TokenReceiver` behaviours. - -## Specification -Implementing contracts **MUST** implement the [ERC-1363](./eip-1363.md) interface as well as the [ERC-20](./eip-20.md) and [ERC-165](./eip-165.md) interfaces. - -```solidity -pragma solidity ^0.8.0; - -interface ERC1363 /* is ERC20, ERC165 */ { - /* - * Note: the ERC-165 identifier for this interface is 0xb0202a11. - * 0xb0202a11 === - * bytes4(keccak256('transferAndCall(address,uint256)')) ^ - * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ - * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ - * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ - * bytes4(keccak256('approveAndCall(address,uint256)')) ^ - * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) - */ - - /** - * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferAndCall(address to, uint256 value) external returns (bool); - - /** - * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferAndCall(address to, uint256 value, bytes memory data) external returns (bool); - - /** - * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferFromAndCall(address from, address to, uint256 value) external returns (bool); - - - /** - * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool); - - /** - * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param value uint256 The amount of tokens to be spent - */ - function approveAndCall(address spender, uint256 value) external returns (bool); - - /** - * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param value uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format, sent in call to `spender` - */ - function approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool); -} - -interface ERC20 { - function totalSupply() external view returns (uint256); - function balanceOf(address account) external view returns (uint256); - function transfer(address recipient, uint256 amount) external returns (bool); - function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); - function allowance(address owner, address spender) external view returns (uint256); - function approve(address spender, uint256 amount) external returns (bool); - event Transfer(address indexed from, address indexed to, uint256 value); - event Approval(address indexed owner, address indexed spender, uint256 value); -} - -interface ERC165 { - function supportsInterface(bytes4 interfaceId) external view returns (bool); -} -``` - -A contract that wants to accept token payments via `transferAndCall` or `transferFromAndCall` **MUST** implement the following interface: - -```solidity -/** - * @title ERC1363Receiver interface - * @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall` - * from ERC1363 token contracts. - */ -interface ERC1363Receiver { - /* - * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. - * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) - */ - - /** - * @notice Handle the receipt of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function - * @param from address The address which are token transferred from - * @param value uint256 The amount of tokens transferred - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` - * unless throwing - */ - function onTransferReceived(address operator, address from, uint256 value, bytes memory data) external returns (bytes4); -} -``` - -A contract that wants to accept token payments via `approveAndCall` **MUST** implement the following interface: - -```solidity -/** - * @title ERC1363Spender interface - * @dev Interface for any contract that wants to support `approveAndCall` - * from ERC1363 token contracts. - */ -interface ERC1363Spender { - /* - * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. - * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) - */ - - /** - * @notice Handle the approval of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after an `approve`. This function MAY throw to revert and reject the - * approval. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param owner address The address which called `approveAndCall` function - * @param value uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` - * unless throwing - */ - function onApprovalReceived(address owner, uint256 value, bytes memory data) external returns (bytes4); -} -``` - -## Rationale -The choice to use `transferAndCall`, `transferFromAndCall` and `approveAndCall` derives from the [ERC-20](./eip-20.md) naming. They want to highlight that they have the same behaviours of `transfer`, `transferFrom` and `approve` with the addition of a callback on receiver or spender. - -## Backwards Compatibility -This proposal has been inspired also by [ERC-223](https://github.com/ethereum/EIPs/issues/223) and [ERC-677](https://github.com/ethereum/EIPs/issues/677) but it uses the [ERC-721](./eip-721.md) approach, so it doesn't override the [ERC-20](./eip-20.md) `transfer` and `transferFrom` methods and defines the interfaces IDs to be implemented maintaining the [ERC-20](./eip-20.md) backwards compatibility. - -## Security Considerations -The `approveAndCall` and `transferFromAndCall` methods can be affected by the same issue of the standard [ERC-20](./eip-20.md) `approve` and `transferFrom` method. - -Changing an allowance with the `approveAndCall` methods brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. - -One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards ([EIP-20#issuecomment-263524729](https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)). - -## 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-1363.md diff --git a/EIPS/eip-137.md b/EIPS/eip-137.md index b35e9ef62c2649..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: - -```javascript -var node = namehash("beercoin.eth"); -var resolver = ens.resolver(node); -``` - -Then, ask the resolver for the address for the contract: - -```javascript -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: - -```solidity -function owner(bytes32 node) constant returns (address); -``` - -Returns the owner (registrar) of the specified node. - -```solidity -function resolver(bytes32 node) constant returns (address); -``` - -Returns the resolver for the specified node. - -```solidity -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. - -```solidity -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)`. - -```solidity -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)`. - -```solidity -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)`. - -```solidity -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: - -```solidity -function supportsInterface(bytes4 interfaceID) constant returns (bool) -``` - -The `supportsInterface` function is documented in [EIP-165](./eip-165.md), 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: - -```solidity -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: - -```solidity -event AddrChanged(bytes32 indexed node, address a); -``` -# Appendix A: Registry Implementation - -```solidity -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: - -```solidity -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: - -```solidity -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: - -```solidity -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. - -```solidity -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 481c0b18a207e1..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 -```solidity -/* 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 360ab3de2b59a2..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 -```solidity -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 1dba3a254f2e1a..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 -```solidity - /* 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 aa9f51c36821d1..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](./eip-1261.md)). 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](./eip-20.md) or (./eip-777.md)) and membership standard such as [EIP-1261](./eip-1261.md) -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)](./eip-20.md) -- [EIP-165: Standard Interface Detection](./eip-165.md) -- [EIP-721: Non-Fungible Token Standard(a.k.a. ERC-721)](./eip-721.md) -- [ERC-1261 MV Token Standard](./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 3d13ac80e9ff5a..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](/assets/eip-1438/intro.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](/assets/eip-1438/avatar.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](/assets/eip-1438/wallet.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 4977ed7de67e0a..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](./eip-1066.md). 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](./eip-1066.md)) 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 c905b7a2d4f783..9650ebb2ee5350 100644 --- a/EIPS/eip-1450.md +++ b/EIPS/eip-1450.md @@ -1,326 +1,7 @@ --- eip: 1450 -title: ERC-1450 A compatible security token for issuing and trading SEC-compliant securities -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: - -```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); -} -``` - -`ERC-20` is extended as follows: - -```solidity -/** - * 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)](./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 e559fc2bd8110a..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. -# 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 @@ -30,7 +31,7 @@ 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 +## Specification A 'node list' is a list of 'node records' [as defined by EIP-778](./eip-778.md) of arbitrary length. Lists @@ -41,7 +42,7 @@ 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 of the compressed 32-byte binary public key. +URL and is the base32 encoding (RFC-4648) of the compressed 32-byte binary public key. Example: @@ -51,7 +52,7 @@ 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 +### DNS Record Structure 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 @@ -65,7 +66,7 @@ where 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. + record content, excluding the `sig=` part, encoded as URL-safe base64 (RFC-4648). 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) @@ -89,17 +90,15 @@ packets. This limits the number of hashes that can be placed into an Example in zone file format: -```text -; 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 -``` + ; 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 +### Client Protocol To find nodes at a given DNS name, say "mynodes.org": @@ -124,7 +123,7 @@ 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? @@ -162,12 +161,12 @@ 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. -# References +## Security Considerations -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 base64 - and base32 data. +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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1462.md b/EIPS/eip-1462.md index 6893c3878b889f..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](./eip-20.md), 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](https://github.com/ethereum/EIPs/issues/1411), also [ERC-1450](https://eips.ethereum.org/EIPS/eip-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](./eip-777.md) 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](./eip-1066.md). Localization of these codes is out of the scope of this proposal and may be optionally solved by adopting [ERC-1444](./eip-1444.md) 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](./eip-20.md) 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](./eip-777.md) 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](./eip-1066.md). - -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](./eip-1450.md) 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 ee705c4685617c..2436f43e3cf419 100644 --- a/EIPS/eip-1470.md +++ b/EIPS/eip-1470.md @@ -3,7 +3,7 @@ eip: 1470 title: Smart Contract Weakness Classification (SWC) author: Gerhard Wagner (@thec00n) discussions-to: https://github.com/ethereum/EIPs/issues/1469 -status: Draft +status: Stagnant type: Informational created: 2018-09-18 --- @@ -40,7 +40,7 @@ Before discussing the SWC specification it is important to describe the terminol - 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. @@ -101,4 +101,4 @@ properties: 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 82bbce978b7ef5..52575223dd45cd 100644 --- a/EIPS/eip-1474.md +++ b/EIPS/eip-1474.md @@ -3,7 +3,7 @@ eip: 1474 title: Remote procedure call specification 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 @@ -293,10 +293,10 @@ Common chain IDs: ```sh # Request curl -X POST --data '{ - "id": 1337 + "id": 1337, "jsonrpc": "2.0", "method": "net_version", - "params": [], + "params": [] }' # Response @@ -2251,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 9f25ec464320ab..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 @@ -55,4 +55,4 @@ These would be important to have. _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 d5777e8ca8dec4..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](./eip-725.md) and [ERC-1056](./eip-1056.md) 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](./eip-725.md), [735](https://github.com/ethereum/EIPs/issues/735), [780](https://github.com/ethereum/EIPs/issues/780), [1056](./eip-1056.md), 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](./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](./eip-191.md) -- [ERC-725 Identities](./eip-725.md) -- [ERC-1056 Identities](./eip-1056.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-1484.md diff --git a/EIPS/eip-1485.md b/EIPS/eip-1485.md index bbddd55bb5abfc..ae8f0500595801 100644 --- a/EIPS/eip-1485.md +++ b/EIPS/eip-1485.md @@ -1,200 +1,200 @@ ---- -eip: 1485 -title: TEthashV1 -author: trustfarm , 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](./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, - -```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/). +--- +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://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 2905d797018660..e5cdf4854be6e5 100644 --- a/EIPS/eip-1491.md +++ b/EIPS/eip-1491.md @@ -1,528 +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 +status: Moved --- -## 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 -```solidity -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 - -```solidity - -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 - -```solidity -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 - -```solidity -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/). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1491.md diff --git a/EIPS/eip-1504.md b/EIPS/eip-1504.md index cb7eb3d3a6b11d..3badb18dfe7716 100644 --- a/EIPS/eip-1504.md +++ b/EIPS/eip-1504.md @@ -1,351 +1,7 @@ --- eip: 1504 -title: ERC-1504 Upgradable Smart Contract -author: Kaidong Wu , Chuqiao Ren , Ruthia He , Yun Ma , Xuanzhe Liu -discussions-to: https://github.com/ethereum/EIPs/issues/1503 -status: Draft -type: Standards Track category: ERC -created: 2018-10-17 +status: Moved --- -## Simple Summary - -A standard interface/guideline that makes a smart contract upgradable. - -## Abstract - -Ethereum smart contracts have suffered a number of security issues in the past few years. The cost of fixing such a bug in smart contract is significant; for example, the consequences of The DAO attack in June 2016 caused tremendous financial loss and the hard fork of Ethereum blockchain. - -The following standard makes it possible to upgrade a standard API within smart contracts. This standard provides basic functionalities to upgrade the operations of the contract without data migration. To ensure the decentralization/community interests, it also contains a voting mechanism to control the upgrading process. - -## Motivation - -Smart contract is immutable after deployment. If any security risk is identified or program bug is detected, developers always have to destruct the old contract, deploy a new one and potentially migrate the data (hard fork) to the new contract. In some cases, deploying a smart contract with bugs and potential security vulnerabilities can cause a significant amount of financial loss. - -We propose this upgradable contract to fix the current situation. With the upgradable contract, developers can deploy a new version of smart contract after previous deployment and retain the data at the same time. - -For example, after an ERC20-compliant token contract is deployed, the users exploit a vulnerability in the source code. Without the support of upgradable contract, developers have to fix this issue by deploy a new, secured contract otherwise the attackers would take advantage of the security hole, which may cause a tremendous financial loss. A challenge is how to migrate data from the old contract to a new one. With the upgradable contract below, this will become relatively easy as developers only have to upgrade the Handler contract to fix bugs while the Data contract will remain the same. - -## Specification - -The upgradable contract consists of three parts: - -- **Handler contract** (implements **Handler interface**) defines operations and provides services. This contract can be upgraded; -- **Data contract** keeps the resources (data) and is controlled by the Handler contract; -- **Upgrader contract (optional)** deals with the voting mechanism and upgrades the Handler contract. The voters are pre-defined by the contract owner. - -> The following codes are exact copies of the [ERC-1504 Upgradable Smart Contract.](https://gist.github.com/swordghost/77c96a972106af6ec6ccea9c2d66e768) - -### Handler contract and Handler interface - -Functions of the Handler contract vary with requirements, so developers would better design interfaces for Handler contracts to limit them and make sure external applications are always supported. - -Below is the specification of Handler interface. In the Handler interface we define the following actions: - -- Initialize the Data contract; -- Register the Upgrader contract address; -- Destruct the Handler contract after upgrading is done; -- Verify the current Handler is the working one → it should always return true. - -Developers have to define their business-related functions as well. - - -```solidity -/// Handler interface. -/// Handler defines business related functions. -/// Use the interface to ensure that your external services are always supported. -/// Because of function live(), we design IHandler as an abstract contract rather than a true interface. -contract IHandler { - - /// Initialize the data contarct. - /// @param _str value of exmStr of Data contract. - /// @param _int value of exmInt of Data contract. - /// @param _array value of exmArray of Data contract. - function initialize (string _str, uint256 _int, uint16 [] _array) public; - - /// Register Upgrader contract address. - /// @param _upgraderAddr address of the Upgrader contract. - function registerUpgrader (address _upgraderAddr) external; - - /// Upgrader contract calls this to check if it is registered. - /// @return if the Upgrader contract is registered. - function isUpgraderRegistered () external view returns(bool); - - /// Handler has been upgraded so the original one has to self-destruct. - function done() external; - - /// Check if the Handler contract is a working Handler contract. - /// It is used to prove the contract is a Handler contract. - /// @return always true. - function live() external pure returns(bool) { - return true; - } - - /** Functions - define functions here */ - - /** Events - add events here */ -} -``` - - -The process of deploying a Handler contract: - -1. Deploy Data contract; -2. Deploy a Handler contract at a given address specified in the Data contract; -3. Register the Handler contract address by calling setHandler() in the Data contract, or use an Upgrader contract to switch the Handler contract, which requires that Data contract is initialized; -4. Initialize Data contract if haven’t done it already. - -### Data Contract - -Below is the specification of Data contract. There are three parts in the Data contract: - -- **Administrator Data**: owner’s address, Handler contract’s address and a boolean indicating whether the contract is initialized or not; -- **Upgrader Data**: Upgrader contract’s address, upgrade proposal’s submission timestamp and proposal’s time period; -- **Resource Data**: all other resources that the contract needs to keep and manage. - - -```solidity -/// Data Contract -contract DataContract { - - /** Management data */ - /// Owner and Handler contract - address private owner; - address private handlerAddr; - - /// Ready? - bool private valid; - - /** Upgrader data */ - address private upgraderAddr; - uint256 private proposalBlockNumber; - uint256 private proposalPeriod; - /// Upgrading status of the Handler contract - enum UpgradingStatus { - /// Can be upgraded - Done, - /// In upgrading - InProgress, - /// Another proposal is in progress - Blocked, - /// Expired - Expired, - /// Original Handler contract error - Error - } - - /** Data resources - define variables here */ - - /** Modifiers */ - - /// Check if msg.sender is the Handler contract. It is used for setters. - /// If fail, throw PermissionException. - modifier onlyHandler; - - /// Check if msg.sender is not permitted to call getters. It is used for getters (if necessary). - /// If fail, throw GetterPermissionException. - modifier allowedAddress; - - /// Check if the contract is working. - /// It is used for all functions providing services after initialization. - /// If fail, throw UninitializationException. - modifier ready; - - /** Management functions */ - - /// Initializer. Just the Handler contract can call it. - /// @param _str default value of this.exmStr. - /// @param _int default value of this.exmInt. - /// @param _array default value of this.exmArray. - /// exception PermissionException msg.sender is not the Handler contract. - /// exception ReInitializationException contract has been initialized. - /// @return if the initialization succeeds. - function initialize (string _str, uint256 _int, uint16 [] _array) external onlyHandler returns(bool); - - /// Set Handler contract for the contract. Owner must set one to initialize the Data contract. - /// Handler can be set by owner or Upgrader contract. - /// @param _handlerAddr address of a deployed Handler contract. - /// @param _originalHandlerAddr address of the original Handler contract, only used when an Upgrader contract want to set the Handler contract. - /// exception PermissionException msg.sender is not the owner nor a registered Upgrader contract. - /// exception UpgraderException Upgrader contract does not provide a right address of the original Handler contract. - /// @return if Handler contract is successfully set. - function setHandler (address _handlerAddr, address _originalHandlerAddr) external returns(bool); - - /** Upgrader contract functions */ - - /// Register an Upgrader contract in the contract. - /// If a proposal has not been accepted until proposalBlockNumber + proposalPeriod, it can be replaced by a new one. - /// @param _upgraderAddr address of a deployed Upgrader contract. - /// exception PermissionException msg.sender is not the owner. - /// exception UpgraderConflictException Another Upgrader contract is working. - /// @return if Upgrader contract is successfully registered. - function startUpgrading (address _upgraderAddr) public returns(bool); - - /// Getter of proposalPeriod. - /// exception UninitializationException uninitialized contract. - /// exception GetterPermissionException msg.sender is not permitted to call the getter. - /// @return this.proposalPeriod. - function getProposalPeriod () public view isReady allowedAddress returns(uint256); - - /// Setter of proposalPeriod. - /// @param _proposalPeriod new value of this.proposalPeriod. - /// exception UninitializationException uninitialized contract. - /// exception PermissionException msg.sender is not the owner. - /// @return if this.proposalPeriod is successfully set. - function setProposalPeriod (uint256 _proposalPeriod) public isReady returns(bool); - - /// Return upgrading status for Upgrader contracts. - /// @param _originalHandlerAddr address of the original Handler contract. - /// exception UninitializationException uninitialized contract. - /// @return Handler contract's upgrading status. - function canBeUpgraded (address _originalHandlerAddr) external view isReady returns(UpgradingStatus); - - /// Check if the contract has been initialized. - /// @return if the contract has been initialized. - function live () external view returns(bool); - - /** Getters and setters of data resources: define functions here */ -} -``` - - -### Upgrader Contract (Optional) - -Handler contract can be upgraded by calling setHandler() of Data contract. If the owner wants to collect ideas from users, an Upgrader contract will help him/her manage voting and upgrading. - -Below is the specification of Upgrader contract: - -- The Upgrader contract has the ability to take votes from the registered voters. - - The contract owner is able to add voters any time before the proposal expires; - - Voter can check the current status of the proposal (succeed or expired). -- Developers are able to delete this Upgrader contract by calling done() any time after deployment. - -The Upgrader contract works as follows: - -1. Verify the Data contract, its corresponding Handler contract and the new Handler contract have all been deployed; -2. Deploy an Upgrader contract using Data contract address, previous Handler contract address and new Handler contract address; -3. Register upgrader address in the new Handler contract first, then the original handler and finally the Data contract; -4. Call startProposal() to start the voting process; -5. Call getResolution() before the expiration; -6. Upgrading succeed or proposal is expired. - -Note: - -- Function done() can be called at any time to let upgrader destruct itself. -- Function status() can be called at any time to show caller status of the upgrader. - - -```solidity -/// Handler upgrader -contract Upgrader { - // Data contract - DataContract public data; - // Original Handler contract - IHandler public originalHandler; - // New Handler contract - address public newHandlerAddr; - - /** Marker */ - enum UpgraderStatus { - Preparing, - Voting, - Success, - Expired, - End - } - UpgraderStatus public status; - - /// Check if the proposal is expired. - /// If so, contract would be marked as expired. - /// exception PreparingUpgraderException proposal has not been started. - /// exception ReupgradingException upgrading has been done. - /// exception ExpirationException proposal is expired. - modifier notExpired { - require(status != UpgraderStatus.Preparing, "Invalid proposal!"); - require(status != UpgraderStatus.Success, "Upgrading has been done!"); - require(status != UpgraderStatus.Expired, "Proposal is expired!"); - if (data.canBeUpgraded(address(originalHandler)) != DataContract.UpgradingStatus.InProgress) { - status = UpgraderStatus.Expired; - require(false, "Proposal is expired!"); - } - _; - } - - /// Start voting. - /// Upgrader must do upgrading check, namely checking if Data contract and 2 Handler contracts are ok. - /// exception RestartingException proposal has been already started. - /// exception PermissionException msg.sender is not the owner. - /// exception UpgraderConflictException another upgrader is working. - /// exception NoPreparationException original or new Handler contract is not prepared. - function startProposal () external; - - /// Anyone can try to get resolution. - /// If voters get consensus, upgrade the Handler contract. - /// If expired, self-destruct. - /// Otherwise, do nothing. - /// exception PreparingUpgraderException proposal has not been started. - /// exception ExpirationException proposal is expired. - /// @return status of proposal. - function getResolution() external returns(UpgraderStatus); - - /// Destruct itself. - /// exception PermissionException msg.sender is not the owner. - function done() external; - - /** Other voting mechanism related variables and functions */ -} -``` - - -### Caveats - -Since the Upgrader contract in [ERC-1504](./eip-1504.md) has a simple voting mechanism, it is prone to all the limitations that the voting contract is facing: - -- The administrator can only be the owner of data and Handler contracts. Furthermore, only the administrator has the power to add voters and start a proposal. -- It requires voters to be constantly active, informative and attentive to make a upgrader succeed. -- The voting will only be valid in a given time period. If in a given time period the contract cannot collect enough “yes” to proceed, the proposal will be marked expired. - -## Rationale - -### Data Contract and Handler Contract - -A smart contract is actually a kind of software, which provides some kind of services. From the perspective of software engineering, a service consists of **resources** that abstract the data and **operations** that abstract the process logic on the data. The requirement of upgrading is mostly on the logic part. Therefore, in order to make a smart contract upgradable, we divide it into two parts: - -1. Data contract keeps the resources; -2. Handler contract contains operations. - -The Handler contract can be upgraded in the future while the Data contract is permanent. Handler contract can manipulate the variables in Data contract through the getter and setter functions provided by Data contract. - -### Upgrader Contract and Voting Mechanism - -In order to prevent centralization and protect the interests of the community and stakeholders, we also design a voting mechanism in the Upgrader contract. Upgrader contract contains addresses of Data contract and two Handler contracts, and collects votes from pre-defined voters to upgrade the Handler contract when the pre-set condition is fulfilled. - -For simplicity, the upgradable contract comes with a very minimal version of the voting mechanism. If the contract owner wants to implement a more complex voting mechanism, he/she can modify the existing voting mechanism to incorporate upgradability. The expiration mechanism (see modifier notExpried in Upgrader contract and related functions in Data contract) and upgrading check (see function startProposal() in Upgrader contract) to the contract are mandatory. - -### Gas and Complexity (regarding the enumeration extension) - -Using an upgrader will cost some gas. If the Handler contract is upgraded by the owner, it just costs gas that a contract call will cost, which is usually significantly lower than creating and deploying a new contract. - -Although upgrading contract may take some efforts and gas, it is a much less painful than deprecating the insecure contract/creating a new contract or hard fork (e.g. DAO attack). Contract creation requires a significant amount of effort and gas. One of the advantages of upgradable contracts is that the contract owners don’t have to create new contracts; instead, they only need to upgrade parts of contract that cause issues, which is less expensive compared to data loss and blockchain inconsistency. In other words, upgradable contracts make Data contract more scalable and flexible. - -### Community Consensus - -Thank you to those who helped on review and revise the proposal: - -- [@lsankar4033](https://github.com/lsankar4033) from MIT -- more - -The proposal is initiated and developed by the team Renaissance and the Research Group of Blockchain System @ Center for Operating System at Peking University. - -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. - -## Implementations - -1. [Renaissance](https://www.renaissance.app) - a protocol that connect creators and fans financially -2. [ERC-1504](./eip-1504.md) - a reference 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-1504.md diff --git a/EIPS/eip-152.md b/EIPS/eip-152.md index 167f93c4d176c3..2762bfcff3e549 100644 --- a/EIPS/eip-152.md +++ b/EIPS/eip-152.md @@ -80,8 +80,8 @@ function callF() public view returns (bytes32[2] memory) { m[3] = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes8[2] memory t; - t[0] = hex"03000000"; - t[1] = hex"00000000"; + t[0] = hex"0300000000000000"; + t[1] = hex"0000000000000000"; bool f = true; @@ -264,4 +264,4 @@ PrecompiledBlake2F/testVectors2bX_580 1 131 7.633 ## 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-1523.md b/EIPS/eip-1523.md index 3a08cab63f19cd..a74d332e5eb318 100644 --- a/EIPS/eip-1523.md +++ b/EIPS/eip-1523.md @@ -1,121 +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 6eeb8735b470bc..f984a6b46164e9 100644 --- a/EIPS/eip-1538.md +++ b/EIPS/eip-1538.md @@ -1,468 +1,7 @@ --- eip: 1538 -title: Transparent Contract Standard -author: Nick Mudge -discussions-to: https://github.com/ethereum/EIPs/issues/1538 -status: Withdrawn -type: Standards Track category: ERC -created: 2018-10-31 +status: Moved --- -Replaced by [EIP-2535 Diamond Standard](./eip-2535.md). - -## 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-1559.md b/EIPS/eip-1559.md index 425c4a8e57e52d..26a5b739e1661f 100644 --- a/EIPS/eip-1559.md +++ b/EIPS/eip-1559.md @@ -3,7 +3,7 @@ eip: 1559 title: Fee market change for ETH 1.0 chain 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: Review +status: Final type: Standards Track category: Core created: 2019-04-13 @@ -11,17 +11,17 @@ requires: 2718, 2930 --- ## Simple Summary -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. +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 -We introduce a new [EIP-2718](./eip-2718.md) transaction type, with the format `0x02 || rlp([chainId, nonce, maxInclusionFeePerGas, maxFeePerGas, gasLimit, to, value, data, access_list, signatureYParity, signatureR, signatureS])`. +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])`. -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 (formerly known as gas limit) of parent block. +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: inclusion fee). -Transactions also specify the maximum fee per gas they are willing to pay total (aka: max fee), which covers both the inclusion fee and the block's network fee per gas (aka: base fee). -The transaction will always pay the base fee per gas of the block it was included in, and they will pay the inclusion 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. +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 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: @@ -31,9 +31,9 @@ Ethereum historically priced transaction fees using a simple auction mechanism, * **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. -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 inclusion 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. +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 inclusion 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 inclusion 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. +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 Block validity is defined in the reference implementation below. @@ -43,11 +43,11 @@ As of `FORK_BLOCK_NUMBER`, a new [EIP-2718](./eip-2718.md) transaction is introd 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([chainId, nonce, maxInclusionFeePerGas, maxFeePerGas, gasLimit, to, value, data, access_list, signatureYParity, signatureR, signatureS])`. +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 `signatureYParity, signatureR, signatureS` elements of this transaction represent a secp256k1 signature over `keccak256(0x02 || rlp([chainId, nonce, maxInclusionFeePerGas, maxFeePerGas, gasLimit, to, value, data, access_list]))`. +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, cumulativeGasUsed, logsBloom, logs])`. +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 @@ -90,7 +90,7 @@ class Transaction2930Envelope: class Transaction1559Payload: chain_id: int = 0 signer_nonce: int = 0 - max_inclusion_fee_per_gas: int = 0 + max_priority_fee_per_gas: int = 0 max_fee_per_gas: int = 0 gas_limit: int = 0 destination: int = 0 @@ -114,7 +114,7 @@ Transaction = Union[TransactionLegacy, Transaction2718] class NormalizedTransaction: signer_address: int = 0 signer_nonce: int = 0 - max_inclusion_fee_per_gas: int = 0 + max_priority_fee_per_gas: int = 0 max_fee_per_gas: int = 0 gas_limit: int = 0 destination: int = 0 @@ -133,13 +133,13 @@ class Block: logs_bloom: int = 0 difficulty: int = 0 number: int = 0 - gas_target: int = 0 # note the name change to gas_target from gas_limit + 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 # default to 1,000,000,000 for blocks before INITIAL_FORK_BLOCK_NUMBER + base_fee_per_gas: int = 0 @dataclass class Account: @@ -149,26 +149,40 @@ class Account: 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 - parent_gas_target = self.parent(block).gas_target transactions = self.transactions(block) # check if the block used too much gas - assert block.gas_used <= block.gas_target * ELASTICITY_MULTIPLIER, 'invalid block: too much gas used' + 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 block changed the gas target too much - assert block.gas_target <= parent_gas_target + parent_gas_target // 1024, 'invalid block: gas target increased too much' - assert block.gas_target >= parent_gas_target - parent_gas_target // 1024, 'invalid block: gas target 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 parent_gas_used == parent_gas_target: + 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 @@ -177,7 +191,7 @@ class World(ABC): 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 = max(parent_base_fee_per_gas - base_fee_per_gas_delta, 0) + 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 @@ -191,13 +205,23 @@ class World(ABC): 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 - # inclusion fee is capped because the base fee is filled first - inclusion_fee_per_gas = min(transaction.max_inclusion_fee_per_gas, transaction.max_fee_per_gas - block.base_fee_per_gas) - # signer pays both the inclusion fee and the base fee - effective_gas_price = inclusion_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) @@ -205,8 +229,8 @@ class World(ABC): cumulative_transaction_gas_used += gas_used # signer gets refunded for unused gas signer.balance += gas_refund * effective_gas_price - # miner only receives the inclusion fee; note that the base fee is not given to anyone (it is burned) - self.account(block.author).balance += gas_used * inclusion_fee_per_gas + # 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' @@ -221,7 +245,7 @@ class World(ABC): signer_address = signer_address, signer_nonce = transaction.signer_nonce, gas_limit = transaction.gas_limit, - max_inclusion_fee_per_gas = transaction.gas_price, + max_priority_fee_per_gas = transaction.gas_price, max_fee_per_gas = transaction.gas_price, destination = transaction.destination, amount = transaction.amount, @@ -234,7 +258,7 @@ class World(ABC): signer_address = signer_address, signer_nonce = transaction.payload.signer_nonce, gas_limit = transaction.payload.gas_limit, - max_inclusion_fee_per_gas = transaction.payload.gas_price, + 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, @@ -247,7 +271,7 @@ class World(ABC): signer_address = signer_address, signer_nonce = transaction.payload.signer_nonce, gas_limit = transaction.payload.gas_limit, - max_inclusion_fee_per_gas = transaction.payload.max_inclusion_fee_per_gas, + 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, @@ -278,7 +302,7 @@ class World(ABC): ``` ## Backwards Compatibility -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 `inclusion_fee_per_gas`. +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. @@ -286,23 +310,20 @@ The datastructure that is passed into keccak256 to calculate the block hash is c ### 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. -## Test Cases -TODO - ## 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. ### Transaction Ordering -With most people not competing on inclusion 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 inclusion 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 tip transactions over those with a lower tip, purely from a selfish mining perspective. +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 inclusion 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 money from inclusion fee while defectors would make double the money from inclusion 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. +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. 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 token 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 Ethereum's long term monetary policy. +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 88655fe8fb0940..5338fd0088d32c 100644 --- a/EIPS/eip-1571.md +++ b/EIPS/eip-1571.md @@ -3,7 +3,7 @@ eip: 1571 title: EthereumStratum/2.0.0 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: Interface created: 2018-11-09 @@ -548,4 +548,4 @@ 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 f73fd507eeb0cc..97c2eae9470fb3 100644 --- a/EIPS/eip-1577.md +++ b/EIPS/eip-1577.md @@ -1,116 +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), you can also find this smart contract deployed on: - -* Mainnet : [0xd3ddccdd3b25a8a7423b5bee360a42146eb4baf3](https://etherscan.io/address/0xd3ddccdd3b25a8a7423b5bee360a42146eb4baf3) -* Ropsten : [0xde469c7106a9fbc3fb98912bb00be983a89bddca](https://ropsten.etherscan.io/address/0xde469c7106a9fbc3fb98912bb00be983a89bddca) - -There are also implementations in multiple languages to encode and decode `contenthash`: - -* [JavaScript](https://github.com/pldespaigne/content-hash) -* [Python](https://github.com/filips123/ContentHashPy) - -## 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 6dde3019a62ef7..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: 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 1c5808fc5d8200..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 key pairs. - -## 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 f25760a697adb4..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 @@ -23,4 +23,4 @@ This meta-EIP specifies the changes included in the alternative Ethereum hardfor ## 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 9345541329cf99..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](./eip-902.md), -[EIP-1066](./eip-1066.md) -and [EIP-1175](./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. - -```solidity -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-161.md b/EIPS/eip-161.md index f148c76c75daaa..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 @@ -13,7 +13,7 @@ created: 2016-10-24 ### 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 2de2b2a663656d..bcfccf6d9a323b 100644 --- a/EIPS/eip-1613.md +++ b/EIPS/eip-1613.md @@ -1,300 +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 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](./eip-1077.md) could allow transactions from addresses that hold no ETH. - -The gas stations network is an [EIP-1077](./eip-1077.md) 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 `getSender()` and `getMessageData()` instead of `msg.sender` and `msg.data`, everywhere. `RelayRecipient` provides these functions and gets the information from `RelayHub`. -* Implement a `acceptRelayedCall(address relay, address from, bytes memory encodedFunction, uint gasPrice, uint transactionFee, bytes memory approval)` view function that returns **zero** if and only if it is willing to accept a transaction and pay for it. - `acceptRelayedCall` 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 `acceptRelayedCall` returns **zero**. Some examples of `acceptRelayedCall()` 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. - * A dapp can provide off-chain a signed message called `approval` to a transaction sender and validate it. - * 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 `preRelayedCall(address relay, address from, bytes memory encodedFunction, uint transactionFee) returns (bytes32)`. This method is called before a transaction is relayed. By default, it does nothing. - -* Implement `postRelayedCall(ddress relay, address from, bytes memory encodedFunction, bool success, uint usedGas, uint transactionFee, bytes32 preRetVal)`. This method is called after a transaction is relayed. By default, it does nothing. - - These two methods can be used 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 key pair 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](/assets/eip-1613/sequence.png) - -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 unstakeDelay)`. -* `RelayHub` puts the `owner` and `unstake delay` in the relays map, indexed by `relay` address. -* Relay calls `RelayHub.registerRelay(uint transactionFee, 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, transactionFee, relayStake, unstakeDelay, 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.canRelay()`, a view function, - which checks the recipient's `acceptRelayedCall`, 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.penalizeRepeatedNonce` through another relay, to collect his reward and burn the remainder of 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 `initialGas` 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 `acceptRelayedCall` function, asking whether it's going to accept the transaction. If not, the `TransactionRelayed` will be emitted with status `CanRelayFailed`, and `chargeOrCanRelayStatus` will contain the return value of `acceptRelayedCall`. In this case, Relay doesn't get paid, as it was its responsibility to check `RelayHub.canRelay` before releasing the transaction. - * Calls recipient's `preRelayedCall` function. If this call reverts the `TransactionRelayed` will be emitted with status `PreRelayedFailed`. - * Sends the transaction to the recipient. If this call reverts the `TransactionRelayed` will be emitted with status `RelayedCallFailed`. - 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.getSender()` 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 `postRelayedCall`. -* `RelayHub` checks call's return value of call, and emits `TransactionRelayed(address relay, address from, address to, bytes4 selector, uint256 status, uint256 chargeOrCanRelayStatus)`. -* `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 `canRelay` 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 `acceptRelayedCall()` 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.removeRelayByOwner(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.penalizeRepeatedNonce(bytes transaction1, bytes transaction2)`, which verifies the attack, confiscates Relay's stake, -and sends half of it to the sender who delivered the `penalizeRepeatedNonce` call. The other half of the stake is burned by sending it to `address(0)`. Burning is done to prevent cheating relays from effectively penalizing themselves and getting away without any loss. -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 acceptRelayedCall() 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 acceptRelayedCall (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 acceptRelayedCall 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 acceptRelayedCall 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 acceptRelayedCall() 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 aca47691cb6a0f..77e12726f4766d 100644 --- a/EIPS/eip-1616.md +++ b/EIPS/eip-1616.md @@ -1,387 +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: -```solidity -/** - * @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: -```solidity -/** - * @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 -```solidity -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 -```solidity -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 -```solidity -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 -```solidity -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): - -```solidity -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 e3a86f87e46e0e..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](./eip-137.md). - -> 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](./eip-137.md) 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 cd22385d8dbcb7..0b348ff48c4163 100644 --- a/EIPS/eip-1620.md +++ b/EIPS/eip-1620.md @@ -1,296 +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 - -### 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](#logcreate) - -```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](#logwithdraw) - -```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](#logredeem) - -```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](#logconfirmupdate) - -**Triggers Event**: [LogExecuteUpdate](#logexecuteupdate) 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](#logrevokeupdate) - -```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/). +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 index 7fddba9bbff121..d6d4959661f223 100644 --- a/EIPS/eip-1633.md +++ b/EIPS/eip-1633.md @@ -1,174 +1,7 @@ --- eip: 1633 -title: Re-Fungible Token Standard (RFT) -author: Billy Rennekamp (@okwme), Dan Long , Kiryl Yermakou , Nate van der Ende -discussions-to: https://github.com/ethereum/EIPs/issues/1634 -status: Draft -type: Standards Track category: ERC -created: 2018-11-18 -requires: 20, 165, 721 +status: Moved --- -## Simple Summary -[ERC-20](./eip-20.md) extension for proportional ownership of an [ERC-721](./eip-721.md) token. - -## Abstract -The intention of this proposal, the Re-Fungible Token Standard, is to extend the ERC-20 Token Standard and utilize ERC-165 Standard Interface Detection in order to represent the shared ownership of an ERC-721 Non-Fungible Token. The ERC-20 Token Standard was modified as little as possible in order to allow this new class of token to operate in all of the ways and locations which are familiar to assets that follow the original ERC-20 specification. While there are many possible variations of this specification that would enable many different capabilities and scenarios for shared ownership, this proposal is focused on the minimal commonalities to enable as much flexibility as possible for various further extensions. This proposal makes it possible to verify, from the contract level or from an external query, whether a fungible token represents a form of shared ownership of a non-fungible token. The inclusion of ERC-165 makes it possible to verify, from the contract level or from an external query, whether a non-fungible token is owned by ERC-20 token representing shared ownership. - -## Motivation -Shared ownership occurs across many industries and for many reasons. As more assets are registered, regulated and/or represented by the ERC-721 Non-Fungible Token Standard there will be more instances where the need for shared ownership of these assets will arise. For example, ARTBLX Inc. is working towards facilitating a protocol for collective ownership of physical, digital and conceptual artworks. The fungible tokens created from this process will have a value attached to the non-fungible tokens which they represent. This will be useful for price discovery of the underlying asset, liquidity for shared owners and as a new class of asset which can be used as collateral for loans or other financial instruments like stable coins. Providing an interface to this special class of fungible tokens is necessary to allow third parties to recognize them as a special class of fungible token and to recognize when a non-fungible token is collectively owned. This might be useful in the case of a wallet who would want to utilize the metadata of the underlying NFT to show additional info next to an RFT, or on an exchange who might want to make that sort of info similarly available, or an NFT marketplace who may want to direct customers to a relevant exchange who wish to purchase shares in a NFT which is owned by an RFT. Anywhere an ERC-20 is applicable it would be useful for a user to know whether that token represents a shared NFT, and what attributes that NFT may have. - -## Specification -At a minimum, third parties need two things: 1) to be able to distinguish re-fungible tokens from other token standards and 2) to determine when a non-fungible token is collectively owned. These two scenarios can be encountered from the perspective of initial contact with the non-fungible token or from the perspective of initial contact with the re-fungible token. - -#### Initial Contact with the Re-Fungible Token - -In order for a third party to confirm which non-fungible token is owned by the re-fungible token there needs to be a pointer from the RFT contract to the NFT contract and the relevant token id. This is possible with two public getters named `parentToken()` and `parentTokenId()`. The first getter returns a variable of type `address` and designates the contract address of the Non-Fungible Token contract. The second getter returns a variable of type `uint256` and designates the token ID of the Non-Fungible Token. With these getters, the identity of the Non-Fungible Token can be determined. Below is an example of the Re-Fungible Token Standard interface that includes these getter functions: - -```solidity -pragma solidity ^0.4.20; - -/// @dev Note: the ERC-165 identifier for this interface is 0x5755c3f2. -interface RFT /* is ERC20, ERC165 */ { - - function parentToken() external view returns(address _parentToken); - function parentTokenId() external view returns(uint256 _parentTokenId); - -} -``` - -The validity of this claim can be confirmed from another contract (on-chain) or from interacting with an RPC endpoint (off-chain). Below is an example of the on-chain scenario: - -```solidity -pragma solidity ^0.4.20; - -import './RFT.sol'; -import './ERC721.sol'; - -contract ConfirmRFT { - - function confirmRFT(address _RFT) external view returns(bool) { - address _NFT = RFT(_RFT).parentToken(); // returns address of NFT contract - uint256 _tokenId = RFT(_RFT).parentTokenId(); // returns id of ID of NFT - - return - NFT(_NFT).supportsInterface(0x80ac58cd) && // confirm it is ERC-721 - NFT(_NFT).ownerOf(_tokenId) == _RFT; // confirm the owner of the NFT is the RFT contract address - } - -} -``` - -Below is an off-chain example using an instance of web3.js in javascript: -```javascript -async function confirmRFT(web3) { - - const ERC721ABI = [...] // abi for ERC721 - const RFTABI = [...] // abi for RFT - const RFTAddress = '0x0123456789abcdef0123456789abcdef' // address for the deployed RFT - - const RFTContract = new web3.eth.Contract(RFTABI, RFTAddress) // deployed RFT contract instance - const ERC721Address = await RFTcontract.methods.parentToken().call() // returns address of NFT contract - const ERC721TokenId = await RFTcontract.methods.parentTokenId().call() // returns id of ID of NFT - - const ERC721Contract = new web3.eth.Contract(ERC721ABI, ERC721Address) // deployed ERC721 (as reported by RFT) - const isERC721 = await ERC721Contract.methods.supportsInterface('0x80ac58cd').call() // confirm it is ERC-721 - const ownerOfAddress = await ERC721Contract.methods.ownerOf(ERC721TokenId).call() // get the owner of the NFT - - return ERC721Response.toLowerCase() === RFTAddress.toLowerCase() // confirm the owner of the NFT is the RFT contract -} -``` - -#### Initial Contact with the Non-Fungible Token - -When checking the owner of a specific non-fungible token it's important to be able to determine whether owner is in fact a re-fungible token contract. This is possible by utilizing ERC-165 Standard Interface Detection. In order to comply with that standard a contract must include the following getter function which returns `true` when passed the `bytes4` parameter `0x01ffc9a7`: -``` -function supportsInterface(bytes4 interfaceID) external view returns (bool); -``` -After establishing support for this interface it becomes useful in determining whether the contract adheres to the Re-Fungible Token Standard. To do so the `supportsInterface(bytes4 interfaceID)` getter function must return `true` when passed the `bytes4` parameter `0x5755c3f2` which is the result of `bytes4(keccak256('parentToken()')) ^ bytes4(keccak256('parentTokenId()'))` or `parentToken.selector ^ parentTokenId.selector`. This could be achieved with the following code: -```solidity -pragma solidity ^0.4.20; - -import "./ERC20.sol"; - -/// @dev Note: the ERC-165 identifier for this interface is 0x5755c3f2. -interface RFT is ERC20 /*, ERC165 */ { - - function supportsInterface(bytes4 interfaceID) external view returns(bool) { - return - interfaceID == this.supportsInterface.selector || // ERC165 - interfaceID == this.parentToken.selector || // parentToken() - interfaceID == this.parentTokenId.selector || // parentTokenId() - interfaceID == this.parentToken.selector ^ this.parentTokenId.selector; // RFT - } - - function parentToken() external view returns(address _parentToken); - function parentTokenId() external view returns(uint256 _parentTokenId); - -} -``` -The flow of actually checking the status of a non-fungible token owner as a re-fungible token contract can be done from another contract (on-chain) as well as with an RPC endpoint (off-chain). Below is an example of the on-chain scenario: -```solidity -pragma solidity ^0.4.20; - -import './RFT.sol'; -import './ERC721.sol'; - -contract ConfirmRFT { - - function confirmRFT(address _NFT, uint256 _tokenId) external view returns(bool) { - address _RFT = ERC721(_NFT).ownerOf(_tokenId); // get the owner of the NFT - - return - RFT(_RFT).supportsInterface(0x01ffc9a7) && // confirm it supports ERC-165 - RFT(_RFT).supportsInterface(0x5755c3f2) // confirm it is RFT - } - -} -``` -Below is an off-chain example using web3.js in javascript: -```javascript -async function confirmRFT(web3) { - - const ERC721ABI = [...] // abi for ERC721 - const RFTABI = [...] // abi for RFT - const ERC721Address = '0x0123456789abcdef0123456789abcdef' // address for the deployed NFT - const ERC721TokenId = '7' // token Id of the NFT - - const ERC721Contract = new web3.eth.Contract(ERC721ABI, ERC721Address) // deployed ERC721 - const RFTAddress = await ERC721Contract.methods.ownerOf(ERC721TokenId).call() // owner address of the NFT - - - const RFTContract = new web3.eth.Contract(RFTABI, RFTAddress) // deployed RFT contract instance - const isERC165 = await RFTContract.methods.supportsInterface('0x01ffc9a7').call() // confirm it is ERC-165 - return isERC165 && await RFTContract.methods.supportsInterface('0x5755c3f2').call() // confirm it is RFT - -} -``` -## Rationale -Most of the decisions made around the design of this standard were done in the hopes of keeping it as flexible as possible for as many use cases as possible. This includes making the standard 100% backwards compatible with ERC-20 Token Standard and able to interact with any previously deployed or future ERC-721 non-fungible token. This allows for each project to determine their own system for minting, burning and governing their re-fungible tokens depending on their specific use case. - -## Backwards Compatibility -The Re-Fungible Token Standard is 100% backwards compatible with ERC-20 Token Standard. It is a small extension to the original specification and meant to be further extended for more specific use cases. Keeping the standard compatible with ERC-20 is important to allow for this token to benefit from the ecosystem that has grown around supporting the ubiquitous ERC-20 Token Standard. - -The Re-Fungible Token Standard is intended to interact with the ERC-721 Non-Fungible Token Standard. It is kept purposefully agnostic to extensions beyond the standard in order to allow specific projects to design their own token relationships such as governance over, rights to or permissions on each non-fungible token relative to the respective re-fungible token owners. - -## Implementation -```solidity -pragma solidity ^0.4.20; - -/// @dev Note: the ERC-165 identifier for this interface is 0x5755c3f2. -interface RFT /* is ERC20, ERC165 */ { - - function parentToken() external view returns(address _parentToken); - function parentTokenId() external view returns(uint256 _parentTokenId); - -} -``` - -## Security Considerations -TBD - -## 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-1633.md diff --git a/EIPS/eip-165.md b/EIPS/eip-165.md index 1998ffa47f8bfb..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](./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](./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 0c968c1e181b69..a6bf39fa837eb3 100644 --- a/EIPS/eip-1679.md +++ b/EIPS/eip-1679.md @@ -18,7 +18,7 @@ This meta-EIP specifies the changes included in the Ethereum hardfork named Ista - Codename: Istanbul ### Activation - - `Block >= 9,069,000` on the Ethereum mainnet + - `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 @@ -39,4 +39,4 @@ 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). 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 index 48213b3499321d..3a0f0a5ee13217 100644 --- a/EIPS/eip-1682.md +++ b/EIPS/eip-1682.md @@ -217,4 +217,4 @@ TBA 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-170.md b/EIPS/eip-170.md index d2448f2f0e9bf4..632f216a62e340 100644 --- a/EIPS/eip-170.md +++ b/EIPS/eip-170.md @@ -12,12 +12,13 @@ created: 2016-11-04 [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 e0241d9ddcbce8..bfcc9a76b829cb 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 @@ -129,7 +129,7 @@ parsing strategy when additional fields are added. 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 @@ -233,9 +233,9 @@ To be added. ## References -The source of this specification can be found at +The source of this specification can be found at [43-VER](https://specs.corepaper.org/43-ver/). ## 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-1706.md b/EIPS/eip-1706.md index f7ac77a38fec87..6c559b96589921 100644 --- a/EIPS/eip-1706.md +++ b/EIPS/eip-1706.md @@ -4,13 +4,12 @@ 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: Withdrawn +withdrawal-reason: The authors prefer [EIP-2200](./eip-2200.md) type: Standards Track category: Core created: 2019-01-15 requires: 1283 -superseded-by: 2200 --- -> :information_source: **[EIP-2200] has superseded [EIP-1706].** :information_source: ## 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. @@ -27,7 +26,7 @@ https://www.reddit.com/r/ethereum/comments/agdqsm/security_alert_ethereum_consta ## 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. @@ -60,4 +59,4 @@ 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 f18e9f5f6db774..a9b72bb081ae5c 100644 --- a/EIPS/eip-1710.md +++ b/EIPS/eip-1710.md @@ -1,59 +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](./eip-831.md) 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](./eip-155.md) 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 00b98d0f832ff6..031f20d3bc3dce 100644 --- a/EIPS/eip-1716.md +++ b/EIPS/eip-1716.md @@ -17,7 +17,7 @@ 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 >= 4_321_234` on the Rinkeby testnet @@ -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 bc77693e94c801..0e0fb9515c2485 100644 --- a/EIPS/eip-173.md +++ b/EIPS/eip-173.md @@ -1,109 +1,7 @@ --- eip: 173 -title: Contract Ownership Standard -author: Nick Mudge , Dan Finlay -discussions-to: https://github.com/ethereum/EIPs/issues/173 -type: Standards Track category: ERC -status: Last Call -review-period-end: 2020-09-06 -created: 2018-06-07 +status: Moved --- -## Simple Summary - -A standard interface for ownership of contracts. - -## Abstract - -This specification defines standard functions for owning or controlling a contract. - -An implementation allows reading the current owner (`owner() returns (address)`) and transferring ownership (`transferOwnership(address newOwner)`) along with a standardized event for when ownership is changed (`OwnershipTransferred(address indexed previousOwner, address indexed newOwner)`). - -## 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 user interfaces and 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. -4. User interfaces that show and transfer ownership of contracts. - -## Specification - -Every ERC-173 compliant contract must implement the `ERC173` interface. Contracts should also implement `ERC165` for the ERC-173 interface. - -```solidity - -/// @title ERC-173 Contract Ownership Standard -/// 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 returns(address); - - /// @notice Set the address of the new owner of the contract - /// @dev Set _newOwner to address(0) to renounce any ownership. - /// @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`. - -To renounce any ownership of a contract set `_newOwner` to the zero address: `transferOwnership(address(0))`. If this is done then a contract is no longer owned by anybody. - -The OwnershipTransferred event should be emitted when a contract is created. - -## Rationale - -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 - -Several ownership schemes were considered. The scheme chosen in this standard was chosen because of its simplicity, low gas cost and backwards compatibility with existing contracts. - -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. - -This standard can be extended by other standards to add additional ownership functionality. For example [EIP-2767](./eip-2767.md) uses and extends this standard by adding decentralized contract ownership governance. - -## Security Considerations - -If the address returned by `owner()` is an externally owned account then its private key must not be lost or compromised. - -## Backwards Compatibility - -Many existing contracts already implement this standard. - -## Implementations - -* [OpenZeppelin's implementation of Ownable](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol) -* [0xcert ownable](https://github.com/0xcert/ethereum-erc721/blob/master/src/contracts/ownership/ownable.sol) -* [FriendlyUser Ownable](https://github.com/FriendlyUser/solidity-smart-contracts//blob/v0.2.0/contracts/other/CredVert/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 index ef92881b3aed63..f68dacb368cde3 100644 --- a/EIPS/eip-1753.md +++ b/EIPS/eip-1753.md @@ -1,248 +1,7 @@ --- eip: 1753 -title: Smart Contract Interface for Licences -author: Lucas Cullen (@BitcoinBrisbane), Kai Yeung (@CivicKai), Anna Crowley , Caroline Marshall , Katrina Donaghy -status: Draft -type: Standards Track category: ERC -created: 2019-02-06 +status: Moved --- -## Abstract - -This Ethereum Improvement Proposal (EIP) proposes an Ethereum standard for the issuance of licences, permits and grants (Licences). - -A Licence is a limited and temporary authority, granted to a natural (e.g. you) or legal person (e.g. a corporation), to do something that would otherwise be unlawful pursuant to a legal framework. A public Licence is granted by the government, directly (e.g. by the New South Wales Department of Primary Industries, Australia) or indirectly (e.g. by an agent operating under the government’s authority), and derives its authority from legislation, though this is often practically achieved via delegated legislation such as regulations. This can be contrasted to a private licence – for example, the licence you grant to a visitor who comes onto your property. - -A Licence has the following properties: - -* granted personally to the licencee (Licencee), though it may be transferrable to another person or company; -* conferring a temporary right to the Licencee to own, use or do something that would otherwise be prohibited, without conferring any property interest in the underlying thing. For example, you may be granted a licence to visit a national park without acquiring any ownership in or over the park itself; -* allowing the government authority responsible for the Licence to amend, revoke, renew, suspend or deny the issuance of the Licence, or to impose conditions or penalties for non-compliance; and -* usually issued only after the payment of a fee or the meeting of some criteria. - -Additionally, a Licence may be granted in respect of certain information. For example, a Licence may be issued in respect of a vehicle registration number and attaching to that specific registered vehicle. - -## Motivation - -Governments are responsible for the issuance and management of Licences. However, maintaining and sharing this data can be complicated and inefficient. The granting of Licences usually requires the filing of paper-based application forms, manual oversight of applicable legislation and data entry into registries, as well as the issuance of paper based Licences. If individuals wish to sight information on Licence registries, they often need to be present at the government office and complete further paper-based enquiry forms in order to access that data (if available publicly). - -This EIP seeks to define a standard that will allow for the granting and/or management of Licences via Ethereum smart contracts. The motivation is, in essence, to address the inefficiencies inherent in current licencing systems. - -## Specification - -### 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 permit - e.g. `"MyPermit"`. - -``` js -function name() public view returns (string); -``` - -#### totalSupply - -Returns the total permit supply. - -``` js -function totalSupply() public view returns (uint256); -``` - -#### grantAuthority - -Adds an ethereum address to a white list of addresses that have authority to modify a permit. - -``` js -function grantAuthority(address who) public; -``` - -#### revokeAuthority - -Removes an ethereum address from a white list of addresses that have authority to modify a permit. - -``` js -function revokeAuthority(address who) public; -``` - -#### hasAuthority - -Checks to see if the address has authority to grant or revoke permits. - -``` js -function hasAuthority(address who) public view; -``` - -#### issue - -Issues an ethereum address a permit between the specified date range. - -``` js -function issue(address who, uint256 validFrom, uint256 validTo) public; -``` - -#### revoke - -Revokes a permit from an ethereum address. - -``` js -function revoke(address who) public; -``` - -#### hasValid - -Checks to see if an ethereum address has a valid permit. - -``` js -function hasValid(address who) external view returns (bool); -``` - -#### purchase - -Allows a user to self procure a licence. - -``` js -function purchase(uint256 validFrom, uint256 validTo) external payable; -``` - -## Rationale - -The use of smart contracts to apply for, renew, suspend and revoke Licences will free up much needed government resources and allow for the more efficient management of Licences. The EIP also seeks to improve the end user experience of the Licence system. In an era of open government, there is also an increased expectation that individuals will be able to easily access Licence registries, and that the process will be transparent and fair. - -By creating an EIP, we hope to increase the use of Ethereum based and issued Licences, which will address these issues. - -The Ethereum blockchain is adaptable to various Licences and government authorities. It will also be easily translatable into other languages and can be used by other governmental authorities across the world. Moreover, a blockchain will more effectively protect the privacy of Licence-holders’ data, particularly at a time of an ever-increasing volume of government data breaches. - -The EIP has been developed following the review of a number of licensing regulations at the national and state level in Australia. The review allowed the identification of the common licence requirements and criteria for incorporation into the EIP. We have included these in the proposed standard but seek feedback on whether these criteria are sufficient and universal. - -## Test Cases - -A real world example of a Licence is a permit required to camp in a national park in Australia (e.g. Kakadu national park in the Northern Territory of Australia) under the Environment Protection and Biodiversity Conservation Regulations 2000 (Cth) (EPBC Act) and the Environment Protection and Biodiversity Conservation Regulations 2000 (the Regulations). Pursuant to the EPBC Act and the Regulations, the Director of National Parks oversees a camping permit system, which is intended to help regulate certain activities in National Parks. Permits allowing access to National Parks can be issued to legal or natural persons if the applicant has met certain conditions. - -The current digital portal and application form to camp at Kakadu National Park (the Application) can be accessed at: https://www.environment.gov.au/system/files/resources/b3481ed3-164b-4e72-a9f8-91fc987d90e7/files/kakadu-camping-permit-form-19jan2015-pdf.pdf - -The user must provide the following details when making an Application: - -* The full name and contact details of each person to whom the permit is to be issued; - -* If the applicant is a company or other incorporated body: - -o the name, business address and postal address of the company or incorporated body; - -o if the applicant is a company— - -* the full name of each of the directors of the company; - -* the full name and contact details of the person completing the application form; - -* the ACN or ABN of the company or other incorporated body (if applicable); - -* Details of the proposed camping purpose (e.g. private camping, school group, etc.); - -* A start date and duration for the camping (up to the maximum duration allowed by law); - -* Number of campers (up to the maximum allowed by law); - -* All other required information not essential to the issuance of the Licence (e.g. any particular medical needs of the campers); and - -* Fees payable depending on the site, duration and number of campers. - -The Regulations also set out a number of conditions that must be met by licensees when the permit has been issued. The Regulations allow the Director of National Parks to cancel, renew or transfer the licence. The above workflow could be better performed by way of a smart contract. - -The key criteria required as part of this process form part of the proposed Ethereum standard. We have checked this approach by also considering the issuance of a Commercial Fishing Licence under Part 8 “Licensing and other commercial fisheries management” of the Fisheries Management (General) Regulation 2010 (NSW) (Fisheries Regulations) made pursuant to the Fisheries Management Act 1994 (NSW) (Fisheries Act). - -## Implementation - -The issuance and ownership of a Licence can be digitally represented on the Ethereum blockchain. - -Smart contracts can be used to embed regulatory requirements with respect to the relevant Licence in the blockchain. The Licence would be available electronically in the form of a token. This might be practically represented by a QR code, for example, displaying the current Licence information. The digital representation of the Licence would be stored in a digital wallet, typically an application on a smartphone or tablet computer. The proposed standard allows issuing authorities or regulators to amend, revoke or deny Licences from time to time, with the result of their determinations reflected in the Licence token in near real-time. Licence holders will therefore be notified almost instantly of any amendments, revocations or issues involving their Licence. - -## Interface - -### Solidity Example -```solidity -interface EIP1753 { - string public name; - uint256 public totalSupply; - - function grantAuthority(address who) public; - function revokeAuthority(address who) public; - function hasAuthority(address who) external view returns (bool); - - function issue(address who, uint256 from, uint256 to) external; - function revoke(address who) public; - - function hasValid(address who) external view returns (bool); - function purchase(uint256 validFrom, uint256 validTo) public payable; -} - -pragma solidity ^0.5.3; - -contract EIP is EIP1753 { - - string public name = "Kakadu National Park Camping Permit"; - uint256 public totalSupply; - - address private _owner; - mapping(address => bool) private _authorities; - mapping(address => Permit) private _holders; - - struct Permit { - address issuer; - uint256 validFrom; - uint256 validTo; - } - - constructor() public { - _owner = msg.sender; - } - - function grantAuthority(address who) public onlyOwner() { - _authorities[who] = true; - } - - function revokeAuthority(address who) public onlyOwner() { - delete _authorities[who]; - } - - function hasAuthority(address who) external view returns (bool) { - return _authorities[who] == true; - } - - function issue(address who, uint256 start, uint256 end) public onlyAuthority() { - _holders[who] = Permit(_owner, start, end); - totalSupply += 1; - } - - function revoke(address who) public onlyAuthority() { - delete _holders[who]; - } - - function hasValid(address who) external view returns (bool) { - return _holders[who].start > now && _holders[who].end < now; - } - - function purchase(uint256 validFrom, uint256 validTo) external payable { - require(msg.value == 1 ether, "Incorrect fee"); - issue(msg.sender, from, to); - } - - modifier onlyOwner() { - require(msg.sender == _owner, "Only owner can perform this function"); - _; - } - - modifier onlyAuthority() { - require(hasAuthority(msg.sender), "Only an authority can perform this function"); - _; - } -} -``` - -## 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-1753.md diff --git a/EIPS/eip-1761.md b/EIPS/eip-1761.md index bd62772bc14a4b..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](./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 IdsAddedToScope(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 IdsRemovedFromScope(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](./eip-1155.md) -- [ERC-165 Standard Interface Detection](./eip-165.md) -- [JSON Schema](https://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 84c83bc114ca6a..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 @@ -415,4 +415,4 @@ TBD. - 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 9eb79ee299c163..efc42dbbf536aa 100644 --- a/EIPS/eip-1775.md +++ b/EIPS/eip-1775.md @@ -1,196 +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 +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 a master account (or app key) unique for the domain from an user private key (her root private key or any other private key of an account derived or not from her root one). This EIP aims at becoming a standard on how to derive keys specific to each application that can be regenerated from scratch without further input from the user if she restores her wallet and uses again the application for which this key was derived. -These app keys can then be endowed a different set of permissions (through the requestPermission model introduced in [EIP-2255](./eip-2255.md)). This will potentially allow an user to partly trust some apps to perform some crypto operations on their behalf without compromising any security with respect to her main accounts. - -## 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. [EIP-1102](./eip-1102.md) 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 a cryptographic key specifically derived for this usage. It can be any form of cryptography/identity relying application, Ethereum based but not only. - -Once connected to a wallet, an application can request to access an account derived exclusively for that application using the following algorithm. - -### Private App Key generation algorithm - -We now propose an algorithm to generate application keys that: -- are uniquely defined, with respect to the account that the user selected to generate these keys, -- and thus can be isolated when changing the user account, allowing persona management (see next section), -- are specific to each application, -- can be fully restored from the user master seed mnemonic and the applications' names. - -#### Using different accounts as personas - -We allow the user to span a different set of application keys by changing the account selected to generate each key. Thus from the same master seed mnemonic, an user can use each of her account index to generate an alternative set of application keys. One can describe this as using different personas. -This would allow potentially an user to 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 accounts to generate these. The app or domain, will not be aware that it is the same person and mnemonic behind both. -If an application interacts with several main accounts of an user, one of these accounts, a master account can be used as persona and the others as auxiliary accounts. - -This EIP is agnostic about the way one generates the private keys used to span different app keys spaces. However for compatibility purposes and for clean disambiguation between personas and cryptocurrency accounts, a new EIP, distinct from this one but to be used alongside, will be proposed soon introducing clean persona generation and management. - -#### Applications' Unique Identifiers - -Each application is uniquely defined and authenticated by its origin, a domain string. It can be a Domain Name Service (DNS) name or, in the future, an Ethereum Name Service (ENS) name or IPFS hash. - -For Ipfs or swam origins, but we could probably use the ipfs or swarm addresses as origin or we could require those to be pointed at through an ENS entry and use the ENS address as origin, although this would mean that the content it refers to could change. It would thus allow for different security and updatibility models. - -We will probably require for protocol prefixes when using an ENS domain to point to an IPFS address: -`ens://ipfs.snap.eth` - - -#### Private App Key generation algorithm - -Using the domain name of an application, we generate a private key for each application (and per main account) : - -`const appKeyPrivKey = keccak256(privKey + originString)` - -where `+` is concatenation, `privKey` is the private key of the user's account selected to span the application key and `originString` represents the origin url from which the permission call to access the application key is originated from. - -This is exposed as an RPC method to allow any domain to request its own app key associated with the current requested account (if available): - -``` -const appKey = await provider.send({ - method: 'wallet_getAppKeyForAccount', - params: [address1] -}); -``` - -See here for an implementation: -https://github.com/MetaMask/eth-simple-keyring/blob/master/index.js#L169 - -#### App keys and Hierarchical Deterministic keys - -The app keys generated using the algorithm described in the previous section will not be BIP32 compliant. Therefore apps will not be able to create several app keys or use non-hardening and extended public keys techniques directly. They get a single private key (per origin, per persona). -Yet they can use this as initial entropy to span a new HD tree and generate addresses that can be either hardened or not. Thus we should not be losing use cases. - -## Rationale - -### Sharing application keys across domains: -While this does not explicit cover cases of sharing these app keys between pages on its own, this need can be met by composition: - -Since a domain would get a unique key per persona, and because domains can intercommunicate, one domain (app) could request another domain (signer) to perform its cryptographic operation on some data, with its appKey as a seed, potentially allowing new signing strategies to be added as easily as new websites. - -This could also pass it to domains that are loading specific signing strategies. This may sound dangerous at first, but if a domain represents a static hash of a trusted cryptographic function implementation, it could be as safe as calling any audited internal dependency. - -### 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 compatibility issues 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 may want to reflect on if and how they would like to leverage the power offered by `app keys` to migrate to them and leverage on the new app designs they permit. - -## Implementation - -Here is an early implementation of app keys for standard (non HW) MetaMask accounts. -https://github.com/MetaMask/eth-simple-keyring/blob/6d12bd9d73adcccbe0b0c7e32a99d279085e2934/index.js#L139-L152 - -See here for a fork of MetaMask that implements app keys along side plugins: -https://github.com/MetaMask/metamask-snaps-beta -https://github.com/MetaMask/metamask-snaps-beta/wiki/Plugin-API - -## 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](./eip-1581.md) - -* 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) - -* [SLIP44: Registered coin types for BIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) - - -#### 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](./eip-600.md) - - -* [EIP601 Ethereum hierarchy for deterministic wallets](./eip-601.md) - - -### 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](./eip-1102.md) - -* [EIP1581: Non-wallet usage of keys derived from BIP-32 trees](./eip-1581.md) - -* [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 855b51242ec329..2d0e50c1b93b03 100644 --- a/EIPS/eip-1803.md +++ b/EIPS/eip-1803.md @@ -5,7 +5,7 @@ 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 --- @@ -39,4 +39,4 @@ Renaming `SHA3` was previously proposed by [EIP-59](https://github.com/ethereum/ ## 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 8d2ae33f5a3622..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 7b496dadd2f493..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](./eip-712.md). - -## Abstract -A new method for Off-Chain Verifiable Claims built on [EIP-712](./eip-712.md). 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](./eip-712.md) 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](./eip-1056.md) 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 641555ff3064ef..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: **[ERC-1820] has superseded [ERC-820].** :information_source: -> [ERC-1820] fixes the incompatibility in the [ERC-165] logic which was introduced by the Solidity 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, [ERC-1820] is functionally equivalent to [ERC-820]. -> -> :warning: [ERC-1820] MUST be used in lieu of [ERC-820]. :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 [ERC-165]. - -## 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 [ERC-165] interfaces, -and this registry SHALL forward the call to the contract to see if it implements the interface. - -This contract also acts as an [ERC-165] cache to reduce gas consumption. - -## Motivation - -There have been different approaches to define pseudo-introspection in Ethereum. -The first is [ERC-165] which has the limitation that it cannot be used by regular accounts. -The second attempt is [ERC-672] 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 [ERC-672], 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 - -### [ERC-1820] 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 [EIP-155] 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 [ERC-1820] 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")` - -#### **[ERC-165] Compatible Interfaces** - -> The compatibility with [ERC-165], 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 [ERC-165] interface. - -**[ERC-165] Lookup** - -Anyone can explicitly check if a contract implements an [ERC-165] 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 [ERC-165] 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`: [ERC-165] 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 [ERC-165] interface or not without using nor updating the cache. - -> **identifier:** `b7056765` -> **parameters** -> `_contract`: Address of the contract to check. -> `_interfaceId`: [ERC-165] interface to check. -> **returns:** `true` if `_contract` implements `_interfaceId`, false otherwise. - -**[ERC-165] Cache** - -Whether a contract implements an [ERC-165] interface or not can be cached manually to save gas. - -If a contract dynamically changes its interface and relies on the [ERC-165] cache of the [ERC-1820] 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`: [ERC-165] 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 [ERC-1820] 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 [ERC-165] 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 [ERC-1820] 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 [ERC-165] interface and the registry SHALL forward the call to the contract at `_addr` to see if it implements the [ERC-165] interface (the first 4 bytes of `_interfaceHash`). -The registry SHALL also cache [ERC-165] 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 [ERC-165] cache in order to save gas when looking up if a contract implements a specific [ERC-165] 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 [ERC-165], 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]. - -[EIP-155]: ./eip-155.md -[ERC-165]: ./eip-165.md -[ERC-672]: https://github.com/ethereum/EIPs/issues/672 -[ERC-820]: ./eip-820.md -[ERC-1820]: ./eip-1820.md -[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 ec1f7aeb83de1d..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 49e82e894b5064..8a2a27a389cb80 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 @@ -146,5 +146,5 @@ This EIP overlaps in scope with * [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 1245ecd5ce6f94..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: - -```solidity -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 fe840d1497e495..7fcab2afc6d2c0 100644 --- a/EIPS/eip-1872.md +++ b/EIPS/eip-1872.md @@ -3,7 +3,7 @@ eip: 1872 title: Ethereum Network Upgrade Windows author: Danno Ferrin (@shemnon) discussions-to: https://ethereum-magicians.org/t/eip-1872-ethereum-network-upgrade-windows/2993 -status: Draft +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 a16dc9cdba0669..e085625dc199b9 100644 --- a/EIPS/eip-1884.md +++ b/EIPS/eip-1884.md @@ -82,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. @@ -155,6 +155,6 @@ func opSelfBalance(pc *uint64, interpreter *EVMInterpreter, contract *Contract, - 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]: ./eip-150.md diff --git a/EIPS/eip-1890.md b/EIPS/eip-1890.md index c927937226bf34..8c3a38b76f303e 100644 --- a/EIPS/eip-1890.md +++ b/EIPS/eip-1890.md @@ -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 60fe433aac6e03..5c520839e0774b 100644 --- a/EIPS/eip-1895.md +++ b/EIPS/eip-1895.md @@ -3,7 +3,7 @@ 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-03-31 @@ -157,4 +157,4 @@ Proper benchmarks will be done in order to make this choice and to price the ope ## 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 8a387deddcaae2..0bb8bc4d7c5ae6 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: Review type: Standards Track category: Interface -status: Draft created: 2019-04-01 -requires: 234, 1474 +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](./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 -It is supported by Geth 1.9.6 ([PR](https://github.com/ethereum/go-ethereum/pull/19491)). ## 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 bf909700db3f26..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](./eip-137.md) 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 index decd47e06d7c7f..0cc739bb3846ef 100644 --- a/EIPS/eip-1900.md +++ b/EIPS/eip-1900.md @@ -1,276 +1,7 @@ --- eip: 1900 -title: dType - Decentralized Type System for EVM -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/1882 -status: Draft -type: Standards Track category: ERC -created: 2019-03-28 +status: Moved --- -## Simple Summary - -The EVM and related languages such as Solidity need consensus on an extensible Type System in order to further evolve into the Singleton Operating System (The World Computer). - -## Abstract - -We are proposing a decentralized Type System for Ethereum, to introduce data definition (and therefore ABI) consistency. This ERC focuses on defining an on-chain Type Registry (named `dType`) and a common interface for creating types, based on `struct`s. - - -## Motivation - -In order to build a network of interoperable protocols on Ethereum, we need data standardization, to ensure a smooth flow of on-chain information. Off-chain, the Type Registry will allow a better analysis of blockchain data (e.g. for blockchain explorers) and creation of smart contract development tools for easily using existing types in a new smart contract. - -However, this is only the first phase. As defined in this document and in the future proposals that will be based on this one, we are proposing something more: a decentralized Type System with Data Storage - [ERC-2158](https://github.com/ethereum/EIPs/pull/2158). In addition, developers can create libraries of `pure` functions that know how to interact and modify the data entries - [dType Functions Extension](https://github.com/ethereum/EIPs/issues/1921). This will effectively create the base for a general functional programming system on Ethereum, where developers can use previously created building blocks. - -To summarize: - -* We would like to have a good decentralized medium for integrating all Ethereum data, and relationships between the different types of data. Also, a way to address the behavior related to each data type. -* Functional programming becomes easier. Functions like `map`, `reduce`, `filter`, are implemented by each type library. -* Solidity development tools could be transparently extended to include the created types (For example in IDEs like Remix). At a later point, the EVM itself can have precompiled support for these types. -* The system can be easily extended to types pertaining to other languages. (With type definitions in the source (Swarm stored source code in the respective language)) -* The dType database should be part of the System Registry for the Operating System of The World Computer - - -## Specification - -The Type Registry can have a governance protocol for its CRUD operations. However, this, and other permission guards are not covered in this proposal. - -### Type Definition and Metadata - -The dType registry should support the registration of Solidity's elementary and complex types. In addition, it should also support contract events definitions. In this EIP, the focus will be on describing the minimal on-chain type definition and metadata needed for registering Solidity user-defined types. - -#### Type Definition: TypeLibrary - -A type definition consists of a type library containing: -- the nominal `struct` used to define the type -- additional functions: - - `isInstanceOf`: checks whether a given variable is an instance of the defined type. Additional rules can be defined for each type fields, e.g. having a specific range for a `uint16 amount`. - - provide HOFs such as `map`, `filter`, `reduce` - - `structureBytes` and `destructureBytes`: provide type structuring and destructuring. This can be useful for low-level calls or assembly code, when importing contract interfaces is not an efficient option. It can also be used for type checking. - -A simple example is: - -```solidity -pragma solidity ^0.5.0; -pragma experimental ABIEncoderV2; - -library myBalanceLib { - - struct myBalance { - string accountName; - uint256 amount; - } - - function structureBytes(bytes memory data) pure public returns(myBalance memory balance) - - function destructureBytes(myBalance memory balance) pure public returns(bytes memory data) - - function isInstanceOf(myBalance memory balance) pure public returns(bool isInstance) - - function map( - address callbackAddr, - bytes4 callbackSig, - myBalance[] memory balanceArr - ) - view - internal - returns (myBalance[] memory result) -} -``` - -Types can also use existing types in their composition. However, this will always result in a directed acyclic graph. - -```solidity -library myTokenLib { - using myBalanceLib for myBalanceLib.myBalance; - - struct myToken { - address token; - myBalanceLib.myBalance; - } -} -``` - -#### Type Metadata: dType Registry - -Type metadata will be registered on-chain, in the dType registry contract. This consists of: -- `name` - the type's name, as it would be used in Solidity; it can be stored as a `string` or encoded as `bytes`. The name can have a human-readable part and a version number. -- `typeChoice` - used for storing additional ABI data that differentiate how types are handled on and off chain. It is defined as an `enum` with the following options: `BaseType`, `PayableFunction`, `StateFunction`, `ViewFunction`, `PureFunction`, `Event` -- `contractAddress` - the Ethereum `address` of the `TypeRootContract`. For this proposal, we can consider the Type Library address as the `TypeRootContract`. Future EIPs will make it more flexible and propose additional TypeStorage contracts that will modify the scope of `contractAddress` - [ERC-2158](https://github.com/ethereum/EIPs/pull/2158). -- `source` - a `bytes32` Swarm hash where the source code of the type library and contracts can be found; in future EIPs, where dType will be extended to support other languages (e.g. JavaScript, Rust), the file identified by the Swarm hash will contain the type definitions in that language. -- `types` - metadata for subtypes: the first depth level internal components. This is an array of objects (`structs`), with the following fields: - - `name` - the subtype name, of type `string`, similar to the above `name` definition - - `label` - the subtype label - - `dimensions` - `string[]` used for storing array dimensions. E.g.: - - `[]` -> `TypeA` - - `[""]` -> `TypeA[]` - - `["2"]` -> `TypeA[2]` - - `["",""]` -> `TypeA[][]` - - `["2","3"]` -> `TypeA[2][3]` - -Examples of metadata, for simple, value types: -```javascript -{ - "contractAddress": "0x0000000000000000000000000000000000000000", - "typeChoice": 0, - "source": "0x0000000000000000000000000000000000000000000000000000000000000000", - "name": "uint256", - "types": [] -} - -{ - "contractAddress": "0x0000000000000000000000000000000000000000", - "typeChoice": 0, - "source": "0x0000000000000000000000000000000000000000000000000000000000000000", - "name": "string", - "types": [] -} -``` - -Composed types can be defined as: -```javascript -{ - "contractAddress": "0x105631C6CdDBa84D12Fa916f0045B1F97eC9C268", - "typeChoice": 0, - "source": , - "name": "myBalance", - "types": [ - {"name": "string", "label": "accountName", dimensions: []}, - {"name": "uint256", "label": "amount", dimensions: []} - ] -} -``` - -Composed types can be further composed: -```javascript -{ - "contractAddress": "0x91E3737f15e9b182EdD44D45d943cF248b3a3BF9", - "typeChoice": 0, - "source": , - "name": "myToken", - "types": [ - {"name": "address", "label": "token", dimensions: []}, - {"name": "myBalance", "label": "balance", dimensions: []} - ] -} -``` - -`myToken` type will have the final data format: `(address,(string,uint256))` and a labeled format: `(address token, (string accountName, uint256 amount))`. - -##### dType Registry Data Structures and Interface - -To store this metadata, the dType registry will have the following data structures: - -```solidity -enum TypeChoices { - BaseType, - PayableFunction, - StateFunction, - ViewFunction, - PureFunction, - Event -} - -struct dTypes { - string name; - string label; - string[] dimensions; -} - -struct dType { - TypeChoices typeChoice; - address contractAddress; - bytes32 source; - string name; - dTypes[] types; -} - -``` - -For storage, we propose a pattern which isolates the type metadata from additional storage-specific data and allows CRUD operations on records. - -```solidity -// key: identifier -mapping(bytes32 => Type) public typeStruct; - -// array of identifiers -bytes32[] public typeIndex; - -struct Type { - dType data; - uint256 index; -} -``` - -Note that we are proposing to define the type's primary identifier, `identifier`, as `keccak256(abi.encodePacked(name))`. If the system is extended to other programming languages, we can define `identifier` as `keccak256(abi.encodePacked(language, name))`. -Initially, single word English names can be disallowed, avoiding name squatting. - - -The dType registry interface is: - -```solidity -import './dTypeLib.sol'; -interface dType { - event LogNew(bytes32 indexed identifier, uint256 indexed index); - event LogUpdate(bytes32 indexed identifier, uint256 indexed index); - event LogRemove(bytes32 indexed identifier, uint256 indexed index); - - function insert(dTypeLib.dType calldata data) external returns (bytes32 identifier); - - function remove(bytes32 identifier) external returns(uint256 index); - - function count() external view returns(uint256 counter); - - function getTypeIdentifier(string memory name) pure external returns (bytes32 identifier); - - function getByIdentifier(bytes32 identifier) view external returns(dTypeLib.dType memory dtype); - - function get(string memory name) view external returns(dTypeLib.dType memory dtype); - - function isRegistered(bytes32 identifier) view external returns(bool registered); -} -``` - -**Notes:** - -To ensure backward compatibility, we suggest that updating types should not be supported. - -The `remove` function can also be removed from the interface, to ensure immutability. One reason for keeping it would be clearing up storage for types that are not in use or have been made obsolete. However, this can have undesired effects and should be accompanied by a solid permissions system, testing and governance process. This part will be updated when enough feedback has been received. - -## Rationale - -The Type Registry must store the minimum amount of information for rebuilding the type ABI definition. This allows us to: -* support on-chain interoperability -* decode blockchain side effects off-chain (useful for block explorers) -* allow off-chain tools to cache and search through the collection (e.g. editor plugin for writing typed smart contracts) - -There is one advantage that has become clear with the emergence of global operating systems, like Ethereum: we can have a global type system through which the system’s parts can interoperate. Projects should agree on standardizing types and a type registry, continuously working on improving them, instead of creating encapsulated projects, each with their own types. - -The effort of having consensus on new types being added or removing unused ones is left to the governance system. - -After the basis of such a system is specified, we can move forward to building a static type checking system at compile time, based on the type definitions and rules stored in the dType registry. - -The Type Library must express the behavior strictly pertinent to its defined type. Additional behavior, required by various project's business logic can be added later, through libraries containing functions that handle the respective type. These can also be registered in dType, but will be detailed in a future ERC. - -This is an approach that will separate definitions from stored data and behavior, allowing for easier and more secure fine-grained upgrades. - -## Backwards Compatibility - -This proposal does not affect extant Ethereum standards or implementations. It uses the present experimental version of ABIEncoderV2. - -## Test Cases - -Will be added. - -## Implementation - -An in-work implementation can be found at https://github.com/pipeos-one/dType/tree/master/contracts/contracts. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - -A video demo of the current implementation (a more extended version of this proposal) can be seen at https://youtu.be/pcqi4yWBDuQ. - - -## 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-1900.md diff --git a/EIPS/eip-1901.md b/EIPS/eip-1901.md index cb0397f9448424..7585b479f73a02 100644 --- a/EIPS/eip-1901.md +++ b/EIPS/eip-1901.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2019-02-25 @@ -16,7 +16,7 @@ This is a proposal to add [OpenRPC](https://github.com/open-rpc/spec) support to 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. +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 @@ -102,4 +102,4 @@ The [OpenRPC mock server](https://github.com/open-rpc/mock-server) provides a mo ## 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-191.md b/EIPS/eip-191.md index 910c30ee85993b..69a96210719f60 100644 --- a/EIPS/eip-191.md +++ b/EIPS/eip-191.md @@ -1,83 +1,7 @@ --- eip: 191 -title: Signed Data Standard -author: Martin Holst Swende (@holiman), Nick Johnson -status: Last Call -type: Standards Track category: ERC -created: 2016-01-20 -review-period-end: 2021-05-01 +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]: ./eip-191.md -[EIP-712]: ./eip-712.md - -### 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 index 8c530a056e3d10..ee46bc42861c18 100644 --- a/EIPS/eip-1921.md +++ b/EIPS/eip-1921.md @@ -1,141 +1,7 @@ --- eip: 1921 -title: dType Functions Extension -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/1921 -status: Draft -type: Standards Track category: ERC -created: 2019-04-06 -requires: 1900 +status: Moved --- -## Simple Summary -In the context of dType, the Decentralized Type System described in [EIP-1900](./eip-1900.md), we are proposing to add support for registering functions (with a preference for `pure` and `view`) in the dType Registry. - -## Abstract - -This proposal is part of a series of EIPs focused on expanding the concept of a Decentralized Type System, as explained in [EIP-1900](./eip-1900.md). -The current EIP specifies the data definitions and interfaces needed to support registering individual smart contract functions, as entries in the dType Registry. - -## Motivation - -In order to evolve the EVM into a Singleton Operating System, we need a way to register, find and address contract functions that we want to run in an automated way. -This implies having access to all the data needed to run the function inside the EVM. - -Aside from the above motivation, there are also near future benefits for this proposal. Having a globally available, non-custodial functions registry, will democratize the development of tools, such as those targeting: blockchain data analysis (e.g. block explorers), smart contract IDEs, security analysis of smart contracts. - -Registering new smart contract functions can be done through the same consensus mechanism as [EIP-1900](./eip-1900.md) mentions, in order to avoid burdening the chain state with redundant or improper records. - - -## Specification - -This specification targets `pure` and `view` functions. - -For each function, we can store: -* `name` - type `string` unique function name, as defined in EIP-1900; required -* `types` - the type data and label of each input, as defined in EIP-1900; required -* `outputs` - the type data and label of each output; required -* `contractAddress` - type `address` - smart contract where the function resides, as defined in EIP-1900; optional for interfaces -* `source` - type `bytes32` - reference to an external file containing the function source code, as defined in EIP-1900; optional - -Therefore, this proposal adds `outputs` to the EIP-1900 type registration definition. - -An example of a function registration object for the dType registry is: - -``` -{ - "name": "setStaked", - "types": [ - {"name": "TypeA", "label": "typeA", "relation":0, "dimensions":[]} - ], - "typeChoice": 4, - "contractAddress":
, - "source": , - "outputs": [ - {"name": "TypeB", "label": "typeB", "relation":0, "dimensions":[]} - ] -} -``` - -The above object will be passed to `.insert({...})` - -An additional `setOutputs` function is proposed for the dType registry: - -``` -function setOutputs( - bytes32 identifier, - dTypes[] memory outputs -) - public -``` - -- `identifier` - type `bytes32`, the type's identifier, as defined in EIP-1900 -- `outputs` - type `dTypes`, as defined in EIP-1900 - -### Implementation Suggestions - - -In the dType registry implementation, `outputs` can be stored in a `mapping`: - -``` -mapping(bytes32 => dTypes[]) public outputs; -``` - -## Rationale - - -The suggestion to treat each `pure` or `view` function as a separate entity instead of having a contract-based approach allows us to: -* have a global context of readily available functions -* scale designs through functional programming patterns rather than contract-encapsulated logic (which can be successfully used to scale development efforts independently) -* bidirectionally connect functions with the types they use, making automation easier -* cherry-pick functions from already deployed contracts if the other contract functions do not pass community consensus -* have scope-restricted improvements - instead of redeploying entire contracts, we can just redeploy the new function versions that we want to be added to the registry -* enable fine-grained auditing of individual functions, for the common good -* enable testing directly on a production chain, without state side-effects - -The proposal to store the minimum ABI information on-chain, for each function, allows us to: -* enable on-chain automation (e.g. function chaining and composition) -* be backward compatible in case the function signature format changes (e.g. from `bytes4` to `bytes32`): multiple signature calculation functions can be registered with dType. Examples: - -``` -function getSignatureBytes4(bytes32 identifier) - view - public - returns (bytes4 signature) - -function getSignatureBytes32(bytes32 identifier) - view - public - returns (bytes32 signature) -``` - -- `identifier` - the type's identifier, as defined in EIP-1900 -- `signature` - the function's signature - - -Concerns about this design might be: -* redundancy of storing `contractAddress` for each function that is part of the same contract - -We think that state/storage cost will be compensated through DRYness across the chain, due to reusing types and functions that have already been registered and are now easy to find. Other state/storage cost calculations will be added once the specification and implementation are closer to be finalized. - - -Note that the input and output types are based on types that have already been registered. This lowers the amount of ABI information needed to be stored for each function and enables developers to aggregate and find functions that use the same types for their I/O. This can be a powerful tool for interoperability and smart contract composition. - - -## Backwards Compatibility - -This proposal does not affect extant Ethereum standards or implementations. Registering functions for existing contract deployments should be fully supported. - -## Test Cases - -Will be added. - - -## Implementation - -In-work implementation examples can be found at https://github.com/pipeos-one/dType. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - -## 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-1921.md diff --git a/EIPS/eip-1922.md b/EIPS/eip-1922.md index aa6d0810699b24..9bce442d20f524 100644 --- a/EIPS/eip-1922.md +++ b/EIPS/eip-1922.md @@ -1,207 +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. ./eip-20.md - -1. ERC-165 Standard Interface Detection. ./eip-165.md -1. ERC-173 Contract Ownership Standard (DRAFT). ./eip-173.md -1. ERC-196 Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128. ./eip-196.md -1. ERC-197 Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128. ./eip-197.md -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 2e2fc46591ca68..dd3d9382335887 100644 --- a/EIPS/eip-1923.md +++ b/EIPS/eip-1923.md @@ -1,164 +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. ./eip-20.md - -1. ERC-165 Standard Interface Detection. ./eip-165.md -2. ERC-173 Contract Ownership Standard (DRAFT). ./eip-173.md -3. ERC-196 Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128. ./eip-196.md -4. ERC-197 Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128. ./eip-197.md -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 162704ffbd914c..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 --- @@ -86,7 +86,7 @@ Currently the gas specified as part of these opcodes is simply a maximum value. 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 interpreting wrongly that the callee is not implementing the interface in question. @@ -127,7 +127,7 @@ 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 @@ -147,4 +147,4 @@ None fully implemented yet. But see Specifications for an example in geth. ## 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 index d6be67ee4cabcc..6658ba14e44a09 100644 --- a/EIPS/eip-1948.md +++ b/EIPS/eip-1948.md @@ -1,159 +1,7 @@ --- eip: 1948 -title: Non-fungible Data Token -author: Johann Barbie (@johannbarbie), Ben Bollen , pinkiebell (@pinkiebell) -discussions-to: https://ethereum-magicians.org/t/erc-non-fungible-data-token/3139 -status: Draft -type: Standards Track category: ERC -created: 2019-04-18 -requires: 721 +status: Moved --- -## Simple Summary - -Some NFT use-cases require to have dynamic data associated with a non-fungible token that can change during its lifetime. Examples for dynamic data: -- cryptokitties that can change color -- intellectual property tokens that encode rights holders -- tokens that store data to transport them across chains - -The existing metadata standard does not suffice as data can only be set at minting time and not modified later. - -## Abstract - -Non-fungible tokens (NFTs) are extended with the ability to store dynamic data. A 32 bytes data field is added and a read function allows to access it. The write function allows to update it, if the caller is the owner of the token. An event is emitted every time the data updates and the previous and new value is emitted in it. - -## Motivation - -The proposal is made to standardize on tokens with dynamic data. Interactions with bridges for side-chains like xDAI or Plasma chains will profit from the ability to use such tokens. Protocols that build on data tokens like [distributed breeding](https://ethresear.ch/t/a-distributed-breeding-function/5264) will be enabled. - -## Specification - -An extension of [ERC-721](./eip-721.md) interface with the following functions and events is suggested: - -``` solidity -pragma solidity ^0.5.2; - -/** - * @dev Interface of the ERC1948 contract. - */ -interface IERC1948 { - - /** - * @dev Emitted when `oldData` is replaced with `newData` in storage of `tokenId`. - * - * Note that `oldData` or `newData` may be empty bytes. - */ - event DataUpdated(uint256 indexed tokenId, bytes32 oldData, bytes32 newData); - - /** - * @dev Reads the data of a specified token. Returns the current data in - * storage of `tokenId`. - * - * @param tokenId The token to read the data off. - * - * @return A bytes32 representing the current data stored in the token. - */ - function readData(uint256 tokenId) external view returns (bytes32); - - /** - * @dev Updates the data of a specified token. Writes `newData` into storage - * of `tokenId`. - * - * @param tokenId The token to write data to. - * @param newData The data to be written to the token. - * - * Emits a `DataUpdated` event. - */ - function writeData(uint256 tokenId, bytes32 newData) external; - -} -``` - -## Rationale - -The suggested data field in the NFT is used either for storing data directly, like a counter or address. If more data is required the implementer should fall back to authenticated data structures, like merkle- or patricia-trees. - -The proposal for this ERC stems from the [distributed breeding proposal](https://ethresear.ch/t/a-distributed-breeding-function/5264) to allow better integration of NFTs across side-chains. [ost.com](https://ost.com/), [Skale](https://skalelabs.com/), [POA](https://poa.network/), and [LeapDAO](https://leapdao.org/) have been part of the discussion. - -## Backwards Compatibility - -🤷‍♂️ No related proposals are known to the author, hence no backwards compatibility to consider. - -## Test Cases - -Simple happy test: - -``` javascript -const ERC1948 = artifacts.require('./ERC1948.sol'); - -contract('ERC1948', (accounts) => { - const firstTokenId = 100; - const empty = '0x0000000000000000000000000000000000000000000000000000000000000000'; - const data = '0x0101010101010101010101010101010101010101010101010101010101010101'; - let dataToken; - - beforeEach(async () => { - dataToken = await ERC1948.new(); - await dataToken.mint(accounts[0], firstTokenId); - }); - - it('should allow to write and read', async () => { - let rsp = await dataToken.readData(firstTokenId); - assert.equal(rsp, empty); - await dataToken.writeData(firstTokenId, data); - rsp = await dataToken.readData(firstTokenId); - assert.equal(rsp, data); - }); - -}); -``` - - -## Implementation - -An example implementation of the interface in solidity would look like this: - -``` solidity -/** - * @dev Implementation of ERC721 token and the `IERC1948` interface. - * - * ERC1948 is a non-fungible token (NFT) extended with the ability to store - * dynamic data. The data is a bytes32 field for each tokenId. If 32 bytes - * do not suffice to store the data, an authenticated data structure (hash or - * merkle tree) shall be used. - */ -contract ERC1948 is IERC1948, ERC721 { - - mapping(uint256 => bytes32) data; - - /** - * @dev See `IERC1948.readData`. - * - * Requirements: - * - * - `tokenId` needs to exist. - */ - function readData(uint256 tokenId) external view returns (bytes32) { - require(_exists(tokenId)); - return data[tokenId]; - } - - /** - * @dev See `IERC1948.writeData`. - * - * Requirements: - * - * - `msg.sender` needs to be owner of `tokenId`. - */ - function writeData(uint256 tokenId, bytes32 newData) external { - require(msg.sender == ownerOf(tokenId)); - emit DataUpdated(tokenId, data[tokenId], newData); - data[tokenId] = newData; - } - -} -``` - -## 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-1948.md diff --git a/EIPS/eip-1959.md b/EIPS/eip-1959.md index 36c9624734e1ae..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 --- @@ -38,7 +38,7 @@ The approach proposed by EIP-1344 is to give access to the latest chainID. This 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 f3be641133d900..6538d198b1db10 100644 --- a/EIPS/eip-196.md +++ b/EIPS/eip-196.md @@ -102,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 d880f2be506094..5a69e321a551f9 100644 --- a/EIPS/eip-1962.md +++ b/EIPS/eip-1962.md @@ -5,7 +5,7 @@ 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 --- @@ -134,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 89357acbd80f07..bb791ced399219 100644 --- a/EIPS/eip-1965.md +++ b/EIPS/eip-1965.md @@ -5,7 +5,7 @@ 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 --- @@ -16,7 +16,7 @@ This EIP adds a precompile that returns whether a specific chainID (EIP-155 uniq ## Motivation [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 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-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](./eip-1959.md) 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.** @@ -60,4 +60,4 @@ While the pair could be optional for contract that do not care about replays or 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/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1967.md b/EIPS/eip-1967.md index 185350b946a835..48b32f9e9dec16 100644 --- a/EIPS/eip-1967.md +++ b/EIPS/eip-1967.md @@ -1,95 +1,7 @@ --- eip: 1967 -title: Standard Proxy Storage Slots -author: Santiago Palladino (@spalladino) -discussions-to: https://ethereum-magicians.org/t/eip-1967-standard-proxy-storage-slots/3185 -status: Draft -type: Standards Track category: ERC -created: 2019-04-24 +status: Moved --- -## Simple Summary -Standardise how proxies store the address of the logic contract they delegate to, and other proxy specific information. - -## Abstract -Delegating **proxy contracts** are widely used for both upgradeability and gas savings. These proxies rely on a **logic contract** (also known as implementation contract or master copy) that is called using `delegatecall`. This allows proxies to keep a persistent state (storage and balance) while the code is delegated to the logic contract. - -To avoid clashes in storage usage between the proxy and logic contract, the address of the logic contract is typically saved in a [specific storage slot](https://blog.zeppelinos.org/upgradeability-using-unstructured-storage/) guaranteed to be never allocated by a compiler. This EIP proposes a set of standard slots to store proxy information. This allows clients like block explorers to properly extract and show this information to end users, and logic contracts to optionally act upon it. - -## Motivation -Delegating proxies are widely in use, as a means to both support upgrades and reduce gas costs of deployments. Examples of these proxies are found in [ZeppelinOS](https://blog.zeppelinos.org/the-transparent-proxy-pattern/), [Terminal](https://medium.com/terminaldotco/escape-hatch-proxy-efb681de108d), [Gnosis](https://blog.gnosis.pm/solidity-delegateproxy-contracts-e09957d0f201), [AragonOS](https://github.com/aragon/aragonOS/blob/dev/contracts/common/DelegateProxy.sol), [Melonport](https://github.com/melonproject/melon-mail/blob/782aeff9418ac8cdd80875fd6c400bf96f3b03b3/solidity/contracts/DelegateProxy.sol), [Limechain](https://github.com/LimeChain/UpgradeableSolidityContract/blob/14bcabc338130fb2aba2ce8bd27b885305566fce/contracts/Upgradeability/Forwardable.sol), [WindingTree](https://github.com/windingtree/upgradeable-token-labs/blob/af3b66096091d8282d5c9c55c33365315d85f3e1/contracts/upgradable/DelegateProxy.sol), [Decentraland](https://github.com/decentraland/land/blob/5154046844f6f94a5074e82abe01381e6fd7c39d/contracts/upgradable/DelegateProxy.sol), and many others. - -However, the lack of a common interface for obtaining the logic address for a proxy makes it impossible to build common tools that act upon this information. - -A classic example of this is a block explorer. Here, the end user wants to interact with the underlying logic contract and not the proxy itself. Having a common way to retrieve the logic contract address from a proxy would allow a block explorer, among other things, to show the ABI of the logic contract and not that of the proxy (see [this proxy](https://etherscan.io/token/0x00fdae9174357424a78afaad98da36fd66dd9e03#readContract) for an example). The explorer should check the storage of the contract at the distinguished slots to determine if it is indeed a proxy, in which case it should show information on both the proxy and the logic contract. - -Another example are logic contracts that explicitly act upon the fact that they are being proxied. This allows them to potentially trigger a code update as part of their logic, as is the case of [Universal Upgradeable Proxy Standard (EIP1822)](./eip-1822.md). A common storage slot allows these use cases independently of the specific proxy implementation being used. - -## Specification -The main requirement for the storage slots chosen is that they must never be picked by the compiler to store any contract state variable. Otherwise, a logic contract could inadvertently overwrite this information on the proxy when writing to a variable of its own. - -[Solidity](https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html#layout-of-state-variables-in-storage) maps variables to storage based on the order in which they were declared, after the contract inheritance chain is linearized: the first variable is assigned the first slot, and so on. The exception are values in dynamic arrays and mappings, which are stored in the hash of the concatenation of the key and the storage slot. The Solidity development team has [confirmed](https://twitter.com/ethchris/status/1073692785176444928) that the storage layout is to be preserved among new versions. Vyper seems to [follow the same strategy as Solidity](https://github.com/ethereum/vyper/issues/769). Note that contracts written in other languages, or directly in assembly, may incur in clashes. - -As such, the proposed storage slots for proxy-specific information are the following. They are chosen in such a way so they are guaranteed to not clash with state variables allocated by the compiler, since they depend on the hash of a string that does not start with a storage index. Furthermore, a `-1` offset is added so the preimage of the hash cannot be known, further reducing the chances of a possible attack. - -More slots for additional information can be added in subsequent ERCs as needed. - -### Logic contract address - -Storage slot `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` -(obtained as `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`). - -Holds the address of the logic contract that this proxy delegates to. SHOULD be empty if a beacon is used instead. - -### Beacon contract address - -Storage slot `0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50` (obtained as `bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)`). - -Holds the address of the beacon contract this proxy relies on (fallback). SHOULD be empty if a logic address is used directly instead, and should only be considered if the logic contract slot is empty. See the Beacons section below. - -### Admin address - -Storage slot `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` -(obtained as `bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)`). - -Holds the address that is allowed to upgrade the logic contract address for this proxy (optional). - -## Rationale - -This EIP standardises the **storage slot** for the logic contract address, instead of a public method on the proxy contract as [DelegateProxy (EIP897)](./eip-897.md) does. The rationale for this is that proxies should never expose functions to end users that could potentially clash with those of the logic contract. - -Note that a clash may occur even among functions with different names, since the ABI relies on just four bytes for the function selector. This can lead to unexpected errors, or even exploits, where a call to a proxied contract returns a different value than expected, since the proxy intercepts the call and answers with a value of its own. - -From [_Malicious backdoors in Ethereum proxies_](https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357) by Nomic Labs: - -> Any function in the Proxy contract whose selector matches with one in the implementation contract will be called directly, completely skipping the implementation code. -> -> Because the function selectors use a fixed amount of bytes, there will always be the possibility of a clash. This isn’t an issue for day to day development, given that the Solidity compiler will detect a selector clash within a contract, but this becomes exploitable when selectors are used for cross-contract interaction. Clashes can be abused to create a seemingly well-behaved contract that’s actually concealing a backdoor. - -The fact that proxy public functions are potentially exploitable makes it necessary to standardise the logic contract address in a different way. This approach is also used as part of [Universal Upgradeable Proxy Standard (EIP1822)](./eip-1822.md), which could become a specialization of this EIP. - -## Beacons - -Some use-cases rely on multiple proxy contracts delegating their calls to the same logic contract. If each contract was to store the address of the logic contract using the logic contract storage slot, upgrading them would require writing to the corresponding storage slot of every instance, which could be very expensive in terms of gas. - -Another approach is to have each proxy retrieve the logic contract's address from a dedicated "beacon". Using this pattern, the address of the logic contract can be modified in the beacon and take immediate effect for all the corresponding proxy contracts. - -A beacon MUST implement the function: - -``` -function implementation() returns (address) -``` - -Beacon based proxy contracts do not use the logic contract slot. Instead, they use the beacon contract slot to store the address of the beacon they are attached to. In order to know the logic contract used by a beacon proxy, one should: - -- Read the address of the beacon for the beacon logic storage slot; -- Call the `implementation()` function on the beacon contract. - -The result of the `implementation()` function on the beacon contract SHOULD NOT depend on the caller (`msg.sender`). - -## Implementation -Sample proxy implementations that follow this standard can be found in the [ZeppelinOS repository](https://github.com/zeppelinos/zos/blob/dc9e4ed/packages/lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol), albeit with a different set of slots. - -## 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-1967.md diff --git a/EIPS/eip-197.md b/EIPS/eip-197.md index 795d721ca6fdc8..9f9b3d33440e7c 100644 --- a/EIPS/eip-197.md +++ b/EIPS/eip-197.md @@ -137,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 1f64ae0f35888e..8ee3f7066323e4 100644 --- a/EIPS/eip-1973.md +++ b/EIPS/eip-1973.md @@ -1,270 +1,7 @@ --- eip: 1973 -title: Scalable Rewards -author: Lee Raj (@lerajk), Qin Jian (@qinjian) -type: Standards Track 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/ +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 f3f713ff81c7c5..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 @@ -127,7 +127,7 @@ TBA 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 index 8043fa5c816e3d..3305a10c98c649 100644 --- a/EIPS/eip-1996.md +++ b/EIPS/eip-1996.md @@ -1,294 +1,7 @@ --- eip: 1996 -title: Holdable Token -author: Julio Faura , Fernando Paris , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2103 -status: Draft -type: Standards Track category: ERC -created: 2019-04-10 -requires: 20 +status: Moved --- -## Simple Summary -An extension to the ERC-20 standard token that allows tokens to be put on hold. This guarantees a future transfer and makes the held tokens unavailable for transfer in the mean time. Holds are similar to escrows in that are firm and lead to final settlement. - -## Actors - -#### Operator -An account which has been approved by an account to create holds on its behalf. - -#### Hold issuer -The account, which creates a hold. This can be the account owner itself, or any account, which has been approved as an operator for the account. - -#### Notary -The account which decides if a hold should be executed. - -## Abstract -A hold specifies a payer, a payee, a maximum amount, a notary and an expiration time. When the hold is created, the specified token balance from the payer is put on hold. A held balance cannot be transferred until the hold is either executed or released. The hold can only be executed by the notary, which triggers the transfer of the tokens from the payer to the payee. If a hold is released, either by the notary at any time, or by anyone after the expiration, no transfer is carried out and the amount is available again for the payer. - -A hold can be partially executed, if the execution specifies an amount less than the maximum amount. In this case the specified amount is transferred to the payee and the remaining amount is available again to the payer. - -Holds can be specified to be perpetual. In this case, the hold cannot be released upon expiration, and thus can only be executed by the notary or released by the notary or payee. - -## Motivation - -A hold has to be used in different scenarios where a immediate transfer between accounts is not possible or has to be guaranteed beforehand: - -1. A regulated token may not allow to do a token transfer between accounts without verifying first, that it follows all the regulations. In this case a clearable transfer has to be used. During the clearing process a hold is created to ensure, that the transfer is successful after all checks have passed. If the transfer violates any of the regulations, it is cleared and not further processed. - -1. In certain business situations a payment has to be guaranteed before its services can be used. For example: When checking in a hotel, the hotel will put a hold on the guest's account to ensure that enough balance is available to pay for the room before handing over the keys. - -1. In other occasions a payment has to be guaranteed without knowing the exact amount beforehand. To stay with the hotel example: The hotel can put a hold on the guest's account as a guarantee for any possible extras, like room service. When the guest checks out the hold is partially executed and the remaining amount is available again on the guest's account. - -The ERC-20 `approve` function provides some of the necessary functionality for the use cases above. The main difference to holds, is that `approve` does not ensure a payment, as the approved money is not blocked and can be transferred at any moment. - -## Specification - -```solidity -interface IHoldable /* is ERC-20 */ { - enum HoldStatusCode { - Nonexistent, - Ordered, - Executed, - ReleasedByNotary, - ReleasedByPayee, - ReleasedOnExpiration - } - - function hold(string calldata operationId, address to, address notary, uint256 value, uint256 timeToExpiration) external returns (bool); - function holdFrom(string calldata operationId, address from, address to, address notary, uint256 value, uint256 timeToExpiration) external returns (bool); - function releaseHold(string calldata operationId) external returns (bool); - function executeHold(string calldata operationId, uint256 value) external returns (bool); - function renewHold(string calldata operationId, uint256 timeToExpiration) external returns (bool); - function retrieveHoldData(string calldata operationId) external view returns (address from, address to, address notary, uint256 value, uint256 expiration, HoldStatusCode status); - - function balanceOnHold(address account) external view returns (uint256); - function netBalanceOf(address account) external view returns (uint256); - function totalSupplyOnHold() external view returns (uint256); - - function authorizeHoldOperator(address operator) external returns (bool); - function revokeHoldOperator(address operator) external returns (bool); - function isHoldOperatorFor(address operator, address from) external view returns (bool); - - event HoldCreated(address indexed holdIssuer, string operationId, address from, address to, address indexed notary, uint256 value, uint256 expiration); - event HoldExecuted(address indexed holdIssuer, string operationId, address indexed notary, uint256 heldValue, uint256 transferredValue); - event HoldReleased(address indexed holdIssuer, string operationId, HoldStatusCode status); - event HoldRenewed(address indexed holdIssuer, string operationId, uint256 oldExpiration, uint256 newExpiration); - event AuthorizedHoldOperator(address indexed operator, address indexed account); - event RevokedHoldOperator(address indexed operator, address indexed account); -} -``` - -### Functions - -#### hold - -Creates a hold on behalf of the msg.sender in favor of the payee. It specifies a notary who is responsible to either execute or release the hold. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | -| timeToExpiration | The duration until the hold is expired. If it is '0' the hold must be perpetual. | - -#### holdFrom - -Creates a hold on behalf of the payer in favor of the payee. The `from` account has to approve beforehand, that another account can issue holds on its behalf by calling `approveToHold`. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | -| timeToExpiration | The duration until the hold is expired. If it is '0' the hold must be perpetual. | - -#### releaseHold - -Releases a hold. Release means that the transfer is not executed and the held amount is available again for the payer. Until a hold has expired it can only be released by the notary or the payee. After it has expired it can be released by anyone. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | - -#### executeHold - -Executes a hold. Execute means that the specified value is transferred from the payer to the payee. If the specified value is less than the hold value the remaining amount is available again to the payer. The implementation must verify that only the notary is able to successfully call the function. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| value | The amount to be transferred. This amount has to be less or equal than the hold value | - -#### renewHold - -Renews a hold. The new expiration time must be the block timestamp plus the given `timeToExpiration`, independently if the hold was perpetual or not before that. Furthermore a hold must be made perpetual if `timeToExpiration` is '0'. The implementation must verify that only the payer or operator are able to successfully call the function. Furthermore the only a hold, which has not yet expired can be successfully renewed. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| timeToExpiration | The new duration until the hold is expired. | - -#### retrieveHoldData - -Retrieves all the information available for a particular hold. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | - -#### balanceOnHold - -Retrieves how much of the balance is currently held and therefore not available for transfer. - -| Parameter | Description | -| ---------|-------------| -| account | The address which held balance should be returned | - -#### netBalanceOf - -Retrieves the net balance, which is the sum of `balanceOf` and `balanceOnHold`. - -| Parameter | Description | -| ---------|-------------| -| account | The address which net balance should be returned | - -#### totalSupplyOnHold - -Retrieves the total sum of how many tokens are on hold. - -| Parameter | Description | -| ---------|-------------| -| - | - | - -#### authorizeHoldOperator - -Approves an operator to issue holds on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of holds | - -#### revokeHoldOperator - -Revokes the approval to issue holds on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be revoked as operator of holds | - -#### isHoldOperatorFor - -Retrieves if an operator is approved to create holds on behalf of `from`. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be a operator of holds | -| from | The address on which the holds would be created | - -#### balanceOf - -The standard implementation of ERC-20 has to be changed in order to deduct the held balance from the ERC-20 balance. - -#### transfer - -The standard implementation of ERC-20 has to be changed in order to deduct the held balance from the ERC-20 balance. Any amount that is held must not be transferred. - -#### transferFrom - -The standard implementation of ERC-20 has to be changed in order to deduct the held balance from the ERC-20 balance. Any amount that is held must not be transferred. - -### Events - -#### HoldCreated - -Emitted when a hold has been created. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | -| expiration | The unix timestamp when the hold is expired | - -#### HoldExecuted - -Emitted when a hold has been executed. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| notary | The address of the notary who executed the hold | -| heldValue | The amount which was put on hold during creation | -| transferredValue | The amount which was used for the transfer | - -#### HoldReleased - -Emitted when a hold has been released. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| status | Can be one of the following values: `ReleasedByNotary`, `ReleasedByPayee`, `ReleasedOnExpiration` | - -#### HoldRenewed - -Emitted when a hold has been renewed. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| oldExpiration | The expiration time before the renewal | -| newExpiration | The expiration time after the renewal | - -#### AuthorizedHoldOperator - -Emitted when an operator has been approved to create holds on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be a operator of holds | -| account | Address on which behalf holds will potentially be created | - -#### RevokedHoldOperator - -Emitted when an operator has been revoked from creating holds on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be a operator of holds | -| account | Address on which behalf holds could potentially be created | - -## Rationale - -This standards provides a functionality, to guarantee future payments, which is needed for many business cases where transfers have to be guaranteed. - -It goes a step further than the ERC-20 `approve` function by ensuring that the held balance will be available when the transfer is done. Something that can not be done with `approve`, as the approved amount is only a maximum spending amount, but never guaranteed to be available. - -While not requiring it, the naming of the functions `authorizeHoldOperator`, `revokeHoldOperator` and `isHoldOperatorFor` follows the naming convention of [ERC-777](./eip-777.md). - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but nor required, that the hold issuers used a unique prefix to avoid collisions. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation extends the functionality of ERC-20. - -## Implementation -The GitHub repository [IoBuilders/holdable-token](https://github.com/IoBuilders/holdable-token) contains the reference implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## 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-1996.md diff --git a/EIPS/eip-2.md b/EIPS/eip-2.md index 14bc9e606f93ae..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 diff --git a/EIPS/eip-20-token-standard.md b/EIPS/eip-20-token-standard.md deleted file mode 100644 index 0a18b5683ad3b8..00000000000000 --- a/EIPS/eip-20-token-standard.md +++ /dev/null @@ -1 +0,0 @@ -Moved to [EIP-20](./eip-20.md). 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 index d8b81488ee0ac5..c96aac070908c8 100644 --- a/EIPS/eip-2003.md +++ b/EIPS/eip-2003.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2019-05-09 @@ -104,7 +104,7 @@ EVMC provides the [evmc-vmtester] tool for checking compatibility with the EVMC ## 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-1352]: ./eip-1352.md diff --git a/EIPS/eip-2009.md b/EIPS/eip-2009.md index 31ddc0a2fdd021..8fe47e1a42df3d 100644 --- a/EIPS/eip-2009.md +++ b/EIPS/eip-2009.md @@ -1,300 +1,7 @@ --- eip: 2009 -title: Compliance Service -author: Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2022 -status: Draft -type: Standards Track category: ERC -created: 2019-05-09 -requires: 1066 +status: Moved --- -## Simple Summary - -This EIP proposes a service for decentralized compliance checks for regulated tokens. - -## Actors - -#### Operator -An account which has been approved by a token to update the tokens accumulated. - -#### Token -An account, normally a smart contract, which uses the `Compliance Service` to check if the an action can be executed or not. - -#### Token holder -An account which is in possession of tokens and on for which the checks are made. - -## Abstract - -A regulated token needs to comply with several legal requirements, especially [KYC][KYC-Wikipedia] and [AML][AML-Wikipedia]. If the necessary checks have to be made off-chain the token transfer becomes centralized. Further the transfer in this case takes longer to complete as it can not be done in one transaction, but requires a second confirmation step. The goal of this proposal is to make this second step unnecessary by providing a service for compliance checks. - -## Motivation - -Currently there is no proposal on how to accomplish decentralized compliance checks. [ERC-1462][ERC-1462] proposes a basic set of functions to check if `transfer`, `mint` and `burn` are allowed for a user, but not how those checks should be implemented. This EIP proposes a way to implement them fully on-chain while being generic enough to leave the actual implementation of the checks up to the implementers, as these may vary a lot between different tokens. - -The proposed `Compliance Service` supports more than one token. Therefore it could be used by law-makers to maintain the compliance rules of regulated tokens in one smart contract. This smart contract could be used by all of the tokens that fall under this jurisdiction and ensure compliance with the current laws. - -By having a standard for compliance checks third-party developers can use them to verify if token movements for a specific account are allowed and act accordingly. - -## Specification - -```solidity -interface CompliantService { - function checkTransferAllowed(bytes32 tokenId, address from, address to, uint256 value) external view returns (byte); - function checkTransferFromAllowed(bytes32 tokenId, address sender, address from, address to, uint256 value) external view returns (byte); - function checkMintAllowed(bytes32 tokenId, address to, uint256 value) external view returns (byte); - function checkBurnAllowed(bytes32 tokenId, address from, uint256 value) external view returns (byte); - - function updateTransferAccumulated(bytes32 tokenId, address from, address to, uint256 value) external; - function updateMintAccumulated(bytes32 tokenId, address to, uint256 value) external; - function updateBurnAccumulated(bytes32 tokenId, address from, uint256 value) external; - - function addToken(bytes32 tokenId, address token) external; - function replaceToken(bytes32 tokenId, address token) external; - function removeToken(bytes32 tokenId) external; - function isToken(address token) external view returns (bool); - function getTokenId(address token) external view returns (bytes32); - - function authorizeAccumulatedOperator(address operator) external returns (bool); - function revokeAccumulatedOperator(address operator) external returns (bool); - function isAccumulatedOperatorFor(address operator, bytes32 tokenId) external view returns (bool); - - event TokenAdded(bytes32 indexed tokenId, address indexed token); - event TokenReplaced(bytes32 indexed tokenId, address indexed previousAddress, address indexed newAddress); - event TokenRemoved(bytes32 indexed tokenId); - event AuthorizedAccumulatedOperator(address indexed operator, bytes32 indexed tokenId); - event RevokedAccumulatedOperator(address indexed operator, bytes32 indexed tokenId); -} -``` - -### Mandatory checks - -The checks must be verified in their corresponding actions. The action must only be successful if the check return an `Allowed` status code. In any other case the functions must revert. - -### Status codes - -If an action is allowed `0x11` (Allowed) or an issuer-specific code with equivalent but more precise meaning must be returned. If the action is not allowed the status must be `0x10` (Disallowed) or an issuer-specific code with equivalent but more precise meaning. - -### Functions - -#### checkTransferAllowed - -Checks if the `transfer` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### checkTransferFromAllowed - -Checks if the `transferFrom` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| sender | The address of the sender, who initiated the transaction | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### checkMintAllowed - -Checks if the `mint` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| to | The address of the payee, to whom the tokens are to be given if executed | -| value | The amount to be minted | - -#### checkBurnAllowed - -Checks if the `burn` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| value | The amount to be burned | - -#### updateTransferAccumulated - -Must be called in the same transaction as `transfer` or `transferFrom`. It must revert if the update violates any of the compliance rules. It is up to the implementer which specific logic is executed in the function. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### updateMintAccumulated - -Must be called in the same transaction as `mint`. It must revert if the update violates any of the compliance rules. It is up to the implementer which specific logic is executed in the function. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| to | The address of the payee, to whom the tokens are to be given if executed | -| value | The amount to be minted | - -#### updateBurnAccumulated - -Must be called in the same transaction as `burn`. It must revert if the update violates any of the compliance rules. It is up to the implementer which specific logic is executed in the function. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| value | The amount to be minted | - -#### addToken - -Adds a token to the service, which allows the token to call the functions to update the accumulated. If an existing token id is used the function must revert. It is up to the implementer if adding a token should be restricted or not. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| token | The address from which the update functions will be called | - -#### replaceToken - -Replaces the address of a added token with another one. It is up to the implementer if replacing a token should be restricted or not, but a token should be able to replace its own address. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| token | The address from which the update functions will be called | - -#### removeToken - -Removes a token from the service, which disallows the token to call the functions to update the accumulated. It is up to the implementer if removing a token should be restricted or not. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | - -#### isToken - -Returns `true` if the address has been added to the service, `false` if not. - -| Parameter | Description | -| ---------|-------------| -| token | The address which should be checked | - -#### getTokenId - -Returns the token id of a token. If the token has not been added to the service, '0' must be returned. - -| Parameter | Description | -| ---------|-------------| -| token | The address which token id should be returned | - -#### authorizeAccumulatedOperator - -Approves an operator to update accumulated on behalf of the token id of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of accumulated updates | - -#### revokeAccumulatedOperator - -Revokes the approval to update accumulated on behalf the token id the token id ofof msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be revoked as operator of accumulated updates | - -#### isAccumulatedOperatorFor - -Retrieves if an operator is approved to create holds on behalf of `tokenId`. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which is operator of updating the accumulated | -| tokenId | The unique ID which identifies a token | - -### Events - -#### TokenAdded - -Must be emitted after a token has been added. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| token | The address from which the update functions will be called | - -#### TokenReplaced - -Must be emitted after the address of a token has been replaced. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| previousAddress | The previous address which was used before | -| newAddress | The address which will be used from now on | - -#### TokenRemoved - -Must be emitted after the a token has been removed. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | - -#### AuthorizedAccumulatedOperator - -Emitted when an operator has been approved to update the accumulated on behalf of a token. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which is operator of updating the accumulated | -| tokenId | Token id on which behalf updates of the accumulated will potentially be made | - -#### RevokedHoldOperator - -Emitted when an operator has been revoked from updating the accumulated on behalf of a token. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which was operator of updating the accumulated | -| tokenId | Token id on which behalf updates of the accumulated could be made | - -## Rationale - -The usage of a token id instead of the address has been chosen to give tokens the possibility to update their smart contracts and keeping all their associated accumulated. If the address would be used, a migration process would needed to be done after a smart contract update. - -No event is emitted after updating the accumulated as those are always associated with a `transfer`, `mint` or `burn` of a token which already emits an event of itself. - -While not requiring it, the naming of the functions `checkTransferAllowed`, `checkTransferFromAllowed`, `checkMintAllowed` and `checkBurnAllowed` was adopted from [ERC-1462][ERC-1462]. - -While not requiring it, the naming of the functions `authorizeAccumulatedOperator`, `revokeAccumulatedOperator` and `isAccumulatedOperatorFor` follows the naming convention of [ERC-777][ERC-777]. - -Localization is not part of this EIP, but [ERC-1066][ERC-1066] and [ERC-1444][ERC-1444] can be used together to achieve it. - -## Backwards Compatibility - -As the EIP is not using any existing EIP there are no backwards compatibilities to take into consideration. - -## Implementation - -The GitHub repository [IoBuilders/compliance-service](https://github.com/IoBuilders/compliance-service) contains the work in progress implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[KYC-Wikipedia]: https://en.wikipedia.org/wiki/Know_your_customer -[AML-Wikipedia]: https://en.wikipedia.org/wiki/Money_laundering#Anti-money_laundering -[ERC-777]: ./eip-777.md -[ERC-1066]: ./eip-1066.md -[ERC-1444]: ./eip-1444.md -[ERC-1462]: ./eip-1462.md +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 ee8df44a72a141..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 @@ -87,7 +87,7 @@ TBA 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]: ./eip-140.md diff --git a/EIPS/eip-2015.md b/EIPS/eip-2015.md index e57fc49ffbf749..d5b4d3aaecb308 100644 --- a/EIPS/eip-2015.md +++ b/EIPS/eip-2015.md @@ -1,108 +1,74 @@ --- eip: 2015 -title: Wallet Update Ethereum Chain RPC Method (`wallet_updateEthereumChain`) -author: Pedro Gomes (@pedrouid), Erik Marks (@rekmarks) +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: 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_updateEthereumChain` 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`, `chainName`, `rpcUrl`, `nativeCurrency` and `blockExplorerUrl`. 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](./eip-1102.md) 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 (string): the id of the chain compliant with EIP-155 -- chainName (string): the name of the chain to update -- rpcUrl (string): the url endpoint for RPC requests for this chain -- nativeCurrency (Object): includes three fields for `name` (string), `symbol` (string) and `decimals` (number) -- blockExplorerUrl (string): the url endpoint for a block explorer web site for the chain. - -### Best Practices -- The Wallet should display a UI view similar to a [EIP-1102](./eip-1102.md) 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": 0x5, - "chainName": "Goerli", - "rpcUrl": "https://goerli.infura.io/v3/406405f9c65348f99d0d5c27104b2213", - "nativeCurrency": { - "name": "Goerli ETH", - "symbol": "gorETH" - }, - "blockExplorerUrl": "https://goerli.etherscan.io" - } - ] + +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": "0x5", - "chainName": "Goerli", - "rpcUrl": "https://goerli.infura.io/v3/406405f9c65348f99d0d5c27104b2213", - "nativeCurrency": { - "name": "Goerli ETH", - "symbol": "gorETH" - }, - "blockExplorerUrl": "https://goerli.etherscan.io" - } - ] +interface EthereumChainSwitchRequest { + chainId: string; + chainName?: string; + rpcUrls?: string[]; + nativeCurrency?: NativeCurrencyData; + blockExplorerUrl?: string; } ``` -### Responses +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`. -A success response: +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. -```json -{ - "id": 1, - "jsonrpc": "2.0", - "result": true -} -``` +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`. -A failure response: +## Rationale -```json -{ - "id": 1, - "jsonrpc": "2.0", - "error": { - "code": 4001, - "message": "The user rejected the request." - } -} -``` +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 index ec98a676098488..dce10628acf0ae 100644 --- a/EIPS/eip-2018.md +++ b/EIPS/eip-2018.md @@ -1,261 +1,7 @@ --- eip: 2018 -title: Clearable Token -author: Julio Faura , Fernando Paris , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2104 -status: Draft -type: Standards Track category: ERC -created: 2019-04-30 -requires: 1996 +status: Moved --- -## Simple Summary - -> "In banking and finance, clearing denotes all activities from the time a commitment is made for a transaction until it is settled." [[1]][Clearing-Wikipedia] - -## Actors - -#### Clearing Agent - -An account which processes, executes or rejects a clearable transfer. - -#### Operator -An account which has been approved by an account to order clearable transfers on its behalf. - -#### Orderer -The account which orders a clearable transfer. This can be the account owner itself, or any account, which has been approved as an operator for the account. - -## Abstract - -The clearing process turns the promise of a transfer into the actual movement of money from one account to another. A clearing agent decides if the transfer can be executed or not. The amount which should be transferred is not deducted from the balance of the payer, but neither is it available for another transfer and therefore ensures, that the execution of the transfer will be successful when it is executed. - -## Motivation - -A regulated token needs to comply with all the legal requirements, especially [KYC][KYC-Wikipedia] and [AML][AML-Wikipedia]. Some of these checks may not be able to be done on-chain and therefore a transfer may not be completed in one step. Currently there is no EIP to make such off-chain checks possible. This proposal allows a user to order a transfer, which can be checked by a clearing agent off-chain. Depending on the result of it, the clearing agent will either execute or cancel the transfer. To provide more information why a transfer is cancelled, the clearing agent can add a reason why it is not executed. - -## Specification - -```solidity -interface ClearableToken /* is ERC-1996 */ { - enum ClearableTransferStatusCode { Nonexistent, Ordered, InProcess, Executed, Rejected, Cancelled } - - function orderTransfer(string calldata operationId, address to, uint256 value) external returns (bool); - function orderTransferFrom(string calldata operationId, address from, address to, uint256 value) external returns (bool); - function cancelTransfer(string calldata operationId) external returns (bool); - function processClearableTransfer(string calldata operationId) external returns (bool); - function executeClearableTransfer(string calldata operationId) external returns (bool); - function rejectClearableTransfer(string calldata operationId, string calldata reason) external returns (bool); - function retrieveClearableTransferData(string calldata operationId) external view returns (address from, address to, uint256 value, ClearableTransferStatusCode status); - - function authorizeClearableTransferOperator(address operator) external returns (bool); - function revokeClearableTransferOperator(address operator) external returns (bool); - function isClearableTransferOperatorFor(address operator, address from) external view returns (bool); - - event ClearableTransferOrdered(address indexed orderer, string operationId, address indexed from, address indexed to, uint256 value); - event ClearableTransferInProcess(address indexed orderer, string operationId); - event ClearableTransferExecuted(address indexed orderer, string operationId); - event ClearableTransferRejected(address indexed orderer, string operationId, string reason); - event ClearableTransferCancelled(address indexed orderer, string operationId); - event AuthorizedClearableTransferOperator(address indexed operator, address indexed account); - event RevokedClearableTransferOperator(address indexed operator, address indexed account); -} -``` - -### Functions - -#### orderTransfer - -Orders a clearable transfer on behalf of the msg.sender in favor of `to`. A clearing agent is responsible to either execute or reject the transfer. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | - -#### orderTransferFrom - -Orders a clearable transfer on behalf of the payer in favor of the `to`. A clearing agent is responsible to either execute or reject the transfer. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | - -#### cancelTransfer - -Cancels the order of a clearable transfer. Only the orderer can cancel their own orders. It must not be successful as soon as the transfer is in status `InProcess`. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### processClearableTransfer - -Sets a clearable transfer to status `InProcess`. Only a clearing agent can successfully execute this action. This status is optional, but without it the orderer can cancel the transfer at any time. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### executeClearableTransfer - -Executes a clearable transfer, which means that the tokens are transferred from the payer to the payee. Only a clearing agent can successfully execute this action. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### rejectClearableTransfer - -Rejects a clearable transfer, which means that the amount that is held is available again to the payer and no transfer is done. Only a clearing agent can successfully execute this action. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | -| reason | A reason given by the clearing agent why the transfer has been rejected | - -#### retrieveClearableTransferData - -Retrieves all the information available for a particular clearable transfer. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### authorizeClearableTransferOperator - -Approves an operator to order transfers on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of clearable transfers | - -#### revokeClearableTransferOperator - -Revokes the approval to order transfers on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be revoked as operator of clearable transfers | - -#### isClearableTransferOperatorFor - -Returns if an operator is approved to order transfers on behalf of `from`. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be an operator of clearable transfers | -| from | The address on which the holds would be created | - -#### transfer - -It is up to the implementer of the EIP if the `transfer` function of ERC-20 should always revert or is allowed under certain circumstances. - -#### transferFrom - -It is up to the implementer of the EIP if the `transferFrom` function of ERC-20 should always revert or is allowed under certain circumstances. - - -### Events - -#### ClearableTransferOrdered - -Must be emitted when a clearable transfer is ordered. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred if executed | - -#### ClearableTransferInProcess - -Must be emitted when a clearable transfer is put in status `ÌnProcess`. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | - -#### ClearableTransferExecuted - -Must be emitted when a clearable transfer is executed. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | - -#### ClearableTransferRejected - -Must be emitted when a clearable transfer is rejected. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | -| reason | A reason given by the clearing agent why the transfer has been rejected | - -#### ClearableTransferCancelled - -Must be emitted when a clearable transfer is cancelled by its orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | - -#### AuthorizedClearableTransferOperator - -Emitted when an operator has been approved to order transfers on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which has been approved as operator of clearable transfers | -| account | Address on which behalf transfers will potentially be ordered | - -#### RevokedClearableTransferOperator - -Emitted when an operator has been revoked from ordering transfers on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which has been revoked as operator of clearable transfers | -| account | Address on which behalf transfers could potentially be ordered | - -## Rationale - -This EIP uses [EIP-1996][EIP-1996] to hold the money after a transfer is ordered. A clearing agent, whose implementation is not part of this proposal, acts as a predefined notary to decide if the transfer complies with the rules of the token or not. - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but not required, that the hold issuers used a unique prefix to avoid collisions. - -While not requiring it, the naming of the functions `authorizeClearableTransferOperator`, `revokeClearableTransferOperator` and `isClearableTransferOperatorFor` follows the naming convention of [ERC-777](./eip-777.md). - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of [EIP-1996][EIP-1996]. - -## Implementation - -The GitHub repository [IoBuilders/clearable-token](https://github.com/IoBuilders/clearable-token) contains the reference implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[1] https://en.wikipedia.org/wiki/Clearing_(finance) - -[Clearing-Wikipedia]: https://en.wikipedia.org/wiki/Clearing_(finance) -[KYC-Wikipedia]: https://en.wikipedia.org/wiki/Know_your_customer -[AML-Wikipedia]: https://en.wikipedia.org/wiki/Money_laundering#Anti-money_laundering -[EIP-1996]: ./eip-1996.md +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 index 152bec120528e7..c4ad7b3c4f315d 100644 --- a/EIPS/eip-2019.md +++ b/EIPS/eip-2019.md @@ -1,255 +1,7 @@ --- eip: 2019 -title: Fundable Token -author: Fernando Paris , Julio Faura , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2105 -status: Draft -type: Standards Track category: ERC -created: 2019-05-10 -requires: 20 +status: Moved --- -## Simple Summary -An extension to the [ERC-20] standard token that allows Token wallet owners to request a wallet to be funded, by calling the smart contract and attaching a fund instruction string. - -## Actors - -#### Token Wallet Owners -The person or company who owns the wallet, and will order a token fund request into the wallet. - -#### Token contract owner / agent -The entity, company responsible/owner of the token contract, and token issuing/minting. This actor is in charge of trying to fulfill all fund request(s), reading the fund instruction(s), and correlate the private payment details. - -#### Orderer -An actor who is enabled to initiate funding orders on behalf of a token wallet owner. - -## Abstract -Token wallet owners (or approved addresses) can order tokenization requests through blockchain. This is done by calling the ```orderFund``` or ```orderFundFrom``` methods, which initiate the workflow for the token contract operator to either honor or reject the fund request. In this case, fund instructions are provided when submitting the request, which are used by the operator to determine the source of the funds to be debited in order to do fund the token wallet (through minting). - -In general, it is not advisable to place explicit routing instructions for debiting funds on a verbatim basis on the blockchain, and it is advised to use a private communication alternatives, such as private channels, encrypted storage or similar, to do so (external to the blockchain ledger). Another (less desirable) possibility is to place these instructions on the instructions field in encrypted form. - -## Motivation -Nowadays most of the token issuing/funding request, based on any fiat based payment method need a previous centralized transaction, to be able to get the desired tokens issued on requester's wallet. -In the aim of trying to bring all the needed steps into decentralization, exposing all the needed steps of token lifecycle and payment transactions, a funding request can allow wallet owner to initiate the funding request via blockchain. -Key benefits: - -* Funding and payment traceability is enhanced bringing the initiation into the ledger. All payment stat -s can be stored on chain. -* Almost all money/token lifecycle is covered via a decentralized approach, complemented with private communications which is common use in the ecosystem. - -## Specification - -```solidity -interface IFundable /* is ERC-20 */ { - enum FundStatusCode { - Nonexistent, - Ordered, - InProcess, - Executed, - Rejected, - Cancelled - } - function authorizeFundOperator(address orderer) external returns (bool); - function revokeFundOperator(address orderer) external returns (bool) ; - function orderFund(string calldata operationId, uint256 value, string calldata instructions) external returns (bool); - function orderFundFrom(string calldata operationId, address walletToFund, uint256 value, string calldata instructions) external returns (bool); - function cancelFund(string calldata operationId) external returns (bool); - function processFund(string calldata operationId) external returns (bool); - function executeFund(string calldata operationId) external returns (bool); - function rejectFund(string calldata operationId, string calldata reason) external returns (bool); - - function isFundOperatorFor(address walletToFund, address orderer) external view returns (bool); - function retrieveFundData(address orderer, string calldata operationId) external view returns (address walletToFund, uint256 value, string memory instructions, FundStatusCode status); - - event FundOrdered(address indexed orderer, string indexed operationId, address indexed , uint256 value, string instructions); - event FundInProcess(address indexed orderer, string indexed operationId); - event FundExecuted(address indexed orderer, string indexed operationId); - event FundRejected(address indexed orderer, string indexed operationId, string reason); - event FundCancelled(address indexed orderer, string indexed operationId); - event FundOperatorAuthorized(address indexed walletToFund, address indexed orderer); - event FundOperatorRevoked(address indexed walletToFund, address indexed orderer); -} -``` - -### Functions - -#### authorizeFundOperator - -Wallet owner, authorizes a given address to be fund orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. - -#### revokeFundOperator - -Wallet owner, revokes a given address to be fund orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. - -#### orderFund - -Creates a fund request, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### orderFundFrom - -Creates a fund request, on behalf of a wallet owner, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId |The unique ID to identify the request | -| walletToFund | The wallet to be funded on behalf. -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### cancelFund - -Cancels a funding request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that is going to be cancelled. This can only be done by token holder, or the fund initiator. | - -#### processFund - -Marks a funding request as on process. After the status is on process, order cannot be cancelled. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request is in process. - -#### executeFund - -Issues the amount of tokens and marks a funding request as executed. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. - -#### rejectFund - -Rejects a given operation with a reason. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. -| reason | The specific reason that explains why the fund request was rejected. EIP 1066 codes can be used | - -#### isFundOperatorFor - -Checks that given player is allowed to order fund requests, for a given wallet. - -| Parameter | Description | -| ---------|-------------| -| walletToFund | The wallet to be funded, and checked for approval permission. -| orderer | The address of the orderer, to be checked for approval permission. - -#### retrieveFundData - -Retrieves all the fund request data. Only operator, tokenHolder, and orderer can get the given operation data. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the fund order. - -### Events - -#### FundOrdered - -Emitted when an token wallet owner orders a funding request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| walletToFund | The wallet that the player is allowed to start funding requests | -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### FundInProcess - -Emitted when an operator starts a funding request after validating the instruction, and the operation is marked as in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | - -#### FundExecuted - -Emitted when an operator has executed a funding request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | - -#### FundRejected - -Emitted when an operator has rejected a funding request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | -| reason | The specific reason that explains why the fund request was rejected. EIP 1066 codes can be used | - -#### FundCancelled - -Emitted when a token holder, orderer, has cancelled a funding request. This can only be done if the operator hasn't put the funding order in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | - -#### FundOperatorAuthorized - -Emitted when a given player, operator, company or a given persona, has been approved to start fund request for a given token holder. - -| Parameter | Description | -| ---------|-------------| -| walletToFund | The wallet that the player is allowed to start funding requests | -| orderer | The address that allows the the player to start requests. | - -#### FundOperatorRevoked - -Emitted when a given player has been revoked initiate funding requests. - -| Parameter | Description | -| ---------|-------------| -| walletToFund | The wallet that the player is allowed to start funding requests | -| orderer | The address that allows the the player to start requests. | - -## Rationale -This standards provides a functionality to allow token holders to start funding requests in a decentralized way. - -It's important to highlight that the token operator, need to process all funding request, updating the fund status based on the linked payment that will be done. - -Funding instruction format is open. ISO payment standard like is a good start point, - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but not required, that the hold issuers used a unique prefix to avoid collisions. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-20]. - -## Implementation -The GitHub repository [IoBuilders/fundable-token](https://github.com/IoBuilders/fundable-token) contains the work in progress implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[ERC-20]: ./eip-20.md +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 index 24dbf6bcf5961d..9cdaef6e9f076d 100644 --- a/EIPS/eip-2020.md +++ b/EIPS/eip-2020.md @@ -1,233 +1,7 @@ --- eip: 2020 -title: E-Money Standard Token -author: Julio Faura , Fernando Paris , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2407 -status: Draft -type: Standards Track category: ERC -created: 2019-05-10 -requires: 20, 1066, 1996, 2009, 2018, 2019, 2021 +status: Moved --- -## Simple Summary - -The E-Money Standard Token aims to enable the issuance of regulated electronic money on blockchain networks, and its practical usage in real financial applications. - -## Actors - -#### Operator -An account, which has been approved by an account to perform an action on the behalf of another account. - -## Abstract - -Financial institutions work today with electronic systems, which hold account balances in databases on core banking systems. In order for an institution to be allowed to maintain records of client balances segregated and available for clients, such institution must be regulated under a known legal framework and must possess a license to do so. Maintaining a license under regulatory supervision entails ensuring compliance (i.e. performing KYC on all clients and ensuring good AML practices before allowing transactions) and demonstrating technical and operational solvency through periodic audits, so clients depositing funds with the institution can rest assured that their money is safe. - -## Motivation - -There are only a number of potential regulatory license frameworks that allow institutions to issue and hold money balances for customers (be it retail corporate or institutional types). The most important and practical ones are three: -* **Electronic money entities**: these are legally regulated vehicles that are mostly used today for cash and payments services, instead of more complex financial services. For example prepaid cards or online payment systems such as PayPal run on such schemes. In most jurisdictions, electronic money balances are required to be 100% backed by assets, which often entails holding cash on an omnibus account at a bank with 100% of the funds issued to clients in the electronic money ledger. -* **Banking licenses**: these include commercial and investment banks, which segregate client funds using current and other type of accounts implemented on core banking systems. Banks can create money by lending to clients, so bank money can be backed by promises to pay and other illiquid assets. -* **Central banks**: central banks hold balances for banks in RTGS systems, similar to core banking systems but with much more restricted yet critical functionality. Central banks create money by lending it to banks, which pledge their assets to central banks as a lender of last resort for an official interest rate. - -Regulations for all these types of electronic money are local, i.e. only valid for each jurisdiction and not valid in others. Regulations can vary as well dramatically in different jurisdictions — for example there are places with no electronic money frameworks, on everything has to be done through banking licenses or directly with a central bank. But in all cases compliance with existing regulation needs to ensured, in particular: -* **Know Your Customer (KYC)**: the institution needs to identify the client before providing them with the possibility of depositing money or transact. In different jurisdictions and for different types of licenses there are different levels of balance and activity that can be allowed for different levels of KYC. For example, low KYC requirements with little checks or even no checks at all can usually be acceptable in many jurisdictions if cashin balances are kept low (i.e. hundreds of dollars) -* **Anti Money Laundering (AML)**: the institution needs to perform checks of parties transacting with its clients, typically checking against black lists and doing sanction screening, most notably in the context of international transactions - -Beyond cash, financial instruments such as equities or bonds are also registered in electronic systems in most cases, although all these systems and the bank accounting systems are only connected through rudimentary messaging means, which leads to the need for reconciliations and manual management in many cases. Cash systems to provide settlement of transactions in the capital markets are not well-connected to the transactional systems, and often entail delays and settlement risk. - -The E-Money Standard Token builds on Ethereum standards currently in use such as [ERC-20], but it extends them to provide few key additional pieces of functionality, needed in the regulated financial world: -* **Compliance**: E-Money Standard Token implements a set of methods to check in advance whether user-initiated transactions can be done from a compliance point of view. Implementations must `require` that these methods return a positive answer before executing the transaction. -* **Clearing**: In addition to the standard [ERC-20] `transfer` method, E-Money Standard Token provides a way to submit transfers that need to be cleared by the token issuing authority off-chain. These transfers are then executed in two steps: - 1. transfers are ordered - 1. after clearing them, transfers are executed or rejected by the operator of the token contract -* **Holds**: token balances can be put on hold, which will make the held amount unavailable for further use until the hold is resolved (i.e. either executed or released). Holds have a payer, a payee, and a notary who is in charge of resolving the hold. Holds also implement expiration periods, after which anyone can release the hold Holds are similar to escrows in that are firm and lead to final settlement. Holds can also be used to implement collateralization. -* **Funding requests**: users can request for a wallet to be funded by calling the smart contract and attaching a debit instruction string. The tokenizer reads this request, interprets the debit instructions, and triggers a transfer in the bank ledger to initiate the tokenization process. -* **Payouts**: users can request payouts by calling the smart contract and attaching a payment instruction string. The (de)tokenizer reads this request, interprets the payment instructions, and triggers the transfer of funds (typically from the omnibus account) into the destination account, if possible. Note that a redemption request is a special type of payout in which the destination (bank) account for the payout is the bank account linked to the token wallet. - -The E-Money Standard Token is thus different from other tokens commonly referred to as "stable coins" in that it is designed to be issued, burnt and made available to users in a compliant manner (i.e. with full KYC and AML compliance) through a licensed vehicle (an electronic money entity, a bank, or a central bank), and in that it provides the additional functionality described above, so it can be used by other smart contracts implementing more complex financial applications such as interbank payments, supply chain finance instruments, or the creation of E-Money Standard Token denominated bonds and equities with automatic delivery-vs-payment. - -## Specification - -```solidity -interface EMoneyToken /* is ERC-1996, ERC-2018, ERC-2019, ERC-2021 */ { - function currency() external view returns (string memory); - function version() external pure returns (string memory); - - function availableFunds(address account) external view returns (uint256); - - function checkTransferAllowed(address from, address to, uint256 value) external view returns (byte status); - function checkApproveAllowed(address from, address spender, uint256 value) external view returns (byte status); - - function checkHoldAllowed(address from, address to, address notary, uint256 value) external view returns (byte status); - function checkAuthorizeHoldOperatorAllowed(address operator, address from) external view returns (byte status); - - function checkOrderTransferAllowed(address from, address to, uint256 value) external view returns (byte status); - function checkAuthorizeClearableTransferOperatorAllowed(address operator, address from) external view returns (byte status); - - function checkOrderFundAllowed(address to, address operator, uint256 value) external view returns (byte status); - function checkAuthorizeFundOperatorAllowed(address operator, address to) external view returns (byte status); - - function checkOrderPayoutAllowed(address from, address operator, uint256 value) external view returns (byte status); - function checkAuthorizePayoutOperatorAllowed(address operator, address from) external view returns (byte status); -} -``` - -### Mandatory checks - -The checks must be verified in their corresponding actions. The action must only be successful if the check return an `Allowed` status code. In any other case the functions must revert. - -### Status codes - -If an action is allowed `0x11` (Allowed), or an issuer-specific code with equivalent but more precise meaning must be returned. If the action is not allowed the status must be `0x10` (Disallowed), or an issuer-specific code with equivalent but more precise meaning. - -### Functions - -#### currency - -Returns the currency that backs the token. The value must be a code defined in [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217). - -| Parameter | Description | -| ---------|-------------| -| - | - | - -#### version - -Returns the current version of the smart contract. The format of the version is up to the implementer of the EIP. - -| Parameter | Description | -| ---------|-------------| -| - | - | - -#### availableFunds - -Returns the total net funds of an account. Taking into consideration the outright balance and the held balances. - -| Parameter | Description | -| ---------|-------------| -| account | The account which available funds should be returned | - -#### checkTransferAllowed - -Checks if the `transfer` or `transferFrom` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### checkApproveAllowed - -Checks if the `approve` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| spender | The address of the spender, which potentially can initiate transfers on behalf of `from` | -| value | The maximum amount to be transferred | - -#### checkHoldAllowed - -Checks if the `hold` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer | - -#### checkAuthorizeHoldOperatorAllowed - -Checks if the `checkAuthorizeHoldOperatorAllowed` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of clearable transfers | -| from | The address on which behalf holds could potentially be issued | - -#### checkOrderTransferAllowed - -Checks if the `orderTransfer` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred. Must be less or equal than the balance of the payer | - -#### checkAuthorizeClearableTransferOperatorAllowed - -Checks if the `authorizeClearableTransferOperator` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of clearable transfers | -| from | The address on which behalf clearable transfers could potentially be ordered | - -#### checkOrderFundAllowed - -Checks if the `orderFund` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| to | The address to which the tokens are to be given if executed | -| operator | The address of the requester, which initiates the funding order | -| value | The amount to be funded | - -#### checkAuthorizeFundOperatorAllowed - -Checks if the `authorizeFundOperator` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of ordering funding | -| to | The address which the tokens are to be given if executed | - -#### checkOrderPayoutAllowed - -Checks if the `orderPayout` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address from whom the tokens are to be taken if executed | -| operator | The address of the requester, which initiates the payout request | -| value | The amount to be paid out | - -#### checkAuthorizePayoutOperatorAllowed - -Checks if the `authorizePayoutOperator` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of ordering payouts | -| from | The address from which the tokens are to be taken if executed | - -## Rationale - -This EIP unifies [ERC-1996][ERC-1996], [ERC-2018][ERC-2018], [ERC-2019][ERC-2019] and [ERC-2021][ERC-2021] and adds the checks for the compliance on top of it. By this way the separate EIPs are otherwise independent of each other, and the E-Money Standard Token offers a solution for all necessary functionality of regulated electronic money. - -While not requiring it, the naming of the check functions was adopted from [ERC-1462][ERC-1462]. - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-1996][ERC-1996], [ERC-2018][ERC-2018], [ERC-2019][ERC-2019], [ERC-2021][ERC-2021] and [ERC-1066][ERC-1066]. - -## Implementation - -The GitHub repository [IoBuilders/em-token](https://github.com/IoBuilders/em-token) contains the work in progress implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[ERC-20]: ./eip-20.md -[ERC-1066]: ./eip-1066.md -[ERC-1462]: ./eip-1462.md -[ERC-1996]: ./eip-1996.md -[ERC-2018]: ./eip-2018.md -[ERC-2019]: ./eip-2019.md -[ERC-2021]: ./eip-2021.md +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 index f8e43fcc424f41..a4f4befe9f91ca 100644 --- a/EIPS/eip-2021.md +++ b/EIPS/eip-2021.md @@ -1,290 +1,7 @@ --- eip: 2021 -title: Payoutable Token -author: Fernando Paris , Julio Faura , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2106 -status: Draft -type: Standards Track category: ERC -created: 2019-05-10 -requires: 20, 1066, 1996 +status: Moved --- -## Simple Summary -An extension to the [ERC-20] standard token that allows Token wallet owners to request payout from their wallet, by calling the smart contract and attaching a payout instruction string. - -## Actors - -#### Token Wallet Owners -The person or company who owns the wallet, and will order payout. - -#### Token contract owner / agent -The entity, company responsible/owner of the token contract, and token issuing/minting. This actor is in charge of trying to fulfill all payout request(s), reading the payout instruction(s), and correlate the payout details. - -#### Orderer -An actor who is enabled to initiate payout orders on behalf of a token wallet owner. - -## Abstract -Token wallet owners (or approved addresses) can order payout requests through blockchain. This is done by calling the ```orderPayoutFrom``` or ```orderPayoutFrom``` methods, which initiate the workflow for the token contract operator to either honor or reject the payout request. In this case, payout instructions are provided when submitting the request, which are used by the operator to determine the destination of the funds. - -In general, it is not advisable to place explicit routing instructions for the payouts on a verbatim basis on the blockchain, and it is advised to use a private communication alternatives, such as private channels, encrypted storage or similar, to do so (external to the blockchain ledger). Another (less desirable) possibility is to place these instructions on the instructions field in encrypted form. - -## Motivation -Nowadays most of the token payout requests, need a previous centralized transaction, to be able to define the payout destination to be able to execute the payout (burn transaction). -In the aim of trying to bring all the needed steps into decentralization, exposing all the needed steps of token lifecycle and payment transactions, a payout request can allow wallet owner to initiate the payout order via blockchain. -Key benefits: - -* Payout, burning traceability is enhanced bringing the initiation into the ledger. All payment, payout statuses can be stored on chain. -* Almost all money/token lifecycle is covered via a decentralized approach, complemented with private communications which is common use in the ecosystem. - -In this case, the following movement of tokens are done as the process progresses: - -* Upon launch of the payout request, the appropriate amount of funds are placed on a hold with a predefined notary defined by the platform, and the payout is placed into a ```Ordered``` state -* The operator then can put the payout request ```InProcess```, which prevents the _orderer_ of the payout from being able to cancel the payout request -* After checking the payout is actually possible the operator then executes the hold, which moves the funds to a suspense wallet and places the payout into the ```FundsInSuspense``` state -* The operator then moves the funds offchain (usually from the omnibus account) to the appropriate destination account, then burning the tokens from the suspense wallet and rendering the payout into the ```Executed``` state -* Either before or after placing the request ```InProcess```, the operator can also reject the payout, which returns the funds to the payer and eliminates the hold. The resulting end state of the payout is ```Rejected``` -* When the payout is ```Ordered``` and before the operator places it into the ```InProcess``` state, the orderer of the payout can also cancel it, which frees up the hold and puts the payout into the final ```Cancelled``` state - -## Specification - -```solidity -interface IPayoutable /* is ERC-20 */ { - enum PayoutStatusCode { - Nonexistent, - Ordered, - InProcess, - FundsInSuspense, - Executed, - Rejected, - Cancelled - } - function authorizePayoutOperator(address orderer) external returns (bool); - function revokePayoutOperator(address orderer) external returns (bool); - function orderPayout(string calldata operationId, uint256 value, string calldata instructions) external returns (bool); - function orderPayoutFrom(string calldata operationId, address walletToBePaidOut, uint256 value, string calldata instructions) external returns (bool); - function cancelPayout(string calldata operationId) external returns (bool); - function processPayout(string calldata operationId) external returns (bool); - function putFundsInSuspenseInPayout(string calldata operationId) external returns (bool); - function executePayout(string calldata operationId) external returns (bool); - function rejectPayout(string calldata operationId, string calldata reason) external returns (bool); - - function isPayoutOperatorFor(address walletToDebit, address orderer) external view returns (bool); - function retrievePayoutData(string calldata operationId) external view returns (address walletToDebit, uint256 value, string memory instructions, PayoutStatusCode status); - - event PayoutOrdered(address indexed orderer, string indexed operationId, address indexed walletToDebit, uint256 value, string instructions); - event PayoutInProcess(address indexed orderer, string indexed operationId); - event PayoutFundsInSuspense(address indexed orderer, string indexed operationId); - event PayoutExecuted(address indexed orderer, string indexed operationId); - event PayoutRejected(address indexed orderer, string indexed operationId, string reason); - event PayoutCancelled(address indexed orderer, string indexed operationId); - event PayoutOperatorAuthorized(address indexed walletToBePaidOut, address indexed orderer); - event PayoutOperatorRevoked(address indexed walletToBePaidOut, address indexed orderer); -} -``` - -### Functions - -#### authorizePayoutOperator - -Wallet owner, allows a given address to be payout orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. | - -#### revokePayoutOperator - -Wallet owner, Revokes a given address to be payout orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. | - -#### orderPayout - -Creates a payout request, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| value | The amount to be paid out. | -| instruction | A string including the payment instruction. | - -#### orderPayoutFrom - -Creates a payout request, on behalf of a wallet owner, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId |The unique ID to identify the request | -| walletToBePaidOut | The wallet to be paid out on behalf. | -| value | The amount to be paid out. | -| instruction | A string including the payment instruction. | - -#### cancelPayout - -Cancels a payout request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that is going to be cancelled. This can only be done by token holder, or the payout initiator/orderer. | -| reason | The specific reason that explains why the payout request was rejected. [EIP-1066] codes can be used. | - - -#### processPayout - -Marks a payout request as on process. After the status is on process, order cannot be cancelled. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify that the request is in process. | - -#### putFundsInSuspenseInPayout - -Put a given payout in suspense. Can only be done if it is in process. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify that the request is in process. | - -#### executePayout - -Burn the amount of tokens and marks a payout request as executed. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. | - -#### rejectPayout - -Rejects a given operation with a reason. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. | -| reason | The specific reason that explains why the payout request was rejected. [EIP-1066] codes can be used | - -#### isApprovedToOrderPayout - -Checks that given player is allowed to order payout requests, for a given wallet. - -| Parameter | Description | -| ---------|-------------| -| walletToBePaidOut | The wallet to be paid out, and checked for approval permission. | -| orderer | The address of the orderer, to be checked for approval permission. | - -#### retrievePayoutData - -Retrieves all the payout request data. Only operator, tokenHolder, and orderer can get the given operation data. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer, to correlate the right data. | -| operationId | The unique ID to identify the payout order. | - -### Events - -#### Payout Ordered - -Emitted when an token wallet owner orders a payout request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| walletToBePaidOut | The wallet that is requested to be paid out | -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### PayoutFundsInSuspense - -Emitted when an operator puts fund in suspense. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | - -#### PayoutInProcess - -Emitted when an operator accepts a payout request, and the operation is in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | - -#### PayoutExecuted - -Emitted when an operator has executed a payout request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | - -#### PayoutRejected - -Emitted when an operator has rejected a payout request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | -| reason | The specific reason that explains why the payout request was rejected. [EIP-1066] codes can be used | - -#### PayoutCancelled - -Emitted when a token holder, orderer, has cancelled a payout request. This can only be done if the operator hasn't put the payout order in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID per payout issuer to identify the payout. | - -#### PayoutOperatorAuthorized - -Emitted when a given player, operator, company or a given persona, has been approved to start payout request for a given token holder. - -| Parameter | Description | -| ---------|-------------| -| walletToBePaidOut | The wallet that the player is allowed to start payout requests | -| orderer |The address that allows the the player to start requests. | - -#### PayoutOperatorRevoked - -Emitted when a given player has been revoked initiate payout requests. - -| Parameter | Description | -| ---------|-------------| -| walletToBePaidOut | The wallet that the player is allowed to start payout requests | -| orderer |The address that allows the the player to start requests. | - -## Rationale -This standards provides a functionality to allow token holders to start payout requests in a decentralized way. - -It's important to highlight that the token operator, need to process all payout request, updating the payout status based on the linked payment that will be done. - -Payout instruction format is open. ISO payment standard like is a good start point. - -This EIP uses [EIP-1996] to hold the money after a payout is ordered. The token contract owner or agent, whose implementation is not part of this proposal, acts as a predefined notary to decide if the payout is executed or not. - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but not required, that the hold issuers used a unique prefix to avoid collisions. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-20] and [ERC-1996]. - -## Implementation -The GitHub repository [IoBuilders/payoutable-token](https://github.com/IoBuilders/payoutable-token) contains the reference implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[ERC-20]: ./eip-20.md -[EIP-1066]: ./eip-1066.md -[EIP-1996]: ./eip-1996.md +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 index 44115af814e00b..ae9baa017c31db 100644 --- a/EIPS/eip-2025.md +++ b/EIPS/eip-2025.md @@ -65,7 +65,7 @@ FOR BENEFICIARY in BENEFICIARY_ADDRESSES: *With a price of Etheruem 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 +![Block Rewards Distribution](../assets/eip-2025/block_rewards_distribution.png) *Specific Addresses to be determined * [FAQ - Why hardcoded values?]( #why-hardcoded-values ) @@ -80,7 +80,7 @@ The Eth1x initiative needs funding now, not in 18 months. A loan is necessary to ### Loan Repayment -![Loan State Diagram](/assets/eip-2025/loan_state.png) +![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. @@ -206,4 +206,4 @@ The loan is for the specific use of supporting Eth1.X research and development. #### ## 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-2026.md b/EIPS/eip-2026.md index cc26677dc46dca..e230dae7c2dbcc 100644 --- a/EIPS/eip-2026.md +++ b/EIPS/eip-2026.md @@ -3,7 +3,7 @@ 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 @@ -27,7 +27,7 @@ The penalty is levied to the transaction sender. Rather than raising the gas cos ## 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 @@ -45,7 +45,7 @@ Prior to rent prepayments, other alternatives were considered: 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. @@ -58,4 +58,4 @@ Tests cases will be generated out of a reference 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 e09f93cf7b0add..9faf2ab6a2307b 100644 --- a/EIPS/eip-2027.md +++ b/EIPS/eip-2027.md @@ -3,7 +3,7 @@ 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 @@ -61,4 +61,4 @@ Tests cases will be generated out of a reference 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 6a7d1bd8d2a618..707e63ce5bd00a 100644 --- a/EIPS/eip-2028.md +++ b/EIPS/eip-2028.md @@ -76,4 +76,4 @@ To suggest the gas cost of calldata we shall conduct two types of tests: [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 b6da59d61756d5..d3cacaa692ef3e 100644 --- a/EIPS/eip-2029.md +++ b/EIPS/eip-2029.md @@ -3,7 +3,7 @@ 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 @@ -48,4 +48,4 @@ Tests cases will be created to ensure that the state counter contract returns it 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 40de135a8f550d..ceb2723f79ddf4 100644 --- a/EIPS/eip-2031.md +++ b/EIPS/eip-2031.md @@ -3,7 +3,7 @@ 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 @@ -47,5 +47,5 @@ Tests cases will be generated out of a reference 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 81e469ad61f69c..11342e67c6f3c4 100644 --- a/EIPS/eip-2035.md +++ b/EIPS/eip-2035.md @@ -3,7 +3,7 @@ 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 @@ -67,5 +67,5 @@ Tests cases will be generated out of a reference 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 index 1b907af472bf63..e5a8b602ad6a5b 100644 --- a/EIPS/eip-2045.md +++ b/EIPS/eip-2045.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2019-05-17 @@ -118,4 +118,4 @@ TODO 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2046.md b/EIPS/eip-2046.md index 00d3644ca58b40..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 @@ -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]: ./eip-1352.md diff --git a/EIPS/eip-205.md b/EIPS/eip-205.md index e4753a3ef65047..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](https://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 index c8e53d48cb5bce..14d8d52f587860 100644 --- a/EIPS/eip-2069.md +++ b/EIPS/eip-2069.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Informational created: 2017-02-11 --- @@ -99,7 +99,7 @@ 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). [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 index 66bcbb7da95fd0..a3c30508a2d6ee 100644 --- a/EIPS/eip-2070.md +++ b/EIPS/eip-2070.md @@ -4,7 +4,7 @@ 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: Draft +status: Withdrawn created: 2019-05-20 requires: 1679 --- @@ -22,4 +22,4 @@ For an accurate status please refer to the [`berlin.md`](https://github.com/ethe ## 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-2098.md b/EIPS/eip-2098.md index 2a98c2a676a3bd..1fd5c74486e65e 100644 --- a/EIPS/eip-2098.md +++ b/EIPS/eip-2098.md @@ -1,219 +1,7 @@ --- eip: 2098 -title: Compact Signature Representation -status: Draft -type: Informational -author: Richard Moore (@ricmoo), Nick Johnson -discussions-to: https://github.com/ethereum/EIPs/issues/2440 -created: 2019-03-14 +category: ERC +status: Moved --- -## Simple Summary - -This proposal describes a compact representation of an Ethereum Signature. - - -## Abstract - -The secp256k1 curve permits the computation of the public key of signed -digest when coupled with a signature, which is used implicitly to -establish the origin of a transaction from an Externally Owned Account -as well as on-chain in EVM contracts for example, in meta-transactions and -multi-sig contracts. - -Currently signatures require 65 bytes to represent, which when aligned -to 256-bit words, requires 96 bytes (with 31 zero bytes injected). With -compact signatures, this can be reduced to 64 bytes, which remains 64 -bytes when word-aligned. - - -## Motivation - -The motivations for a compact representation are to simplify handling -transactions in client code, reduce gas costs and reduce transaction sizes. - - -## Specification - -A secp256k1 signature is made up of 3 parameters, `r`, `s` and `v`. The `r` -represents the `x` component on the curve (from which the `y` can be -computed), and the `s` represents the challenge solution for signing by a -private key. Due to the symmetric nature of an elliptic curve, a `v` is -required, which indicates which of the 2 possible solutions was intended, -by indicating its parity (odd-ness). - -Two key observations are required to create a compact representation. - -First, the `v` parameter is always either 0 or 1 (canonically the values used -have been 27 and 28, as these values didn't collide with other binary prefixes -used in Bitcoin.) - -Second, the top bit of the `s` parameters is **always** 0, due to the use of -canonical signatures which flip the solution parity to prevent negative values, -which was introduced as [a constraint in Homestead](./eip-2.md). - -So, we can hijack the top bit in the `s` parameter to store the value of `v`, resulting in: - -``` -[256-bit r value][1-bit v value][255-bit s value] -``` - - -### Example Implementation In Python - -```python -def to_compact(r, s, v): - return { - "r": r, - "vs": ((v - 27) << 255) | s - } - -def to_canonical(r, vs): - return { - "r": r, - "s": vs & ((1 << 255) - 1), - "v": (27 + (vs >> 255)) - } -``` - - -## Rationale - -The compact representation proposed is simple to both compose and decompose -in clients and in Solidity, so that it can be easily (and intuitively) supported, -while reducing transaction sizes and gas costs. - - -## Backwards Compatibility - -The Compact Representation does not collide with canonical signature as -it uses 2 parameters (r, vs) while canonical signatures involve 3 -separate parameters (r, s, v). - - -## Test Vectors - -``` -Private Key: 0x1234567890123456789012345678901234567890123456789012345678901234 -Message: "Hello World" -Signature: - r: 0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90 - s: 0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064 - v: 27 -Compact Signature: - r: 0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90 - vs: 0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064 -``` - -``` -Private Key: 0x1234567890123456789012345678901234567890123456789012345678901234 -Message: "It's a small(er) world" -Signature: - r: 0x9328da16089fcba9bececa81663203989f2df5fe1faa6291a45381c81bd17f76 - s: 0x139c6d6b623b42da56557e5e734a43dc83345ddfadec52cbe24d0cc64f550793 - v: 28 -Compact Signature: - r: 0x9328da16089fcba9bececa81663203989f2df5fe1faa6291a45381c81bd17f76 - vs: 0x939c6d6b623b42da56557e5e734a43dc83345ddfadec52cbe24d0cc64f550793 -``` - - -## Gas Analysis - -**Solidity** - -``` -// See: https://ropsten.etherscan.io/address/0xce826fbc499e3723df5668ea90a4bc51aeca13b8 - -pragma solidity 0.5.6; - -contract TestCompact { - address _lastAddr; - - function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public returns (address) { - _lastAddr = ecrecover(hash, v, r, s); - } - - function recoverCompact(bytes32 hash, bytes32 r, bytes32 vs) public returns (address) { - bytes32 s = vs & 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; - uint8 v = 27 + uint8(uint256(vs) >> 255); - _lastAddr = ecrecover(hash, v, r, s); - } - - function lastAddr() public view returns (address) { - return _lastAddr; - } -} -``` - -**JavaScript** - -``` -let address = "0xcE826fbC499e3723DF5668Ea90a4BC51AeCa13b8"; -let abi = [ - 'function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public returns (address)', - 'function recoverCompact(bytes32 hash, bytes32 r, bytes32 vs) public returns (address)', - 'function lastAddr() public view returns (address)' -]; -let wallet = Wallet.fromMnemonic("relief cousin sorry cabin burst frog slush flavor pitch tragic hip disagree").connect(provider); - -let hash = "0x6ac9e083f46825a57816e023ae641ee45ac9b82cc2c370c10ec1ef4c835fa182"; -let sig = wallet.signingKey.signDigest(hash) - -let contract = new Contract(address, abi, wallet); -(async function() { - let tx, receipt; - - console.log("Canonical:"); - tx = await contract.recover(hash, sig.v, sig.r, sig.s); - console.log(" Hash: ", tx.hash); - console.log(" Data: ", tx.data); - console.log(" Length: ", utils.hexDataLength(tx.data)); - receipt = await tx.wait(); - console.log(" Gas Used:", receipt.gasUsed.toString()); - - console.log("Compact:"); - tx = await contract.recoverCompact(hash, sig.r, sig._vs); - console.log(" Hash: ", tx.hash); - console.log(" Data: ", tx.data); - console.log(" Length: ", utils.hexDataLength(tx.data)); - receipt = await tx.wait(); - console.log(" Gas Used:", receipt.gasUsed.toString()); -})(); -``` - - -**Result** - -``` -/home/ricmoo> ethers --network ropsten run test.js -Canonical: - Hash: 0x3280985011d2f25e76141681e865216e796cf065880eb9dd1f8221f3243028d2 - Data: 0xc2bf17b06ac9e083f46825a57816e023ae641ee45ac9b82cc2c370c10ec1ef4c835fa182000000000000000000000000000000000000000000000000000000000000001be95b1a8633ee7ff851f68cf4303030b1e2596d686cafd9803cef74919a9139291c492d05696da754cf342bec961d00d9f7dfac3ab90b1e9352177c7b9bfa2a5d - Length: 132 - Gas Used: 37541 -Compact: - Hash: 0x513bd8bd8710a84903235ca60591fc60f2f3db524d14cc1b6874edc628512176 - Data: 0x1230abb66ac9e083f46825a57816e023ae641ee45ac9b82cc2c370c10ec1ef4c835fa182e95b1a8633ee7ff851f68cf4303030b1e2596d686cafd9803cef74919a9139291c492d05696da754cf342bec961d00d9f7dfac3ab90b1e9352177c7b9bfa2a5d - Length: 100 - Gas Used: 37329 -``` - - -## Implementations - -The ethers.js library [supports this in v5](https://github.com/ethers-io/ethers.js/blob/ethers-v5-beta/packages/bytes/src.ts/index.ts#L323) -as an unofficial property of split signatures (i.e. `sig._vs`), but should be -considered an internal property that may change at discretion of the community -and any changes to this EIP. - - -## Acknowledgments - -- [Original Tweet from Nick and conversation](https://twitter.com/nicksdjohnson/status/1030830279487709185) -- [Original Solidity Inspiration](https://github.com/HarryR/solcrypto/blob/01a3c5d91053f3b8bffde328146d5f18015ebfed/contracts/ECDSA.sol#L6) - - -## 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-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 index 3f8ee13b91fbee..32479f557f4dc5 100644 --- a/EIPS/eip-2124.md +++ b/EIPS/eip-2124.md @@ -3,8 +3,7 @@ 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: Last Call -review-period-end: 2020-09-18 +status: Final type: Standards Track category: Networking created: 2019-05-03 @@ -309,4 +308,4 @@ Geth: https://github.com/ethereum/go-ethereum/tree/master/core/forkid ## 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-2135.md b/EIPS/eip-2135.md index 970cae1b198aed..731777c2aea3e3 100644 --- a/EIPS/eip-2135.md +++ b/EIPS/eip-2135.md @@ -1,79 +1,7 @@ --- eip: 2135 -title: Consumable Interface -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://github.com/ethereum/EIPs/issues/2135 -status: Draft -type: Standards Track category: ERC -created: 2019-06-23 +status: Moved --- -## Simple Summary -An interface marking certain digital assets being consumable. - -## Abstract -The interface identifies functions and events needed for creating a contract to be able to mark a digital asset as "consumable", and react to the request of "consumption". - -## Motivation -Being a digital assets sometimes means a consumable power. One most common seen examples would be a concert ticket. It will be "consumed" at the moment the ticket-holder uses the ticket to get access to enter a concert. - -By having a standard ERC interface, the Ethereum ecosystem can interoperate to provide services, clients, UI, and inter-contract functionalities on top of this very general use-case. - -## Specification -The standard will mainly contain the following interface. - -### The required interface - -```solidity -pragma solidity ^0.5.8; - -contract EIP2135 { - // The main consume function - function consume(uint256 assetId) public returns(bool success); - - // The interface to check whether an asset is consumable. - function isConsumable(uint256 assetId) public view returns (bool consumable); - - // The interface to check whether an asset is consumable. - event OnConsumption(uint256 indexed assetId); -} -``` - -## Rationale - -The function `consume` performs the consume action. Being an interface standard, -this EIP does not impose any assumption of - - - who has the power to perform such activity. - - under what condition such consumption can occur. - -It does, however, assume the asset can be identified in a `uint256` assetId as in th parameter. A design convention and compatibility consideration is put in place to follow the ERC-721 - -The event notifies subscribers whoever are interested to learn an asset is being consumed. The boolean function of `isConsumable` can be used to check whether an asset is still consumable. - -To keep it simple, this standard *intentionally* contains no functions or events related to creation of a consumable asset. This is because the creation of a consumable asset will need to make assumption of the nature of an actual use-case. If we see some common use-case of creation, we can have another follow up standard. - -We also left out metadata associated to the consumables from the standard. If necessary, related metadata can be created with a separate metadata extension interface like [`ERC-721 Metadata`](./eip-721.md) - -## Backwards Compatibility - -This interface is designed to be compatible with ERC-721. - -## Implementation - -A reference implementation accompany with tests of **ERC-721 based ticket** contract is built and you can found it [here](https://github.com/xinbenlv/eip-2135/blob/master/impl/contracts/Ticket721.sol). - -See [GitHub/xinbenlv/eip-2135/impl](https://github.com/xinbenlv/eip-2135/tree/master/impl) - -## Test Cases - -See [GitHub/xinbenlv/eip-2135/impl/test](https://github.com/xinbenlv/eip-2135/tree/master/impl/test) - -## Reference - -### Standards -- [ERC-721](./eip-721.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-2135.md diff --git a/EIPS/eip-214.md b/EIPS/eip-214.md index 3490f01553ff47..009d0e1ce76b2c 100644 --- a/EIPS/eip-214.md +++ b/EIPS/eip-214.md @@ -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 index 699c34ba956172..0a6c2541e17816 100644 --- a/EIPS/eip-2157.md +++ b/EIPS/eip-2157.md @@ -1,136 +1,7 @@ --- eip: 2157 -title: dType Storage Extension - Decentralized Type System for EVM -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/2157 -status: Draft -type: Standards Track category: ERC -created: 2019-06-28 -requires: 1900 +status: Moved --- -## Simple Summary - -This ERC is an extension of ERC-1900, proposing an optional storage extension for dType, a decentralized type system, specifying a general ABI for all storage contracts that contain type instances. - -## Abstract - -The storage extension will enable easy navigation and retrieval of type data that is intended to be of public use. This is possible through standardizing the ABI of the dType storage contracts, with the effect of having a deterministic path to a type instance record. This standardization enables a more effective on-chain and off-chain use of data and opens up possibilities for decentralized applications, enabling developers to build on top of public global data. - -## Motivation - -Currently, Ethereum does not have standardization of data addressability. This might not be needed for data that is meant to be quasi-private, however, it is needed for data that is meant for public consumption. ERC-1900 has started standardizing data types for increasing interoperability between projects, but this is not enough if we want to build a global ecosystem. Deterministic data addressability will enable anyone to build upon the same public data sets, off-chain or on-chain. - -It is true that with ERC-1900, blockchain data analysis and type-specific data retrieval will be possible off-chain, but this implies relying on centralized data caches (blockchain explorers) or maintaining your own data cache. Moreover, this option does not allow on-chain standardization on data retrieval paths, therefore limiting the type of on-chain interoperable operations that can be done. - -Having a clear way of retrieving data, instead of analyzing the blockchain for contracts that have a certain type in their ABI or bytecode, will make development easier and more decentralized for applications that target global data on specific types. - -For example, a decentralized market place can be built on top of some marketplace-specific types, and by knowing exactly where the type data is stored, it is easy to create custom algorithms that provide the user with the product information they seek. Everyone has access to the data and the data path is standardized. - -Moreover, by standardizing storage contract interfaces, ABI inference is possible. The common interface, together with the dType registry will provide all the data needed to reconstruct the ABI. - -This system can be extended with access and mutability control later on, in a future proposal. Access and mutability control will be necessary for public-use global systems. Moreover, we can have a homogeneous application of permissions across system components. This is not detailed in the present proposal. - -Another use case is data bridges between Ethereum shards or between Ethereum and other chains. Data syncing between shards/chains can be done programmatically, across data types (from various projects). Imagine a user having a public profile/identity contract on one chain, wishing to move that profile on Ethereum. By supporting the origin chain types and having a standardized storage mechanism, data moving processes will be the same. - -This pattern of separating data type definitions and storage allows developers to create functional programming-like patterns on Ethereum, even though languages such as Solidity are not functional. - -## Specification - -### TypeRootContract - -ERC-1900 defines a `contractAddress` field in the type metadata. For the limited purpose of ERC-1900, this field contains the value of the Ethereum type library in which the type definition exists. For the purpose of this ERC, the `contractAddress` will contain the Etherereum address of a `TypeRootContract`. - -```solidity -contract TypeRootContract { - address public libraryAddress; - address public storageAddress; - - constructor(address _library, address _storage) public { - libraryAddress = _library; - storageAddress = _storage; - } -} -``` - -- `libraryAddress` - Ethereum address of the type definition library, from ERC-1900 -- `storageAddress` - Ethereum address of the type data storage contract - - -### TypeStorageContract - -This contract will use the type library to define the internal data stored in it. Each record will be a type instance, addressable by a primary identifier. The primary identifier is calculated by the type library's `getIdentifier` function, based on the type instance values. - -We propose a Solidity CRUD pattern, as described in https://medium.com/robhitchens/solidity-crud-part-1-824ffa69509a, where records can also be retrieved using their index - a monotonically increasing counter. - -An stub implementation for the TypeStorageContract would look like: - -```solidity -import './TypeALib.sol'; - -contract TypeAStorage { - using TypeALib for TypeALib.TypeA; - - bytes32[] public typeIndex; - mapping(bytes32 => Type) public typeStruct; - - struct Type { - TypeALib.TypeA data; - uint256 index; - } - - event LogNew(bytes32 indexed identifier, uint256 indexed index); - event LogUpdate(bytes32 indexed identifier, uint256 indexed index); - event LogRemove(bytes32 indexed identifier, uint256 indexed index); - - function insert(TypeALib.TypeA memory data) public returns (bytes32 identifier); - - function insertBytes(bytes memory data) public returns (bytes32 identifier); - - function remove(bytes32 identifier) public returns(uint256 index); - - function update(bytes32 identifier, TypeALib.TypeA memory data) public returns(bytes32 identifier) - - function isStored(bytes32 identifier) public view returns(bool stored); - - function getByHash(bytes32 identifier) public view returns(TypeALib.TypeA memory data); - - function getByIndex(uint256 index) public view returns(TypeALib.TypeA memory data); - - function count() public view returns(uint256 counter); -} -``` - -## Rationale - -We are now thinking about a building block as a smart contract with an encapsulated object that contains state changing functions that are only understood from within. This is more akin to Object-Oriented Programming and poses interoperability and scalability issues. Not necessarily for an individual project, but for a global Ethereum OS. This is why we are proposing to separate data from business logic and data structure definitions. - -When you have public aggregated data, categorized on each type, anyone can build tools on top of it. This is a radical change from the closed or dispersed data patterns that we find in web2. - -We have chosen to define a `TypeRootContract` instead of extending the dType registry with fields for the TypeStorage contract, because this approach enables easier interface updates in the future. It is more extensible. - -The storage pattern used for dType itself and all the Type Storage contracts can be the same. This lowers the cost of building, testing and auditing the code. - -The `TypeStorageContract` pattern should ensure: -- type instance addressability by the primary identifier -- a way to retrieve all records from the contract -- counting the number of records - - -## Backwards Compatibility - -This proposal does not affect existent Ethereum standards or implementations. It uses the present experimental version of ABIEncoderV2. - -## Test Cases - -Will be added. - -## Implementation - -An in-work implementation can be found at https://github.com/pipeos-one/dType/tree/master/contracts/contracts. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - - -## 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-2157.md diff --git a/EIPS/eip-2159.md b/EIPS/eip-2159.md index 1bced7eceef93b..ca57907ded2b17 100644 --- a/EIPS/eip-2159.md +++ b/EIPS/eip-2159.md @@ -56,4 +56,4 @@ Pantheon switched to using these standard metric names in its 1.2 release: https 2. Beacon chain metrics specification. https://github.com/ethereum/eth2.0-metrics/blob/master/metrics.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-2193.md b/EIPS/eip-2193.md index 1d65946b606702..a27b4aa888bb95 100644 --- a/EIPS/eip-2193.md +++ b/EIPS/eip-2193.md @@ -1,92 +1,7 @@ --- eip: 2193 -title: dType Alias Extension - Decentralized Type System -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/2192 -status: Draft -type: Standards Track category: ERC -created: 2019-07-16 -requires: 155, 1900, 2157 +status: Moved --- -## Simple Summary - -We are proposing Alias - a semantic standard for identifying on-chain resources by human-readable qualifiers, supporting any type of data. - -## Abstract - -The dType Alias is a system for providing human-readable resource identifiers to on-chain content. A resource identifier is based on the type of data (identifier provided by dType, [EIP-1900](./eip-1900.md)) and the data content (identifier provided by a dType Storage Contract, [EIP-2157](./eip-2157.md)). It is a universal way of addressing content, supporting any type of data. - -## Motivation - -There are standards that currently address the need for attaching human-readable identifiers to Ethereum accounts, such as [EIP-137](./eip-137.md). These standards are an attempt to bring domain names to Ethereum, following the same format as DNS: `subdomain.domain.tld`. This leaf -> root format is unintuitive and contradicts the semantic meaning that `.` has in programming languages, which is a root -> leaf connection (e.g. in OOP, when accessing an object's property). A more intuitive and widely used approach is a root->leaf format, used in file browsers, hierarchical menus, and even in other decentralized systems, which give unique identifiers to resources (e.g. `0x56.Currency.TCoin` in [Libra](https://medium.com/r/?url=https%3A%2F%2Fdevelopers.libra.org). - -Moreover, [EIP-137](./eip-137.md) is not flexible enough to address smart contract content, which can contain heterogeneous data that belongs to various accounts. For example, a `PaymentChannel` smart contract can have an domain name. However, the `Alice-Bob` channel data from inside the smart contract, cannot have a subdomain name. Having uniquely identified, granular resources opens the way to creating both human and machine-readable protocols on top of Ethereum. It also provides a basis for protocols based on functional programming. - -This ERC proposes a set of separators which maintain their semantic meaning and provides a way to address any type of resource - from Ethereum addresses, to individual `struct` instances inside smart contracts. - -Imagine the following dType types: `SocialNetwork` and `Profile`, with related storage data about user profiles. One could access such a profile using an alias for the data content: `alice@socialnetwork.profile`. For a `PaymentChannel` type, Alice can refer to her channel with Bob with `alice-bob.paymentchannel`. -This alias system can be used off-chain, to replace the old DNS system with a deterministic and machine-readable way of displaying content, based on the dType type's metadata. - -## Specification - -The dType registry will provide domain and subdomain names for the resource type. Subdomains can be attributed recursively, to dType types which contain other complex types in their composition. - -We define an `Alias` registry contract, that keeps track of the human-readable identifiers for data resources, which exist in dType storage contracts. -Anyone can set an alias in the `Alias` registry, as long as the Ethereum address that signs the alias data has ownership on the resource, in the dType storage contract. Storage contract data ownership will be detailed in [EIP-2157](./eip-2157.md). An owner can update or delete an alias at any time. - -```solidity -interface Alias { - - event AliasSet(bytes32 dtypeIdentifier, bytes1 separator, string name, bytes32 indexed identifier); - - function setAlias(bytes32 dtypeIdentifier, bytes1 separator, string memory name, bytes32 identifier, bytes memory signature) external; - - function getAliased(bytes1 separator, string memory name) view external returns (bytes32 identifier); -} -``` - -- `dtypeIdentifier`: Type identifier from the dType registry, needed to ensure uniqueness of `name` for a dType type. `dtypeIdentifier` is checked to see if it exists in the dType registry. The dType registry also links the type's data storage contract, where the existence and ownership of the `identifier` is checked. -- `name`: user-defined human-readable name for the resource referenced by `identifier` -- `separator`: Character acting as a separator between the name and the rest of the alias. Allowed values: - - `.`: general domain separation, using root->leaf semantics. E.g. `domain.subdomain.leafsubdomain.resource` - - `@`: identifying actor-related data, such as user profiles, using leaf->root semantics. E.g. `alice@socialnetwork.profile` or `alice@dao@eth` - - `#`: identifying concepts, using root->leaf semantics. E.g. `topicX#postY` - - `/`: general resource path definition, using root->leaf semantics. E.g. `resourceRoot/resource` -- `identifier`: Resource identifier from a smart contract linked with dType -- `signature`: Alias owner signature on `dtypeIdentifier`, `identifier`, `name`, `separator`, `nonce`, `aliasAddress`, `chainId`. - - `nonce`: monotonically increasing counter, used to prevent replay attacks - - `aliasAddress`: Ethereum address of `Alias` contract - - `chainId`: chain on which the `Alias` contract is deployed, as detailed in [EIP-155](./eip-155.md), used to prevent replay attacks when updating the `identifier` for an alias. - -Content addressability can be done: -- using the `bytes32` identifiers directly, e.g. `0x0b5e76559822448f6243a6f76ac7864eba89c810084471bdee2a63429c92d2e7@0x9dbb9abe0c47484c5707699b3ceea23b1c2cca2ac72681256ab42ae01bd347da` -- using the human identifiers, e.g. `alice@socialnetwork` - -Both of the above examples will resolve to the same content. - - -## Rationale - -Current attempts to solve content addressability, such as [EIP-137](./eip-137.md), only target Ethereum accounts. These are based on inherited concepts from HTTP and DNS, which are not machine friendly. - -With [EIP-1900](./eip-1900.md) and [EIP-2157](./eip-2157.md), general content addressability can be achieved. dType provides type information and a reference to the smart contract where the type instances are stored. Additionally, Alias uses the semantic meaning of subdomain separators to have a [intuitive order rule](https://github.com/loredanacirstea/articles/blob/master/articles/Flexible_Alias_or_Why_ENS_is_Obsolete.md). - -Multiple aliases can be assigned to a single resource. Either by using a different `name` or by using a different `separator`. Each `separator` can have a specific standard for displaying and processing data, based on its semantic meaning. - -## Backwards Compatibility - -Will be added. - -## Test Cases - -Will be added. - -## Implementation - -An in-work implementation can be found at https://github.com/pipeos-one/dType/blob/master/contracts/contracts/Alias.sol. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - -## 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-2193.md diff --git a/EIPS/eip-2200.md b/EIPS/eip-2200.md index a5182f9fa829bb..9da3dc1360fc1f 100644 --- a/EIPS/eip-2200.md +++ b/EIPS/eip-2200.md @@ -177,7 +177,7 @@ 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 +it does not introduce incompatibility to the Ethereum Mainnet. Gas estimation should account for this requirement. ## Test Cases @@ -312,7 +312,7 @@ 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). [EIP-1283]: ./eip-1283.md [EIP-1706]: ./eip-1706.md diff --git a/EIPS/eip-2228.md b/EIPS/eip-2228.md index d3779d7adc8260..c8ac1a4cf1972f 100644 --- a/EIPS/eip-2228.md +++ b/EIPS/eip-2228.md @@ -1,26 +1,26 @@ --- eip: 2228 -title: Canonicalize the name of network with chain ID 1 +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: Review +status: Final type: Informational created: 2019-08-04 --- ## Simple Summary -The Ethereum network with chainid 1 is named Ethereum Mainnet. +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 use to refer to this network. +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 chainid 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 chainid 1. Names in use at the time of this writing include: +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" @@ -29,33 +29,32 @@ The Ethereum network with chainid 1 is referenced using several conflicting name ## Specification -The network name 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. +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 -Note: Ethereum is a registered trademark (USPTO serial number 86634529, US registration number 5110579) of Ethereum Foundation and "you must not use [this mark] without the prior written permission of the Foundation" (per the Ethereum Foundation website, Terms of Use page). +"Ethereum" is trademarked by the Ethereum Foundation. For more information on your obligations when mentioning "Ethereum", and possibly "Ethereum Mainnet", see: -Your application MAY reference "Ethereum® Mainnet" and include a note "Ethereum is a registered trademark of Ethereum Foundation" elsewhere. - -Trademark status, fair use of trademarks, and any written permissions you have with the Ethereum Foundation are outside the scope of this EIP. +* 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 name of the network referred to using different names in different software, so let's avoid this. +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 currently uses the wording "Main Ethereum Network" in the account network chooser. In this context, it is understood that "main" is used as an adjective, not a proper noun form. Such usage is acceptable per this EIP. MetaMask is using "Main" and "Network" with a capitalized first letter for stylistic purposes, not to designate a proper noun. +- 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-161](./eip-161.md), [EIP-170](./eip-170.md), [EIP-190](./eip-190.md), [EIP-225](./eip-225.md), [EIP-1013](./eip-1013.md), [EIP-1679](./eip-1679.md), [EIP-1716](./eip-1716.md), [EIP-2028](./eip-2028.md), [EIP-2200](./eip-2200.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. +- 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 +### Examples referencing the name of the network ✅ > The contract was deployed to Ethereum Mainnet. @@ -71,21 +70,21 @@ This example shows a user interface which is in uppercase. To be semantically co 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 +### 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 +### 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 chain ID 1. +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) +### 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 / chain_id: 62. Therefore this word usage is less crisp. Do NOT use wording like this. +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. @@ -93,4 +92,4 @@ These words literally mean nothing. The lowercase, not-proper-noun word "mainnet ## 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-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 index 4be7be2946e0e1..7dc308cef0e5c7 100644 --- a/EIPS/eip-2242.md +++ b/EIPS/eip-2242.md @@ -3,7 +3,7 @@ eip: 2242 title: Transaction Postdata author: John Adler (@adlerjohn) discussions-to: https://ethereum-magicians.org/t/eip-2242-transaction-postdata/3557 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-08-16 @@ -57,4 +57,4 @@ TODO 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-225.md b/EIPS/eip-225.md index a1630f29d574d8..2dce2e16cca8e2 100644 --- a/EIPS/eip-225.md +++ b/EIPS/eip-225.md @@ -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 @@ -448,7 +449,7 @@ 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{ {signer: "A"}, @@ -474,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 index 883ac33961a587..14d31a8f67727d 100644 --- a/EIPS/eip-2255.md +++ b/EIPS/eip-2255.md @@ -1,42 +1,29 @@ --- eip: 2255 title: Wallet Permissions System -author: Dan Finlay (@danfinlay), Erik Marks (@rekmarks) +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: Draft +status: Final type: Standards Track category: Interface created: 2019-08-22 -requires: 1474 +requires: 1193 --- -![Sample prompt screenshot](../assets/eip-2255/permissions.png) - -## Simple Summary - -A proposed standard interface for restricting and permitting access to security-sensitive methods within a restricted web3 context like a website or "dapp". - ## Abstract -Web3 JavaScript wallet browsers may implement `wallet_getPermissions` and `wallet_requestPermissions`. This provides a standard interface for requesting permissions and checking a domain's current permissions status. +This EIP adds two new wallet-namespaced RPC endpoints, `wallet_getPermissions` and `wallet_requestPermissions`, providing a standard interface for requesting and checking permissions. ## Motivation -Web3 Wallets are built around the responsibility of mediating the interactions between untrusted applications and a user's keys on their computer, getting appropriate consent from the user. - -Today web3 browsers like MetaMask always prompt on a per-action basis. 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. +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 is common around the web, from login with Facebook, Twitter, GitHub, and even Apple, making it a very familiar pattern. +The pattern of permissions requests (typically using Oauth2) is common around the web, making it a very familiar pattern: -
- Facebook Permissions - Facebook Permissions -
+![Facebook Permissions](../assets/eip-2255/facebook_permissions.png) -
- Log in With Apple - Log in With Apple -
+![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: @@ -46,83 +33,90 @@ Many web3 applications today begin their sessions with a series of repetitive re - 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. +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) -On the user's end, each of these permissions could be individually rejected (unchecked), or even _attenuated_, or 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), making the web3 login a sort of user-revisable terms of use. +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 -This proposal adds two new methods to a wallet's web3 provider API: +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. -- `wallet_getPermissions` -- `wallet_requestPermissions` +This proposal adds two new methods to a wallet's web3 provider API: `wallet_getPermissions` and `wallet_requestPermissions`. -The `wallet_getPermissions` method is used for getting an array of current permissions (empty by default), while the `wallet_requestPermissions` method is used for an application to request additional permissions. +### `wallet_getPermissions` -These two methods are used to restrict a few hypothetical "restricted methods". The first such method we would suggest should be included as part of the standard is `eth_accounts`. +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. -In this framework, the permission for a user to reveal their accounts would look like this: +#### `wallet_getPermissions` Returns -```javascript -const response = await provider.send({ - method: 'wallet_requestPermissions', - params: [{ - 'eth_accounts': {}, - }] -}) +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[]; +} ``` -If this request was rejected, it would throw an error with a `code` value equal to `4001`, per [EIP 1193 errors](./eip-1193.md), which the MetaMask team has canonized in a module [eth-json-rpc-errors](https://github.com/metamask/eth-json-rpc-errors). +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`. -If the request is accepted by the user, then subsequent requests to `eth_accounts` will succeed, and return an accounts array as usual. +### `wallet_requestPermissions` -A call to `wallet_getPermissions` will then return a permissions schema object that describes the current permission. +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. -```javascript -const response = await provider.send({ - method: 'wallet_getPermissions' -}) -``` +#### `wallet_requestPermissions` Parameters -Would return a value something like this: - -```json -[ - { - invoker: 'ens://your-site.eth', - parentCapability: 'eth_accounts', - caveats: [ - { - type: 'filterResponse', - value: ["0x0c54fccd2e384b4bb6f2e405bf5cbc15a017aafb"] - } - ] - } -] +The `wallet_requestPermissions` method takes a single parameter, a `PermissionRequest` object, which is defined as follows: + +```typescript +interface PermissionRequest { + [methodName: string]: { + [caveatName: string]: any; + }; +} ``` -Where `invoker` is a unique domain string used to identify the source of the current dapp. To start, this may include only `https` prefixes, but `ens`, `swarm`, `ipfs`, and others may all be valid sources in the future. +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. -The term `parentCapability` comes from the [zcap-ld spec](https://w3c-ccg.github.io/zcap-ld/), which these permissions objects are based on, and refers to the method that is being permitted. +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). -The `caveats` array represents the specific restrictions applied to the permitted method. +#### `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; +} +``` -You can see above how internally the user-selected account is transformed into a [`caveat`](https://github.com/MetaMask/json-rpc-capabilities-middleware/blob/master/src/%40types/ocap-ld.d.ts#L28-L33), which is a restriction on the response values, in this case ensuring the page can only be notified of approved accounts. This also means this permissions system is forward-extensible to support logging into a page with multiple accounts. +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 `eth_sendTransaction` method itself could be a restricted method (requested by default with the `provider.enable()` method), and the user could at sign-in time decide whether they wanted to require confirmations, approve all transactions, or only approve transactions to a certain contract, or up to a certain token limit, for example. By restricting this method by default, wallets could prevent sites from spamming the user with popups. +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. -If `eth_call` were a restricted method, then random websites would not be able to drain a user's subscription to a hosted provider, making it easier to protect services like Infura against DDoS attacks. +## Test Cases -On-chain actions could be represented as a permission under this model, for example, the permission to send an allowance-setting transaction to a specific token address is virtually equivalent to the approval of that transaction, except the site could choose to only invoke the transaction when it was needed. This could allow a standard interface for applications to request permissions which may require different actions depending on different types of accounts (hot wallets, hardware wallets, cold wallets, contract accounts). +### Requesting permissions -The `requestPermissions` method could 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, maybe like this: +The following example should prompt the user to approve the `eth_accounts` permission, and return the permission object if approved. ```javascript -provider.send({ +provider.request({ method: 'requestPermissions', params: [ { @@ -131,33 +125,27 @@ provider.send({ } } ] -}) +}); ``` -That type of API will also be up for discussion on [The MetaMask repository](https://github.com/MetaMask/metamask-extension/issues/6994). +### Getting permissions -This would allow the wallet to limit the user's options to valid ones, and allows dapps to ensure selected accounts are compatible with their service, while preserving the user's privacy regarding how they are storing their keys. +The following example should return the current permissions object. -## Implementation - -We have [a branch of MetaMask available now](https://github.com/MetaMask/metamask-extension/tree/LoginPerSite) which adds these methods via an [rpc-engine](https://github.com/MetaMask/json-rpc-engine) middleware called [json-rpc-capabilities-middleware](https://github.com/MetaMask/json-rpc-capabilities-middleware) (or often `RpcCap` internally, for short). - -The latest build of this branch of MetaMask can be downloaded from [the draft pull request](https://github.com/MetaMask/metamask-extension/pull/7004) (look for the latest post by `@MetaMaskBot`). A guide to adding a custom build of MetaMask to Chrome can be found [here](https://github.com/MetaMask/metamask-extension/blob/develop/docs/add-to-chrome.md). - -This branch of MetaMask can be used with [this sample site](https://metamask.github.io/permissions-adventure/) ([source](https://github.com/metamask/permissions-adventure)), which uses a couple sample permissions for demonstration purposes: - -- `readYourProfile`: We have bundled this build with an imaginary concept of a local "profile", a simple [POJO](https://en.wikipedia.org/wiki/Plain_old_Java_object). Eventually this could be extended to instead expose the user's [3box profile](https://3box.io/). -- `writeToYourProfile`: This permission allows the requesting app to freely update/edit the user's profile. -- `sendEther`: A permission allowing the sending of transactions. +```javascript +provider.request({ + method: 'getPermissions' +}); +``` -![sample dapp](../assets/eip-2255/permissions_adventure.gif) +## Security Considerations -It is notable that this branch is the first version of MetaMask that allows you to be connected to each site with a different account, which persists on that site, along with any other permissions granted to the site. +### Server-Side Request Forgery (SSRF) -You can get more detailed API and type information [on the RpcCap repository's readme](https://github.com/MetaMask/json-rpc-capabilities-middleware#rpc-methods). +This consideration is applicable if the favicon of a website is to be displayed. -New hypothetical and proposed permissions can be easily added to [the `restrictedMethods` hash in the MetaMask permissions controller](https://github.com/MetaMask/metamask-extension/blob/774d931cb9f16a8f2df8c6deee1dd553b40d5ad5/app/scripts/controllers/permissions.js#L187) or proposed for discussion on the [MetaMask/wallet-permissions-spec](https://github.com/MetaMask/wallet-permissions-spec) repository. +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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2256.md b/EIPS/eip-2256.md index fcdeb3da52ad7a..eb556fff2523d8 100644 --- a/EIPS/eip-2256.md +++ b/EIPS/eip-2256.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2019-08-29 @@ -194,4 +194,4 @@ To be done. ## 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-2266.md b/EIPS/eip-2266.md index 0371bfbab5c3e1..ae3e2df3601021 100644 --- a/EIPS/eip-2266.md +++ b/EIPS/eip-2266.md @@ -1,251 +1,7 @@ --- eip: 2266 -title: Atomic Swap-based American Call Option Contract Standard -author: Runchao Han , Haoyu Lin , Jiangshan Yu -discussions-to: https://github.com/ethereum/EIPs/issues/2266 -status: Last Call -type: Standards Track category: ERC -created: 2019-08-17 -review-period-end: 2020-12-31 +status: Moved --- -## Simple Summary - -A standard for token contracts providing Atomic Swap-based American Call Option functionalities. - -## Abstract - -This standard provides functionality to make Atomic Swap-based American Call Option payment. The Atomic Swap protocol based on Hashed Time-Locked Contract (HTLC) [^1] has optionality [^2], and such optionality can be utilised to construct American Call Options without trusted third party. This standard defines the common way of implementing this protocol. In particular, this EIP defines technical terms, provides interfaces, and gives reference implementations of this protocol. - - -## Motivation - -Atomic Swap allows users to atomically exchange their tokens without trusted third parties while the HTLC is commonly used for the implementation. However, the HTLC-based Atomic Swap has optionality. More specifically, the swap initiator can choose to proceed or abort the swap for several hours, which gives him time for speculating according to the exchange rate. A discussion[^2] shows that the HTLC-based Atomic Swap is equivalent to an American Call Option in finance. On the other hand,thanks to such optionality, the HTLC-based Atomic Swap can be utilised to construct American Call Options without trusted third party. A paper[^3] proposes a secure Atomic-Swap-based American Call Option protocol on smart contracts. This protocol not only eliminates the arbitrage opportunity but also prevents any party from locking the other party's money maliciously. This EIP aims at providing the standard of implementing this protocol in existing token standards. - -## Specification - -The Atomic Swap-based American Call Option smart contract should follow the syntax and semantics of Ethereum smart contracts. - -### Definitions - -+ `initiator`: the party who publishes the advertisement of the swap. -+ `participant`: the party who agrees on the advertisement and participates in the swap with `initiator`. -+ `asset`: the amount of token(s) to be exchanged. -+ `premium`: the amount of token(s) that `initiator` pays to `participant` as the premium. -+ `redeem`: the action to claim the token from the other party. -+ `refund`: the action to claim the token from the party herself/himself, because of timelock expiration. -+ `secrect`: a random string chosen by `initiator` as the preimage of a hash. -+ `secrectHash`: a string equals to the hash of `secrect`, used for constructing HTLCs. -+ `timelock`: a timestamp representing the timelimit, before when the asset can be redeemed, and otherwise can only be refunded. - -### Storage Variables - -#### swap - -This mapping stores the metadata of the swap contracts, including the parties and tokens involved. Each contract uses different `secretHash`, and is distinguished by `secretHash`. - -```solidity -mapping(bytes32 => Swap) public swap; -``` - -#### initiatorAsset - -This mapping stores the detail of the asset initiators want to sell, including the amount, the timelock and the state. It is associated with the swap contract with the same `secretHash`. - -```solidity -mapping(bytes32 => InitiatorAsset) public initiatorAsset; -``` - -#### participantAsset - -This mapping stores the details of the asset participants want to sell, including the amount, the timelock and the state. It is associated with the swap contract with the same `secretHash`. - -```solidity -mapping(bytes32 => ParticipantAsset) public participantAsset; -``` - -#### premiumAsset - -This mapping stores the details of the premium initiators attach in the swap contract, including the amount, the timelock and the state. It is associated with the swap contract with the same `secretHash`. - -```solidity -mapping(bytes32 => Premium) public premium; -``` - - -### Methods - -#### setup - -This function sets up the swap contract, including the both parties involved, the tokens to exchanged, and so on. - -```solidity -function setup(bytes32 secretHash, address payable initiator, address tokenA, address tokenB, uint256 initiatorAssetAmount, address payable participant, uint256 participantAssetAmount, uint256 premiumAmount) public payable -``` - -#### initiate - -The initiator invokes this function to fill and lock the token she/he wants to sell and join the contract. - -```solidity -function initiate(bytes32 secretHash, uint256 assetRefundTime) public payable -``` - -#### fillPremium - -The initiator invokes this function to fill and lock the premium. - -```solidity -function fillPremium(bytes32 secretHash, uint256 premiumRefundTime) public payable -``` - -#### participate - -The participant invokes this function to fill and lock the token she/he wants to sell and join the contract. - -```solidity -function participate(bytes32 secretHash, uint256 assetRefundTime) public payable -``` - -#### redeemAsset - -One of the parties invokes this function to get the token from the other party, by providing the preimage of the hash lock `secret`. - -```solidity -function redeemAsset(bytes32 secret, bytes32 secretHash) public -``` - -#### refundAsset - -One of the parties invokes this function to get the token back after the timelock expires. - -```solidity -function refundAsset(bytes32 secretHash) public -``` - -#### redeemPremium - -The participant invokes this function to get the premium. This can be invoked only if the participant has already invoked `participate` and the participant's token is redeemed or refunded. - -```solidity -function redeemPremium(bytes32 secretHash) public -``` - -#### refundPremium - -The initiator invokes this function to get the premium back after the timelock expires. - -```solidity -function refundPremium(bytes32 secretHash) public -``` - - -### Events - -#### SetUp - -This event indicates that one party has set up the contract using the function `setup()`. - -```solidity -event SetUp(bytes32 secretHash, address initiator, address participant, address tokenA, address tokenB, uint256 initiatorAssetAmount, uint256 participantAssetAmount, uint256 premiumAmount); -``` - -#### Initiated - -This event indicates that `initiator` has filled and locked the token to be exchanged using the function `initiate()`. - -```solidity -event Initiated(uint256 initiateTimestamp, bytes32 secretHash, address initiator, address participant, address initiatorAssetToken, uint256 initiatorAssetAmount, uint256 initiatorAssetRefundTimestamp); -``` - -#### Participated - -This event indicates that `participant` has filled and locked the token to be exchanged using the function `participate()`. - -```solidity -event Participated(uint256 participateTimestamp, bytes32 secretHash, address initiator, address participant, address participantAssetToken, uint256 participantAssetAmount, uint256 participantAssetRefundTimestamp); -``` - -#### PremiumFilled - -This event indicates that `initiator` has filled and locked `premium` using the function `fillPremium()`. - -```solidity -event PremiumFilled(uint256 fillPremiumTimestamp, bytes32 secretHash, address initiator, address participant, address premiumToken, uint256 premiumAmount, uint256 premiumRefundTimestamp); -``` - -#### InitiatorAssetRedeemed/ParticipantAssetRedeemed - -These two events indicate that `asset` has been redeemed by the other party before the timelock by providing `secret`. - -```solidity -event InitiatorAssetRedeemed(uint256 redeemTimestamp, bytes32 secretHash, bytes32 secret, address redeemer, address assetToken, uint256 amount); -``` - -```solidity -event ParticipantAssetRedeemed(uint256 redeemTimestamp, bytes32 secretHash, bytes32 secret, address redeemer, address assetToken, uint256 amount); -``` - -#### InitiatorAssetRefunded/ParticipantAssetRefunded - -These two events indicate that `asset` has been refunded by the original owner after the timelock expires. - -```solidity -event InitiatorAssetRefunded(uint256 refundTimestamp, bytes32 secretHash, address refunder, address assetToken, uint256 amount); -``` - -```solidity -event ParticipantAssetRefunded(uint256 refundTimestamp, bytes32 secretHash, address refunder, address assetToken, uint256 amount); -``` - -#### PremiumRedeemed - -This event indicates that `premium` has been redeemed by `participant`. This implies that `asset` is either redeemed by `initiator` if it can provide the preimage of `secrectHash` before `asset` timelock expires; or refunded by `participant` if `asset` timelock expires. - -```solidity -event PremiumRedeemed(uint256 redeemTimestamp,bytes32 secretHash,address redeemer,address token,uint256 amount); -``` - -#### PremiumRefunded - -This event indicates that `premium` has been refunded back to `initiator`, because of `participant` doesn't participate at all, by the time of `premium` timelock expires. - -```solidity -event PremiumRefunded(uint256 refundTimestamp, bytes32 secretHash, address refunder, address token, uint256 amount); -``` - -## Rationale - -+ To achieve the atomicity, HTLC is used. -+ The participant should decide whether to participate after the initiator locks the token and sets up the timelock. -+ The initiator should decide whether to proceed the swap (redeem the tokens from the participant and reveal the preimage of the hash lock), after the participant locks the tokens and sets up the time locks. -+ Premium is redeemable for the participant only if the participant participates in the swap and redeems the initiator's token before premium's timelock expires. -+ Premium is refundable for the initiator only if the initiator initiates but the participant does not participate in the swap at all. - - -## Security Considerations - -+ The `initiateTimestamp` should cover the whole swap process. -+ The participant should never participate before the premium has been deposited. - - -## Backwards Compatibility - -This proposal is fully backward compatible. Functionalities of existing standards will not be affected by this proposal, as it only provides additional features to them. - - -## Implementation - -Please visit [here](../assets/eip-2266/Example.sol) to find our example implementation. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -## References - -[^1]: [Hash Time Locked Contracts](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) - -[^2]: [An Argument For Single-Asset Lightning Network](https://lists.linuxfoundation.org/pipermail/lightning-dev/2019-January/001798.html) - -[^3]: [On the optionality and fairness of Atomic Swaps](https://eprint.iacr.org/2019/896) +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..e13f5eb2fafbfa --- /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: Review +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 JsonPRC 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 JsonPRC 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 possbile expansion of chains, such as increasing amount of L2s, L3s, or shards of Ethereum mainnets. +5. Enable hashed based temparary 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` have 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 index 53b98763d4e719..5dadd8d6646379 100644 --- a/EIPS/eip-2304.md +++ b/EIPS/eip-2304.md @@ -1,219 +1,7 @@ --- eip: 2304 -title: Multichain address resolution for ENS -author: Nick Johnson -type: Standards Track category: ERC -status: Draft -created: 2019-09-09 -discussions-to: https://discuss.ens.domains/t/new-standard-proposal-ens-multicoin-support/1148 -requires: 137 +status: Moved --- -## Abstract - -This EIP introduces new overloads for the the `addr` field for ENS resolvers, which permit resolution of addresses for other blockchains via ENS. - -## Motivation - -With the increasing uptake of ENS by multi-coin wallets, wallet authors have requested the ability to resolve addresses for non-Ethereum chains inside ENS. This specification standardises a way to enter and retrieve these addresses in a cross-client fashion. - -## Specification - -A new accessor function for resolvers is specified: - -```solidity -function addr(bytes32 node, uint coinType) external view returns(bytes memory); -``` - -The EIP165 interface ID for this function is 0xf1cb7e06. - -When called on a resolver, this function must return the cryptocurrency address for the specified namehash and coin type. A zero-length string must be returned if the specified coin ID does not exist on the specified node. - -`coinType` is the cryptocurrency coin type index from [SLIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md). - -The return value is the cryptocurency address in its native binary format. Detailed descriptions of the binary encodings for several popular chains are provided in the Address Encoding section below. - -A new event for resolvers is defined: - -```solidity -event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); -``` - -Resolvers MUST emit this event on each change to the address for a name and coin type. - -### Recommended accessor functions - -The following function provides the recommended interface for changing the addresses stored for a node. Resolvers SHOULD implement this interface for setting addresses unless their needs dictate a different interface. - -```solidity -function setAddr(bytes32 node, uint coinType, bytes calldata addr); -``` - -`setAddr` adds or replaces the address for the given node and coin type. The parameters for this function are as per those described in `addr()` above. - -This function emits an `AddressChanged` event with the new address; see also the backwards compatibility section below for resolvers that also support `addr(bytes32)`. - -### Address Encoding - -In general, the native binary representation of the address should be used, without any checksum commonly used in the text representation. - -A table of encodings for common blockchains is provided, followed by a more detailed description of each format. In the table, 'encodings' lists the address encodings supported by that chain, along with any relevant parameters. Details of those address encodings are described in the following sections. - -| Cryptocurrency | Coin Type | Encoding | -| --- | --- | --- | -| Bitcoin | 0 | P2PKH(0x00), P2SH(0x05), SegWit('bc') | -| Litecoin | 2 | P2PKH(0x30), P2SH(0x32), P2SH(0x05), SegWit('ltc') | -| Dogecoin | 3 | P2PKH(0x1e), P2SH(0x16) | -| Monacoin | 22 | P2PKH(0x32), P2SH(0x05) | -| Ethereum | 60 | ChecksummedHex | -| Ethereum Classic | 61 | ChecksummedHex | -| Rootstock | 137 | ChecksummedHex(30) | -| Ripple | 144 | Ripple | -| Bitcoin Cash | 145 | P2PKH(0x00), P2SH(0x05), CashAddr | -| Binance | 714 | Bech32('bnb') | - -#### P2PKH(version) - -Pay to Public Key Hash addresses are [base58check](https://en.bitcoin.it/wiki/Base58Check_encoding) encoded. After decoding, the first byte is a version byte. For example, the Bitcoin address `1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa` base58check decodes to the 21 bytes `0062e907b15cbf27d5425399ebf6f0fb50ebb88f18`. - -P2PKH addresses have a version byte, followed by a 20 byte pubkey hash. Their canonical encoding is their scriptPubkey encoding (specified [here](https://en.bitcoin.it/wiki/Transaction#Types_of_Transaction)) is `OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG`. - -The above example address is thus encoded as the 25 bytes `76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac`. - -##### P2SH(version) - -P2SH addresses are base58check encoded in the same manner as P2PKH addresses. -P2SH addresses have a version, followed by a 20 byte script hash. Their scriptPubkey encoding (specified [here](https://en.bitcoin.it/wiki/Transaction#Pay-to-Script-Hash)) is `OP_HASH160 OP_EQUAL`. A Bitcoin address of `3Ai1JZ8pdJb2ksieUV8FsxSNVJCpoPi8W6` decodes to the 21 bytes `0562e907b15cbf27d5425399ebf6f0fb50ebb88f18` and is encoded as the 23 bytes `a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1887`. - -##### SegWit(hrp) - -SegWit addresses are encoded with [bech32](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki). Bech32 addresses consist of a human-readable part - 'bc' for Bitcoin mainnet - and a machine readable part. For SegWit addresses, this decodes to a 'witness version', between 0 and 15, and a 'witness program', as defined in [BIP141](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki). - -The scriptPubkey encoding for a bech32 address, as defined in BIP141, is `OP_n`, where `n` is the witness version, followed by a push of the witness program. Note this warning from BIP173: - -> Implementations should take special care when converting the address to a scriptPubkey, where witness version n is stored as OP_n. OP_0 is encoded as 0x00, but OP_1 through OP_16 are encoded as 0x51 though 0x60 (81 to 96 in decimal). If a bech32 address is converted to an incorrect scriptPubKey the result will likely be either unspendable or insecure. - -For example, the Bitcoin SegWit address `BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4` decodes to a version of `0` and a witness script of `751e76e8199196d454941c45d1b3a323f1433bd6`, and then encodes to a scriptPubkey of `0014751e76e8199196d454941c45d1b3a323f1433bd6`. - -#### ChecksummedHex(chainId?) - -To translate a text format checksummed hex address into binary format, simply remove the '0x' prefix and hex decode it. `0x314159265dD8dbb310642f98f50C066173C1259b` is hex-decoded and stored as the 20 bytes `314159265dd8dbb310642f98f50c066173c1259b`. - -A checksum format is specified by [EIP-55](./eip-55.md), and extended by [RSKIP60](https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md), which specifies a means of including the chain ID in the checksum. The checksum on a text format address must be checked. Addresses with invalid checksums that are not all uppercase or all lowercase MUST be rejected with an error. Implementations may choose whether to accept non-checksummed addresses, but the authors recommend at least providing a warning to users in this situation. - -When encoding an address from binary to text, an EIP55/RSKIP60 checksum MUST be used - so the correct encoding of the above address for Ethereum is `0x314159265dD8dbb310642f98f50C066173C1259b`. - -#### Ripple - -Ripple addresses are encoded using a version of base58check with an alternative alphabet, described [here](https://xrpl.org/base58-encodings.html). Two types of ripple addresses are supported, 'r-addresses', and 'X-addresss'. r-addresses consist of a version byte followed by a 20 byte hash, while X-addresses consist of a version byte, a 20 byte hash, and a tag, specified [here](https://github.com/xrp-community/standards-drafts/issues/6). - -Both address types should be stored in ENS by performing ripple's version of base58check decoding and storing them directly (including version byte). For example, the ripple address `rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn` decodes to and is stored as `004b4e9c06f24296074f7bc48f92a97916c6dc5ea9`, while the address `X7qvLs7gSnNoKvZzNWUT2e8st17QPY64PPe7zriLNuJszeg` decodes to and is stored as `05444b4e9c06f24296074f7bc48f92a97916c6dc5ea9000000000000000000`. - -#### CashAddr - -Bitcoin Cash defines a new address format called 'CashAddr', specified [here](https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md). This uses a variant of bech32 encoding to encode and decode (non-segwit) Bitcoin Cash addresses, using a prefix of 'bitcoincash:'. A CashAddr should be decoded using this bech32 variant, then converted and stored based on its type (P2PKH or P2SH) as described in the relevant sections above. - -#### Bech32 - -[Bech32](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) addresses consist of a human-readable part - for example, 'bnb' for Binance - and a machine readable part. The encoded data is simply the address, which can be converted to binary and stored directly. - -For example, the BNB address `bnb1grpf0955h0ykzq3ar5nmum7y6gdfl6lxfn46h2` decodes to the binary representation `40c2979694bbc961023d1d27be6fc4d21a9febe6`, which is stored directly in ENS. - -### Example - -An example implementation of a resolver that supports this EIP is provided here: - -```solidity -pragma solidity ^0.5.8; - -contract AddrResolver is ResolverBase { - bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; - bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06; - uint constant private COIN_TYPE_ETH = 60; - - event AddrChanged(bytes32 indexed node, address a); - event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); - - mapping(bytes32=>mapping(uint=>bytes)) _addresses; - - /** - * Sets the address associated with an ENS node. - * May only be called by the owner of that node in the ENS registry. - * @param node The node to update. - * @param a The address to set. - */ - function setAddr(bytes32 node, address a) external authorised(node) { - setAddr(node, COIN_TYPE_ETH, addressToBytes(a)); - } - - /** - * Returns the address associated with an ENS node. - * @param node The ENS node to query. - * @return The associated address. - */ - function addr(bytes32 node) public view returns (address) { - bytes memory a = addr(node, COIN_TYPE_ETH); - if(a.length == 0) { - return address(0); - } - return bytesToAddress(a); - } - - function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) { - emit AddressChanged(node, coinType, a); - if(coinType == COIN_TYPE_ETH) { - emit AddrChanged(node, bytesToAddress(a)); - } - _addresses[node][coinType] = a; - } - - function addr(bytes32 node, uint coinType) public view returns(bytes memory) { - return _addresses[node][coinType]; - } - - function supportsInterface(bytes4 interfaceID) public pure returns(bool) { - return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID); - } -} -``` - -### Implementation - -An implementation of this interface is provided in the [ensdomains/resolvers](https://github.com/ensdomains/resolvers/) repository. - -## Backwards Compatibility - -If the resolver supports the `addr(bytes32)` interface defined in EIP137, the resolver MUST treat this as a special case of this new specification in the following ways: - - 1. The value returned by `addr(node)` from EIP137 should always match the value returned by `addr(node, 60)` (60 is the coin type ID for Ethereum). - 2. Anything that causes the `AddrChanged` event from EIP137 to be emitted must also emit an `AddressChanged` event from this EIP, with the `coinType` specified as 60, and vice-versa. - -## Tests - -The table below specifies test vectors for valid address encodings for each cryptocurrency described above. - -| Cryptocurrency | Coin Type | Text | Onchain (hex) | -| --- | --- | --- | --- | -| Bitcoin | 0 | `1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa` | `76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac` | -| | | `3Ai1JZ8pdJb2ksieUV8FsxSNVJCpoPi8W6` | `a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1887` | -| | | `BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4` | `0014751e76e8199196d454941c45d1b3a323f1433bd6` | -| Litecoin | 2 | `LaMT348PWRnrqeeWArpwQPbuanpXDZGEUz` | `76a914a5f4d12ce3685781b227c1f39548ddef429e978388ac` | -| | | `MQMcJhpWHYVeQArcZR3sBgyPZxxRtnH441` | `a914b48297bff5dadecc5f36145cec6a5f20d57c8f9b87` | -| | | `ltc1qdp7p2rpx4a2f80h7a4crvppczgg4egmv5c78w8` | `0014687c150c26af5493befeed7036043812115ca36c` | -| Dogecoin | 3 | `DBXu2kgc3xtvCUWFcxFE3r9hEYgmuaaCyD` | `76a9144620b70031f0e9437e374a2100934fba4911046088ac` | -| | | `AF8ekvSf6eiSBRspJjnfzK6d1EM6pnPq3G` | `a914f8f5d99a9fc21aa676e74d15e7b8134557615bda87` | -| Monacoin | 22 | `MHxgS2XMXjeJ4if2PRRbWYcdwZPWfdwaDT` | `76a9146e5bb7226a337fe8307b4192ae5c3fab9fa9edf588ac` | -| Ethereum | 60 | `0x314159265dD8dbb310642f98f50C066173C1259b` | `314159265dd8dbb310642f98f50c066173c1259b` | -| Ethereum Classic | 61 | `0x314159265dD8dbb310642f98f50C066173C1259b` | `314159265dd8dbb310642f98f50c066173c1259b` | -| Rootstock | 137 | `0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD` | `5aaeb6053f3e94c9b9a09f33669435e7ef1beaed` | -| Ripple | 144 | `rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn` | `004b4e9c06f24296074f7bc48f92a97916c6dc5ea9` | -| | | `X7qvLs7gSnNoKvZzNWUT2e8st17QPY64PPe7zriLNuJszeg` | `05444b4e9c06f24296074f7bc48f92a97916c6dc5ea9000000000000000000` | -| Bitcoin Cash | 145 | `1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu` | `76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac` | -| | | `bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a` | `76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac` | -| | | `3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC` | `a91476a04053bda0a88bda5177b86a15c3b29f55987387` | -| | | `bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq` | `a91476a04053bda0a88bda5177b86a15c3b29f55987387` | -| Binance | 714 | `bnb1grpf0955h0ykzq3ar5nmum7y6gdfl6lxfn46h2` | `40c2979694bbc961023d1d27be6fc4d21a9febe6` | - -## 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-2304.md diff --git a/EIPS/eip-2309.md b/EIPS/eip-2309.md index 8cccb4af9447a3..5f69168969c98f 100644 --- a/EIPS/eip-2309.md +++ b/EIPS/eip-2309.md @@ -1,121 +1,7 @@ --- eip: 2309 -title: ERC-721 Consecutive Transfer Extension -author: Sean Papanikolas (@pizzarob) -discussions-to: https://github.com/ethereum/EIPs/issues/2309 -status: Final -type: Standards Track category: ERC -created: 2019-10-08 -requires: 721 +status: Moved --- -## Simple Summary - -A standardized event emitted when creating/transferring one, or many non-fungible tokens using consecutive token identifiers. - -## Abstract - -The optional ERC-721 Consecutive Transfer Extension provides a standardized event which could be emitted during the creation/transfer of one, or many non-fungible tokens. This standard does not set the expectation of how you might create/transfer many tokens it is only concerned with the event emitted after the creation, or transfer of ownership of these tokens. This extension assumes that token identifiers are in consecutive order. - -## Motivation - -This extension provides even more scalibility of the [ERC-721 specification](./eip-721.md). It is possible to create, transfer, and burn 2^255 non-fungible tokens in one transaction. However, it is not possible to emit that many `Transfer` events in one transaction. The `Transfer` event is part of the original specification which states: - -> This emits when ownership of any NFT changes by any mechanism. -> This event emits when NFTs are created (`from` == 0) and destroyed -> (`to` == 0). Exception: during contract creation, any number of NFTs -> may be created and assigned without emitting Transfer. At the time of -> any transfer, the approved address for that NFT (if any) is reset to none. - -This allows for the original `Transfer` event to be emitted for one token at a time, which in turn gives us O(n) time complexity. Minting one billion NFTs can be done in one transaction using efficient data structures, but in order to emit the `Transfer` event - according to the original spec - one would need a loop with one billion iterations which is bound to run out of gas, or exceed transaction timeout limits. This cannot be accomplished with the current spec. This extension solves that problem. - -Many decentralized marketplaces and block explorers utilize the `Transfer` event as a way to determine which NFTs an address owns. The Consecutive Transfer Extension provides a standard mechanism for these platforms to use to determine ownership of many tokens. - -## 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. - -**ERC-721 compliant contracts MAY implement this Consecutive Transfer Extension to provide a standard event to be emitted at the time of creation, burn, or transfer of one or many consecutive tokens** - -The address executing the transaction **MUST** own all the tokens within the range of `fromTokenId` and `toTokenId`, or **MUST** be an approved operator to act on the owners behalf. - -The `fromTokenId` and `toTokenId` **MUST** be a consecutive range of tokens IDs. - -The `fromTokenId`, `fromAddress`, and `toAddress` **MUST** be indexed parameters - -The `toTokenId` **MUST NOT** be an indexed parameter - -When minting/creating tokens, the `fromAddress` argument **MUST** be set to `0x0` (i.e. zero address). - -When burning/destroying tokens, the `toAddress` argument **MUST** be set to `0x0` (i.e. zero address). - -When emitting the ConsecutiveTransfer event the Transfer event **MUST NOT** be emitted - -Contracts that implement the `ConsecutiveTransfer` event **MAY** still use the original `Transfer` event, however when emitting the `ConsecutiveTransfer` event the `Transfer` event **MUST NOT** be emitted. - -```solidity - event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); -``` - -### Examples - -The `ConsecutiveTransfer` event can be used for a single token as well as many tokens: - -**Single token creation** - -`emit ConsecutiveTransfer(1, 1, address(0), toAddress);` - -**Batch token creation** - -`emit ConsecutiveTransfer(1, 100000, address(0), toAddress);` - -**Batch token transfer** - -`emit ConsecutiveTransfer(1, 100000, fromAddress, toAddress);` - -**Burn** - -`emit ConsecutiveTransfer(1, 100000, from, address(0));` - - -## Rationale - -Standardizing the `ConsecutiveTransfer` event gives decentralized platforms a standard way of determining ownership of large quantities of non-fungible tokens without the need to support a new token standard. There are many ways in which the batch creation and transfer of NFTs can be implemented. The Consecutive Transfer Extension allows contract creators to implement batch creation, transfer, and burn methods however they see fit, but provides a standardized event in which all implementations can use. By specifying a range of consecutive token identifiers we can easily cover the transfer, or creation of 2^(255) tokens and decentralized platforms can react accordingly. - -Take this example. I sell magical fruit and have a farm with 10,000 magical fruit trees each with different fruit and 1,000 new trees every few years. I want to turn each tree into a non-fungible token that people can own. Each person that owns one of my non-fungible tree tokens will receive a quarterly percentage of each harvest from that tree. The problem is that I would need to create and transfer each of these tokens individually - which will cost me a lot of time and money and frankly would keep me from doing this. - -With this extension I would be able to to mint my initial 10,000 tree tokens in one transaction. I would be able to quickly and cheaply mint my additional 1,000 tree tokens when a new batch is planted. I would then be able to transfer all of the 10,000+ tree tokens to a special smart contract that keeps track of the selling and distribution of funds in one transaction all while adhering to a specified standard. - -**Rationale to have a single event that covers minting, burning, and transferring** - -The `ConsecutiveTransfer` event can be used to cover minting, burning, and transferring events. While there may have been confusion in the beginning adhering to transfer to/from "0" pattern this is mitigated by checking for the `ConsecutiveTransfer` topic and verifying the emitting contract supports the ERC-721 interface by using the ERC-165 standard. - -**Indexed event parameters** - -Events in Solidity can have up to three indexed parameters which will make it possible to filter for specific values of indexed arguments. This standard sets the `fromAddress`, `toAddress`, and `fromTokenId` as the indexed parameters. The `toTokenId` can be retrieved from the data part of the log. The reason for this is that more often than not one may be searching for events to learn about the history of ownership for a given address. The `fromTokenId` can then be retrieved along with the other two indexed parameters for simplicity. Then one only needs to decode the log data which is ensured to be the `toTokenId`. - -**Rationale to not emit `Transfer` when `ConsecutiveTransfer` is also emitted** - -This can lead to bugs and unnecessary complex logic for platforms using these events to track token ownership. When transferring a single token it is acceptable to emit the original `Transfer` event, but the `ConsecutiveTransfer` event should not be emitted during the same transaction and vice-versa. - -**Comparing 2039 and 1155** - -As the NFT market continues to grow so does the need for the ability to scale the smart contracts. Users need to be able to do things like mint a massive amount of tokens at one time, transfer a massive amount of tokens, and be able to track ownership of all these assets. We need to do this in a way that is cost effective and doesn’t fail under the confines of the Ethereum blockchain. As millions of tokens are minted we need contracts with the ability to scale. - -[ERC-1155](./eip-1155.md) was created and added as a standard in 2019 to try to solve these problems, but it falls short when it comes to minting massive amounts of unique tokens in a cost-effective way. With ERC-1155 it’s either going to cost hundreds (or thousands) of dollars or it’s going to run out of gas. ERC-1155 works well when minting many semi-fungible tokens but falls short when minting many unique tokens. Using the 2039 standard you could mint millions of blank NFTs upfront and update the metadata for each one in a cost effective way. - - -## Backwards Compatibility - -This extension was written to allow for the smallest change possible to the original ERC-721 spec while still providing a mechanism to track the creation, transfer, and deletion of a massive amount of tokens. While it is a minimal change the effects on platforms that only use the original `Transfer` event to index token ownership would be severe. They would not be properly recording token ownership information that could be known by listening for the `ConsecutiveTransfer` event. For platforms that wish to support the `ConsecutiveTransfer` event it would be best to support both the original `Transfer` event and the `ConsecutiveTransfer` event to track token ownership. - -## Security Considerations -There are no security considerations related directly to the implementation of this standard. - -## 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-2309.md diff --git a/EIPS/eip-2315.md b/EIPS/eip-2315.md index 5c7fc8c5a80fd6..2da8392004a06c 100644 --- a/EIPS/eip-2315.md +++ b/EIPS/eip-2315.md @@ -1,308 +1,316 @@ --- eip: 2315 title: Simple Subroutines for the EVM -status: Draft +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 -author: Greg Colvin , Martin Holst Swende (@holiman) -discussions-to: https://ethereum-magicians.org/t/eip-2315-simple-subroutines-for-the-evm/3941 created: 2019-10-17 +requires: 3540, 3670, 4200 +withdrawal-reason: This proposal has been superseded by the EOF proposals. --- -## Simple Summary +## Abstract -(Almost) the smallest possible change that provides native subroutines without breaking backwards compatibility. +This proposal provides a _complete_, _efficient_, _safe_ and _static_ control-flow facility. -## Abstract +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. -This proposal introduces three opcodes to support subroutines: `BEGINSUB`, `JUMPSUB` and `RETURNSUB`. (The smallest possible change would do without `BEGINSUB`). +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 -The EVM does not provide subroutines as a primitive. Instead, calls can be synthesized by fetching and pushing the current program counter on the data stack and jumping to the subroutine address; returns can be synthesized by getting the return address to the top of the stack and jumping back to it. In the EVM the return +### A complete control-flow facility. -Facilities to directly support subroutines are provided in some form by most physical and virtual machines going back at least fifty years. In whatever form, these operations provide for capturing the current context of execution, transferring control to a new context, and returning to the original context. +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. -We propose a simple _return-stack_ mechanism, known to work well for stack machines, which we specify here. Note that this specification is entirely semantic. It constrains only stack usage and control flow and imposes no syntax on code beyond being a sequence of bytes to be executed. +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. -In the future, amenability to static analysis equivalent to [EIP-615](https://eips.ethereum.org/EIPS/eip-615) could be ensured by enforcing a few simple rules, and validated with the provided algorithm, still without imposing syntactic constraints. +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. -## Specification +### 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. -We introduce one more stack into the EVM in addition to the existing `data stack` which we call the `return stack`. The `return stack` is limited to `1024` items. +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. -#### `BEGINSUB` +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. -Marks the entry point to a subroutine. Execution of a `BEGINSUB` is a no-op. +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. -#### `JUMPSUB` +## Specification + +### Opcodes + +#### `RJUMPSUB (0x5f) relative_offset` Transfers control to a subroutine. -1. Pop the `location` off the `data stack`. -2. If the opcode at `location` is not a `BEGINSUB` _`abort`_. -3. If the `return stack` already has `1024` items _`abort`_. -4. Push the current `pc + 1` to the `return stack`. -5. Set `pc` to `location + 1`. +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. -* _pops one item off the `data stack`_ -* _pushes one item on the `return stack`_ +The gas cost is _low_. -#### `RETURNSUB` +#### `RETURNSUB (0x5e)` Returns control to the caller of a subroutine. -1. If the `return stack` is empty _`abort`_. -2. Pop `pc` off the `return stack`. +1. Pop the `return stack` to `PC`. -* _pops one item off the `return stack`_ +The gas cost is _verylow_. -_Note 1: If a resulting `pc` to be executed is beyond the last instruction then the opcode is implicitly a `STOP`, which is not an error._ +_Notes:_ -_Note 2: Values popped off the `return stack` do not need to be validated, since they are alterable only by `JUMPSUB` and `RETURNSUB`._ +* _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.)_ -_Note 3: The description above lays out the semantics of this feature 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 implementor may code `JUMPSUB` 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 + 1` location.)_ +### Validity -### Indirect Jumps +_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. -If [EIP-2327: BEGINDATA](https://eips.ethereum.org/EIPS/eip-2327) or similar is implemented then the indirect jumps from [EIP-615](https://eips.ethereum.org/EIPS/eip-615) -- `JUMPV` and `JUMPSUBV` -- can be implemented. These could take two arguments on the stack: a constant offset relative to `BEGINDATA` to a jump table, and a variable index into that table. +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 -We modeled this design on the simple, proven, archetypal Forth virtual machine of 1970. It is a two-stack design -- the data stack is supplemented with a return stack to support jumping into and returning from subroutines, as specified above. The separate return stack ensures that the return address cannot be overwritten or mislaid, and obviates any need to swap the return address past the arguments on the stack. Importantly, a dynamic jump is not needed to implement subroutine returns, allowing for deprecation of dynamic uses of JUMP and JUMPI. Eventually deprecating dynamic jumps is key to practical static analysis of code. +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. -(JUMPSUB and RETURNSUB were also defined in terms of a `return stack` in [EIP-615](https://eips.ethereum.org/EIPS/eip-615)) -. -## Backwards and Forwards Compatibility +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. -These changes do not affect the semantics of existing EVM code. +_Note: The JVM and Wasm enforce similar constraints for similar reasons._ -These changes are compatible with using [EIP-3337](https://eips.ethereum.org/EIPS/eip-3337) to provide stack frames, by associating a frame with each subroutine. +### Alternative Designs -## Implementations +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. -Three clients have implemented this (or an earlier version of this) proposal: +*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. -- [geth](https://github.com/ethereum/go-ethereum/pull/20619) . -- [besu](https://github.com/hyperledger/besu/pull/717), and -- [openethereum](https://github.com/openethereum/openethereum/pull/11629). +*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. -### Costs and Codes +#### We prefer the dedicated return stack. -We suggest that the cost of +* 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. -- `BEGINSUB` be _jumpdest_ (`1`) -- `JUMPSUB` be _high_ (`10`) - - This is the same as `JUMPI`, and `2` more than `JUMP`. -- `RETURNSUB` be _low_ (`5`). +### Efficiency -Benchmarking might be needed to tell if the costs are well-balanced. +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`. -We suggest the following opcodes: +#### **Simple Subroutine Call** +Consider these examples of a fairly minimal subroutine, including the code to call it. + +Subroutine call, using `RJUMPSUB`: ``` -0x5c BEGINSUB -0x5d RETURNSUB -0x5e JUMPSUB +SQUARE: + dup1 ; 3 gas + mul ; 5 gas + returnsub ; 3 gas + +CALL_SQUARE: + push 0x02 ; 3 gas + rjumpsub SQUARE ; 5 gas ``` +_Total gas: 19_ -## Security Considerations +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_. -These changes do introduce new flow control instructions, so any software which does static/dynamic analysis of evm-code needs to be modified accordingly. The `JUMPSUB` semantics are similar to `JUMP` (but jumping to a `BEGINSUB`), whereas the `RETURNSUB` instruction is different, since it can 'land' on any opcode (but the possible destinations can be statically inferred). +Using `RJUMPSUB` versus `JUMP` saves _41 - 19 = 22 gas_ — a _54%_ improvement. -The safety and amenability to static analysis of valid programs can be made comparable to [EIP-615](https://eips.ethereum.org/EIPS/eip-615), but without imposing syntactic constraints, and thus with minimal impact on low-level optimizations. Validity can ensured by following the rules given in the next section, and programs can be validated with the provided algorithm. The validation algorithm is simple and bounded by the size of the code, allowing for validation at deploy time or at load time. +#### **Tail Call Optimization** -While it is crucial going forward that it be possible to validate programs, this EIP does propose that validity be enforced. Note that much value for people doing static analysis (e.g. for proofs that bytecode meets formal specifications of a contract) can be had without enforcement. Code can be scanned in linear time to ensure that the rules are or are not followed before analysis begins. And compilers can easily follow the rules up front. +Of course in cases like this one we can optimize the tail call, so that the return from `SQUARE` actually returns from `TEST_SQUARE`. -### Validity +Tail call optimization, using `RJUMPSUB` and `RETURNSUB`: +```SQUARE: + dup1 ; 3 gas + mul ; 5 gas + returnsub ; 3 gas -#### Exceptional Halting States +CALL_SQUARE: + push 0x02 ; 3 gas + rjump SQUARE ; 3 gas +``` +_Total: 17 gas_ -_Execution_ is as defined in the [Yellow Paper](https://ethereum.github.io/yellowpaper/paper.pdf)—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 five such states. -1. Insufficient gas -2. More than 1024 stack items -3. Insufficient stack items -4. Invalid jump destination -5. Invalid instruction -We would like to consider EVM code valid iff no execution of the program can lead to an exceptional halting state, but we must be able to validate code in linear time to avoid denial of service attacks. So in practice, we can only partially meet these requirements. Our validation algorithm does not consider the code’s data and computations, only its control flow and stack use. This means we will reject programs with any invalid code paths, even if those paths are not reachable at runtime. Further, conditions 1 and 2 —Insufficient gas and stack overflow—must in general be checked at runtime. Conditions 3, 4, and 5 cannot occur if the code conforms to the following rules. +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_ -#### The Rules +Using `RJUMPSUB` versus `JUMP` saves _38 - 17 = 21 gas_ — a _55%_ improvement. -1. `JUMP` and `JUMPI` address only valid `JUMPDEST` instructions. -2. `JUMPSUB` addresses only valid `BEGINSUB` instructions. -3. `JUMP`, `JUMPI` and `JUMPSUB` are always preceded by one of the `PUSH` instructions. -4. For each instruction in the code the `stack depth` is always the same. -5. The `stack depth` is always positive and at most 1024. +#### Efficiency Caveats -Rules 1 and 2 are currently enforced at runtime. _Note: Valid instructions are not part of PUSH data._ +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. -Rule 3, requiring a `PUSH` before each `JUMP*` would forbid dynamic jumps. Absent dynamic jumps another mechanism is needed for subroutine returns, as provided here. +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. -For rules 4 and 5 we need to define `stack depth`. The Yellow Paper has the `stack pointer` or `SP` pointing just past the top item on the `data stack`. We define the `stack base` as where the `SP` pointed at the most recent `JUMPSUB`, or `0` on program entry. So we can define the `stack depth` as the number of stack elements between the current `SP` and the current `stack base`. +### Costs -Given our definition of `stack depth` Rule 4 ensures that control flows which return to the same place with a different `stack depth` are invalid. These can be caused by irreducible paths like jumping into loops and subroutines, and calling subroutines with different numbers of arguments. Taken together, these rules allow for code to be validated by following the control-flow graph, traversing each edge only once. +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. -Finally, Rule 5 precludes all stack underflows (and some stack overflows.) +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. -### Validation +## 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. -The following is a pseudo-Go specification of an algorithm for enforcing program validity. It recursively traverses the bytecode, following its control flow and stack use and checking for violations of the rules above. (For simplicity we ignore the issue of JUMPDEST or BEGINSUB bytes in PUSH data.) It runs in time == O(vertices + edges) in the program's control-flow graph, where vertices represent control-flow instructions and the edges represent basic blocks. -``` - var bytecode []byte - var stack_depth []int - var SP := 0 - - func validate(PC :=0) boolean { - // traverse code sequentially, recurse for subroutines and conditional jumps - while true { - instruction = bytecode[PC] - if is_invalid(instruction) { - return false; - } - - // if stack depth non-zero we have been here before - // check for constant depth and return to break cycle - if stack_depth[PC] != 0 { - if SP != stack_depth[PC] { - return false - } - return true - } - stack_depth[PC] = SP - - // effect of instruction on stack - SP -= removed_items(instruction) - SP += added_items(instruction) - if SP < 0 || 1024 < SP { - return false - } - - // successful validation of path - if instruction == STOP, RETURN, or SUICIDE { - return true - } - - if instruction == JUMP { - - // check for constant and correct destination - if (bytecode[PC - 33] != PUSH32) { - return false - } - PC = stack[PC-32] - if byte_code[PC] != JUMPDEST { - return false - } - - // reset PC to destination of jump - PC = stack[PC-32] - continue - } - if instruction == JUMPI { - - // check for constant and correct destination - if (bytecode[PC - 33] != PUSH32) { - return false - } - PC = stack[PC-32] - if byte_code[PC] != JUMPDEST { - return false - } - // recurse to jump to code to validate - if !validate(stack[SP])) { - return false - } - continue - } - if instruction == JUMPSUB { - - // check for constant and correct destination - if (bytecode[PC - 33] != PUSH32) - return false - prevPC = PC - PC = stack[PC-32] - if byte_code[PC] != BEGINSUB { - return false - } - - // recurse to jump to code to validate - prevSP = SP - depth = SP - prevSP - SP = depth - if !validate(stack[SP]+1)) { - return false - } - SP = prevSP - depth + SP - PC = prevPC - continue - } - if instruction == RETURNSUB { - PC = prevPC - return true - } - - // advance PC according to instruction - PC = advance_pc(PC, instruction) - } - } -``` ## Test Cases ### Simple routine This should jump into a subroutine, back out and stop. -Bytecode: `0x60045e005c5d` (`PUSH1 0x04, JUMPSUB, STOP, BEGINSUB, RETURNSUB`) +Bytecode: `0x5f0003005e` (`RJUMPSUB 3, RETURNSUB, STOP`) | Pc | Op | Cost | Stack | RStack | |-------|-------------|------|-----------|-----------| -| 0 | PUSH1 | 3 | [] | [] | -| 2 | JUMPSUB | 10 | [4] | [] | -| 5 | RETURNSUB | 5 | [] | [ 2] | -| 3 | STOP | 0 | [] | [] | +| 0 | RJUMPSUB | 5 | [] | [] | +| 2 | STOP | 0 | [] | [] | +| 3 | RETURNSUB | 3 | [] | [] | Output: 0x -Consumed gas: `18` +Consumed gas: `10` ### Two levels of subroutines This should execute fine, going into one two depths of subroutines -Bytecode: `0x6800000000000000000c5e005c60115e5d5c5d` (`PUSH9 0x00000000000000000c, JUMPSUB, STOP, BEGINSUB, PUSH1 0x11, JUMPSUB, RETURNSUB, BEGINSUB, RETURNSUB`) +Bytecode: `0x5f00045F00025200` (`RJUMPSUB 4, RJUMPSUB 2, RETURNSUB, RETURNSUB, STOP`) | Pc | Op | Cost | Stack | RStack | |-------|-------------|------|-----------|-----------| -| 0 | PUSH9 | 3 | [] | [] | -| 10 | JUMPSUB | 10 | [12] | [] | -| 13 | PUSH1 | 3 | [] | [10] | -| 15 | JUMPSUB | 10 | [17] | [10] | -| 18 | RETURNSUB | 5 | [] | [10,15] | -| 16 | RETURNSUB | 5 | [] | [10] | -| 11 | STOP | 0 | [] | [] | +| 0 | RJUMPSUB | 5 | [] | [] | +| 3 | RJUMPSUB | 5 | [] | [] | +| 4 | RETURNSUB | 5 | [] | [] | +| 5 | RETURNSUB | 5 | [] | [] | +| 6 | STOP | 0 | [] | [] | -Consumed gas: `36` +Consumed gas: `20` ### Failure 1: invalid jump -This should fail, since the given location is outside of the code-range. The code is the same as previous example, -except that the pushed location is `0x01000000000000000c` instead of `0x0c`. +This should fail, since the given location is outside of the code-range. -Bytecode: `0x6801000000000000000c5e005c60115e5d5c5d` (`PUSH9 0x01000000000000000c, JUMPSUB, STOP, BEGINSUB, PUSH1 0x11, JUMPSUB, RETURNSUB, BEGINSUB, RETURNSUB`) +Bytecode: `0X5fff`(`RJUMPSUB -1`) | Pc | Op | Cost | Stack | RStack | |-------|-------------|------|-----------|-----------| -| 0 | PUSH9 | 3 | [] | [] | -| 10 | JUMPSUB | 10 |[18446744073709551628] | [] | +| 0 | RJUMPSUB | 10 | [] | [] | ``` -Error: at pc=10, op=JUMPSUB: invalid jump destination +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: `0x5d5858` (`RETURNSUB, PC, PC`) +Bytecode: `0x5e` (`RETURNSUB`) | Pc | Op | Cost | Stack | RStack | |-------|-------------|------|-----------|-----------| @@ -314,27 +322,124 @@ Error: at pc=0, op=RETURNSUB: invalid retsub ### Subroutine at end of code -In this example. the JUMPSUB 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 +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: `0x6005565c5d5b60035e` (`PUSH1 0x05, JUMP, BEGINSUB, RETURNSUB, JUMPDEST, PUSH1 0x03, JUMPSUB`) +Bytecode: `0x5c00045e5fffff` (`RJUMP 4, RETURNSUB, RJUMPSUB -1`) | Pc | Op | Cost | Stack | RStack | |-------|-------------|------|-----------|-----------| -| 0 | PUSH1 | 3 | [] | [] | -| 2 | JUMP | 8 | [5] | [] | -| 5 | JUMPDEST | 1 | [] | [] | -| 6 | PUSH1 | 3 | [] | [] | -| 8 | JUMPSUB | 10 | [3] | [] | -| 4 | RETURNSUB | 5 | [] | [ 8] | -| 9 | STOP | 0 | [] | [] | - -Consumed gas: `30` - -## References -Gavin Wood, [Ethereum: A Secure Decentralized Generalized Transaction Ledger](https://ethereum.github.io/yellowpaper/paper.pdf), 2014-2021 -Greg Colvin, Brooklyn Zelenka, Paweł Bylica, Christian Reitwiessner, [EIP-615: Subroutines and Static Jumps for the EVM](https://eips.ethereum.org/EIPS/eip-615), 2016-2019 -Martin Lundfall, [EIP-2327: BEGINDATA Opcode](https://eips.ethereum.org/EIPS/eip-2327), 2019 -Nick Johnson, [EIP-3337: Frame pointer support for memory load and store operations](https://eips.ethereum.org/EIPS/eip-3337), 2021 +| 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2327.md b/EIPS/eip-2327.md index 3546458110da69..f2e4449bbefd69 100644 --- a/EIPS/eip-2327.md +++ b/EIPS/eip-2327.md @@ -3,7 +3,7 @@ eip: 2327 title: BEGINDATA opcode author: Martin Lundfall (@MrChico) discussions-to: https://ethereum-magicians.org/t/new-opcode-begindata/3727 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-10-28 @@ -46,4 +46,4 @@ Test cases should include: Not 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-233.md b/EIPS/eip-233.md index c70c6b49c7ab56..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 --- @@ -104,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 %} ``` @@ -115,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 index 58a8342e3a65bd..a648f15e78e970 100644 --- a/EIPS/eip-2330.md +++ b/EIPS/eip-2330.md @@ -1,63 +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: Draft +status: Stagnant type: Standards Track category: Core created: 2019-10-29 +requires: 2929 --- -## Simple Summary -A new `EXTSLOAD ` EVM opcode to read external contract storage data and corresponding allowing to build registry and token contracts that use less gas. - ## Abstract -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. + +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 -The gas cost when reading from registry style contract such as ERC-20s, 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. 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. Furthermore with the use of the existing `EXTCODEHASH` an external contracts implementation can be verified and allows `EXTSLOAD` to make deterministic reads even from third-party smart contracts. + +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 -**Proposal** -A new EVM instruction `EXTSLOAD (0x5c)` that works like `SLOAD (0x54)` but an additional parameter representing the contract that is to be read from. The gas cost of `EXTSLOAD` would be the sum of the [fee schedule G](https://ethereum.github.io/yellowpaper/paper.pdf) for G\[EXTCODE\](700) + G\[SLOAD\](800) = 1500 gas +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. -**Example** +### Gas cost pre-verkle -An example assuming [further Solidity changes](https://github.com/ethereum/solidity/issues/7593) for illustration: +Gas to be charged before Verkle Tree change is specified as `ACCOUNT_ACCESS_COST + STORAGE_READ_COST` where: -```solidity -interface MemberList { - public fixed(@5) mapping(address => bool) members; -} -``` +- `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`. -And a corresponding contract function that uses this member list. Similarly tokens or other registries could be implemented. +### Gas cost post-verkle -```solidity -function membersOnly(address list, address member) { - MemberList ml = MemberList(list); - if (ml.members[client] == false) revert("Nonmember!"); -} -``` +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). -The call `ml.members[client]` here could let the Solidity compiler generate the normal map access logic but using the new `EXTSLOAD ` instructions to read from the `ml` contract storage instead of the local contract storage. +## 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. -## Test Cases -Not started yet. +## Security Considerations -## Implementation -[Aleth Pull Request](https://github.com/ethereum/aleth/pull/5805) +- 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](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2333.md b/EIPS/eip-2333.md index 7e601b0c3c7a39..962cb23c8fa536 100644 --- a/EIPS/eip-2333.md +++ b/EIPS/eip-2333.md @@ -1,816 +1,7 @@ --- eip: 2333 -title: BLS12-381 Key Generation -author: Carl Beekhuizen -discussions-to: https://github.com/ethereum/EIPs/issues/2337 -status: Draft -type: Standards Track category: ERC -created: 2019-09-30 +status: Moved --- -## Simple Summary - -This EIP is a method based on a tree structure for deriving BLS private keys from a single source of entropy while providing a post-quantum cryptographic fallback for each key. - -## Abstract - -This standard is a method for deriving a tree-hierarchy of BLS12-381 keys based on an entropy seed. Starting with the aforementioned seed, a tree of keys is built out using only the parent node's private key and the index of the desired child. This allows for a practically limitless number of keys to be derived for many different purposes while only requiring knowledge of a single ancestor key in the tree. This allows for keys, or families thereof, to be provisioned for different purposes by further standards. - -In addition to the above, this method of deriving keys provides an emergency backup signature scheme that is resistant to quantum computers for in the event that BLS12-381 is ever deemed insecure. - -## A note on purpose - -This specification is designed not only to be an Ethereum 2.0 standard, but one that is adopted by the wider community who have adopted the BLS12-381 signature standard. It is therefore important also to consider the needs of the wider industry along with those specific to Ethereum. As a part of these considerations, it is the intention of the author that this standard eventually migrate to a more neutral repository in the future. - -## Motivation - -### Deficiencies of the existing mechanism - -The new curve (BLS12-381) used for signatures within Ethereum 2.0 (alongside many other projects) mandates a new key derivation scheme. The most commonly used scheme for key derivation within Ethereum 1.x is [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) (also known as HD derivation) which deems keys greater than the curve order invalid. Based on the order of the private key subgroup of BLS12-381 and the size of the entropy utilised, more than 54% of keys generated by BIP32 would be invalid. (secp256k1 keys derived by BIP32 are invalid with probability less than 1 in 2-127.) - -### Establishing a multi-chain standard early on - -By establishing a standard before the first users begin to generate their keys, the hope is that a single standard is highly pervasive and therefore can be assumed to be the method by which the majority of keys are provided. This is valuable for two reasons, firstly in order for a post-quantum backup mechanism to be effective, there needs to be an enshrined mechanism whereby users can switch to a post-quantum signature scheme with pre-shared public keys (something this EIP provides at 0 extra storage cost). Secondly, this unifies the inter- and intra-chain ecosystem by having common tooling ideally allowing users to switch between key-management systems. - -### A post-quantum backup - -This key derivation scheme has a Lamport key pair which is generated as a intermediate step in the key generation process. This key pair can be used to provide a Lamport signature which is a useful backup in the event of BLS12-381 no longer being considered secure (in the event of quantum computing making a sudden advancement, for example). The idea is the Lamport signature will act as a bridge to a new signature scheme which is deemed to be secure. - -## Specification - -### Version - -Due to the evolving BLS standard (currently v4), the `KeyGen` function was updated, meaning that `hkdf_mod_r` no longer reflected what appeared in the BLS standard. This EIP was updated on the 17th of September 2020 to reflect this new method for deriving keys, **if you are implementing this EIP, please make sure your version is up to date.** - -### Specification - -Keys are defined in terms of a tree structure where a key is determined by the tree's seed and a tree path. This is very useful as one can start with a single source of entropy and build out a practically unlimited number of keys. The specification can be broken into two sub-components: generating the master key, and constructing a child key from its parent. The master key is used as the root of the tree and then the tree is built in layers on top of this root. - -### The Tree Structure - -The key tree is defined purely through the relationship between a child-node and its ancestors. Starting with the root of the tree, the *master key*, a child node can be derived by knowing the parent's private key and the index of the child. The tree is broken up into depths which are indicated by `/` and the master node is described as `m`. The first child of the master node is therefore described as `m / 0` and `m / 0`'s siblings are `m / i` for all `0 <= i < 2**32`. - -```text - [m / 0] - [m / 0 / 0] - / \ - / [m / 0 / 1] -[m] - [m / 1] - \ - ... - [m / i] -``` - -### Key derivation - -Every key generated via the key derivation process derives a child key via a set of intermediate Lamport keys. The idea behind the Lamport keys is to provide a post-quantum backup in case BLS12-381 is no longer deemed secure. At a high level, the key derivation process works by using the parent node's privkey as an entropy source for the Lamport private keys which are then hashed together into a compressed Lamport public key, this public key is then hashed into BLS12-381's private key group. - -#### `IKM_to_lamport_SK` - -##### Inputs - -* `IKM`, a secret octet string -* `salt`, an octet string - -##### Outputs - -* `lamport_SK`, an array of 255 32-octet strings - -##### Definitions - -* `HKDF-Extract` is as defined in [RFC5869](https://tools.ietf.org/html/rfc5869), instantiated with SHA256 -* `HKDF-Expand` is as defined in [RFC5869](https://tools.ietf.org/html/rfc5869), instantiated with SHA256 -* `K = 32` is the digest size (in octets) of the hash function (SHA256) -* `L = K * 255` is the HKDF output size (in octets) -* `""` is the empty string -* `bytes_split` is a function takes in an octet string and splits it into `K`-byte chunks which are returned as an array - -##### Procedure - -``` text -0. PRK = HKDF-Extract(salt, IKM) -1. OKM = HKDF-Expand(PRK, "" , L) -2. lamport_SK = bytes_split(OKM, K) -3. return lamport_SK -``` - -#### `parent_SK_to_lamport_PK` - -##### Inputs - -* `parent_SK`, the BLS Secret Key of the parent node -* `index`, the index of the desired child node, an integer `0 <= index < 2^32` - -##### Outputs - -* `lamport_PK`, the compressed lamport PK, a 32 octet string - -##### Definitions - -* `I2OSP` is as defined in [RFC3447](https://ietf.org/rfc/rfc3447.txt) (Big endian decoding) -* `flip_bits` is a function that returns the bitwise negation of its input -* `""` is the empty string -* `a | b` is the concatenation of `a` with `b` - -##### Procedure - -```text -0. salt = I2OSP(index, 4) -1. IKM = I2OSP(parent_SK, 32) -2. lamport_0 = IKM_to_lamport_SK(IKM, salt) -3. not_IKM = flip_bits(IKM) -4. lamport_1 = IKM_to_lamport_SK(not_IKM, salt) -5. lamport_PK = "" -6. for i in 1, .., 255 - lamport_PK = lamport_PK | SHA256(lamport_0[i]) -7. for i in 1, .., 255 - lamport_PK = lamport_PK | SHA256(lamport_1[i]) -8. compressed_lamport_PK = SHA256(lamport_PK) -9. return compressed_lamport_PK -``` - -**Note:** The indexing, `i`, in the above procedure iterates from 1 to 255 (inclusive). This is due to the limit to which HKDF can stretch the input bytes (255 times the length of the input bytes). The result of this is that the security of the lamport-backup signature is \*only\* 127.5 bit. - -#### `HKDF_mod_r` - -`hkdf_mod_r()` is used to hash 32 random bytes into the subgroup of the BLS12-381 private keys. - -##### Inputs - -* `IKM`, a secret octet string >= 256 bits in length -* `key_info`, an optional octet string (default=`""`, the empty string) - -##### Outputs - -* `SK`, the corresponding secret key, an integer 0 <= SK < r. - -##### Definitions - -* `HKDF-Extract` is as defined in RFC5869, instantiated with hash H. -* `HKDF-Expand` is as defined in RFC5869, instantiated with hash H. -* `L` is the integer given by `ceil((3 * ceil(log2(r))) / 16)`.(`L=48`) -* `"BLS-SIG-KEYGEN-SALT-"` is an ASCII string comprising 20 octets. -* `OS2IP` is as defined in [RFC3447](https://ietf.org/rfc/rfc3447.txt) (Big endian encoding) -* `I2OSP` is as defined in [RFC3447](https://ietf.org/rfc/rfc3447.txt) (Big endian decoding) -* `r` is the order of the BLS 12-381 curve defined in [the draft IETF BLS signature scheme standard](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04) `r=52435875175126190479447740508185965837690552500527637822603658699938581184513` - -##### Procedure - -```text -1. salt = "BLS-SIG-KEYGEN-SALT-" -2. SK = 0 -3. while SK == 0: -4. salt = H(salt) -5. PRK = HKDF-Extract(salt, IKM || I2OSP(0, 1)) -6. OKM = HKDF-Expand(PRK, key_info || I2OSP(L, 2), L) -7. SK = OS2IP(OKM) mod r -8. return SK -``` - -### `derive_child_SK` - -The child key derivation function takes in the parent's private key and the index of the child and returns the child private key. - -##### Inputs - -* `parent_SK`, the secret key of the parent node, a big endian encoded integer -* `index`, the index of the desired child node, an integer `0 <= index < 2^32` - -##### Outputs - -* `child_SK`, the secret key of the child node, a big endian encoded integer - -##### Procedure - -```text -0. compressed_lamport_PK = parent_SK_to_lamport_PK(parent_SK, index) -1. SK = HKDF_mod_r(compressed_lamport_PK) -2. return SK -``` - -### `derive_master_SK` - -The child key derivation function takes in the parent's private key and the index of the child and returns the child private key. The seed should ideally be derived from a mnemonic, with the intention being that [BIP39 mnemonics](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki), with the associated [mnemonic_to_seed method](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#from-mnemonic-to-seed) be used. - -##### Inputs - -* `seed`, the source entropy for the entire tree, a octet string >= 256 bits in length - -##### Outputs - -* `SK`, the secret key of master node within the tree, a big endian encoded integer - -##### Procedure - -```text -0. SK = HKDF_mod_r(seed) -1. return SK -``` - -## Rationale - -### Lamport signatures - -Lamport signatures are used as the backup mechanism because of their relative simplicity for a post-quantum signature scheme. Lamport signatures are very easy both to explain and implement as the sole cryptographic dependency is a secure hash function. This is important as it minimises the complexity of implementing this standard as well as the compute time for deriving a key. Lamport signatures have very large key sizes which make them impractical for many use cases, but this is not deemed to be an issue in this case as this scheme is only meant to be a once-off event to migrate to a new scheme. - -Revealing the associated Lamport public key for a corresponding BLS key is done by verifying that the Lamport public key is the pre-image of the corresponding BLS private key (which in turn is verified against the BLS public key). This means that using a key's Lamport signature reveals the BLS private key rendering the BLS key pair unsafe. This has the upside of not requiring additional storage space for backup keys alongside BLS keys but does require that the Lamport signatures be used once and that the BLS key is no longer trusted after that point. - -The Lamport signatures used within this scheme have 255 bits worth of security, not 256. This is done because HKDF-SHA256, the mechanism used to stretch a key's entropy, has a length-limit of `255 * hash_function_digest_size`. The 1-bit reduction in security is deemed preferable over increasing the complexity of the entropy stretching mechanism. - -### SHA256 - -SHA256 is used as the hash function throughout this standard as it is the hash function chosen by the for the [IETF BLS12-381 standard](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04). Using a single hash function for everything decreases the number of cryptographic primitives required to implement the entire BLS standardised key-stack while reducing the surface for flaws in the overall system. - -### `hkdf_mod_r()` - -The function `hkdf_mod_r()` in this standard is the same as the `KeyGen` function described in the [draft IETF BLS standard](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04) and therefore the private key obtained from `KeyGen` is equal to that obtained from `hkdf_mod_r` for the same seed bytes. This means that common engineering can be done when implementing this function. Additionally because of its inclusion in an IETF standard, it has had much scrutiny by many cryptographers and cryptanalysts, thereby lending credence to its safety as a key derivation mechanism. - -While `hkdf_mod_r()` has modulo bias, the magnitude of this bias is minuscule (the output size of HKDF is set to 48 bytes which is greater 2128 time larger than the curve order). This bias is deemed acceptable in light of the simplicity of the constant time scheme. - -### Only using hardened keys - -Widely accepted standards that existed before this one ([BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) utilise the notion of hardened and non-hardened keys whereas this specification only offers the former. Non-hardened keys are primarily useful in a UTXO system in which having one's balance spilt amongst many accounts does not present much additionally complexity, but such keys are much less useful outside of this context. Further complicating matters is the problem of deriving non-hardened keys using a post-quantum signature scheme as non-hardened keys are made possible by the very group arithmetic quantum computers gain an advantage over. - -## Backwards Compatibility - -There are no major backwards compatibility issues brought upon by this EIP as it is not designed for use within Ethereum 1.0 as it currently stands. That said, this standard is not compatible with BIP32/ BIP44 style paths as paths specified by these systems make use of non-hardened keys, something that does not exist within this standard. - -## Test Cases - -### Test Case 0 - -```text -seed = 0xc55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04 -master_SK = 6083874454709270928345386274498605044986640685124978867557563392430687146096 -child_index = 0 -child_SK = 20397789859736650942317412262472558107875392172444076792671091975210932703118 -``` - -This test case can be extended to test the entire mnemonic-to-`child_SK` stack, assuming [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) is used as the mnemonic generation mechanism. Using the following parameters, the above seed can be calculated: - -```test -mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" -passphrase = "TREZOR" -``` - -This test case can be extended to test the entire `mnemonic-to -child_SK` stack, assuming [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) is used as the mnemonic generation mechanism. Using the following parameters, the above seed can be calculated: - -```text -mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" -passphrase = "TREZOR" -``` - -### Test Case 1 - -```text -seed = 0x3141592653589793238462643383279502884197169399375105820974944592 -master_SK = 29757020647961307431480504535336562678282505419141012933316116377660817309383 -child_index = 3141592653 -child_SK = 25457201688850691947727629385191704516744796114925897962676248250929345014287 -``` - -### Test Case 2 - -```text -seed = 0x0099FF991111002299DD7744EE3355BBDD8844115566CC55663355668888CC00 -master_SK = 27580842291869792442942448775674722299803720648445448686099262467207037398656 -child_index = 4294967295 -child_SK = 29358610794459428860402234341874281240803786294062035874021252734817515685787 -``` - -### Test Case 3 - -```text -seed = 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3 -master_SK = 19022158461524446591288038168518313374041767046816487870552872741050760015818 -child_index = 42 -child_SK = 31372231650479070279774297061823572166496564838472787488249775572789064611981 -``` - -### Test Vector with Intermediate values - -```text -seed = 0xc55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04 -master_SK = 6083874454709270928345386274498605044986640685124978867557563392430687146096 -child_index = 0 -lamport_0 = [0xe345d0ad7be270737de05cf036f688f385d5f99c7fddb054837658bdd2ebd519, -0x65050bd4db9c77c051f67dcc801bf1cdf33d81131e608505bb3e4523868eb76c, -0xc4f8e8d251fbdaed41bdd9c135b9ed5f83a614f49c38fffad67775a16575645a, -0x638ad0feace7567255120a4165a687829ca97e0205108b8b73a204fba6a66faa, -0xb29f95f64d0fcd0f45f265f15ff7209106ab5f5ce6a566eaa5b4a6f733139936, -0xbcfbdd744c391229f340f02c4f2d092b28fe9f1201d4253b9045838dd341a6bf, -0x8b9cf3531bfcf0e4acbfd4d7b4ed614fa2be7f81e9f4eaef53bedb509d0b186f, -0xb32fcc5c4e2a95fb674fa629f3e2e7d85335f6a4eafe7f0e6bb83246a7eced5f, -0xb4fe80f7ac23065e30c3398623b2761ac443902616e67ce55649aaa685d769ce, -0xb99354f04cfe5f393193c699b8a93e5e11e6be40ec16f04c739d9b58c1f55bf3, -0x93963f58802099ededb7843219efc66a097fab997c1501f8c7491991c780f169, -0x430f3b027dbe9bd6136c0f0524a0848dad67b253a11a0e4301b44074ebf82894, -0xd635c39b4a40ad8a54d9d49fc8111bd9d11fb65c3b30d8d3eaef7d7556aac805, -0x1f7253a6474cf0b2c05b02a7e91269137acddedcb548144821f9a90b10eccbab, -0x6e3bdb270b00e7b6eb8b044dbfae07b51ea7806e0d24218c59a807a7fd099c18, -0x895488ad2169d8eaae332ce5b0fe1e60ffab70e62e1cb15a2a1487544af0a6e8, -0x32d45a99d458c90e173a3087ea3661ab62d429b285089e92806a9663ba825342, -0xc15c52106c3177f5848a173076a20d46600ca65958a1e3c7d45a593aaa9670ed, -0xd8180c550fbe4cd6d5b676ff75e0728729d8e28a3b521d56152594ac6959d563, -0x58fe153fac8f4213aaf175e458435e06304548024bcb845844212c774bdffb2a, -0x10fff610a50f4bee5c978f512efa6ab4fafacb65929606951ba5b93eeb617b5a, -0x78ac9819799b52eba329f13dd52cf0f6148a80bf04f93341814c4b47bb4aa5ec, -0xa5c3339caa433fc11e74d1765bec577a13b054381a44b23c2482e750696876a9, -0x9f716640ab5cdc2a5eb016235cddca2dc41fa4ec5acd7e58af628dade99ec376, -0x2544364320e67577c4fed8c7c7c839deed93c24076d5343c5b8faca4cc6dc2d8, -0x62553e782541f822c589796be5d5c83bfc814819100b2be0710b246f5aa7149c, -0x229fb761c46c04b22ba5479f2696be0f936fded68d54dd74bcd736b8ba512afb, -0x0af23996a65b98a0ebaf19f3ec0b3ef20177d1bfd6eb958b3bd36e0bdbe04c8c, -0x6f0954f9deab52fd4c8d2daba69f73a80dea143dd49d9705c98db3d653adf98c, -0xfa9221dd8823919a95b35196c1faeb59713735827f3e84298c25c83ac700c480, -0x70c428e3ff9e5e3cda92d6bb85018fb89475c19f526461cca7cda64ebb2ff544, -0xdcaac3413e22314f0f402f8058a719b62966b3a7429f890d947be952f2e314ba, -0xb6b383cb5ec25afa701234824491916bfe6b09d28cf88185637e2367f0cf6edc, -0x7b0d91488fc916aba3e9cb61a5a5645b9def3b02e4884603542f679f602afb8d, -0xe9c20abca284acfde70c59584b9852b85c52fa7c263bb981389ff8d638429cd7, -0x838524f798daee6507652877feb9597f5c47e9bb5f9aa52a35fb6fff796813b9, -0xbe1ca18faf9bf322474fad1b3d9b4f1bc76ae9076e38e6dd2b16e2faf487742b, -0xbf02d70f1a8519343a16d24bade7f7222912fd57fe4f739f367dfd99d0337e8e, -0xc979eb67c107ff7ab257d1c0f4871adf327a4f2a69e01c42828ea27407caf058, -0xf769123d3a3f19eb7b5c3fd4f467a042944a7c5ff8834cebe427f47dbd71460c, -0xaefc8edc23257e1168a35999fe3832bcbc25053888cc89c38667482d6748095b, -0x8ff399f364d3a2428b1c92213e4fdc5341e7998007da46a5a2f671929b42aaab, -0xcf2a3d9e6963b24c5001fbba1e5ae7f45dd6cf520fd24861f745552db86bab48, -0xb380e272d7f3091e5c887fa2e7c690c67d59f4d95f8376d150e555da8c738559, -0xc006a749b091d91204dbb64f59059d284899de5986a7f84f8877afd5e0e4c253, -0x818d8bb9b7da2dafa2ef059f91975e7b6257f5e199d217320de0a576f020de5c, -0x7aabf4a1297d2e550a2ee20acb44c1033569e51b6ec09d95b22a8d131e30fd32, -0xdd01c80964a5d682418a616fb10810647c9425d150df643c8ddbbe1bfb2768b7, -0x1e2354e1d97d1b06eb6cfe9b3e611e8d75b5c57a444523e28a8f72a767eff115, -0x989c9a649dca0580256113e49ea0dd232bbfd312f68c272fe7c878acc5da7a2c, -0x14ee1efe512826fff9c028f8c7c86708b841f9dbf47ce4598298b01134ebdc1a, -0x6f861dba4503f85762d9741fa8b652ce441373f0ef2b7ebbd5a794e48cdab51b, -0xda110c9492ffdb87efe790214b7c9f707655a5ec08e5af19fb2ab2acc428e7dc, -0x5576aa898f6448d16e40473fcb24c46c609a3fc46a404559faa2d0d34d7d49ce, -0x9bd9a35675f2857792bc45893655bfdf905ffeaee942d93ad39fbcadd4ca9e11, -0xfa95e4c37db9303d5213890fd984034089cbc9c6d754741625da0aa59cc45ccf, -0xfef7d2079713f17b47239b76c8681bf7f800b1bfeac7a53265147579572ddf29, -0x39aa7c0fecf9a1ed037c685144745fda16da36f6d2004844cf0e2d608ef6ed0e, -0x5530654d502d6ba30f2b16f49cc5818279697308778fd8d40db8e84938144fb6, -0xb1beaa36397ba1521d7bf7df16536969d8a716e63510b1b82a715940180eb29f, -0x21abe342789f7c15a137afa373f686330c0db8c861572935a3cd8dcf9e4e1d45, -0x27b5a1acda55b4e0658887bd884d3203696fcae0e94f19e31bfe931342b1c257, -0x58401a02502d7708a812c0c72725f768f5a556480517258069f2d72543cda888, -0x4b38f291548f51bee7e4cf8cc5c8aa8f4ad3ec2461dba4ccbab70f1c1bfd7feb, -0x9b39a53fdafaaf1d23378e0aa8ae65d38480de69821de2910873eefc9f508568, -0x932200566a3563ee9141913d12fd1812cb008cb735724e8610890e101ec10112, -0x6a72f70b4ec5491f04780b17c4776a335fcc5bff5073d775150e08521dc74c91, -0x86d5c60e627a4b7d5d075b0ba33e779c45f3f46d22ed51f31360afd140851b67, -0x5ca2a736bb642abc4104faa781c9aff13d692a400d91dc961aec073889836946, -0xa14bca5a262ac46ceac21388a763561fc85fb9db343148d786826930f3e510cd, -0x87be03a87a9211504aa70ec149634ee1b97f7732c96377a3c04e98643dcba915, -0x8fe283bc19a377823377e9c326374ebb3f29527c12ea77bfb809c18eef8943b0, -0x8f519078b39a3969f7e4caeca9839d4e0eccc883b89e4a86d0e1731bfc5e33fc, -0x33d7c28c3d26fdfc015a8c2131920e1392ef0aea55505637b54ea63069c7858e, -0xe57de7c189fcc9170320c7acedb38798562a48dbc9943b2a8cd3441d58431128, -0x513dac46017050f82751a07b6c890f14ec43cadf687f7d202d2369e35b1836b4, -0xfd967d9f805bb7e78f7b7caa7692fdd3d6b5109c41ad239a08ad0a38eeb0ac4c, -0xf2013e4da9abcc0f03ca505ed94ec097556dbfd659088cd24ec223e02ac43329, -0xe0dcfac50633f7417f36231df2c81fa1203d358d5f57e896e1ab4b512196556b, -0xf022848130e73fe556490754ef0ecfcdaaf3b9ff16ae1eda7d38c95c4f159ded, -0x2147163a3339591ec7831d2412fb2d0588c38da3cd074fa2a4d3e5d21f9f1d2d, -0x11ee2404731962bf3238dca0d9759e06d1a5851308b4e6321090886ec5190b69, -0xf7679ecd07143f8ac166b66790fa09aed39352c09c0b4766bbe500b1ebace5a5, -0xc7a0e95f09076472e101813a95e6ea463c35bd5ee9cfda3e5d5dbccb35888ef0, -0xde625d3b547eb71bea5325a0191a592fa92a72e4b718a499fdba32e245ddf37e, -0x7e5bdccd95df216e8c59665073249072cb3c9d0aef6b341afc0ca90456942639, -0xc27f65fd9f797ede374e06b4ddb6e8aa59c7d6f36301f18b42c48b1889552fe3, -0x8175730a52ea571677b035f8e2482239dda1cfbff6bc5cde00603963511a81af, -0x09e440f2612dad1259012983dc6a1e24a73581feb1bd69d8a356eea16ba5fd0e, -0x59dcc81d594cbe735a495e38953e8133f8b3825fd84767af9e4ea06c49dbabfa, -0x6c8480b59a1a958c434b9680edea73b1207077fb9a8a19ea5f9fbbf6f47c4124, -0x81f5c89601893b7a5a231a7d37d6ab9aa4c57f174fcfc6b40002fa808714c3a1, -0x41ba4d6b4da141fcc1ee0f4b47a209cfd143d34e74fc7016e9956cedeb2db329, -0x5e0b5b404c60e9892040feacfb4a84a09c2bc4a8a5f54f3dad5dca4acdc899dc, -0xe922eebf1f5f15000d8967d16862ed274390cde808c75137d2fb9c2c0a80e391, -0xbf49d31a59a20484f0c08990b2345dfa954509aa1f8901566ab9da052b826745, -0xb84e07da828ae668c95d6aa31d4087504c372dbf4b5f8a8e4ded1bcf279fd52b, -0x89288bf52d8c4a9561421ad199204d794038c5d19ae9fee765ee2b5470e68e7e, -0xf6f618be99b85ec9a80b728454a417c647842215e2160c6fe547dd5a69bd9302, -0xdd9adc002f98c9a47c7b704fc0ce0a5c7861a5e2795b6014749cde8bcb8a034b, -0xd119a4b2c0db41fe01119115bcc35c4b7dbfdb42ad3cf2cc3f01c83732acb561, -0x9c66bc84d416b9193bad9349d8c665a9a06b835f82dc93ae0cccc218f808aad0, -0xd4b50eefcd2b5df075f14716cf6f2d26dfc8ae02e3993d711f4a287313038fde, -0xaf72bfb346c2f336b8bc100bff4ba35d006a3dad1c5952a0adb40789447f2704, -0xc43ca166f01dc955e7b4330227635feb1b0e0076a9c5633ca5c614a620244e5b, -0x5efca76970629521cfa053fbbbda8d3679cadc018e2e891043b0f52989cc2603, -0x35c57de1c788947f187051ce032ad1e899d9887d865266ec6fcfda49a8578b2b, -0x56d4be8a65b257216eab7e756ee547db5a882b4edcd12a84ed114fbd4f5be1f1, -0x257e858f8a4c07a41e6987aabaa425747af8b56546f2a3406f60d610bcc1f269, -0x40bd9ee36d52717ab22f1f6b0ee4fb38b594f58399e0bf680574570f1b4b8c90, -0xcb6ac01c21fc288c12973427c5df6eb8f6aefe64b92a6420c6388acdf36bc096, -0xa5716441312151a5f0deb52993a293884c6c8f445054ce1e395c96adeee66c6d, -0xe15696477f90113a10e04ba8225c28ad338c3b6bdd7bdeb95c0722921115ec85, -0x8faeaa52ca2f1d791cd6843330d16c75eaf6257e4ba236e3dda2bc1a644aee00, -0xc847fe595713bf136637ce8b43f9de238762953fed16798878344da909cc76ae, -0xb5740dc579594dd110078ce430b9696e6a308078022dde2d7cfe0ef7647b904e, -0x551a06d0771fcd3c53aea15aa8bf700047138ef1aa22265bee7fb965a84c9615, -0x9a65397a5907d604030508d41477de621ce4a0d79b772e81112d634455e7a4da, -0x6462d4cc2262d7faf8856812248dc608ae3d197bf2ef410f00c3ae43f2040995, -0x6782b1bd319568e30d54b324ab9ed8fdeac6515e36b609e428a60785e15fb301, -0x8bcdcf82c7eb2a07e14db20d80d9d2efea8d40320e121923784c92bf38250a8e, -0x46ed84fa17d226d5895e44685747ab82a97246e97d6237014611aaaba65ed268, -0x147e87981673326c5a2bdb06f5e90eaaa9583857129451eed6dde0c117fb061f, -0x4141d6fe070104c29879523ba6669552f3d457c0929bb878d2751f4ff059b895, -0xd866ce4ef226d74841f950fc28cdf2235db21e0e3f07a0c8f807704464db2210, -0xa804f9118bf92558f684f90c2bda832a4f51ef771ffb2765cde3ec6f48124f32, -0xc436d4a65910124e00cded9a637178914a8fbc090400f3f031c03eac4d0295a5, -0x643fdb9243656512316528de04dcc7344ca33783580ad0c3debf8c4a6e7c8bc4, -0x7f4a345b41706b281b2de998e91ff62d908eb29fc333ee336221757753c96e23, -0x6bdc086a5b11de950cabea33b72d98db886b291c4c2f02d3e997edc36785d249, -0xfb10b5b47d374078c0a52bff7174bf1cd14d872c7d20b4a009e2afd3017a9a17, -0x1e07e605312db5380afad8f3d7bd602998102fdd39565b618ac177b13a6527e6, -0xc3161b5a7b93aabf05652088b0e5b4803a18be693f590744c42c24c7aaaeef48, -0xa47e4f25112a7d276313f153d359bc11268b397933a5d5375d30151766bc689a, -0xb24260e2eff88716b5bf5cb75ea171ac030f5641a37ea89b3ac45acb30aae519, -0x2bcacbebc0a7f34406db2c088390b92ee34ae0f2922dedc51f9227b9afb46636, -0xc78c304f6dbe882c99c5e1354ce6077824cd42ed876db6706654551c7472a564, -0x6e2ee19d3ee440c78491f4e354a84fa593202e152d623ed899e700728744ac85, -0x2a3f438c5dc012aa0997b66f661b8c10f4a0cd7aa5b6e5922b1d73020561b27f, -0xd804f755d93173408988b95e9ea0e9feae10d404a090f73d9ff84df96f081cf7, -0xe06fda941b6936b8b33f00ffa02c8b05fd78fbec953da61da2043f5644b30a50, -0x45ee279b465d53148850a16cc7f6bd33e7627aef554a9418ed012ca8f9717f80, -0x9c79348c1bcd6aa2135452491d73564413a247ea8cc38fa7dcc6c43f8a2d61d5, -0x7c91e056f89f2a77d3e3642e595bcf4973c3bca68dd2b10f51ca0d8945e4255e, -0x669f976ebe38cbd22c5b1f785e14b76809d673d2cb1458983dbda41f5adf966b, -0x8bc71e99ffcc119fd8bd604af54c0663b0325a3203a214810fa2c588089ed5a7, -0x36b3f1ffeae5d9855e0965eef33f4c5133d99685802ac5ce5e1bb288d308f889, -0x0aad33df38b3f31598e04a42ec22f20bf2e2e9472d02371eb1f8a06434621180, -0x38c5632b81f90efbc51a729dcae03626a3063aa1f0a102fd0e4326e86a08a732, -0x6ea721753348ed799c98ffa330d801e6760c882f720125250889f107915e270a, -0xe700dd57ce8a653ce4269e6b1593a673d04d3de8b79b813354ac7c59d1b99adc, -0xe9294a24b560d62649ca898088dea35a644d0796906d41673e29e4ea8cd16021, -0xf20bb60d13a498a0ec01166bf630246c2f3b7481919b92019e2cfccb331f2791, -0xf639a667209acdd66301c8e8c2385e1189b755f00348d614dc92da14e6866b38, -0x49041904ee65c412ce2cd66d35570464882f60ac4e3dea40a97dd52ffc7b37a2, -0xdb36b16d3a1010ad172fc55976d45df7c03b05eab5432a77be41c2f739b361f8, -0x71400cdd2ea78ac1bf568c25a908e989f6d7e2a3690bc869c7c14e09c255d911, -0xf0d920b2d8a00b88f78e7894873a189c580747405beef5998912fc9266220d98, -0x1a2baefbbd41aa9f1cc5b10e0a7325c9798ba87de6a1302cf668a5de17bc926a, -0x449538a20e52fd61777c45d35ff6c2bcb9d9165c7eb02244d521317f07af6691, -0x97006755b9050b24c1855a58c4f4d52f01db4633baff4b4ef3d9c44013c5c665, -0xe441363a27b26d1fff3288222fa8ed540f8ca5d949ddcc5ff8afc634eec05336, -0xed587aa8752a42657fea1e68bc9616c40c68dcbbd5cb8d781e8574043e29ef28, -0x47d896133ba81299b8949fbadef1c00313d466827d6b13598685bcbb8776c1d2, -0x7786bc2cb2d619d07585e2ea4875f15efa22110e166af87b29d22af37b6c047d, -0x956b76194075fe3daf3ca508a6fad161deb05d0026a652929e37c2317239cbc6, -0xec9577cb7b85554b2383cc4239d043d14c08d005f0549af0eca6994e203cb4e7, -0x0722d0c68d38b23b83330b972254bbf9bfcf32104cc6416c2dad67224ac52887, -0x532b19d54fb6d77d96452d3e562b79bfd65175526cd793f26054c5f6f965df39, -0x4d62e065e57cbf60f975134a360da29cabdcea7fcfc664cf2014d23c733ab3b4, -0x09be0ea6b363fd746b303e482cb4e15ef25f8ae57b7143e64cbd5c4a1d069ebe, -0x69dcddc3e05147860d8d0e90d602ac454b609a82ae7bb960ee2ecd1627d77777, -0xa5e2ae69d902971000b1855b8066a4227a5be7234ac9513b3c769af79d997df4, -0xc287d4bc953dcff359d707caf2ccba8cc8312156eca8aafa261fb72412a0ea28, -0xb27584fd151fb30ed338f9cba28cf570f7ca39ebb03eb2e23140423af940bd96, -0x7e02928194441a5047af89a6b6555fea218f1df78bcdb5f274911b48d847f5f8, -0x9ba611add61ea6ba0d6d494c0c4edd03df9e6c03cafe10738cee8b7f45ce9476, -0x62647ec3109ac3db3f3d9ea78516859f0677cdde3ba2f27f00d7fda3a447dd01, -0xfa93ff6c25bfd9e17d520addf5ed2a60f1930278ff23866216584853f1287ac1, -0x3b391c2aa79c2a42888102cd99f1d2760b74f772c207a39a8515b6d18e66888a, -0xcc9ae3c14cbfb40bf01a09bcde913a3ed208e13e4b4edf54549eba2c0c948517, -0xc2b8bce78dd4e876da04c54a7053ca8b2bedc8c639cee82ee257c754c0bea2b2, -0xdb186f42871f438dba4d43755c59b81a6788cb3b544c0e1a3e463f6c2b6f7548, -0xb7f8ba137c7783137c0729de14855e20c2ac4416c33f5cac3b235d05acbab634, -0x282987e1f47e254e86d62bf681b0803df61340fdc9a8cf625ef2274f67fc6b5a, -0x04aa195b1aa736bf8875777e0aebf88147346d347613b5ab77bef8d1b502c08c, -0x3f732c559aee2b1e1117cf1dec4216a070259e4fa573a7dcadfa6aab74aec704, -0x72699d1351a59aa73fcede3856838953ee90c6aa5ef5f1f7e21c703fc0089083, -0x6d9ce1b8587e16a02218d5d5bed8e8d7da4ac40e1a8b46eeb412df35755c372c, -0x4f9c19b411c9a74b8616db1357dc0a7eaf213cb8cd2455a39eb7ae4515e7ff34, -0x9163dafa55b2b673fa7770b419a8ede4c7122e07919381225c240d1e90d90470, -0x268ff4507b42e623e423494d3bb0bc5c0917ee24996fb6d0ebedec9ce8cd9d5c, -0xff6e6169d233171ddc834e572024586eeb5b1bda9cb81e5ad1866dbc53dc75fe, -0xb379a9c8279205e8753b6a5c865fbbf70eb998f9005cd7cbde1511f81aed5256, -0x3a6b145e35a592e037c0992c9d259ef3212e17dca81045e446db2f3686380558, -0x60fb781d7b3137481c601871c1c3631992f4e01d415841b7f5414743dcb4cfd7, -0x90541b20b0c2ea49bca847e2db9b7bba5ce15b74e1d29194a12780e73686f3dd, -0xe2b0507c13ab66b4b769ad1a1a86834e385b315da2f716f7a7a8ff35a9e8f98c, -0xeefe54bc9fa94b921b20e7590979c28a97d8191d1074c7c68a656953e2836a72, -0x8676e7f59d6f2ebb0edda746fc1589ef55e07feab00d7008a0f2f6f129b7bb3a, -0x78a3d93181b40152bd5a8d84d0df7f2adde5db7529325c13bc24a5b388aed3c4, -0xcc0e2d0cba7aaa19c874dbf0393d847086a980628f7459e9204fda39fad375c0, -0x6e46a52cd7745f84048998df1a966736d2ac09a95a1c553016fef6b9ec156575, -0x204ac2831d2376d4f9c1f5c106760851da968dbfc488dc8a715d1c764c238263, -0xbdb8cc7b7e5042a947fca6c000c10b9b584e965c3590f92f6af3fe4fb23e1358, -0x4a55e4b8a138e8508e7b11726f617dcf4155714d4600e7d593fd965657fcbd89, -0xdfe064bb37f28d97b16d58b575844964205e7606dce914a661f2afa89157c45b, -0x560e374fc0edda5848eef7ff06471545fcbdd8aefb2ecddd35dfbb4cb03b7ddf, -0x10a66c82e146da5ec6f48b614080741bc51322a60d208a87090ad7c7bf6b71c6, -0x62534c7dc682cbf356e6081fc397c0a17221b88508eaeff798d5977f85630d4f, -0x0138bba8de2331861275356f6302b0e7424bbc74d88d8c534479e17a3494a15b, -0x580c7768bf151175714b4a6f2685dc5bcfeb088706ee7ed5236604888b84d3e4, -0xd290adb1a5dfc69da431c1c0c13da3be788363238d7b46bc20185edb45ab9139, -0x1689879db6c78eb4d3038ed81be1bc106f8cfa70a7c6245bd4be642bfa02ebd7, -0x6064c384002c8b1594e738954ed4088a0430316738def62822d08b2285514918, -0x01fd23493f4f1cc3c5ff4e96a9ee386b2a144b50a428a6b5db654072bddadfe7, -0xd5d05bb7f23ab0fa2b82fb1fb14ac29c2477d81a85423d0a45a4b7d5bfd81619, -0xd72b9a73ae7b24db03b84e01106cea734d4b9d9850b0b7e9d65d6001d859c772, -0x156317cb64578db93fee2123749aff58c81eae82b189b0d6f466f91de02b59df, -0x5fba299f3b2c099edbac18d785be61852225890fc004bf6be0787d62926a79b3, -0x004154f28f685bdbf0f0d6571e7a962a4c29b6c3ebedaaaf66097dfe8ae5f756, -0x4b45816f9834c3b289affce7a3dc80056c2b7ffd3e3c250d6dff7f923e7af695, -0x6ca53bc37816fff82346946d83bef87860626bbee7fd6ee9a4aeb904d893a11f, -0xf48b2f43184358d66d5b5f7dd2b14a741c7441cc7a33ba3ebcc94a7b0192d496, -0x3cb98f4baa429250311f93b46e745174f65f901fab4eb8075d380908aaaef650, -0x343dfc26b4473b3a20e706a8e87e5202a4e6b96b53ed448afb9180c3f766e5f8, -0x1ace0e8a735073bcbaea001af75b681298ef3b84f1dbab46ea52cee95ab0e7f9, -0xd239b110dd71460cdbc41ddc99494a7531186c09da2a697d6351c116e667733b, -0x22d6955236bd275969b8a6a30c23932670a6067f68e236d2869b6a8b4b493b83, -0x53c1c01f8d061ac89187e5815ef924751412e6a6aa4dc8e3abafb1807506b4e0, -0x2f56dd20c44d7370b713e7d7a1bfb1a800cac33f8a6157f278e17a943806a1f7, -0xc99773d8a5b3e60115896a65ac1d6c15863317d403ef58b90cb89846f4715a7f, -0x9f4b6b77c254094621cd336da06fbc6cbb7b8b1d2afa8e537ceca1053c561ef5, -0x87944d0b210ae0a6c201cba04e293f606c42ebaed8b4a5d1c33f56863ae7e1b5, -0xa7d116d962d03ca31a455f9cda90f33638fb36d3e3506605aa19ead554487a37, -0x4042e32e224889efd724899c9edb57a703e63a404129ec99858048fbc12f2ce0, -0x36759f7a0faeea1cd4cb91e404e4bf09908de6e53739603d5f0db52b664158a3, -0xa4d50d005fb7b9fea8f86f1c92439cc9b8446efef7333ca03a8f6a35b2d49c38, -0x80cb7c3e20f619006542edbe71837cdadc12161890a69eea8f41be2ee14c08a3, -0xbb3c44e1df45f2bb93fb80e7f82cee886c153ab484c0095b1c18df03523629b4, -0x04cb749e70fac3ac60dea779fceb0730b2ec5b915b0f8cf28a6246cf6da5db29, -0x4f5189b8f650687e65a962ef3372645432b0c1727563777433ade7fa26f8a728, -0x322eddddf0898513697599b68987be5f88c0258841affec48eb17cf3f61248e8, -0x6416be41cda27711d9ec22b3c0ed4364ff6975a24a774179c52ef7e6de9718d6, -0x0622d31b8c4ac7f2e30448bdadfebd5baddc865e0759057a6bf7d2a2c8b527e2, -0x40f096513588cc19c08a69e4a48ab6a43739df4450b86d3ec2fb3c6a743b5485, -0x09fcf7d49290785c9ea2d54c3d63f84f6ea0a2e9acfcdbb0cc3a281ce438250e, -0x2000a519bf3da827f580982d449b5c70fcc0d4fa232addabe47bb8b1c471e62e, -0xf4f80008518e200c40b043f34fb87a6f61b82f8c737bd784292911af3740245e, -0x939eaab59f3d2ad49e50a0220080882319db7633274a978ced03489870945a65, -0xadcad043d8c753fb10689280b7670f313253f5d719039e250a673d94441ee17c, -0x58b7b75f090166b8954c61057074707d7e38d55ce39d9b2251bbc3d72be458f8, -0xf61031890c94c5f87229ec608f2a9aa0a3f455ba8094b78395ae312cbfa04087, -0x356a55def50139f94945e4ea432e7a9defa5db7975462ebb6ca99601c614ea1d, -0x65963bb743d5db080005c4db59e29c4a4e86f92ab1dd7a59f69ea7eaf8e9aa79] -lamport_1 = [0x9c0bfb14de8d2779f88fc8d5b016f8668be9e231e745640096d35dd5f53b0ae2, -0x756586b0f3227ab0df6f4b7362786916bd89f353d0739fffa534368d8d793816, -0x710108dddc39e579dcf0819f9ad107b3c56d1713530dd94325db1d853a675a37, -0x8862b5f428ce5da50c89afb50aa779bb2c4dfe60e6f6a070b3a0208a4a970fe5, -0x54a9cd342fa3a4bf685c01d1ce84f3068b0d5b6a58ee22dda8fbac4908bb9560, -0x0fa3800efeaddd28247e114a1cf0f86b9014ccae9c3ee5f8488168b1103c1b44, -0xbb393428b7ebfe2eda218730f93925d2e80c020d41a29f4746dcbb9138f7233a, -0x7b42710942ef38ef2ff8fe44848335f26189c88c22a49fda84a51512ac68cd5d, -0x90e99786a3e8b04db95ccd44d01e75558d75f3ddd12a1e9a2c2ce76258bf4813, -0x3f6f71e40251728aa760763d25deeae54dc3a9b53807c737deee219120a2230a, -0xe56081a7933c6eaf4ef2c5a04e21ab8a3897785dd83a34719d1b62d82cfd00c2, -0x76cc54fa15f53e326575a9a2ac0b8ed2869403b6b6488ce4f3934f17db0f6bee, -0x1cd9cd1d882ea3830e95162b5de4beb5ddff34fdbf7aec64e83b82a6d11b417c, -0xb8ca8ae36d717c448aa27405037e44d9ee28bb8c6cc538a5d22e4535c8befd84, -0x5c4492108c25f873a23d5fd7957b3229edc22858e8894febe7428c0831601982, -0x907bcd75e7465e9791dc34e684742a2c0dc7007736313a95070a7e6b961c9c46, -0xe7134b1511559e6b2440672073fa303ec3915398e75086149eb004f55e893214, -0x2ddc2415e4753bfc383d48733e8b2a3f082883595edc5515514ebb872119af09, -0xf2ad0f76b08ffa1eee62228ba76f4982fab4fbede5d4752c282c3541900bcd5b, -0x0a84a6b15abd1cbc2da7092bf7bac418b8002b7000236dfba7c8335f27e0f1d4, -0x97404e02b9ff5478c928e1e211850c08cc553ebac5d4754d13efd92588b1f20d, -0xfa6ca3bcff1f45b557cdec34cb465ab06ade397e9d9470a658901e1f0f124659, -0x5bd972d55f5472e5b08988ee4bccc7240a8019a5ba338405528cc8a38b29bc21, -0x52952e4f96c803bb76749800891e3bfe55f7372facd5b5a587a39ac10b161bcc, -0xf96731ae09abcad016fd81dc4218bbb5b2cb5fe2e177a715113f381814007314, -0xe7d79e07cf9f2b52623491519a21a0a3d045401a5e7e10dd8873a85076616326, -0xe4892f3777a4614ee6770b22098eaa0a3f32c5c44b54ecedacd69789d676dffe, -0x20c932574779e2cc57780933d1dc6ce51a5ef920ce5bf681f7647ac751106367, -0x057252c573908e227cc07797117701623a4835f4b047dcaa9678105299e48e70, -0x20bad780930fa2a036fe1dea4ccbf46ac5b3c489818cdb0f97ae49d6e2f11fbf, -0xc0d7dd26ffecdb098585a1694e45a54029bb1e31c7c5209289058efebb4cc91b, -0x9a8744beb1935c0abe4b11812fc02748ef7c8cb650db3024dde3c5463e9d8714, -0x8ce6eea4585bbeb657b326daa4f01f6aef34954338b3ca42074aedd1110ba495, -0x1c85b43f5488b370721290d2faea19d9918d094c99963d6863acdfeeca564363, -0xe88a244347e448349e32d0525b40b18533ea227a9d3e9b78a9ff14ce0a586061, -0x352ca61efc5b8ff9ee78e738e749142dd1606154801a1449bbb278fa6bcc3dbe, -0xa066926f9209220b24ea586fb20eb8199a05a247c82d7af60b380f6237429be7, -0x3052337ccc990bfbae26d2f9fe5d7a4eb8edfb83a03203dca406fba9f4509b6e, -0x343ce573a93c272688a068d758df53c0161aa7f9b55dec8beced363a38b33069, -0x0f16b5593f133b58d706fe1793113a10750e8111eadee65301df7a1e84f782d3, -0x808ae8539357e85b648020f1e9d255bc4114bee731a6220d7c5bcb5b85224e03, -0x3b2bd97e31909251752ac57eda6015bb05b85f2838d475095cfd146677430625, -0xe4f857c93b2d8b250050c7381a6c7c660bd29066195806c8ef11a2e6a6640236, -0x23d91589b5070f443ddcefa0838c596518d54928119251ecf3ec0946a8128f52, -0xb72736dfad52503c7f5f0c59827fb6ef4ef75909ff9526268abc0f296ee37296, -0x80a8c66436d86b8afe87dde7e53a53ef87e057a5d4995963e76d159286de61b6, -0xbec92c09ee5e0c84d5a8ba6ca329683ff550ace34631ea607a3a21f99cd36d67, -0x83c97c9807b9ba6d9d914ae49dabdb4c55e12e35013f9b179e6bc92d5d62222b, -0x8d9c79f6af3920672dc4cf97a297c186e75083d099aeb5c1051207bad0c98964, -0x2aaa5944a2bd852b0b1be3166e88f357db097b001c1a71ba92040b473b30a607, -0x46693d27ec4b764fbb516017c037c441f4558aebfe972cdcd03da67c98404e19, -0x903b25d9e12208438f203c9ae2615b87f41633d5ffda9cf3f124c1c3922ba08f, -0x3ec23dc8bc1b49f5c7160d78008f3f235252086a0a0fa3a7a5a3a53ad29ec410, -0xa1fe74ceaf3cccd992001583a0783d7d7b7a245ea374f369133585b576b9c6d8, -0xb2d6b0fe4932a2e06b99531232398f39a45b0f64c3d4ebeaaebc8f8e50a80607, -0xe19893353f9214eebf08e5d83c6d44c24bffe0eceee4dc2e840d42eab0642536, -0x5b798e4bc099fa2e2b4b5b90335c51befc9bbab31b4dd02451b0abd09c06ee79, -0xbab2cdec1553a408cac8e61d9e6e19fb8ccfb48efe6d02bd49467a26eeeca920, -0x1c1a544c28c38e5c423fe701506693511b3bc5f2af9771b9b2243cd8d41bebfc, -0x704d6549d99be8cdefeec9a58957f75a2be4af7bc3dc4655fa606e7f3e03b030, -0x051330f43fe39b08ed7d82d68c49b36a8bfa31357b546bfb32068712df89d190, -0xe69174c7b03896461cab2dfaab33d549e3aac15e6b0f6f6f466fb31dae709b9b, -0xe5f668603e0ddbbcde585ac41c54c3c4a681fffb7a5deb205344de294758e6ac, -0xca70d5e4c3a81c1f21f246a3f52c41eaef9a683f38eb7c512eac8b385f46cbcd, -0x3173a6b882b21cd147f0fc60ef8f24bbc42104caed4f9b154f2d2eafc3a56907, -0xc71469c192bf5cc36242f6365727f57a19f924618b8a908ef885d8f459833cc3, -0x59c596fc388afd8508bd0f5a1e767f3dda9ed30f6646d15bc59f0b07c4de646f, -0xb200faf29368581f551bd351d357b6fa8cbf90bdc73b37335e51cad36b4cba83, -0x275cede69b67a9ee0fff1a762345261cb20fa8191470159cc65c7885cfb8313c, -0x0ce4ef84916efbe1ba9a0589bed098793b1ea529758ea089fd79151cc9dc7494, -0x0f08483bb720e766d60a3cbd902ce7c9d835d3f7fdf6dbe1f37bcf2f0d4764a2, -0xb30a73e5db2464e6da47d10667c82926fa91fceb337d89a52db5169008bc6726, -0x6b9c50fed1cc404bf2dd6fffbfd18e30a4caa1500bfeb080aa93f78d10331aaf, -0xf17c84286df03ce175966f560600dd562e0f59f18f1d1276b4d8aca545d57856, -0x11455f2ef96a6b2be69854431ee219806008eb80ea38c81e45b2e58b3f975a20, -0x9a61e03e2157a5c403dfcde690f7b7d704dd56ea1716cf14cf7111075a8d6491, -0x30312c910ce6b39e00dbaa669f0fb7823a51f20e83eaeb5afa63fb57668cc2f4, -0x17c18d261d94fba82886853a4f262b9c8b915ed3263b0052ece5826fd7e7d906, -0x2d8f6ea0f5b9d0e4bc1478161f5ed2ad3d8495938b414dcaec9548adbe572671, -0x19954625f13d9bab758074bf6dee47484260d29ee118347c1701aaa74abd9848, -0x842ef2ad456e6f53d75e91e8744b96398df80350cf7af90b145fea51fbbcf067, -0x34a8b0a76ac20308aa5175710fb3e75c275b1ff25dba17c04e3a3e3c48ca222c, -0x58efcbe75f32577afe5e9ff827624368b1559c32fcca0cf4fd704af8ce019c63, -0x411b4d242ef8f14d92bd8b0b01cb4fa3ca6f29c6f9073cfdd3ce614fa717463b, -0xf76dbda66ede5e789314a88cff87ecb4bd9ca418c75417d4d920e0d21a523257, -0xd801821a0f87b4520c1b003fe4936b6852c410ee00b46fb0f81621c9ac6bf6b4, -0x97ad11d6a29c8cf3c548c094c92f077014de3629d1e9053a25dbfaf7eb55f72d, -0xa87012090cd19886d49521d564ab2ad0f18fd489599050c42213bb960c9ee8ff, -0x8868d8a26e758d50913f2bf228da0444a206e52853bb42dd8f90f09abe9c859a, -0xc257fb0cc9970e02830571bf062a14540556abad2a1a158f17a18f14b8bcbe95, -0xfe611ce27238541b14dc174b652dd06719dfbcda846a027f9d1a9e8e9df2c065, -0xc9b25ea410f420cc2d4fc6057801d180c6cab959bce56bf6120f555966e6de6d, -0x95437f0524ec3c04d4132c83be7f1a603e6f4743a85ede25aa97a1a4e3f3f8fc, -0x82a12910104065f35e983699c4b9187aed0ab0ec6146f91728901efecc7e2e20, -0x6622dd11e09252004fb5aaa39e283333c0686065f228c48a5b55ee2060dbd139, -0x89a2879f25733dab254e4fa6fddb4f04b8ddf018bf9ad5c162aea5c858e6faaa, -0x8a71b62075a6011fd9b65d956108fa79cc9ebb8f194d64d3105a164e01cf43a6, -0x103f4fe9ce211b6452181371f0dc4a30a557064b684645a4495136f4ebd0936a, -0x97914adc5d7ce80147c2f44a6b29d0b495d38dedd8cc299064abcc62ed1ddabc, -0x825c481da6c836a8696d7fda4b0563d204a9e7d9e4c47b46ded26db3e2d7d734, -0xf8c0637ba4c0a383229f1d730db733bc11d6a4e33214216c23f69ec965dcaaad, -0xaed3bdaf0cb12d37764d243ee0e8acdefc399be2cabbf1e51dc43454efd79cbd, -0xe8427f56cc5cec8554e2f5f586b57adccbea97d5fc3ef7b8bbe97c2097cf848c, -0xba4ad0abd5c14d526357fd0b6f8676ef6126aeb4a6d80cabe1f1281b9d28246c, -0x4cff20b72e2ab5af3fafbf9222146949527c25f485ec032f22d94567ff91b22f, -0x0d32925d89dd8fed989912afcbe830a4b5f8f7ae1a3e08ff1d3a575a77071d99, -0xe51a1cbeae0be5d2fdbc7941aea904d3eade273f7477f60d5dd6a12807246030, -0xfb8615046c969ef0fa5e6dc9628c8a9880e86a5dc2f6fc87aff216ea83fcf161, -0x64dd705e105c88861470d112c64ca3d038f67660a02d3050ea36c34a9ebf47f9, -0xb6ad148095c97528180f60fa7e8609bf5ce92bd562682092d79228c2e6f0750c, -0x5bae0cd81f3bd0384ca3143a72068e6010b946462a73299e746ca639c026781c, -0xc39a0fc7764fcfc0402b12fb0bbe78fe3633cbfb33c7f849279585a878a26d7c, -0x2b752fda1c0c53d685cc91144f78d371db6b766725872b62cc99e1234cca8c1a, -0x40ee6b9635d87c95a528757729212a261843ecb06d975de91352d43ca3c7f196, -0x75e2005d3726cf8a4bb97ea5287849a361e3f8fdfadc3c1372feed1208c89f6b, -0x0976f8ab556153964b58158678a5297da4d6ad92e284da46052a791ee667aee4, -0xdbeef07841e41e0672771fb550a5b9233ae8e9256e23fa0d34d5ae5efe067ec8, -0xa890f412ab6061c0c5ee661e80d4edc5c36b22fb79ac172ddd5ff26a7dbe9751, -0xb666ae07f9276f6d0a33f9efeb3c5cfcba314fbc06e947563db92a40d7a341e8, -0x83a082cf97ee78fbd7f31a01ae72e40c2e980a6dab756161544c27da86043528, -0xfa726a919c6f8840c456dc77b0fec5adbed729e0efbb9317b75f77ed479c0f44, -0xa8606800c54faeab2cbc9d85ff556c49dd7e1a0476027e0f7ce2c1dc2ba7ccbf, -0x2796277836ab4c17a584c9f6c7778d10912cb19e541fb75453796841e1f6cd1c, -0xf648b8b3c7be06f1f8d9cda13fd6d60f913e5048a8e0b283b110ca427eeb715f, -0xa21d00b8fdcd77295d4064e00fbc30bed579d8255e9cf3a9016911d832390717, -0xe741afcd98cbb3bb140737ed77bb968ac60d5c00022d722f9f04f56e97235dc9, -0xbeecc9638fac39708ec16910e5b02c91f83f6321f6eb658cf8a96353cfb49806, -0x912eee6cabeb0fed8d6e6ca0ba61977fd8e09ea0780ff8fbec995e2a85e08b52, -0xc665bc0bb121a1229bc56ecc07a7e234fd24c523ea14700aa09e569b5f53ad33, -0x39501621c2bdff2f62ab8d8e3fe47fe1701a98c665697c5b750ee1892f11846e, -0x03d32e16c3a6c913daefb139f131e1e95a742b7be8e20ee39b785b4772a50e44, -0x4f504eb46a82d440f1c952a06f143994bc66eb9e3ed865080cd9dfc6d652b69c, -0xad753dc8710a46a70e19189d8fc7f4c773e4d9ccc7a70c354b574fe377328741, -0xf7f5464a2d723b81502adb9133a0a4f0589b4134ca595a82e660987c6b011610, -0x216b60b1c3e3bb4213ab5d43e04619d13e1ecedbdd65a1752bda326223e3ca3e, -0x763664aa96d27b6e2ac7974e3ca9c9d2a702911bc5d550d246631965cf2bd4a2, -0x292b5c8c8431b040c04d631f313d4e6b67b5fd3d4b8ac9f2edb09d13ec61f088, -0x80db43c2b9e56eb540592f15f5900222faf3f75ce62e78189b5aa98c54568a5e, -0x1b5fdf8969bcd4d65e86a2cefb3a673e18d587843f4f50db4e3ee77a0ba2ef1c, -0x11e237953fff3e95e6572da50a92768467ffdfd0640d3384aa1c486357e7c24a, -0x1fabd4faa8dba44808cc87d0bc389654a98496745578f3d17d134adc7f7b10f3, -0x5eca4aa96f20a56197772ae6b600762154ca9d2702cab12664ea47cbff1a440c, -0x0b4234f5bb02abcf3b5ce6c44ea85f55ec7db98fa5a7b90abef6dd0df034743c, -0x316761e295bf350313c4c92efea591b522f1df4211ce94b22e601f30aefa51ef, -0xe93a55ddb4d7dfe02598e8f909ff34b3de40a1c0ac8c7fba48cb604ea60631fb, -0xe6e6c877b996857637f8a71d0cd9a6d47fdeb03752c8965766f010073332b087, -0xa4f95c8874e611eddd2c4502e4e1196f0f1be90bfc37db35f8588e7d81d34aeb, -0x9351710a5633714bb8b2d226e15ba4caa6f50f56c5508e5fa1239d5cc6a7e1aa, -0x8d0aef52ec7266f37adb572913a6213b8448caaf0384008373dec525ae6cdff1, -0x718e24c3970c85bcb14d2763201812c43abac0a7f16fc5787a7a7b2f37288586, -0x3600ce44cebc3ee46b39734532128eaf715c0f3596b554f8478b961b0d6e389a, -0x50dd1db7b0a5f6bd2d16252f43254d0f5d009e59f61ebc817c4bbf388519a46b, -0x67861ed00f5fef446e1f4e671950ac2ddae1f3b564f1a6fe945e91678724ef03, -0x0e332c26e169648bc20b4f430fbf8c26c6edf1a235f978d09d4a74c7b8754aad, -0x6c9901015adf56e564dfb51d41a82bde43fb67273b6911c9ef7fa817555c9557, -0x53c83391e5e0a024f68d5ade39b7a769f10664e12e4942c236398dd5dbce47a1, -0x78619564f0b2399a9fcb229d938bf1e298d62b03b7a37fe6486034185d7f7d27, -0x4625f15381a8723452ec80f3dd0293c213ae35de737c508f42427e1735398c3a, -0x69542425ddb39d3d3981e76b41173eb1a09500f11164658a3536bf3e292f8b6a, -0x82ac4f5bb40aece7d6706f1bdf4dfba5c835c09afba6446ef408d8ec6c09300f, -0x740f9180671091b4c5b3ca59b9515bd0fc751f48e488a9f7f4b6848602490e21, -0x9a04b08b4115986d8848e80960ad67490923154617cb82b3d88656ec1176c24c, -0xf9ffe528eccffad519819d9eef70cef317af33899bcaee16f1e720caf9a98744, -0x46da5e1a14b582b237f75556a0fd108c4ea0d55c0edd8f5d06c59a42e57410df, -0x098f3429c8ccda60c3b5b9755e5632dd6a3f5297ee819bec8de2d8d37893968a, -0x1a5b91af6025c11911ac072a98b8a44ed81f1f3c76ae752bd28004915db6f554, -0x8bed50c7cae549ed4f8e05e02aa09b2a614c0af8eec719e4c6f7aee975ec3ec7, -0xd86130f624b5dcc116f2dfbb5219b1afde4b7780780decd0b42694e15c1f8d8b, -0x4167aa9bc0075f624d25d40eb29139dd2c452ebf17739fab859e14ac6765337a, -0xa258ce5db20e91fb2ea30d607ac2f588bdc1924b21bbe39dc881e19889a7f5c6, -0xe5ef8b5ab3cc8894452d16dc875b69a55fd925808ac7cafef1cd19485d0bb50a, -0x120df2b3975d85b6dfca56bb98a82025ade5ac1d33e4319d2e0105b8de9ebf58, -0xc964291dd2e0807a468396ebba3d59cfe385d949f6d6215976fc9a0a11de209a, -0xf23f14cb709074b79abe166f159bc52b50de687464df6a5ebf112aa953c95ad5, -0x622c092c9bd7e30f880043762e26d8e9c73ab7c0d0806f3c5e472a4152b35a93, -0x8a5f090662731e7422bf651187fb89812419ab6808f2c62da213d6944fccfe9f, -0xfbea3c0d92e061fd2399606f42647d65cc54191fa46d57b325103a75f5c22ba6, -0x2babfbcc08d69b52c3747ddc8dcad4ea5511edabf24496f3ff96a1194d6f680e, -0x4d3d019c28c779496b616d85aee201a3d79d9eecf35f728d00bcb12245ace703, -0xe76fcee1f08325110436f8d4a95476251326b4827399f9b2ef7e12b7fb9c4ba1, -0x4884d9c0bb4a9454ea37926591fc3eed2a28356e0506106a18f093035638da93, -0x74c3f303d93d4cc4f0c1eb1b4378d34139220eb836628b82b649d1deb519b1d3, -0xacb806670b278d3f0c84ba9c7a68c7df3b89e3451731a55d7351468c7c864c1c, -0x8660fb8cd97e585ea7a41bccb22dd46e07eee8bbf34d90f0f0ca854b93b1ebee, -0x2fc9c89cdca71a1c0224d469d0c364c96bbd99c1067a7ebe8ef412c645357a76, -0x8ec6d5ab6ad7135d66091b8bf269be44c20af1d828694cd8650b5479156fd700, -0x50ab4776e8cabe3d864fb7a1637de83f8fbb45d6e49645555ffe9526b27ebd66, -0xbf39f5e17082983da4f409f91c7d9059acd02ccbefa69694aca475bb8d40b224, -0x3135b3b981c850cc3fe9754ec6af117459d355ad6b0915beb61e84ea735c31bf, -0xa7971dab52ce4bf45813223b0695f8e87f64b614c9c5499faac6f842e5c41be9, -0x9e480f5617323ab104b4087ac4ef849a5da03427712fb302ac085507c77d8f37, -0x57a6d474654d5e8d408159be39ad0e7026e6a4c6a6543e23a63d30610dc8dfc1, -0x09eb3e01a5915a4e26d90b4c58bf0cf1e560fdc8ba53faed9d946ad3e9bc78fa, -0x29c6d25da80a772310226b1b89d845c7916e4a4bc94d75aa330ec3eaa14b1e28, -0x1a1ccfee11edeb989ca02e3cb89f062612a22a69ec816a625835d79370173987, -0x1cb63dc541cf7f71c1c4e8cabd2619c3503c0ea1362dec75eccdf1e9efdbfcfc, -0xac9dff32a69e75b396a2c250e206b36c34c63b955c9e5732e65eaf7ccca03c62, -0x3e1b4f0c3ebd3d38cec389720147746774fc01ff6bdd065f0baf2906b16766a8, -0x5cc8bed25574463026205e90aad828521f8e3d440970d7e810d1b46849681db5, -0x255185d264509bd3a768bb0d50b568e66eb1fec96d573e33aaacc716d7c8fb93, -0xe81b86ba631973918a859ff5995d7840b12511184c2865401f2693a71b9fa07e, -0x61e67e42616598da8d36e865b282127c761380d3a56d26b8d35fbbc7641433c5, -0x60c62ffef83fe603a34ca20b549522394e650dad5510ae68b6e074f0cd209a56, -0x78577f2caf4a54f6065593535d76216f5f4075af7e7a98b79571d33b1822920c, -0xfd4cb354f2869c8650200de0fe06f3d39e4dbebf19b0c1c2677da916ea84f44d, -0x453769cef6ff9ba2d5c917982a1ad3e2f7e947d9ea228857556af0005665e0b0, -0xe567f93f8f88bf1a6b33214f17f5d60c5dbbb531b4ab21b8c0b799b6416891e0, -0x7e65a39a17f902a30ceb2469fe21cba8d4e0da9740fcefd5c647c81ff1ae95fa, -0x03e4a7eea0cd6fc02b987138ef88e8795b5f839636ca07f6665bbae9e5878931, -0xc3558e2b437cf0347cabc63c95fa2710d3f43c65d380feb998511903f9f4dcf0, -0xe3a615f80882fb5dfbd08c1d7a8b0a4d3b651d5e8221f99b879cb01d97037a9c, -0xb56db4a5fea85cbffaee41f05304689ea321c40d4c108b1146fa69118431d9b2, -0xab28e1f077f18117945910c235bc9c6f9b6d2b45e9ef03009053006c637e3e26, -0xefcabc1d5659fd6e48430dbfcc9fb4e08e8a9b895f7bf9b3d6c7661bfc44ada2, -0xc7547496f212873e7c3631dafaca62a6e95ac39272acf25a7394bac6ea1ae357, -0xc482013cb01bd69e0ea9f447b611b06623352e321469f4adc739e3ee189298eb, -0x5942f42e91e391bb44bb2c4d40da1906164dbb6d1c184f00fa62899baa0dba2c, -0xb4bcb46c80ad4cd603aff2c1baf8f2c896a628a46cc5786f0e58dae846694677, -0xd0a7305b995fa8c317c330118fee4bfef9f65f70b54558c0988945b08e90ff08, -0x687f801b7f32fdfa7d50274cc7b126efedbdae8de154d36395d33967216f3086, -0xeb19ec10ac6c15ffa619fa46792971ee22a9328fa53bd69a10ed6e9617dd1bbf, -0xa2bb3f0367f62abdb3a9fa6da34b20697cf214a4ff14fd42826da140ee025213, -0x070a76511f32c882374400af59b22d88974a06fbc10d786dd07ca7527ebd8b90, -0x8f195689537b446e946b376ec1e9eb5af5b4542ab47be550a5700fa5d81440d5, -0x10cc09778699fc8ac109e7e6773f83391eeba2a6db5226fbe953dd8d99126ca5, -0x8cc839cb7dc84fd3b8c0c7ca637e86a2f72a8715cc16c7afb597d12da717530b, -0xa32504e6cc6fd0ee441440f213f082fcf76f72d36b5e2a0f3b6bdd50cdd825a2, -0x8f45151db8878e51eec12c450b69fa92176af21a4543bb78c0d4c27286e74469, -0x23f5c465bd35bcd4353216dc9505df68324a27990df9825a242e1288e40a13bb, -0x35f409ce748af33c20a6ae693b8a48ba4623de9686f9834e22be4410e637d24f, -0xb962e5845c1db624532562597a99e2acc5e434b97d8db0725bdeddd71a98e737, -0x0f8364f99f43dd52b4cfa9e426c48f7b6ab18dc40a896e96a09eceebb3363afe, -0xa842746868da7644fccdbb07ae5e08c71a6287ab307c4f9717eadb414c9c99f4, -0xa59064c6b7fe7d2407792d99ed1218d2dc2f240185fbd8f767997438241b92e9, -0xb6ea0d58e8d48e05b9ff4d75b2ebe0bd9752c0e2691882f754be66cdec7628d3, -0xf16b78c9d14c52b2b5156690b6ce37a5e09661f49674ad22604c7d3755e564d1, -0xbfa8ef74e8a37cd64b8b4a4260c4fc162140603f9c2494b9cf4c1e13de522ed9, -0xf4b89f1776ebf30640dc5ec99e43de22136b6ef936a85193ef940931108e408a, -0xefb9a4555d495a584dbcc2a50938f6b9827eb014ffae2d2d0aae356a57894de8, -0x0627a466d42a26aca72cf531d4722e0e5fc5d491f4527786be4e1b641e693ac2, -0x7d10d21542de3d8f074dbfd1a6e11b3df32c36272891aae54053029d39ebae10, -0x0f21118ee9763f46cc175a21de876da233b2b3b62c6f06fa2df73f6deccf37f3, -0x143213b96f8519c15164742e2350cc66e814c9570634e871a8c1ddae4d31b6b5, -0x8d2877120abae3854e00ae8cf5c8c95b3ede10590ab79ce2be7127239507e18d, -0xaccd0005d59472ac04192c059ed9c10aea42c4dabec9e581f6cb10b261746573, -0x67bc8dd5422f39e741b9995e6e60686e75d6620aa0d745b84191f5dba9b5bb18, -0x11b8e95f6a654d4373cefbbac29a90fdd8ae098043d1969b9fa7885318376b34, -0x431a0b8a6f08760c942eeff5791e7088fd210f877825ce4dcabe365e03e4a65c, -0x704007f11bae513f428c9b0d23593fd2809d0dbc4c331009856135dafec23ce4, -0xc06dee39a33a05e30c522061c1d9272381bde3f9e42fa9bd7d5a5c8ef11ec6ec, -0x66b4157baaae85db0948ad72882287a80b286df2c40080b8da4d5d3db0a61bd2, -0xef1983b1906239b490baaaa8e4527f78a57a0a767d731f062dd09efb59ae8e3d, -0xf26d0d5c520cce6688ca5d51dee285af26f150794f2ea9f1d73f6df213d78338, -0x8b28838382e6892f59c42a7709d6d38396495d3af5a8d5b0a60f172a6a8940bd, -0x261a605fa5f2a9bdc7cffac530edcf976e7ea7af4e443b625fe01ed39dad44b6] -compressed_lamport_PK = 0xdd635d27d1d52b9a49df9e5c0c622360a4dd17cba7db4e89bce3cb048fb721a5 -child_SK = 20397789859736650942317412262472558107875392172444076792671091975210932703118 -``` - -## Implementation - -* [Python](https://github.com/ethereum/eth2.0-deposit-cli) - -## 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-2333.md diff --git a/EIPS/eip-2334.md b/EIPS/eip-2334.md index 300a1ac794eeb2..1ef3c8d3734535 100644 --- a/EIPS/eip-2334.md +++ b/EIPS/eip-2334.md @@ -1,104 +1,7 @@ --- eip: 2334 -title: BLS12-381 Deterministic Account Hierarchy -author: Carl Beekhuizen -discussions-to: https://github.com/ethereum/EIPs/issues/2338 -status: Draft -type: Standards Track category: ERC -created: 2019-09-30 -requires: 2333 +status: Moved --- -## Simple Summary - -This EIP defines the purpose of a given key, or family thereof, within a tree of keys. When combined with [EIP-2333](./eip-2333.md), the combination of a seed and knowledge of the desired purpose of a key is sufficient to determine a key pair. - -## Abstract - -A standard for allocating keys generated by [EIP-2333](./eip-2333.md) to a specific purpose. It defines a `path` which is a string that parses into the indices to be used when traversing the tree of keys that [EIP-2333](./eip-2333.md) generates. - -## A note on purpose - -This specification is designed not only to be an Ethereum 2.0 standard, but one that is adopted by the wider community who have adopted the BLS12-381 signature standard. It is therefore important also to consider the needs of the wider industry along with those specific to Ethereum. As a part of these considerations, it is the intention of the author that this standard eventually migrate to a more neutral repository in the future. - -## Motivation - -Ethereum 2.0 alongside many other projects will use BLS12-381 signatures. This new scheme requires a new key derivation mechanism, which is established within [EIP-2333](./eip-2333.md). This new scheme is incompatible with the current form of this specification ([BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) due to the: exclusive use of hardened keys, the increased number of keys per level, not using [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) for key derivation. It is therefore necessary to establish a new *path* for traversing the [EIP-2333](./eip-2333.md) key-tree. - -The path structure specified in this EIP aims to be more general than [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) by not having UTXO-centric features [which gave rise to the 4 different types of wallet paths being used within Ethereum 1.0](https://github.com/ethereum/EIPs/issues/84#issuecomment-292324521) and gave rise to (draft) [EIP-600](./eip-600.md) & [EIP-601](./eip-601.md) - -## Specification - -### Path - -The path traversed through the tree of keys is defined by integers (which indicate the sibling index) separated by `/` which denote ancestor relations. There are 4 levels (plus the master node) in the path and at least 4 (5 including the master node) MUST be used. - -```text -m / purpose / coin_type / account / use -``` - -#### Notation - -The notation used within the path is specified within the [EIP-2333](./eip-2333.md), but is summarized again below for convenience. - -* `m` Denotes the master node (or root) of the tree -* `/` Separates the tree into depths, thus `i / j` signifies that `j` is a child of `i` - -### Purpose - -The `purpose` is set to `12381` which is the name of the new curve (BLS12-381). In order to be in compliance with this standard, the [EIP-2333](./eip-2333.md) MUST be implemented as the KDF and therefore, the purpose `12381` MAY NOT be used unless this is the case. - -### Coin Type - -The `coin_type` here reflects the coin number for an individual coin thereby acting as a means of separating the keys used for different chains. - -### Account - -`account` is a field that provides the ability for a user to have distinct sets of keys for different purposes, if they so choose. This is the level at which different accounts for a single user SHOULD to be implemented. - -### Use - -This level is designed to provide a set of related keys that can be used for any purpose. The idea being that a single account has many uses which are related yet should remain separate for security reasons. It is required to support this level in the tree, although, for many purposes it will remain `0`. - -### Eth2 Specific Parameters - -#### Coin type - -The coin type used for the BLS12-381 keys in Ethereum 2 is `3600`. - -#### Validator keys - -Each Eth2 validator has two keys, one for withdrawals and transfers (called the *withdrawal key*), and the other for performing their duties as a validator (henceforth referred to as the *signing key*). - -The path for withdrawal keys is `m/12381/3600/i/0` where `i` indicates the `i`th set of validator keys. - -The path for the signing key is `m/12381/3600/i/0/0` where again, `i` indicates the `i`th set of validator keys. Another way of phrasing this is that the signing key is the `0`th child of the associated withdrawal key for that validator. - -**Note:** If the above description of key paths is not feasible in a specific use case (eg. with secret-shared or custodial validators), then the affected keys may be omitted and derived via another means. Implementations of this EIP, must endeavour to use the appropriate keys for the given use case to the extent that is reasonably possible. (eg, in the case of custodial staking, the user making the deposits will follow this standard for their withdrawal keys which has no bearing on how the service provide derives the corresponding signing keys.) - -## Rationale - -`purpose`, `coin_type`, and `account` are widely-adopted terms as per [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) and therefore reusing these terms and their associated meanings makes sense. - -The purpose needs to be distinct from these standards as the KDF and path are not inter-compatible and `12381` is an obvious choice. - -`account` separates user activity into distinct categories thereby allowing users to separate their concerns however they desire. - -`use` will commonly be determined at the application level providing distinct keys for non-intersecting use cases. - -### Eth2 Specific Parameters - -A new coin type is chosen for Eth2 keys to help ensure a clean separation between Eth2 and Eth1 keys. Although the distinction between Eth1 ETH and Eth2 ETH is subtle, they are distinct entities and there are services which only distinguish between coins by their coin name (eg. [ENS' multichain address resolution](./eip-2304.md)). `3600` is chosen specifically because it is the square of the Eth1's `coin_type` (`3600==60^2`) thereby signaling that it is second instantiation of Ether the currency. - -The primary reason validators have separate signing and withdrawal keys is to allow for the different security concerns of actions within Eth2. The signing key is given to the validator client where it signs messages as per the requirements of being a validator, it is therefore a "hot key". If this key is compromised, the worst that can happen (locally) is that a slashable message is signed, resulting in the validator being slashed and forcibly exited. The withdrawal key is only needed when a validator wishes to perform an action not related to validating and has access to the full funds at stake for that validator. The withdrawal key therefore has higher security concerns and should be handled as a "cold key". By having the signing key be a child of the withdrawal key, secure storage of the withdrawal key is sufficient to recover the signing key should the need arise. - -## Backwards Compatibility - -[BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) are the commonly used standards for this purpose within Ethereum 1.0, however they have not been `Accepted` as standards as yet. Due to the use of a new KDF within [EIP-2333](./eip-2333.md), a new path standard is required. This EIP implements this, with minor changes. - -`purpose` `12381` paths do not support hardened keys and therefore the `'` character is invalid. - -## 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-2334.md diff --git a/EIPS/eip-2335.md b/EIPS/eip-2335.md index 4bad77e287bf12..31c28f3c0cb014 100644 --- a/EIPS/eip-2335.md +++ b/EIPS/eip-2335.md @@ -1,301 +1,7 @@ --- eip: 2335 -title: BLS12-381 Keystore -author: Carl Beekhuizen -discussions-to: https://github.com/ethereum/EIPs/issues/2339 -status: Draft -type: Standards Track category: ERC -created: 2019-09-30 -requires: 2333, 2334 +status: Moved --- -## Simple Summary - -A JSON format for the storage and interchange of BLS12-381 private keys. - -## Abstract - -A keystore is a mechanism for storing private keys. It is a JSON file that encrypts a private key and is the standard for interchanging keys between devices as until a user provides their password, their key is safe. - -## A note on purpose - -This specification is designed not only to be an Ethereum 2.0 standard, but one that is adopted by the wider community who have adopted the BLS12-381 signature standard. It is therefore important also to consider the needs of the wider industry along with those specific to Ethereum. As a part of these considerations, it is the intention of the author that this standard eventually migrate to a more neutral repository in the future. - -## Motivation - -The secure storage and exchange of keys is a vital component of the user experience as people are expected to hold their own keys. It allows users to control access to individual keys and their use by applications. - -In Ethereum 1, [the Web3 Secret Storage Definition](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) fulfills these requirements, however it is not perfectly suitable for these purposes moving forward. Specifically the problems with the existing standard are: - -* __The use of Keccak256.__ Eth1 keystores use Keccak for their checksum, a sensible choice considering its usage within Ethereum 1. BLS12-381 [signatures](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-00), [keys (EIP-2333)](./eip-2333.md), and key-storage are inter-chain standards, the establishment and proliferation of which hinges on them being neutral to all chains, something which Keccak is not. - -* __A lack of abstraction.__ Eth1 keystores are a result of an iterative design process whereby functionality was added and modified as needed without considering how abstractions could simplify the notion of different properties. - -## Specification - -The process of decrypting the secret held within a keystore can be broken down into 3 sub-processes: obtaining the decryption key, verifying the password and decrypting the secret. Each process has its own functions which can be selected from as well as parameters required for the function all of which are specified within the keystore file itself. - -### Password requirements - -The password is a string of arbitrary unicode characters. The password is first converted to its NFKD representation, then the control codes (specified below) are stripped from the password and finally it is UTF-8 encoded. - -#### Control codes removal - -The C0, C1, and `Delete` control codes are not valid characters in the password and should therefore be stripped from the password. C0 are the control codes between `0x00` - `0x1F` (inclusive) and C1 codes lie between `0x80` and `0x9F` (inclusive). `Delete`, commonly known as "backspace", is the UTF-8 character `7F` which must also be stripped. Note that space (`Sp` UTF-8 `0x20`) is a valid character in passwords despite it being a pseudo-control character. - -### Modules - -This standard makes use of the notion of a _module_ which serves to represent, in an abstract sense, the different  cryptographic constructions and corresponding parameters for each component of the keystore. The idea being that components can be swapped out without affecting the rest of the specification should the need arise. - -A module is comprised of a `function`, which defines which cryptographic construct is being used, `params`, the parameters required by the function, and `message` the primary input to the function. - -### Decryption key - -The decryption key is an intermediate key which is used both to verify the user-supplied password is correct, as well as for the final secret decryption. This key is simply derived from the password, the `function`, and the `params` specified by the`kdf` module as per the keystore file. - -| KDF | `"function"` | `"params"` | `"message"` | Definition | -|----------------|--------------|------------------------------------------------------------------------------------------|-------------|--------------------------------------------------| -| PBKDF2-SHA-256 | `"pbkdf2"` |
  • `"c"`
  • `"dklen"`
  • `"prf: "hmac-sha256"`
  • `"salt"`
| | [RFC 2898](https://www.ietf.org/rfc/rfc2898.txt) | -| scrypt | `"scrypt"` |
  • `"dklen"`
  • `"n"`
  • `"p"`
  • `"r"`
  • `"salt"`
| | [RFC 7914](https://tools.ietf.org/html/rfc7914) | - -### Password verification - -The password verification verifies step verifies that the password is correct with respect to the `checksum.message`, `cipher.message`, and `kdf`. This is done by appending the `cipher.message` to the 2nd 16 bytes of the decryption key, obtaining its SHA256 hash and verifying whether it matches the `checksum.message`. - -#### Inputs - -* `decryption_key`, the octet string obtained from decryption key process -* `cipher_message`, the octet string obtained from keystore file from `crypto.cipher.message` -* `checksum_message`, the octet string obtained from keystore file from `crypto.checksum.message` - -#### Outputs - -* `valid_password`, a boolean value indicating whether the password is valid - -#### Definitions - -* `a[0:3]` returns a slice of `a` including octets 0, 1, 2 -* `a | b` is the concatenation of `a` with `b` - -#### Procedure - -```text -0. DK_slice = decryption_key[16:32] -1. pre_image = DK_slice | cipher_message -2. checksum = SHA256(pre_image) -3. valid_password = checksum == checksum_message -4. return valid_password -``` - -| Hash | `"function"` | `"params"` | `"message"` | Definition | -|------------|-----------------|------------|-------------|-------------------------------------------------| -| SHA-256 | `"sha256"` | | | [RFC 6234](https://tools.ietf.org/html/rfc6234) | - -### Secret decryption - -The `cipher.function` encrypts the secret using the decryption key, thus to decrypt it, the decryption key along with the `cipher.function` and `cipher.params` must be used. If the `decryption_key` is longer than the key size required by the cipher, it is truncated to the correct number of bits. In the case of aes-128-ctr, only the first 16 bytes of the `decryption_key` are used as the AES key. - -| Cipher | `"function"` | `"params"` | `"message"` | Definition | -|----------------------|-----------------|--------------------------|-------------|-------------------------------------------------| -| AES-128 Counter Mode | `"aes-128-ctr"` |
  • `"iv"`
| | [RFC 3686](https://tools.ietf.org/html/rfc3686) | - -## Description - -This field is an optional field to help explain the purpose and identify a particular keystores in a user-friendly manner. While this field can, and should, be used to help distinguish keystores from one-another, the `description` **is not necessarily unique**. - -## PubKey - -The `pubkey` is the public key associated with the the private key secured within the keystore. It is stored here to improve user experience and security which is achieved by not requiring users to enter their password just to obtain their public keys. This field is required if the secret being stored within the keystore is a private key. The encoding of the `pubkey` is specified in the in the appropriate signature standard (eg. [BLS12-381 signature standard](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-00)), but can be seen as a byte-string in the abstract and should be directly compatible with the appropriate signature library. - -## Path - -The `path` indicates where in the key-tree a key originates from. It is a string defined by [EIP-2334](./eip-2334.md), if no path is known or the path is not relevant, the empty string, `""` indicates this. The `path` can specify an arbitrary depth within the tree and the deepest node within the tree indicates the depth of the key stored within this file. - -## UUID - -The `uuid` provided in the keystore is a randomly generated UUID as specified by [RFC 4122](https://tools.ietf.org/html/rfc4122). It is intended to be used as a 128-bit proxy for referring to a particular set of keys or account. - -## Version - -The `version` is set to `4`. - -## JSON schema - -The keystore, at its core, is constructed with modules which allow for the configuration of the cryptographic constructions used password hashing, password verification and secret decryption. Each module is composed of: `function`, `params`, and `message` which corresponds with which construction is to be used, what the configuration for the construction is, and what the input is. - -```json -{ - "$ref": "#/definitions/Keystore", - "definitions": { - "Keystore": { - "type": "object", - "properties": { - "crypto": { - "type": "object", - "properties": { - "kdf": { - "$ref": "#/definitions/Module" - }, - "checksum": { - "$ref": "#/definitions/Module" - }, - "cipher": { - "$ref": "#/definitions/Module" - } - } - }, - "description": { - "type": "string" - }, - "pubkey": { - "type": "string" - }, - "path": { - "type": "string" - }, - "uuid": { - "type": "string", - "format": "uuid" - }, - "version": { - "type": "integer" - } - }, - "required": [ - "crypto", - "path", - "uuid", - "version" - ], - "title": "Keystore" - }, - "Module": { - "type": "object", - "properties": { - "function": { - "type": "string" - }, - "params": { - "type": "object" - }, - "message": { - "type": "string" - } - }, - "required": [ - "function", - "message", - "params" - ] - } - } -} -``` - -## Rationale - -The rationale behind the design of this specification is largely the same as that behind the [Ethereum 1 keystore definition](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) except for the lack of support for Keccak (explained in [motivation above](#motivation)) and the notion of modules. - -Modules provide a very useful level of abstraction which allow the Key-Derivation-Function, Checksum, and Cipher to be thought of as instances of the same thing allowing for their substitution with minimal effort. - -The `version` is set to 4 to prevent collisions with the existing Ethereum keystore standard. - -## Backwards Compatibility - -This specification is not backwards compatible with the [existing keystore standard](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) due to the lack of Keccak256 checksums as explained above. While this format is capable of supporting Keccak checksums via the Checksum module, it would defeat the purpose of this standard to include it as this standard could no longer be considered neutral with respect to other projects in the industry. - -## Test Cases - -### Scrypt Test Vector - -Password `"𝔱𝔢𝔰𝔱𝔭𝔞𝔰𝔰𝔴𝔬𝔯𝔡🔑"` -Encoded Password: `0x7465737470617373776f7264f09f9491` -Secret `0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f` - -```json -{ - "crypto": { - "kdf": { - "function": "scrypt", - "params": { - "dklen": 32, - "n": 262144, - "p": 1, - "r": 8, - "salt": "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" - }, - "message": "" - }, - "checksum": { - "function": "sha256", - "params": {}, - "message": "d2217fe5f3e9a1e34581ef8a78f7c9928e436d36dacc5e846690a5581e8ea484" - }, - "cipher": { - "function": "aes-128-ctr", - "params": { - "iv": "264daa3f303d7259501c93d997d84fe6" - }, - "message": "06ae90d55fe0a6e9c5c3bc5b170827b2e5cce3929ed3f116c2811e6366dfe20f" - } - }, - "description": "This is a test keystore that uses scrypt to secure the secret.", - "pubkey": "9612d7a727c9d0a22e185a1c768478dfe919cada9266988cb32359c11f2b7b27f4ae4040902382ae2910c15e2b420d07", - "path": "m/12381/60/3141592653/589793238", - "uuid": "1d85ae20-35c5-4611-98e8-aa14a633906f", - "version": 4 -} -``` - -### PBKDF2 Test Vector - -Password `"𝔱𝔢𝔰𝔱𝔭𝔞𝔰𝔰𝔴𝔬𝔯𝔡🔑"` -Encoded Password: `0x7465737470617373776f7264f09f9491` -Secret `0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f` - -```json -{ - "crypto": { - "kdf": { - "function": "pbkdf2", - "params": { - "dklen": 32, - "c": 262144, - "prf": "hmac-sha256", - "salt": "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" - }, - "message": "" - }, - "checksum": { - "function": "sha256", - "params": {}, - "message": "8a9f5d9912ed7e75ea794bc5a89bca5f193721d30868ade6f73043c6ea6febf1" - }, - "cipher": { - "function": "aes-128-ctr", - "params": { - "iv": "264daa3f303d7259501c93d997d84fe6" - }, - "message": "cee03fde2af33149775b7223e7845e4fb2c8ae1792e5f99fe9ecf474cc8c16ad" - } - }, - "description": "This is a test keystore that uses PBKDF2 to secure the secret.", - "pubkey": "9612d7a727c9d0a22e185a1c768478dfe919cada9266988cb32359c11f2b7b27f4ae4040902382ae2910c15e2b420d07", - "path": "m/12381/60/0/0", - "uuid": "64625def-3331-4eea-ab6f-782f3ed16a83", - "version": 4 -} -``` - -## Implementation - -Implementations exist in the following languages: - -* [Python3](https://github.com/ethereum/eth2.0-deposit-cli) -* [TypeScript](https://github.com/nodefactoryio/bls-keystore) -* [Go](https://github.com/wealdtech/go-eth2-wallet-encryptor-keystorev4/) - -## 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-2335.md diff --git a/EIPS/eip-234.md b/EIPS/eip-234.md index 27b111a9104af7..29ab2346df52e7 100644 --- a/EIPS/eip-234.md +++ b/EIPS/eip-234.md @@ -2,10 +2,10 @@ 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: Last Call -review-period-end: 2020-08-08 +status: Final created: 2017-03-24 requires: 1474 --- @@ -28,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). @@ -46,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 index dde5598e4eb9cd..981f56d0253b87 100644 --- a/EIPS/eip-2364.md +++ b/EIPS/eip-2364.md @@ -1,9 +1,10 @@ --- eip: 2364 title: "eth/64: forkid-extended protocol handshake" -author: Péter Szilágyi +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: Draft +status: Final type: Standards Track category: Networking created: 2019-11-08 @@ -12,22 +13,22 @@ 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. -## Motivation - 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 -The specification is tiny since most parts are already specified in EIP-2124. `eth/63` is not specified as an EIP, but is maintained [here](https://github.com/ethereum/devp2p/blob/master/caps/eth.md). - - 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. @@ -40,15 +41,17 @@ Whenever two peers connect using the `eth/64` protocol, the updated `Status` mes ## Rationale -##### 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? +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 ([EIP-1459](./eip-1459.md))) still need a way to filter connections. +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? +### 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). @@ -64,12 +67,10 @@ This EIP does not change the consensus engine, thus does _not_ require a hard fo For calculating and validating fork IDs, see test cases in [EIP-2124](./eip-2124.md). -Testing proper advertising and validation at the networking level will require a [hive](https://github.com/ethereum/hive) test. - -## Implementation +## Security Considerations -Geth: https://github.com/ethereum/go-ethereum/pull/20140 +None. ## 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-2378.md b/EIPS/eip-2378.md index 6740a74f809132..7db43ca52872d1 100644 --- a/EIPS/eip-2378.md +++ b/EIPS/eip-2378.md @@ -3,7 +3,7 @@ eip: 2378 title: EIPs Eligible for Inclusion author: James Hancock (@MadeofTin) discussions-to: https://gitter.im/ethereum/EIPs -status: Draft +status: Stagnant type: Meta created: 2019-11-13 --- @@ -67,4 +67,4 @@ Development of clear specifications and pull requests to existing Ethereum Clien ## 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-2384.md b/EIPS/eip-2384.md index 2c7c39dd8accfe..e8079af021c592 100644 --- a/EIPS/eip-2384.md +++ b/EIPS/eip-2384.md @@ -37,4 +37,4 @@ Test cases shall be created once the specification is to be accepted by the deve 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2386.md b/EIPS/eip-2386.md index 0d3381e65bae47..a942265254e8ed 100644 --- a/EIPS/eip-2386.md +++ b/EIPS/eip-2386.md @@ -1,201 +1,7 @@ --- eip: 2386 -title: Ethereum 2 Hierarchical Deterministic Walletstore -author: Jim McDonald -discussions-to: https://ethereum-magicians.org/t/eip-2386-walletstore/3792 -status: Draft -type: Standards Track category: ERC -created: 2019-11-21 -requires: 2334, 2335 +status: Moved --- -## Simple Summary - -A JSON format for the storage and retrieval of Ethereum 2 hierarchical deterministic (HD) wallet definitions. - -## Abstract - -Ethereum has the concept of keystores: pieces of data that define a key (see [EIP-2335](https://eips.ethereum.org/EIPS/eip-2335) for details). This adds the concept of walletstores: stores that define wallets and how keys in said wallets are created. - -## Motivation - -Hierarchical deterministic wallets create keys from a _seed_ and a _path_. The seed needs to be accessible to create new keys, however it should also be protected to the same extent as private keys to stop it from becoming an easy attack vector. The path, or at least the variable part of it, needs to be stored to ensure that keys are not duplicated. Providing a standard method to do this can promote interoperability between wallets and similar software. - -Given that a wallet has an amount of data and metadata that is useful when accessing existing keys and creating new keys, standardizing this information and how it is stored allows it to be portable between different wallet providers with minimal effort. - -## Specification - -The elements of a hierarchical deterministic walletstore are as follows: - -### UUID - -The `uuid` provided in the walletstore is a randomly-generated type 4 UUID as specified by [RFC 4122](https://tools.ietf.org/html/rfc4122). It is intended to be used as a 128-bit proxy for referring to a particular wallet, used to uniquely identify wallets. - -This element MUST be present. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -### Name - -The `name` provided in the walletstore is a UTF-8 string. It is intended to serve as the user-friendly accessor. The only restriction on the name is that it MUST NOT start with the underscore (`_`) character. - -This element MUST be present. It MUST be a string. - -### Version - -The `version` provided is the version of the walletstore. - -This element MUST be present. It MUST be the integer `1`. - -### Type - -The `type` provided is the type of wallet. This informs mechanisms such as key generation. - -This element MUST be present. It MUST be the string `hierarchical deterministic`. - -### Crypto - -The `crypto` provided is the secure storage of a secret for wallets that require this information. For hierarchical deterministic wallets this is the seed from which they calculate individual private keys. - -This element MUST be present. It MUST be an object that follows the definition described in [EIP-2335](https://eips.ethereum.org/EIPS/eip-2335). - -### Next Account - -The `nextaccount` provided is the index to be supplied to the path `m/12381/60//0` when creating a new private key from the seed. The path follows [EIP-2334](https://eips.ethereum.org/EIPS/eip-2334). - -This element MUST be present if the wallet type requires it. It MUST be a non-negative integer. - -### JSON schema - -The walletstore follows a similar format to that of the keystore described in [EIP-2335](https://eips.ethereum.org/EIPS/eip-2335). - -```json -{ - "$ref": "#/definitions/Walletstore", - "definitions": { - "Walletstore": { - "type": "object", - "properties": { - "crypto": { - "type": "object", - "properties": { - "kdf": { - "$ref": "#/definitions/Module" - }, - "checksum": { - "$ref": "#/definitions/Module" - }, - "cipher": { - "$ref": "#/definitions/Module" - } - } - }, - "name": { - "type": "string" - }, - "nextaccount": { - "type": "integer" - }, - "type": { - "type": "string" - }, - "uuid": { - "type": "string", - "format": "uuid" - }, - "version": { - "type": "integer" - } - }, - "required": [ - "name", - "type", - "uuid", - "version" - "crypto" - "nextaccount" - ], - "title": "Walletstore" - }, - "Module": { - "type": "object", - "properties": { - "function": { - "type": "string" - }, - "params": { - "type": "object" - }, - "message": { - "type": "string" - } - }, - "required": [ - "function", - "message", - "params" - ] - } - } -} -``` - -## Rationale - -A standard for walletstores, similar to that for keystores, provides a higher level of compatibility between wallets and allows for simpler wallet and key interchange between them. - -## Test Cases - -### Test Vector - -Password `'testpassword'` -Seed `0x147addc7ec981eb2715a22603813271cce540e0b7f577126011eb06249d9227c` - -```json -{ - "crypto": { - "checksum": { - "function": "sha256", - "message": "8bdadea203eeaf8f23c96137af176ded4b098773410634727bd81c4e8f7f1021", - "params": {} - }, - "cipher": { - "function": "aes-128-ctr", - "message": "7f8211b88dfb8694bac7de3fa32f5f84d0a30f15563358133cda3b287e0f3f4a", - "params": { - "iv": "9476702ab99beff3e8012eff49ffb60d" - } - }, - "kdf": { - "function": "pbkdf2", - "message": "", - "params": { - "c": 16, - "dklen": 32, - "prf": "hmac-sha256", - "salt": "dd35b0c08ebb672fe18832120a55cb8098f428306bf5820f5486b514f61eb712" - } - } - }, - "name": "Test wallet 2", - "nextaccount": 0, - "type": "hierarchical deterministic", - "uuid": "b74559b8-ed56-4841-b25c-dba1b7c9d9d5", - "version": 1 -} -``` - -## Implementation - -A Go implementation of the hierarchical deterministic wallet can be found at [https://github.com/wealdtech/go-eth2-wallet-hd](https://github.com/wealdtech/go-eth2-wallet-hd). - -## Security Considerations - -The seed stored in the `crypto` section of the wallet can be used to generate any key along the derived path. As such, the security of all keys generated by HD wallets is reduced to the security of the passphrase and strength of the encryption used to protect the seed, regardless of the security of the passphrase and strength of the encryption used to protect individual keystores. - -It is possible to work with only the walletstore plus an index for each key, in which case stronger passphrases can be used as decryption only needs to take place once. It is also possible to use generated keystores without the walletstore, in which case a breach of security will expose only the keystore. - -An example high-security configuration may involve the walletstore existing on an offline computer, from which keystores are generated. The keystores can then be moved individually to an online computer to be used for signing. - -## 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-2386.md diff --git a/EIPS/eip-2387.md b/EIPS/eip-2387.md index 94e810c43825ec..27a441e7a8686a 100644 --- a/EIPS/eip-2387.md +++ b/EIPS/eip-2387.md @@ -72,4 +72,4 @@ Previous Hardforks to address the Ice Age have also included reductions in the b ## 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-2390.md b/EIPS/eip-2390.md index 832efb82c8a5f9..9ab3fca65cf6d3 100644 --- a/EIPS/eip-2390.md +++ b/EIPS/eip-2390.md @@ -1,316 +1,7 @@ --- eip: 2390 -title: Geo-ENS -author: James Choncholas (@james-choncholas) -discussions-to: https://github.com/ethereum/EIPs/issues/2959 -status: Draft -type: Standards Track category: ERC -created: 2019-11-15 -requires: 137, 165, 1062, 1185 +status: Moved --- -## Simple Summary -GeoENS brings geographic split horizon capabilities to ENS. It's GeoDNS for ENS! - -## Abstract -This EIP specifies an ENS resolver interface for geographically split horizon DNS. -Geographic split horizon DNS returns resource records that are specific to an end -user's location. -This technique is commonly used by CDNs to direct traffic to content caches nearest users. -Geographic split horizon resolution is primarily geared towards ENS -resolvers storing DNS resource records [EIP-1185](./eip-1185.md), although the technique could be -used on other interfaces like IPFS content hash storage [EIP-1062](./eip-1062.md). - -## Motivation -There are many use cases for traditional GeoDNS systems, like Amazon's Route53, -in the centralized web. -These use cases include proximity-based load balancing and serving content -specific to the geographic location of the query. -Unfortunately the ENS specification does not provide a mechanism for -geo-specific resolution. -ENS can respond to queries with IP addresses (as described in [EIP-1185](./eip-1185.md)) -however there is no way to respond to geo-specific queries. -This EIP proposes a standard to give the ENS system geo-proximal awareness -to serve a similar purpose as GeoDNS. - -GeoENS can do more than DNS-based solutions. -In addition to geographic split horizon DNS, GeoENS can be used for the following: - - Locating digital resources (like smart contracts) that represent physical objects in the real world. - - Smart contract managing access to a physical object associated with a specific location. - - ENS + IPFS web hosting (as described in [EIP-1062](./eip-1062.md)) with content translated to the native language of the query source. - - Tokenizing objects with a physical location. - -Because of the decentralized nature of ENS, geo-specific resolution is different than traditional GeoDNS. -GeoDNS works as follows. DNS queries are identified by their source IP address. -This IP is looked up in a database like [GeoIP2](https://www.maxmind.com/en/geoip2-services-and-databases) -from MaxMind which maps the IP address to a location. -This method of locating the source of a query is error prone and unreliable. -If the GeoIP database is out of date, queried locations can be vastly different than their true location. -GeoENS does not rely on a database because the user includes a location in their query. - -It follows that queries can be made by users for any location, not just their location. -Traditional DNS will only return the resource assigned to a query's provenance. -GeoENS does not correlate a query's provinance with a location, allowing the -entire globe to be queried from a single location. - -An additional shortcoming of traditional DNS is the fact that there is no way to return a list of servers in a certain proximity. -This is paramount for uses cases that require discovering the resource with the lowest latency. -GeoENS allows a list of resources, like IP addresses, to be gathered within a specific location. -Then a client to determine themselves which resource has the lowest latency. - -Lastly, publicly facing GeoDNS services do not give fine granularity control -over geographic regions for GeoDNS queries. -Cloud based DNS services like [Amazon's Route 53](https://aws.amazon.com/route53/) -only allow specifying geographic regions at the granularity of a State in -the United States. -GeoENS on the other hand gives 8 characters of geohash resolution which -corresponds to +-20 meter accuracy. - -## Specification -This EIP proposes a new interface to ENS resolvers such that geo-spacial information -can be recorded and retrieved from the blockchain. -The interface changes are described below for "address resolvers" described in EIP137 -however the idea applies to any record described in EIP1185 and EIP1062, namely DNS -Resolvers, Text Resolvers, ABI Resolvers, etc. - -### What is a geohash? -A [Geohash](https://en.m.wikipedia.org/wiki/Geohash#Algorithm_and_example) -is an interleaving of latitude and longitude bits, whose -length determines it's precision. -Geohashes are typically encoded in base 32 characters. - -### function setGeoAddr(bytes32 node, string calldata geohash, address addr) external authorised(node) -Sets a resource (contract address, IP, ABI, TEXT, etc.) by node and geohash. -Geohashes must be unique per address and are exactly 8 characters long. -This leads to an accuracy of +-20 meters. -Write default initialized resource value, `address(0)`, to remove a resource from the resolver. - -### function geoAddr(bytes32 node, string calldata geohash) external view returns (address[] memory ret) -Query the resolver contract for a specific node and location. -All resources (contract addresses, IP addresses, ABIs, TEXT records, etc.) matching -the node and prefix geohash provided are returned. -This permits querying by exact geohash of 8 characters to return the content at that location, -or querying by geographic bounding box described by a geohash of less than 8 character precision. - -Any type of geohash can be used including [Z-order](https://en.wikipedia.org/wiki/Z-order_curve) -[Hilbert](https://en.wikipedia.org/wiki/Hilbert_curve) or the more accurate -[S2 Geometry](https://s2geometry.io/devguide/s2cell_hierarchy.html) library -from Google. -There are also ways to search the geographic data using geohashes without -always ending up with a rectangular query region. -[Searching circular shaped regions](https://github.com/ashwin711/proximityhash) is -slightly more complex as it requires multiple queries. - -## Rationale -The proposed implementation uses a sparse [Quadtree](https://dl.acm.org/doi/10.1007/BF00288933) trie as an index for -resource records as it has low storage overhead and good search performance. -The leaf nodes of the tree store resource records while non-leaves represent one geohash character. -Each node in the tree at depth d corresponds to a geohash of precision d. -The tree has depth 8 because the maximum precision of a geohash is 8 characters. -The tree has fanout 32 because the radix of a geohash character is 32. -The path to get to a leaf node always has depth 8 and the leaf contains the content (like IP address) -of the geohash represented by the path to the leaf. -The tree is sparse as 71% of the Earth's surface is covered by water. -The tree facilitates common traversal algorithms (DFS, BFS) to return -lists of resource records within a geographic bounding box. - -## Backwards Compatibility -This EIP does not introduce issues with backwards compatibility. - -## Test Cases -See https://github.com/james-choncholas/resolvers/blob/master/test/TestPublicResolver.js - -## Implementation -This address resolver, written in Solidity, implements the specifications outlined above. -The same idea presented here can be applied to other resolver interfaces as specified in EIP137. -Note that geohashes are passed and stored using 64 bit unsigned integers. -Using integers instead of strings for geohashes is more performant, especially in the `geomap` mapping. -For comparison purposes, see https://github.com/james-choncholas/geoens/tree/master/contracts/StringOwnedGeoENSResolver.sol for the inefficient string implementation. - - -```solidity -pragma solidity ^0.5.0; - -import "../ResolverBase.sol"; - -contract GeoENSResolver is ResolverBase { - bytes4 constant ERC2390 = 0x8fbcc5ce; - uint constant MAX_ADDR_RETURNS = 64; - uint constant TREE_VISITATION_QUEUESZ = 64; - uint8 constant ASCII_0 = 48; - uint8 constant ASCII_9 = 57; - uint8 constant ASCII_a = 97; - uint8 constant ASCII_b = 98; - uint8 constant ASCII_i = 105; - uint8 constant ASCII_l = 108; - uint8 constant ASCII_o = 111; - uint8 constant ASCII_z = 122; - - struct Node { - address data; // 0 if not leaf - uint256 parent; - uint256[] children; // always length 32 - } - - // A geohash is 8, base-32 characters. - // A geomap is stored as tree of fan-out 32 (because - // geohash is base 32) and height 8 (because geohash - // length is 8 characters) - mapping(bytes32=>Node[]) private geomap; - - event GeoENSRecordChanged(bytes32 indexed node, bytes8 geohash, address addr); - - // only 5 bits of ret value are used - function chartobase32(byte c) pure internal returns (uint8 b) { - uint8 ascii = uint8(c); - require( (ascii >= ASCII_0 && ascii <= ASCII_9) || - (ascii > ASCII_a && ascii <= ASCII_z)); - require(ascii != ASCII_a); - require(ascii != ASCII_i); - require(ascii != ASCII_l); - require(ascii != ASCII_o); - - if (ascii <= (ASCII_0 + 9)) { - b = ascii - ASCII_0; - - } else { - // base32 b = 10 - // ascii 'b' = 0x60 - // note base32 skips the letter 'a' - b = ascii - ASCII_b + 10; - - // base32 also skips the following letters - if (ascii > ASCII_i) - b --; - if (ascii > ASCII_l) - b --; - if (ascii > ASCII_o) - b --; - } - require(b < 32); // base 32 can't be larger than 32 - return b; - } - - function geoAddr(bytes32 node, bytes8 geohash, uint8 precision) external view returns (address[] memory ret) { - bytes32(node); // single node georesolver ignores node - assert(precision <= geohash.length); - - ret = new address[](MAX_ADDR_RETURNS); - if (geomap[node].length == 0) { return ret; } - uint ret_i = 0; - - // walk into the geomap data structure - uint pointer = 0; // not actual pointer but index into geomap - for(uint8 i=0; i < precision; i++) { - - uint8 c = chartobase32(geohash[i]); - uint next = geomap[node][pointer].children[c]; - if (next == 0) { - // nothing found for this geohash. - // return early. - return ret; - } else { - pointer = next; - } - } - - // pointer is now node representing the resolution of the query geohash. - // DFS until all addresses found or ret[] is full. - // Do not use recursion because blockchain... - uint[] memory indexes_to_visit = new uint[](TREE_VISITATION_QUEUESZ); - indexes_to_visit[0] = pointer; - uint front_i = 0; - uint back_i = 1; - - while(front_i != back_i) { - Node memory cur_node = geomap[node][indexes_to_visit[front_i]]; - front_i ++; - - // if not a leaf node... - if (cur_node.data == address(0)) { - // visit all the chilins - for(uint i=0; i MAX_ADDR_RETURNS) break; - } - } - - return ret; - } - - // when setting, geohash must be precise to 8 digits. - function setGeoAddr(bytes32 node, bytes8 geohash, address addr) external authorised(node) { - bytes32(node); // single node georesolver ignores node - - // create root node if not yet created - if (geomap[node].length == 0) { - geomap[node].push( Node({ - data: address(0), - parent: 0, - children: new uint256[](32) - })); - } - - // walk into the geomap data structure - uint pointer = 0; // not actual pointer but index into geomap - for(uint i=0; i < geohash.length; i++) { - - uint8 c = chartobase32(geohash[i]); - - if (geomap[node][pointer].children[c] == 0) { - // nothing found for this geohash. - // we need to create a path to the leaf - geomap[node].push( Node({ - data: address(0), - parent: pointer, - children: new uint256[](32) - })); - geomap[node][pointer].children[c] = geomap[node].length - 1; - } - pointer = geomap[node][pointer].children[c]; - } - - Node storage cur_node = geomap[node][pointer]; // storage = get reference - cur_node.data = addr; - - emit GeoENSRecordChanged(node, geohash, addr); - } - - function supportsInterface(bytes4 interfaceID) public pure returns (bool) { - return interfaceID == ERC2390 || super.supportsInterface(interfaceID); - } -} -``` - -## Security Considerations -This contract has similar functionality to ENS Resolvers - refer there for security considerations. -Additionally, this contract has a dimension of data privacy. -Users query via the geoAddr function specifying a geohash of less than 8 characters -which defines the query region. -Users who run light clients leak the query region to their connected full-nodes. -Users who rely on nodes run by third parties (like Infura) will also leak -the query region. -Users who run their own full node or have access to a trusted full node do -not leak any location data. - -Given the way most location services work, the query region is likely to contain -the user's actual location. -The difference between API access, light, and full nodes has always had -an impact on privacy but now the impact is underscored by the involvement -of coarse granularity user location. - - - -## 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-2390.md diff --git a/EIPS/eip-2400.md b/EIPS/eip-2400.md index 9cc754e2a48b17..a6d286dd35b776 100644 --- a/EIPS/eip-2400.md +++ b/EIPS/eip-2400.md @@ -1,104 +1,7 @@ --- eip: 2400 -title: URL Format for Transaction Receipts -author: Ricardo Guilherme Schmidt (@3esmit), Eric Dvorsak (@yenda) -discussions-to: https://ethereum-magicians.org/t/eip-2400-transaction-receipt-uri/ -type: Standards Track category: ERC -status: Draft -created: 2019-11-05 -requires: 155, 831 +status: Moved --- -## Simple Summary - -A standardized URI for transaction receipt with complete information about transaction. - -A standard way of representing a submitted transaction. - -## Abstract - -A transaction hash is not very meaningful on its own, because it looks just like any other hash, and it might lack important information for reading a transaction. -This standard includes all needed information for displaying a transaction and it's details, such as `chainId`, `method` signature called and `events` signatures emitted. - -### Use-cases - -Transaction Receipt URIs embedded in QR-codes, hyperlinks in web-pages, emails or chat messages provide for robust cross-application signaling between very loosely coupled applications. A standardized URI format allows for instant invocation of the user’s preferred transaction explorer application. Such as: - -- In web3 (dapps, mining pools, exchanges), links would automatically open user's preferred transaction explorer; -- In wallets, for users sharing transaction receipts easier; -- In chat applications, as a reply to an [ERC-681] transaction request; -- In crypto vending machines, a QRCode can be displayed when transactions are submitted; -- Anywhere transaction receipts are presented to users. - -## Motivation - -Interoperability for web3: wallets, browsers and messengers. - -## Specification - -### Syntax - -Transaction receipt URLs contain "ethereum" in their schema (protocol) part and are constructed as follows: - - receipt = erc831_part transaction_hash [ "@" chain_id ] [ "?" parameters ] - erc831_part = "ethereum:tx-" - transaction_hash = "0x" 64*HEXDIG - chain_id = 1*DIGIT - parameters = parameter *( "&" parameter ) - parameter = key "=" value - key = "method" / "events" - value = function_signature / event_list - function_signature = function_name "(" TYPE *( "," TYPE) ")" - function_name = STRING - event_list = event_signature *( ";" event_signature ) - event_signature = event_name "(" event_type *( "," event_type) ")" - event_name = STRING - event_type = ["!"] TYPE - - -Where `TYPE` is a standard ABI type name, as defined in [Ethereum Contract ABI specification](https://solidity.readthedocs.io/en/develop/abi-spec.html). `STRING` is a URL-encoded unicode string of arbitrary length. - -The exclamation symbol (`!`), in `event_type`, is used to identify indexed event parameters. - -### Semantics - -`transaction_hash` is mandatory. The hash must be looked up in the corresponding `chain_id` transaction history, if not found it should be looked into the pending transaction queue and rechecked until is found. If not found anequivalent error as "transaction not found error" should be shown instead of the transaction. When the transaction is pending, it should keep checking until the transaction is included in a block and becomes "unrevertable" (usually 12 blocks after transaction is included). - -`chain_id` is optional and contains the decimal chain ID, such that transactions on various test and private networks can be represented as well. If no `chain_id` is present, the $ETH/mainnet (`1`) is considered. - -If `method` is not present, this means that the transaction receipt URI does not specify details, or that it was a transaction with no calldata. When present it needs to be validated by comparing the first 4 bytes of transaction calldata with the first 4 bytes of the keccak256 hash of `method`, if invalid, an equivalent error as "method validation error" must be shown instead of the transaction. - -If `events` is not present, this means that the transaction receipt URI does not specify details, or that the transaction did not raised any events. Pending and failed transactions don't validate events, however, when transaction is successful (or changes from pending to success) and events are present in URI, each event in the `event_list` must occur at least once in the transaction receipt event logs, otherwise an equivalent error as "event validation error: {event(s) [$event_signature, ...] not found}" should be shown instead of the transaction. - -#### Examples - -Simple ETH transfer: -`ethereum:tx-0x1143b5e38fe3cf585fb026fb9b5ce35c85a691786397dc8a23a07a62796d8172@1` - -[Complex contract transaction](https://etherscan.io/tx/0x4465e7cce3c784f264301bfe26fc17609855305213ec74c716c7561154b76fec#eventlog): -`ethereum:tx-0x4465e7cce3c784f264301bfe26fc17609855305213ec74c716c7561154b76fec@1?method="issueAndActivateBounty(address,uint256,string,uint256,address,bool,address,uint256)"&events="Transfer(!address,!address,uint256);BountyIssued(uint256);ContributionAdded(uint256,!address,uint256);BountyActivated(uint256,address)"` - -## Rationale - -The goal of this standard envolves only the transport of submitted transactions, and therefore transaction data must be loaded from blockchain or pending transaction queue, which also serves as a validation of the transaction existence. - -Transaction hash not found is normal in fresh transactions, but can also mean that effectively a transaction was never submitted or have been replaced (through "higher gasPrice" nonce override or through an uncle/fork). - -In order to decode transaction parameters and events, a part of the ABI is required. The transaction signer have to know the ABI to sign a transaction, and is also who is creating a transaction receipt, so the transaction receipt can optionally be shared with the information needed to decode the transaction call data and it's events. - -## Backwards Compatibility - -Future upgrades that are partially or fully incompatible with this proposal must use a prefix other than `tx-` that is separated by a dash (-) character from whatever follows it, as specified by [ERC-831]. - -## References - -* [ERC-831] -* [ERC-681] - -## Copyright - -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[ERC-831]: ./eip-831.md -[ERC-681]: ./eip-681.md +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 index 21ea4bc1ef8249..d4ed2d39754ccb 100644 --- a/EIPS/eip-2458.md +++ b/EIPS/eip-2458.md @@ -70,6 +70,6 @@ An implementation is adding a header option. This standard is informational and does not introduce technical security issues. ## 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-2464.md b/EIPS/eip-2464.md index dea697f81a8880..2cdc86df7f4d18 100644 --- a/EIPS/eip-2464.md +++ b/EIPS/eip-2464.md @@ -1,9 +1,10 @@ --- eip: 2464 title: "eth/65: transaction announcements and retrievals" -author: Péter Szilágyi , Gary Rong +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: Draft +status: Final type: Standards Track category: Networking created: 2020-01-13 @@ -12,7 +13,11 @@ requires: 2364 ## Abstract -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](https://github.com/ethereum/devp2p/blob/master/caps/eth.md)) 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. +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. @@ -20,8 +25,6 @@ A similar issue arises when a new network connection is made between two nodes, 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 - 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. @@ -69,14 +72,10 @@ This EIP extends the `eth` protocol in a backwards incompatible way and requires This EIP does not change the consensus engine, thus does _not_ require a hard fork. -## Test Cases - -TODO - -## Implementation +## Security Considerations -Geth: https://github.com/ethereum/go-ethereum/pull/20234 +None. ## 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-2470.md b/EIPS/eip-2470.md index 811385f030b4c9..65bf8a1aa85fc8 100644 --- a/EIPS/eip-2470.md +++ b/EIPS/eip-2470.md @@ -1,197 +1,7 @@ --- eip: 2470 -title: Singleton Factory -author: Ricardo Guilherme Schmidt (@3esmit) -discussions-to: https://ethereum-magicians.org/t/erc-2470-singleton-factory/3933 -status: Draft -type: Standards Track category: ERC -created: 2020-01-15 -requires: 1014 +status: Moved --- -## Simple Summary - -Some DApps needs one, and only one, instance of an contract, which have the same address on any chain. - -A permissionless factory for deploy of keyless deterministic contracts addresses based on its bytecode. - -## Abstract - -Some contracts are designed to be Singletons which have the same address no matter what chain they are, which means that should exist one instance for all, such as [EIP-1820] and [EIP-2429]. These contracts are usually deployed using a method known as [Nick]'s method, so anyone can deploy those contracts on any chain and they have a deterministic address. -This standard proposes the creation of a CREATE2 factory using this method, so other projects requiring this feature can use this factory in any chain with the same setup, even in development chains. - -## Motivation - -Code reuse, using the factory becomes easier to deploy singletons. - -## Specification - -### [ERC-2470] Singleton Factory - -> This is an exact copy of the code of the [ERC2470 factory smart contract]. - -```solidity -pragma solidity 0.6.2; - - -/** - * @title Singleton Factory (EIP-2470) - * @notice Exposes CREATE2 (EIP-1014) to deploy bytecode on deterministic addresses based on initialization code and salt. - * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) - */ -contract SingletonFactory { - /** - * @notice Deploys `_initCode` using `_salt` for defining the deterministic address. - * @param _initCode Initialization code. - * @param _salt Arbitrary value to modify resulting address. - * @return createdContract Created contract address. - */ - function deploy(bytes memory _initCode, bytes32 _salt) - public - returns (address payable createdContract) - { - assembly { - createdContract := create2(0, add(_initCode, 0x20), mload(_initCode), _salt) - } - } -} -// IV is a value changed to generate the vanity address. -// IV: 6583047 -``` - -### Deployment Transaction - -Below is the raw transaction which MUST be used to deploy the smart contract on any chain. - -``` -0xf9016c8085174876e8008303c4d88080b90154608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c634300060200331b83247000822470 -``` - -The strings of `2470`'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 [EIP-155] 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. Forge a transaction with the following parameters: - ```js - { - nonce: 0, - gasPrice: 100000000000, - value: 0, - data: '0x608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c63430006020033', - gasLimit: 247000, - v: 27, - r: '0x247000', - s: '0x2470' - } - ``` - > The `r` and `s` values, made of starting `2470`, are obviously a human determined value, instead of a real signature. - -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.0247 ether to this single-use deployment account. - -5. Broadcast the deployment transaction. - - > Note: 247000 is the double of gas needed to deploy the smart contract, this ensures that future changes in OPCODE pricing are unlikely to cause this deploy transction to fail out of gas. A left over will sit in the address of about 0.01 ETH will be forever locked in the single use address. - -The resulting transaction hash is `0x803351deb6d745e91545a6a3e1c0ea3e9a6a02a1a4193b70edfcd2f40f71a01c`. - -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 Factory Deployment Account - -![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAB0UlEQVR4nO3asW1CQRBAQdpyCa6CIpxTjgujDGTJNEC2QqvjTbDx33c3P7vL79f1fzLf98dobn8/o5nuP53p/tPzm+5/AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4CMBnH6B0/23L2AbEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ8JYPsCtw+w3g9AvB+AeD8A8X4A4v0AxPsBiPcDEO8HIN4PQLwfgHg/APF+AOL9AMT7AYj3AxDvP/5ByOkApt/PvwgCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgJYDtA9w+gO0fYHsAAGB/CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAdALYfNExnun+9H4B4PwDxfgDi/QDE+wGI9wMQ7wcg3g9AvB+AeD8A8X4A4v0AxPsBiPcDEO8HIN4/fhCy/aDidADb5wcAAGcHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO8CsH2ApwPY/j4Ah+8PAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPB6nlegoDNgrfyiAAAAAElFTkSuQmCC) - -`0xBb6e024b9cFFACB947A71991E386681B1Cd1477D` - -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.0247 ether MUST be sent to this account *first*. - -### Factory Contract Address -![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAABn0lEQVR4nO3coRECMRRF0S2GutCUQzd4WqAMLB4qQGWYP+EecXXeZo/OcTrf35Ndbq+l7F/rmB6w+wXuvh+A+H4A4vsBiO8HIL4fgPh+AOL7AYjvByC+H4D4fgDi+wGI7wcgvh+A+H4A4vuXAUxfwPX5GG33+wMAgL0/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPgGYHrA9A+cbhoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wlgesD0+bvvXz0fgM33AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB8ATB9gZoNgHgAxAMgHgDxAIgHQDwA4gEQD4B4AMQDIB4A8QCIB0A8AOId0w8caK3V/wfA5gEQD4B4AMQDIB4A8QCIB0A8AOIBEA+AeADEAyAeAPEAiAdAPADiARAPgHgAxAMgHgDxAIgHQDwA4gEQD4B4AMQDIB4A8QCItwxg+oECDT8QMT1AAAgAASAABIAAEAACQAAIAAEgAASAANAv+gDxVDRR1CVqRAAAAABJRU5ErkJggg==) - -`0xce0042B868300000d44A59004Da54A005ffdcf9f` - -The contract has the address above for every chain on which it is deployed. -### ABI for SingletonFactory: -```json -[ - { - "constant": false, - "inputs": [ - { - "internalType": "bytes", - "name": "_initCode", - "type": "bytes" - }, - { - "internalType": "bytes32", - "name": "_salt", - "type": "bytes32" - } - ], - "name": "deploy", - "outputs": [ - { - "internalType": "address payable", - "name": "createdContract", - "type": "address" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - } -] -``` - -## Rationale - -SingletonFactory does not allow sending value on create2, this was done to prevent different results on the created object. -SingletonFactory allows user defined salt to facilitate the creation of vanity addresses for other projects. If vanity address is not necessary, salt `bytes(0)` should be used. -Contracts that are constructed by the SingletonFactory MUST not use `msg.sender` in their constructor, all variables must came through initialization data. This is intentional, as if allowing a callback after creation to aid initialization state would lead to contracts with same address (but different chains) to have the same address but different initial state. -The resulting address can be calculated in chain by any contract using this formula: `address(keccak256(bytes1(0xff), 0xce0042B868300000d44A59004Da54A005ffdcf9f, _salt, keccak256(_code)) << 96)` or in javascript using https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/README.md#const-generateaddress2. - -## Backwards Compatibility - -Does not apply as there are no past versions of Singleton Factory being used. - -## Test Cases - -TBD - -## Implementation - -https://github.com/3esmit/ERC2470 - -## Security Considerations - -Some contracts can possibly not support being deployed on any chain, or require a different address per chain, that can be safely done by using comparison in [EIP-1344] in constructor. -Account contracts are singletons in the point of view of each user, when wallets want to signal what chain id is intended, [EIP-1191] should be used. -Contracts deployed on factory must not use `msg.sender` in constructor, instead use constructor parameters, otherwise the factory would end up being the controller/only owner of those. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[EIP-155]: ./eip-155.md -[EIP-1191]: ./eip-1191.md -[EIP-1344]: ./eip-1344.md -[EIP-1820]: ./eip-1820.md -[EIP-2429]: https://gitlab.com/status-im/docs/EIPs/blob/secret-multisig-recovery/EIPS/eip-2429.md -[Nick's article]: https://medium.com/@weka/how-to-send-ether-to-11-440-people-187e332566b7 -[Nick]: https://github.com/Arachnid/ - +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 index df5983cda63859..042a5c69032d1a 100644 --- a/EIPS/eip-2474.md +++ b/EIPS/eip-2474.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-01-19 @@ -17,7 +17,7 @@ Allow contracts to be called directly by `block.coinbase` (block validator), wit _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 an change which also benefits the validator. +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. @@ -59,4 +59,4 @@ 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-2477.md b/EIPS/eip-2477.md index 7ce473676740dd..e5a527b1ae2863 100644 --- a/EIPS/eip-2477.md +++ b/EIPS/eip-2477.md @@ -1,333 +1,7 @@ --- eip: 2477 -title: Token Metadata Integrity -author: Kristijan Sedlak (@xpepermint), William Entriken , Witek Radomski -discussions-to: https://github.com/ethereum/EIPs/issues/2483 -type: Standards Track category: ERC -status: Draft -created: 2020-01-02 -requires: 165, 721, 1155 +status: Moved --- -## Simple Summary - -This specification defines a mechanism by which clients may verify that a fetched token metadata document has been delivered without unexpected manipulation. - -This is the Web3 counterpart of the W3C Subresource Integrity (SRI) specification. - -## Abstract - -An interface `ERC2477` with two functions `tokenURIIntegrity` and `tokenURISchemaIntegrity` are specified for smart contracts and a narrative is provided to explain how this improves the integrity of the token metadata documents. - -## Motivation - -Tokens are being used in many applications to represent, trace and provide access to assets off-chain. These assets include in-game digital items in mobile apps, luxury watches and products in our global supply chain, among many other creative uses. - -Several token standards allow attaching metadata to specific tokens using a URI (RFC 3986) and these are supported by the applications mentioned above. These metadata standards are: - -* ERC-721 metadata extension (`ERC721Metadata`) -* ERC-1155 metadata extension (`ERC1155Metadata_URI`) -* ERC-1046 (DRAFT) ERC-20 Metadata Extension - -Although all these standards allow storing the metadata entirely on-chain (using the "data" URI, RFC 2397), or using a content-addressable system (e.g. IPFS's Content IDentifiers [sic]), nearly every implementation we have found is using Uniform Resource Locators (the exception is The Sandbox which uses IPFS URIs). These URLs provide no guarantees of content correctness or immutability. This standard adds such guarantees. - -## Design - -**Approach A:** A token contract may reference metadata by using its URL. This provides no integrity protection because the referenced metadata and/or schema could change at any time if the hosted content is mutable. This is the world before EIP-2477: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│─────▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -``` - -Note: according to the JSON Schema project, a metadata document referencing a schema using a URI in the `$schema` key is a known approach, but it is not standardized. - -**Approach B:** EIP-2477 provides mechanisms to establish integrity for these references. In one approach, there is integrity for the metadata document. Here, the on-chain data includes a hash of the metadata document. The metadata may or may not reference a schema. In this approach, changing the metadata document will require updating on-chain `tokenURIIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌ ─ ─ ─ ─ -│ TokenID │──────▶│Metadata│─ ─ ─▶ Schema │ -└───────────────────────┘ └────────┘ └ ─ ─ ─ ─ -┌───────────────────────┐ ▲ -│ tokenURIIntegrity │════════════╝ -└───────────────────────┘ -``` - -**Approach C:** In a stronger approach, the schema is referenced by the metadata using an extension to JSON Schema, providing integrity. In this approach, changing the metadata document or the schema will require updating on-chain `tokenURIIntegrity` and the metadata document, additionally changing the schema requires updating the on-chain `tokenURISchemaIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│═════▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -┌───────────────────────┐ ▲ -│ tokenURIIntegrity │════════════╝ -└───────────────────────┘ -``` - -**Approach D:** Equally strong, the metadata can make a normal reference (no integrity protection) to the schema and on-chain data also includes a hash of the schema document. In this approach, changing the metadata document will require updating on-chain `tokenURIIntegrity` and updating the schema document will require updating the `tokenURISchemaIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│─────▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -┌───────────────────────┐ ▲ ▲ -│ tokenURIIntegrity │════════════╝ ║ -└───────────────────────┘ ║ -┌───────────────────────┐ ║ -│tokenURISchemaIntegrity│════════════════════════════╝ -└───────────────────────┘ -``` - -**Approach E:** Lastly, the schema can be referenced with integrity from the metadata and also using on-chain data. In this approach, changing the metadata document or the schema will require updating on-chain `tokenURIIntegrity` and the metadata document, additionally changing the schema requires updating the on-chain `tokenURISchemaIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│═════▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -┌───────────────────────┐ ▲ ▲ -│ tokenURIIntegrity │════════════╝ ║ -└───────────────────────┘ ║ -┌───────────────────────┐ ║ -│tokenURISchemaIntegrity│════════════════════════════╝ -└───────────────────────┘ -``` - -## 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 - -**Smart contracts implementing the ERC-2477 standard MUST implement the `ERC2477` interface.** - -```solidity -pragma solidity ^0.6.0; - -/// @title ERC-2477 Token Metadata Integrity -/// @dev See https://eips.ethereum.org/EIPS/eip-2477 -/// @dev The ERC-165 identifier for this interface is 0x#######. //TODO: FIX THIS -interface ERC2477 /* is ERC165 */ { - /** - * @notice Get the cryptographic hash of the specified tokenID's metadata - * @param tokenId Identifier for a specific token - * @return digest Bytes returned from the hash algorithm, or "" if not available - * @return hashAlgorithm The name of the cryptographic hash algorithm, or "" if not available - */ - function tokenURIIntegrity(uint256 tokenId) external view returns(bytes memory digest, string memory hashAlgorithm); - - /** - * @notice Get the cryptographic hash for the specified tokenID's metadata schema - * @param tokenId Id of the Xcert. - * @return digest Bytes returned from the hash algorithm, or "" if not available - * @return hashAlgorithm The name of the cryptographic hash algorithm, or "" if not available - */ - function tokenURISchemaIntegrity(uint256 tokenId) external view returns(bytes memory digest, string memory hashAlgorithm); -} -``` - -The returned cryptographic hashes correspond to the token's metadata document and that metadata document's schema, respectively. - -For example, with ERC-721 `tokenURIIntegrity(21)` would correspond to `tokenURI(21)`. With ERC-1155, `tokenURIIntegrity(16)` would correspond to `uri(16)`. In both cases, `tokenURISchemaIntegrity(32)` would correspond to the schema of the document matched by `tokenURIIntegrity(32)`. - -**Smart contracts implementing the ERC-2477 standard MUST implement the ERC-165 standard, including the interface identifiers above.** - -Smart contracts implementing the ERC-2477 standard MAY use any hashing or content integrity scheme. - -Smart contracts implementing the ERC-2477 standard MAY use or omit a mechanism to notify when the integrity is updated (e.g. an Ethereum logging operation). - -Smart contracts implementing the ERC-2477 standard MAY use any mechanism to provide schemas for metadata documents and SHOULD use JSON-LD on the metadata document for this purpose (i.e. `"@schema":...`). - -### Metadata - -A metadata document MAY use this schema to provide referential integrity to its schema document. - -```json -{ - "title": "EIP-2477 JSON Object With Refererential Integrity to Schema", - "type": "object", - "properties": { - "$schema": { - "type": "string", - "format": "uri" - }, - "$schemaIntegrity": { - "type": "object", - "properties": { - "digest": { - "type": "string" - }, - "hashAlgorithm": { - "type": "string" - } - }, - "required": [ - "digest", - "hashAlgorithm" - ] - } - }, - "required": [ - "$schema", - "$schemaIntegrity" - ] -} -``` - -### Clients - -A client implementing the ERC-2477 standard MUST support at least the `sha256` hash algorithm and MAY support other algorithms. - -### Caveats - -* This EIP metadata lists ERC-721 and ERC-1155 as "required" for implementation, due to a technical limitation of EIP metadata. In actuality, this standard is usable with any token implementation that has a `tokenURI(uint id)` or similar function. - -## Rationale - -**Function and parameter naming** - -The W3C Subresource Integrity (SRI) specification uses the attribute "integrity" to perform integrity verification. This ERC-2477 standard provides a similar mechanism and reuses the integrity name so as to be familiar to people that have seen SRI before. - -**Function return tuple** - -The SRI integrity attribute encodes elements of the tuple $$(cryptographic\ hash\ function, digest, options)$$. This ERC-2477 standard returns a digest and hash function name and omits forward-compatibility options. - -Currently, the SRI specification does not make use of options. So we cannot know what format they might be when implemented. This is the motivation to exclude this parameter. - -The digest return value is first, this is an optimization because we expect on-chain implementations will be more likely to use this return value if they will only be using one of the two. - -**Function return types** - -The digest is a byte array and supports various hash lengths. This is consistent with SRI. Whereas SRI uses base64 encoding to target an HTML document, we use a byte array because Ethereum already allows this encoding. - -:warning: TODO: WE NEED TO SPECIFY ENDIANNESS ABOVE AND PROVIDE TEST CASES BELOW. AND JUSTIFY THAT HERE. - -The hash function name is a string. Currently there is no universal taxonomy of hash function names. SRI recognizes the names `sha256`, `sha384` and `sha512` with case-insensitive matching. We are aware of two authorities which provide taxonomies and canonical names for hash functions: ETSI Object Identifiers and NIST Computer Security Objects Register. However, SRI's approach is easier to follow and we have adopted this here. - -**Function return type — hash length** - -Clients must support the SHA-256 algorithm and may optionally support others. This is a departure from the SRI specification where SHA-256, SHA-384 and SHA-512 are all required. The rationale for this less-secure requirement is because we expect some clients to be on-chain. Currently SHA-256 is simple and cheap to do on Ethereum whereas SHA-384 and SHA-512 are more expensive and cumbersome. - -The most popular hash function size below 256 bits in current use is SHA-1 at 160 bits. Multiple collisions (the "Shattered" PDF file, the 320 byte file, the chosen prefix) have been published and a recipe is given to generate infinitely more collisions. SHA-1 is broken. The United States National Institute of Standards and Technology (NIST) has first deprecated SHA-1 for certain use cases in November 2015 and has later further expanded this deprecation. - -The most popular hash function size above 256 bits in current use is SHA-384 as specified by NIST. - -The United States National Security Agency requires a hash length of 384 or more bits for the SHA-2 (CNSA Suite Factsheet) algorithm suite for use on TOP SECRET networks. (No unclassified documents are currently available to specify use cases at higher classification networks.) - -We suspect that SHA-256 and the 0xcert Asset Certification will be popular choices to secure token metadata for the foreseeable future. - -**In-band signaling** - -One possible way to achieve strong content integrity with the existing token standards would be to include, for example, a `?integrity=XXXXX` at the end of all URLs. This approach is not used by any existing implementations we know about. There are a few reasons we have not chosen this approach. The strongest reason is that the World Wide Web has the same problem and they chose to use the Sub-Resource Integrity approach, which is a separate data field than the URL. - -Other supplementary reasons are: - -* For on-chain consumers of data, it is easier to parse a direct hash field than to perform string operations - -* Maybe there are some URIs which are not amenable to being modified in that way, therefore limiting the generalizability of that approach - -This design justification also applies to `tokenURISchemaIntegrity`. The current JSON-LD specification allows a JSON document to link to a schema document. But it does not provide integrity. Rather than changing how JSON-LD works, or changing JSON Schemas, we have the `tokenURISchemaIntegrity` property to just provide the integrity. - -## Backwards Compatibility - -Both ERC-721 and ERC-1155 provide compatible token metadata specifications that use URIs and JSON schemas. The ERC-2477 standard is compatible with both, and all specifications are additive. Therefore, there are no backward compatibility regressions. - -ERC-1523 Standard for Insurance Policies as ERC-721 Non Fungible Tokens (DRAFT) proposes an extension to ERC-721 which also tightens the requirements on metadata. Because it is wholly an extension of ERC-721, ERC-1523 is automatically supported by ERC-2477 (since this standard already supports ERC-721). - -ERC-1046 (DRAFT) ERC-20 Metadata Extension proposes a comparate extension for ERC-20. Such a concept is outside the scope of this ERC-2477 standard. Should ERC-1046 (DRAFT) be finalized, we will welcome a new ERC which copies ERC-2477 and removes the `tokenId` parameter. - -Similarly, ERC-918 (DRAFT) Mineable Token Standard proposes an extension for ERC-20 and also includes metadata. The same comment applies here as ERC-1046. - -## Test Cases - -Following is a token metadata document which is simultaneously compatible with ERC-721, ERC-1155 and ERC-2477 standards. - -```json -{ - "$schema": "https://URL_TO_SCHEMA_DOCUMENT", - "name": "Asset Name", - "description": "Lorem ipsum...", - "image": "https:\/\/s3.amazonaws.com\/your-bucket\/images\/{id}.png", -} -``` - -This above example shows how JSON-LD is employed to reference the schema document (`$schema`). - -Following is a corresponding schema document which is accessible using the URI `"https://URL_TO_SCHEMA_DOCUMENT"` above. - -```json -{ - "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" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - } - } -} -``` - -Assume that the metadata and schema above apply to a token with identifier 1234. (In ERC-721 this would be a specific token, in ERC-1155 this would be a token type.) Then these two function calls MAY have the following output: - -* `function tokenURIIntegrity(1234)` - * `bytes digest `: `3fc58b72faff20684f1925fd379907e22e96b660` - * `string hashAlgorithm`: `sha256` -* `function tokenURISchemaIntegrity(1234)` - * `bytes digest `: `ddb61583d82e87502d5ee94e3f2237f864eeff72` - * `string hashAlgorithm`: `sha256` - -To avoid doubt: the previous paragraph specifies "MAY" have that output because other hash functions are also acceptable. - -## Implementation - -TODO: ADD IMPLEMENTATIONS WITH 0XCERT ENJIN, NIKE, AZURE/MICROSOFT - -## Reference - -Normative standard references - -1. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt -2. ERC-165 Standard Interface Detection. ./eip-165.md -3. ERC-721 Non-Fungible Token Standard. ./eip-721.md -4. ERC-1155 Multi Token Standard. ./eip-1155.md -5. JSON-LD. https://www.w3.org/TR/json-ld/ -6. Secure Hash Standard (SHS). https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf - -Other standards - -1. ERC-1046 ERC-20 Metadata Extension (DRAFT). ./eip-1046.md -2. ERC-918 Mineable Token Standard (DRAFT). ./eip-918.md -3. ERC-1523 Standard for Insurance Policies as ERC-721 Non Fungible Tokens (DRAFT). ./eip-1523.md -4. W3C Subresource Integrity (SRI). https://www.w3.org/TR/SRI/ -5. The "data" URL scheme. https://tools.ietf.org/html/rfc2397 -6. Uniform Resource Identifier (URI): Generic Syntax. https://tools.ietf.org/html/rfc3986 -7. CID [Specification] (DRAFT). https://github.com/multiformats/cid - -Discussion - -1. JSON-LD discussion of referential integrity. https://lists.w3.org/Archives/Public/public-json-ld-wg/2020Feb/0003.html -2. JSON Schema use of `$schema` key for documents. https://github.com/json-schema-org/json-schema-spec/issues/647#issuecomment-417362877 - -Other - -1. [Shattered] The first collision for full SHA-1. https://shattered.io/static/shattered.pdf -2. [320 byte file] The second SHA Collision. https://privacylog.blogspot.com/2019/12/the-second-sha-collision.html -3. [Chosen prefix] https://sha-mbles.github.io -4. Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths. (Rev. 1. Superseded.) https://csrc.nist.gov/publications/detail/sp/800-131a/rev-1/archive/2015-11-06 -5. Commercial National Security Algorithm (CNSA) Suite Factsheet. https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/commercial-national-security-algorithm-suite-factsheet.cfm -6. ETSI Assigned ASN.1 Object Identifiers. https://portal.etsi.org/pnns/oidlist -7. Computer Security Objects Register. https://csrc.nist.gov/projects/computer-security-objects-register/algorithm-registration -8. The Sandbox implementation. https://github.com/pixowl/sandbox-smart-contracts/blob/7022ce38f81363b8b75a64e6457f6923d91960d6/src/Asset/ERC1155ERC721.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-2477.md diff --git a/EIPS/eip-2481.md b/EIPS/eip-2481.md index 584c2e6a3e9dc5..c8bc379b8d6dfc 100644 --- a/EIPS/eip-2481.md +++ b/EIPS/eip-2481.md @@ -1,24 +1,21 @@ --- eip: 2481 -title: "eth/66: request identifier" -author: Christoph Burgdorf -discussions-to: https://github.com/ethereum/EIPs/issues/2482 -status: Review +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 --- -## Simple Summary - -This document proposes a way to increase the efficiency of the `eth` networking protocol while at the same time reducing complexity in Ethereum node implementations. It does so by introducing a request id to all requests which their corresponding responses must include. - ## 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/master/caps/eth.md#getblockheaders-0x03) command. +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/master/caps/eth.md#getblockheaders-0x03):* +*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}]` @@ -27,9 +24,9 @@ headers, of rising number when `reverse` is `0`, falling when `1`, `skip` blocks 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/master/caps/eth.md#blockheaders-0x04) response command accordingly. +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/master/caps/eth.md#blockheaders-0x04):* +*Citing from the [`BlockHeaders` spec definition](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md#blockheaders-0x04):* >`[blockHeader_0, blockHeader_1, ...]` @@ -139,16 +136,7 @@ This EIP extends the `eth` protocol in a backwards incompatible way and requires This EIP does not change the consensus engine, thus does *not* require a hard fork. -## Implementation - -Trinity has a [draft PR](https://github.com/ethereum/trinity/pull/1672) with an implementation. -Geth [PR](https://github.com/ethereum/go-ethereum/pull/22241). - -## Security Considerations - -None - -## Test cases +## 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. @@ -169,6 +157,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "GetBlockHeadersPacket66", @@ -185,6 +174,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "BlockHeadersPacket66", @@ -214,6 +204,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "GetBlockBodiesPacket66", @@ -227,6 +218,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "BlockBodiesPacket66", @@ -286,6 +278,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "GetNodeDataPacket66", @@ -299,6 +292,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "NodeDataPacket66", @@ -306,12 +300,13 @@ These testcases cover RLP-encoding of all the redefined messages types, where th "data": { "RequestId": 1111, "NodeDataPacket": [ - "0xdeadcode", + "0xdeadc0de", "0xfeedbeef" ] } } ``` + ```json { "type": "GetReceiptsPacket66", @@ -325,6 +320,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "ReceiptsPacket66", @@ -379,6 +375,7 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } } ``` + ```json { "type": "PooledTransactionsPacket66", @@ -415,6 +412,9 @@ These testcases cover RLP-encoding of all the redefined messages types, where th } ``` +## Security Considerations + +None ## 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-2488.md b/EIPS/eip-2488.md index 35e548a31bc149..5af41eb8bf0775 100644 --- a/EIPS/eip-2488.md +++ b/EIPS/eip-2488.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2019-12-20 @@ -55,4 +55,4 @@ 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-2494.md b/EIPS/eip-2494.md index b8672e79bbcd72..76f5e329227b25 100644 --- a/EIPS/eip-2494.md +++ b/EIPS/eip-2494.md @@ -1,382 +1,7 @@ --- eip: 2494 -title: Baby Jubjub Elliptic Curve -author: Barry WhiteHat (@barryWhiteHat), Marta Bellés (@bellesmarta), Jordi Baylina (@jbaylina) -discussions-to: https://ethereum-magicians.org/t/eip-2494-baby-jubjub-elliptic-curve/3968 -status: Draft -type: Standards Track category: ERC -created: 2020-01-29 +status: Moved --- -## Simple Summary - -This proposal defines Baby Jubjub, an elliptic curve designed to work inside zk-SNARK circuits in Ethereum. - -## Abstract - -Two of the main issues behind why blockchain technology is not broadly used by individuals and industry are scalability and privacy guarantees. With a set of cryptographic tools called zero-knowledge proofs (ZKP) it is possible to address both of these problems. More specifically, the most suitable protocols for blockchain are called zk-SNARKs (zero-knowledge Succinct Non-interactive ARguments of Knowledge), as they are non-interactive, have succinct proof size and sublinear verification time. These types of protocols allow proving generic computational statements that can be modelled with arithmetic circuits defined over a finite field (also called zk-SNARK circuits). - -To verify a zk-SNARK proof, it is necessary to use an elliptic curve. In Ethereum, the curve is alt_bn128 (also referred as BN254), which has primer order `r`. With this curve, it is possible to generate and validate proofs of any `F_r`-arithmetic circuit. This EIP describes *Baby Jubjub*, an elliptic curve defined over the finite field `F_r` which can be used inside any zk-SNARK circuit, allowing for the implementation of cryptographic primitives that make use of elliptic curves, such as the Pedersen Hash or the Edwards Digital Signature Algorithm (EdDSA). - -## Motivation - -A [zero knowledge proof](https://en.wikipedia.org/wiki/Zero-knowledge_proof) (ZKP) is a protocol that enables one party, the prover, to convince another, the verifier, that a statement is true without revealing any information beyond the veracity of the statement. [Non-Interactive ZKPs](https://people.csail.mit.edu/silvio/Selected%20Scientific%20Papers/Zero%20Knowledge/Noninteractive_Zero-Knowkedge.pdf) (NIZK) are a particular type of zero-knowledge proofs in which the prover can generate the proof without interaction with the verifier. NIZK protocols are very suitable for Ethereum applications, because they allow a smart contract to act as a verifier. This way, anyone can generate a proof and send it as part of a transaction to the smart contract, which can perform some action depending on whether the proof is valid or not. In this context, the most preferable NIZK are [zk-SNARK](https://eprint.iacr.org/2013/279.pdf) (Zero-knowledge Succinct Non Interactive ARgument of Knowledge), a set of non-interactive zero-knowledge protocols that have succinct proof size and sublinear verification time. The importance of these protocols is double: on the one hand, they help improve privacy guarantees, and on the other, they are a possible solution to scalability issues (e.g. see [zk-Rollup](https://github.com/barryWhiteHat/roll_up) project). - -Like most ZKPs, zk-SNARKs permit proving computational statements. For example, one can prove things like: the knowledge of a private key associated with a certain public key, the correct computation of a transaction, or the knowledge of the preimage of a particular hash. Importantly, one can do these things without leaking any information about the statements in question. In other words, without leaking any information about the private key, the transaction details, or the value of the preimage. More specifically, zk-SNARKs permit proving any computational statement that can be modelled with an `F_r`-arithmetic circuit, a circuit consisting of set of wires that carry values from the field `F_r` and connect them to addition and multiplication gates `mod r`. This type of circuits are often called zk-SNARK circuits. - -The implementation of most zk-SNARK protocols (e.g. [[Pinnochio]](https://eprint.iacr.org/2013/279.pdf) and [[Groth16]](https://eprint.iacr.org/2016/260.pdf)) make use of an elliptic curve for validating a proof. In Ethereum, the curve used is alt_bn128 (also referred as BN254), which has prime order `r`. While it is possible to generate and validate proofs of `F_r`-arithmetic circuits with BN254, it is not possible to use BN254 to implement elliptic-curve cryptography within these circuits. To implement functions that require the use of elliptic curves inside a zk-SNARK circuit -- such as the [Pedersen Hash](https://github.com/zcash/zips/blob/master/protocol/protocol.pdf) or the [Edwards Digital Signature Algorithm](https://tools.ietf.org/html/rfc8032) (EdDSA) -- a new curve with coordinates in `F_r` is needed. To this end, we propose in this EIP *Baby Jubjub*, an elliptic curve defined over `F_r` that can be used inside any `F_r`-arithmetic circuit. In the next sections we describe in detail the characteristics of the curve, how it was generated, and which security considerations were taken. - -``` - inputs zk-SNARK (alt_bn128) output - +--------------------------------------------+ - | +--------------------+ | - --->| | EdDSA (Baby Jubjub)| | - | +--------------------+ | - --->| |---> - | +-----------------------------+ | - --->| | Pedersen Hash (Baby Jubjub) | | - | +-----------------------------+ | - +--------------------------------------------+ -``` - -## Specification - -### Definitions -Let `F_r` be the prime finite field with `r` elements, where -``` -r = 21888242871839275222246405745257275088548364400416034343698204186575808495617 -``` - -Let `E` be the twisted Edwards elliptic curve defined over `F_r` described by equation -``` -ax^2 + y^2 = 1 + dx^2y^2 -``` -with parameters -``` -a = 168700 -d = 168696 -``` -We call **Baby Jubjub** the curve `E(F_r)`, that is, the subgroup of `F_r`-rational points of `E`. - -### Order - -Baby Jubjub has order - -``` -n = 21888242871839275222246405745257275088614511777268538073601725287587578984328 -``` - -which factors in -``` -n = h x l -``` -where -``` -h = 8 -l = 2736030358979909402780800718157159386076813972158567259200215660948447373041 -``` -The parameter `h` is called *cofactor* and `l` is a prime number of 251 bits. - -### Generator Point - -The point `G = (x,y)` with coordinates -``` -x = 995203441582195749578291179787384436505546430278305826713579947235728471134 -y = 5472060717959818805561601436314318772137091100104008585924551046643952123905 -``` -generates all `n` points of the curve. - -### Base Point - -The point `B = (x,y)` with coordinates - -``` -x = 5299619240641551281634865583518297030282874472190772894086521144482721001553 -y = 16950150798460657717958625567821834550301663161624707787222815936182638968203 -``` -generates the subgroup of points `P` of Baby Jubjub satisfying `l * P = O`. That is, it generates the set of points of order `l` and origin `O`. - -### Arithmetic - -Let `P1 = (x1, y1)` and `P2 = (x2, y2)` be two arbitrary points of Baby Jubjub. Then `P1 + P2 = (x3, y3)` is calculated in the following way: -``` -x3 = (x1*y2 + y1*x2)/(1 + d*x1*x2*y1*y2) -y3 = (y1*y2 - a*x1*x2)/(1 - d*x1*x2*y1*y2) -``` -Note that both addition and doubling of points can be computed using a single formula. - -## Rationale - -The search for Baby Jubjub was motivated by the need for an elliptic curve that allows the implementation of elliptic-curve cryptography in `F_r`-arithmetic circuits. The curve choice was based on three main factors: type of curve, generation process and security criteria. This section describes how these factors were addressed. - -**Form of the Curve** - -Baby Jubjub is a **twisted Edwards** curve birationally equivalent to a **Montgomery** curve. The choice of this form of curve was based on the following facts: -1. The Edwards-curve Digital Signature Scheme is based on twisted Edwards curves. -2. Twisted Edwards curves have a single complete formula for addition of points, which makes the implementation of the group law inside circuits very efficient [[Crypto08/013, Section 6]](https://eprint.iacr.org/2008/013.pdf). -3. As a twisted Edwards curve is generally birationally equivalent to a Montgomery curve [[Crypto08/13,Theorem 3.2]](https://eprint.iacr.org/2008/013.pdf), the curve can be easily converted from one form to another. As addition and doubling of points in a Montgomery curve can be performed very efficiently, computations outside the circuit can be done faster using this form and sped up inside circuits by combining it with twisted Edwards form (see [here](http://hyperelliptic.org/EFD/g1p/index.html)) for more details). - -**Generation of the Curve** - -Baby Jubjub was conceived as a solution to the circuit implementation of cryptographic schemes that require elliptic curves. As with any cryptographic protocol, it is important to reduce the possibility of a backdoor being present. As a result, we designed the generation process to be **transparent** and **deterministic** -- in order to make it clear that no external considerations were taken into account, and to ensure that the process can be reproduced and followed by anyone who wishes to do so. - -The algorithm chosen for generating Baby Jubjub is based in the criteria defined in [[RFC7748, Appendix A.1]](https://tools.ietf.org/html/rfc7748) and can be found in [this github repository](https://github.com/barryWhiteHat/baby_jubjub). Essentially, the algorithm takes a prime number `p = 1 mod 4` and returns the lowest `A>0` such that `A-2` is a multiple of 4 and such that the set of solutions in `F_p` of `y^2 = x^3 + Ax^2 + x` defines a Montgomery curve with cofactor 8. - -Baby Jubjub was generated by running the algorithm with the prime - -`r = 21888242871839275222246405745257275088548364400416034343698204186575808495617`, - -which is the order of alt_bn128, the curve used to verfiy zk-SNARK proofs in Ethereum. The output of the algorithm was `A=168698`. Afterwards, the corresponding Montgomery curve was transformed into twisted Edwards form. Using SAGE libraries for curves, the order `n` of the curve and its factorization `n = 8*l` was calculated. - -- **Choice of generator** : the generator point `G` is the point of order `n` with smallest positive `x`-coordinate in `F_r`. -- **Choice of base point**: the base point `B` is chosen to be `B = 8*G`, which has order `l`. - -**Security Criteria** - -It is crucial that Baby Jubjub be safe against well-known attacks. To that end, we decided that the curve should pass [SafeCurves](https://safecurves.cr.yp.to/) security tests, as they are known for gathering the best known attacks against elliptic curves. Supporting evidence that Baby Jubjub satisfies the SafeCurves criteria can be found [here](https://github.com/barryWhiteHat/baby_jubjub). - - -## Backwards Compatibility - -Baby Jubjub is a twisted Edwards elliptic curve birational to different curves. So far, the curve has mainly been used in its original form, in Montomgery form, and in another (different representation) twisted Edwards form -- which we call the reduced twisted Edwards form. - -Below are the three representations and the birational maps that make it possible to map points from one form of the curve to another. In all cases, the generator and base points are written in the form **`(x,y)`.** - -### Forms of the Curve - -All generators and base points are written in the form (x,y). - -**Twisted Edwards Form** (standard) - -- Equation: ``ax^2 + y^2 = 1 + dx^2y^2`` -- Parameters: ``a = 168700, d = 168696`` -- Generator point: - ``` - (995203441582195749578291179787384436505546430278305826713579947235728471134, 5472060717959818805561601436314318772137091100104008585924551046643952123905) - ``` -- Base point: - ``` - (5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203) - ``` - -**Montgomery Form** - -- Equation: ``By^2 = x^3 + A x^2 + x`` -- Parameters: ``A = 168698, B = 1`` -- Generator point: - ``` - (7, 4258727773875940690362607550498304598101071202821725296872974770776423442226) - ``` -- Base point: - ``` - (7117928050407583618111176421555214756675765419608405867398403713213306743542, 14577268218881899420966779687690205425227431577728659819975198491127179315626) - ``` - -**Reduced Twisted Edwards Form** - -- Equation: ``a' x^2 + y^2 = 1 + d' x^2y^2`` -- Parameters: - ``` - a' = -1 - d' = 12181644023421730124874158521699555681764249180949974110617291017600649128846 - ``` -- Generator point: - ``` - (4986949742063700372957640167352107234059678269330781000560194578601267663727, 5472060717959818805561601436314318772137091100104008585924551046643952123905) - ``` -- Base point: - ``` - (9671717474070082183213120605117400219616337014328744928644933853176787189663, 16950150798460657717958625567821834550301663161624707787222815936182638968203) - ``` - -### Conversion of Points - -Following formulas allow to convert points from one form of the curve to another. We will denote the coordinates - -* ``(u, v)`` for points in the Montomgery form, -* ``(x, y)`` for points in the Twisted Edwards form and -* ``(x', y')`` for points in reduced Twisted Edwards form. - -Note that in the last conversion -- from Twisted Edwards to Reduced Twisted Edwards and back -- we also use the scaling factor `f`, where: -``` -f = 6360561867910373094066688120553762416144456282423235903351243436111059670888 -``` -In the expressions one can also use directly `-f`, where: -``` --f = 15527681003928902128179717624703512672403908117992798440346960750464748824729 -``` - -**Montgomery --> Twisted Edwards** -``` -(u, v) --> (x, y) - -x = u/v -y = (u-1)/(u+1) -``` - -**Twisted Edwards --> Montgomery** -``` -(x, y) --> (u, v) - -u = (1+y)/(1-y) -v = (1+y)/((1-y)x) -``` - -**Montgomery --> Reduced Twisted Edwards** -``` -(u, v) --> (x', y') - -x' = u*(-f)/v -y' = (u-1)/(u+1) -``` - -**Reduced Twisted Edwards --> Montgomery** -``` -(x', y') --> (u, v) - -u = (1+y')/(1-y') -v = (-f)*(1+y')/((1-y')*x') -``` - -**Twisted Edwards --> Reduced Twisted Edwards** -``` -(x, y) --> (x', y') - -x' = x*(-f) -y' = y -``` - -**Reduced Twisted Edwards --> Twisted Edwards** -``` -(x', y') --> (x, y) - -x = x'/(-f) -y = y' -``` -## Security Considerations - -This section specifies the safety checks done on Baby Jubjub. The choices of security parameters are based on [SafeCurves criteria](https://safecurves.cr.yp.to), and supporting evidence that Baby Jubjub satisfies the following requisites can be found [here](https://github.com/barryWhiteHat/baby_jubjub). - -**Curve Parameters** - -Check that all parameters in the specification of the curve describe a well-defined elliptic curve over a prime finite field. - -- The number `r` is prime. -- Parameters `a` and `d` define an equation that corresponds to an elliptic curve. -- The product of `h` and `l` results into the order of the curve and the `G` point is a generator. -- The number `l` is prime and the `B` point has order `l`. - -**Elliptic Curve Discrete Logarithm Problem** - -Check that the discrete logarithm problem remains difficult in the given curve. We checked Baby Jubjub is resistant to the following known attacks. - -- *Rho method* [[Blake-Seroussi-Smart, Section V.1]](https://www.cambridge.org/core/books/elliptic-curves-in-cryptography/16A2B60636EFA7EBCC3D5A5D01F28546): we require the cost for the rho method, which takes on average around `0.886*sqrt(l)` additions, to be above `2^100`. -- *Additive and multiplicative transfers* [[Blake-Seroussi-Smart, Section V.2]](https://www.cambridge.org/core/books/elliptic-curves-in-cryptography/16A2B60636EFA7EBCC3D5A5D01F28546): we require the embedding degree to be at least `(l − 1)/100`. -- *High discriminant* [[Blake-Seroussi-Smart, Section IX.3]](https://www.cambridge.org/core/books/elliptic-curves-in-cryptography/16A2B60636EFA7EBCC3D5A5D01F28546): we require the complex-multiplication field discriminant `D` to be larger than `2^100`. - -**Elliptic Curve Cryptography** - -- *Ladders* [[Montgomery]](https://wstein.org/edu/Fall2001/124/misc/montgomery.pdf): check the curve supports the Montgomery ladder. -- *Twists* [[SafeCurves, twist]](https://safecurves.cr.yp.to/twist.html): check it is secure against the small-subgroup attack, invalid-curve attacks and twisted-attacks. -- *Completeness* [[SafeCurves, complete]](https://safecurves.cr.yp.to/complete.html): check if the curve has complete single-scalar and multiple-scalar formulas. -- *Indistinguishability* [[IACR2013/325]](https://eprint.iacr.org/2013/325): check availability of maps that turn elliptic-curve points indistinguishable from uniform random strings. - -## Test Cases - -**Test 1 (Addition)** - -Consider the points ``P1 = (x1, y1)`` and ``P2 = (x2, y2)`` with the following coordinates: -``` -x1 = 17777552123799933955779906779655732241715742912184938656739573121738514868268 -y1 = 2626589144620713026669568689430873010625803728049924121243784502389097019475 - -x2 = 16540640123574156134436876038791482806971768689494387082833631921987005038935 -y2 = 20819045374670962167435360035096875258406992893633759881276124905556507972311 -``` -Then their sum `` P1+P2 = (x3, y3)`` is equal to: -``` -x3 = 7916061937171219682591368294088513039687205273691143098332585753343424131937 -y3 = 14035240266687799601661095864649209771790948434046947201833777492504781204499 -``` - -**Test 2 (Doubling)** - -Consider the points ``P1 = (x1, y1)`` and ``P2 = (x2, y2)`` with the following coordinates: -``` -x1 = 17777552123799933955779906779655732241715742912184938656739573121738514868268, -y1 = 2626589144620713026669568689430873010625803728049924121243784502389097019475 - -x2 = 17777552123799933955779906779655732241715742912184938656739573121738514868268 -y2 = 2626589144620713026669568689430873010625803728049924121243784502389097019475 -``` -Then their sum `` P1+P2 = (x3, y3)`` is equal to: -``` -x3 = 6890855772600357754907169075114257697580319025794532037257385534741338397365 -y3 = 4338620300185947561074059802482547481416142213883829469920100239455078257889 -``` - -**Test 3 (Doubling the identity)** - -Consider the points ``P1 = (x1, y1)`` and ``P2 = (x2, y2)`` with the following coordinates: -``` -x1 = 0 -y1 = 1 - -x2 = 0 -y2 = 1 -``` -Then their sum `` P1+P2 = (x3, y3)`` results in the same point: -``` -x3 = 0 -y3 = 1 -``` - -**Test 4 (Curve membership)** - -Point ``(0,1)`` is a point on Baby Jubjub. - -Point ``(1,0)`` is not a point on Baby Jubjub. - -**Test 5 (Base point choice)** - -Check that the base point `` B = (Bx, By)`` with coordinates - -``` -Bx = 5299619240641551281634865583518297030282874472190772894086521144482721001553 -By = 16950150798460657717958625567821834550301663161624707787222815936182638968203 -``` -is 8 times the generator point ``G = (Gx, Gy)``, where -``` -Gx = 995203441582195749578291179787384436505546430278305826713579947235728471134 -Gy = 5472060717959818805561601436314318772137091100104008585924551046643952123905 -``` -That is, check that ``B = 8 x G``. - -**Test 6 (Base point order)** - -Check that the base point `` B = (Bx, By)`` with coordinates - -``` -Bx = 5299619240641551281634865583518297030282874472190772894086521144482721001553 -By = 16950150798460657717958625567821834550301663161624707787222815936182638968203 -``` -multiplied by `l`, where -``` -l = 2736030358979909402780800718157159386076813972158567259200215660948447373041 -``` -results in the origin point `O = (0, 1)`. This test checks that the base point `B` has order `l`. - -## Implementation - -Arithmetic of Baby Jubjub and some cryptographic primitives using the curve have already been implemented in different languages. Here are a few such implementations: - -- Python: https://github.com/barryWhiteHat/baby_jubjub_ecc -- JavaScript: https://github.com/iden3/circomlib/blob/master/src/babyjub.js -- Circuit (circom): https://github.com/iden3/circomlib/blob/master/circuits/babyjub.circom -- Rust: https://github.com/arnaucube/babyjubjub-rs -- Solidity: https://github.com/yondonfu/sol-baby-jubjub -- Go: https://github.com/iden3/go-iden3-crypto/tree/master/babyjub - -## 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-2494.md diff --git a/EIPS/eip-2515.md b/EIPS/eip-2515.md index 1c53b19beceb66..7cdd80d6d6778c 100644 --- a/EIPS/eip-2515.md +++ b/EIPS/eip-2515.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-02-10 @@ -43,7 +43,7 @@ Add the variable `DIFFICULTY_FREEZE_DIFFERENCE` and use the `LAST_FORK_HEIGHT` t 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 + DIFFICUTLY_FREEZE_DIFFERENCE) : +if (BLOCK_HEIGHT <= LAST_FORK_HEIGHT + DIFFICULTY_FREEZE_DIFFERENCE) : block_diff = parent_diff + parent_diff // 2048 * max( 1 - (block_timestamp - parent_timestamp) // 10, -99) @@ -85,4 +85,4 @@ Under the current Difficult, Bomb issuance of ETH is reduced as the Ice Age take 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2520.md b/EIPS/eip-2520.md index 5546ee247ec7d9..0ded919d219502 100644 --- a/EIPS/eip-2520.md +++ b/EIPS/eip-2520.md @@ -1,75 +1,7 @@ --- eip: 2520 -title: Multiple contenthash records for ENS -author: Filip Štamcar (@filips123) -discussions-to: https://github.com/ethereum/EIPs/issues/2393 -status: Draft -type: Standards Track category: ERC -created: 2020-02-18 -requires: 1577 +status: Moved --- -## Simple Summary -ENS support for multiple `contenthash` records on a single ENS name. - -## Motivation -Many applications are resolving ENS names to content hosted on distributed systems. To do this, they use `contenthash` record from ENS domain to know how to resolve names and which distributed system should be used. - -However, the domain can store only one `contenthash` record which means that the site owner needs to decide which hosting system to use. Because there are many ENS-compatible hosting systems available (IPFS, Swarm, recently Onion and ZeroNet), and there will probably be even more in the future, lack of support for multiple records could become problematic. Instead, domains should be able to store multiple `contenthash` records to allow applications to resolve to multiple hosting systems. - -## Specification -Setting and getting functions **MUST** have the same public interface as specified in EIP 1577. Additionally, they **MUST** also have new public interfaces introduced by this EIP: - -* For setting a `contenthash` record, the `setContenthash` **MUST** provide additional `proto` parameter and use it to save the `contenthash`. When `proto` is not provided, it **MUST** save the record as default record. - - ```solidity - function setContenthash(bytes32 node, bytes calldata proto, bytes calldata hash) external authorised(node); - ``` - -* For getting a `contenthash` record, the `contenthash` **MUST** provide additional `proto` parameter and use it to get the `contenthash` for requested type. When `proto` is not provided, it **MUST** return the default record. - - ```solidity - function contenthash(bytes32 node, bytes calldata proto) external view returns (bytes memory); - ``` - -* Resolver that supports multiple `contenthash` records **MUST** return `true` for `supportsInterface` with interface ID `0x6de03e07`. - -Applications that are using ENS `contenthash` records **SHOULD** handle them in the following way: - -* If the application only supports one hosting system (like directly handling ENS from IPFS/Swarm gateways), it **SHOULD** request `contenthash` with a specific type. The contract **MUST** then return it and application **SHOULD** correctly handle it. - -* If the application supports multiple hosting systems (like MetaMask), it **SHOULD** request `contenthash` without a specific type (like in EIP 1577). The contract **MUST** then return the default `contenthash` record. - -## Rationale -The proposed implementation was chosen because it is simple to implement and supports all important requested features. However, it doesn't support multiple records for the same type and priority order, as they don't give much advantage and are harder to implement properly. - -## Backwards Compatibility -The EIP is backwards-compatible with EIP 1577, the only differences are additional overloaded methods. Old applications will still be able to function correctly, as they will receive the default `contenthash` record. - -## Implementation -```solidity -contract ContentHashResolver { - bytes4 constant private MULTI_CONTENT_HASH_INTERFACE_ID = 0x6de03e07; - mapping(bytes32=>mapping(bytes=>bytes)) hashes; - - function setContenthash(bytes32 node, bytes calldata proto, bytes calldata hash) external { - hashes[node][proto] = hash; - emit ContenthashChanged(node, hash); - } - - function contenthash(bytes32 node, bytes calldata proto) external view returns (bytes memory) { - return hashes[node][proto]; - } - - function supportsInterface(bytes4 interfaceID) public pure returns(bool) { - return interfaceID == MULTI_CONTENT_HASH_INTERFACE_ID; - } -} -``` - -## Security Considerations -TBD - -## 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-2520.md diff --git a/EIPS/eip-2525.md b/EIPS/eip-2525.md index 4153668eb3cd37..ae319b3ee99cb9 100644 --- a/EIPS/eip-2525.md +++ b/EIPS/eip-2525.md @@ -1,171 +1,7 @@ --- eip: 2525 -title: ENSLogin -author: Hadrien Croubois (@amxx) -discussions-to: https://ethereum-magicians.org/t/discussion-ens-login/3569 -status: Draft -type: Standards Track category: ERC -created: 2020-02-19 -requires: 137, 634, 1193, 2304 +status: Moved --- -## 1. Abstract - -This presents a method to improve a universal method of login to the ethereum blockchain, leveraging the metadata storage provided by the ENS. We consider a user to be logged in when we have an [EIP-1193](./eip-1193.md) provider that can sign transaction and messages on his behalf. This method is inspired by [Alex Van de Sande's work](https://www.youtube.com/watch?v=1LVwWknE-NQ) and [Web3Connect](https://web3connect.com). In the future, the approach described here-after should be extended to work with any blockchain. - -## 2. Motivation - -Multiple wallet solutions can be used to interact with the Ethereum blockchain. Some (metamask, gnosis, ...) are compatible as they inject a standardized wallet object in the browser without requiring any effort from the Dapp developers, but they require an effort on the user side (user has to install the plugin). Other solutions (Portis, Authereum, Torus, Universal Login, ...) propose a more seamless flow to non-crypto-aware users but require an integration effort from the Dapp developers. Hardware wallet (ledger, trezor, keepkey, ...) also require integration effort from the Dapp developers. - -When Dapps integrate login with multiple solutions, they rely on the user choosing the correct wallet-provider. This could prove increasingly difficult as the number of wallet-provider increases, particularly for novice users. Additionally, if decentralized applications pick and choose only a handful of wallets to support, the current incumbent wallets will have a distinct advantage and new wallets will struggle to find adoption. This will create a less competitive environment and stifle innovation. Rather than relying on the user choosing which wallet-provider to connect with (as does Web3Connect), ENSLogin proposes to use user-owned ENS domain as entry points. Metadata attached to these ENS domains is used to detect which wallet-provider if used by the corresponding account. - -That way, ENSLogin would allow any user to connect to any Dapp with any wallet, using a simple domain as a login. - -## 3. Description - -### 3.1. Overview - -The ENSLogin works as follow: - -* Request an ENS domain from the user -* Resolve the ENS domain to retrieve (see [EIP-137](./eip-137.md)) - * An address (see [EIP-137](./eip-137.md)) - * A text entry (see [EIP-634](./eip-634.md)) -* Interpret the text entry and download the file it points to -* Evaluate the content of the downloaded file -* Return the corresponding object to the Dapp - -At this point, the app should process like with any web3 provider. Calling the `enable()` functions should ask the users for wallet specific credentials is needed. - -This workflow is to be implemented by an SDK that Dapp could easily import. The SDK would contain the resolution mechanism and support for both centralized and decentralized storage solution. Wallet-provider specific code should NOT be part of SDK. Wallet-provider specific code should only be present in the external file used to generate the web3 provider. - -### 3.2. Details - -* **Text entry resolution:** A pointer to the code needed to instantiate the wallet-provider is recorded using the ENS support for text entries (see [EIP-634](./eip-634.md)). The corresponding key is `enslogin` (**subject to change**). If no value is associated with the key `enslogin` at the targeted domain, we fallback to metadata store on the parent's node with the key `enslogin-default` (**subject to change**). -**Example:** for the ens domain `username.domain.eth`, the resolution would look for (in order): - * `resolver.at(ens.owner(nodehash("username.domain.eth"))).text(nodehash("username.domain.eth"), 'enslogin')` - * `resolver.at(ens.owner(nodehash("domain.eth"))).text(nodehash("domain.eth"), 'enslogin-default')` - -* **Provider link:** Code for instantiating the wallet-provider must be pointed to in a standardized manner. **This is yet not specified.** The current approach uses a human-readable format `scheme://path` such as: - - * `ipfs://Qm12345678901234567890123456789012345678901234` - * `https://server.com/enslogin-module-someprovider` - - And adds a suffix depending on the targeted blockchain type (see [SLIP 44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md)) and language. Canonical case is a webapp using ethereum so the target would be: - - * `ipfs://Qm12345678901234567890123456789012345678901234/60/js` - * `https://server.com/enslogin-module-someprovider/60/js` - - Note that this suffix mechanism is compatible with http/https as well as IPFS. It is a constraint on the storage layer as some may not be able to do this kind of resolution. - -* **Provider instantiation:** - * [JAVASCRIPT/ETHEREUM] The file containing the wallet-provider's code should inject a function `global.provider: (config) => Promise` that returns a promise to a standardized provider object. For EVM blockchains, the object should follow [EIP-1193](./eip-1193.md). - * Other blockchain types/langages should be detailed in the future. - - -* **Configuration object:** In addition to the username (ENS domain), the Dapp should have the ability to pass a configuration object that could be used by the wallet-provider instantiating function. This configuration should include: - * A body (common to all provider) that specify details about the targeted chain (network name / node, address of the ens entrypoint ...). If any of these are missing, a fallback can be used (mainnet as a default network, bootstrapping an in-browser IPFS node, ...). - * Wallet provider-specific fields (**optional**, starting with one underscore `_`) can be added to pass additional, wallet-provider specific, parameters / debugging flags. - * SDK specific fields (**optional**, starting with two underscores `__`) can be used to pass additional arguments. - - Minimal configuration: - ``` - { - provider: { - network: 'goerli' - } - } - ``` - Example of advanced configuration object: - ``` - { - provider: { - network: 'goerli', - ens: '0x112234455c3a32fd11230c42e7bccd4a84e02010' - }, - ipfs: { - host: 'ipfs.infura.io', - port: 5001, - protocol: 'https' - }, - _authereum: {...}, - _portis: {...}, - _unilogin: {...}, - _torus: {...}, - __callbacks: { - resolved: (username, addr, descr) => { - console.log(`[CALLBACKS] resolved: ${username} ${addr} ${descr}`); - }, - loading: (protocol, path) => { - console.log(`[CALLBACKS] loading: ${protocol} ${path}`); - }, - loaded: (protocol, path) => { - console.log(`[CALLBACKS] loaded: ${protocol} ${path}`); - } - } - } - ``` - -**TODO** *(maybe move that part to section 6.1)*: -Add [SLIP 44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) compliant blockchain description to the config for better multichain support. This will require a additional field `ENS network` to know which ethereum network to use for resolution when the targeted blockchain/network is not ethereum (could also be used for cross chain resolution on ethereum, for example xDAI login with metadata stored on mainnet) - -### 3.3. Decentralization - -Unlike solution like Web3Connect, ENSLogin proposes a modular approach that is decentralized by nature. -The code needed for a Dapp to use ENSLogin (hereafter referred to as the SDK) only contains lookup mechanism for the ethereum blockchain and the data storages solutions. The solution is limited by the protocols (https / ipfs / ...) that the SDK can interact with. Beyond that, any wallet-provider that follows the expected structure and that is available through one of the supported protocol is automatically compatible with all the Dapps proposing ENSLogin support. There is no need to go through a centralized approval process. Furthermore, deployed SDK do not need to be upgraded to benefit from the latest wallet updates. The only permissioned part of the protocol is in the ENS control of the users over the metadata that describes their wallet-provider implementation. Users could also rely on the fallback mechanism to have the wallet-provider update it for them. - -### 3.4. Incentives - -We believe ENSLogin's biggest strength is the fact that it aligns the incentives of Dapp developers and wallet-providers to follow this standard. - -* A wallet-provider that implements the required file and make them available will ensure the compatibility of its wallet with all Dapps using ENSLogin. This will remove the burden of asking all Dapps to integrate their solutions, which Dapps are unlikely to do until the wallet as strong userbase. Consequently, ENSLogin will improve the competition between wallet-providers and encourage innovation in that space -* A Dapp that uses ENSLogin protocol, either by including the ENSLogin's SDK or by implementing compatible behaviour, will make itself available to all the users of all the compatible wallet. At some point, being compatible with ENSLogin will be the easiest to reach a large user-base. -* ENSLogin should be mostly transparent for the users. Most wallet provider will set up the necessary entries without requiring any effort from the user. Advanced users can take control over the wallet resolution process, which will be simple once the right tooling is available. - -### 3.5. Drawbacks - -While ENSLogin allows dapps to support any wallet for logging in, dapps still must choose which wallets they suggest to users for registration. This can be done through a component like Web3Connect or BlockNative's - -## 4. Prototype - -**TODO** - -## 5. Support by the community - -### 5.1. Adoption - -| Name | Live | Module | Assigns ENS names | support by default | -| -------------- | ---- | ------ | ----------------- | ------------------ | -| Argent | yes | no | yes | no | -| Authereum | yes | yes | yes | no | -| Fortmatic | yes | no | no | no | -| Gnosis Safe | yes | yes\* | no | no | -| Ledger | yes | beta | no | no | -| KeepKey | yes | no | no | no | -| Metamask | yes | yes | no | no | -| Opera | yes | yes\* | no | no | -| Portis | yes | yes | no | no | -| SquareLink | yes | no | no | no | -| Shipl | no | no | no | no | -| Torus | yes | yes | no | no | -| Trezor | yes | no | no | no | -| UniLogin | beta | beta | yes | no | - -\*use the metamask module - -## 6. Possible evolutions - -### 6.1. Multichain support - -**TODO** - -## 7. FAQ - -### 7.1. Can anyone connect with my login? Where are my private keys stored? - -ENSLogin only has access to what is recorded on the ENS, namely your address and the provider you use. Private key management is a is handled by the provider and is outside ENSLogin's scope. Some might store the key on disk. Other might rely on custodial keys stored on a remote (hopefully secure) server. Others might use a dedicated hardware component to handle signature and never directly have access to the private key. - -### 7.2. How do I get an ENS Login? - -**TODO** (this might need a separate ERC) +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 index 6adb120d807661..1c2fb213efceb3 100644 --- a/EIPS/eip-2535.md +++ b/EIPS/eip-2535.md @@ -1,659 +1,7 @@ --- eip: 2535 -title: Diamonds -author: Nick Mudge (@mudgen) -discussions-to: https://github.com/ethereum/EIPs/issues/2535 -status: Draft -type: Standards Track category: ERC -created: 2020-02-22 +status: Moved --- - - -## Simple Summary - -Enables people to write smart contracts with virtually no size limit in a modular and gas-efficient way. - -Diamonds can be upgraded on the fly without having to redeploy existing functionality. - -Standardizes contract interfaces and implementation details of diamonds, enabling software integration and interoperability. - -A diamond is a contract that implements the Specification in this standard. - -Terminology from the diamond industry. - -## Motivation - -There are a number of different reasons to use diamonds. Here are some of them: - -1. **A single address for unlimited contract functionality.** Using a single address for contract functionality makes deployment, testing and integration with other smart contracts, software and user interfaces easier. -1. **Your contract exceeds the 24KB maximum contract size.** You may have related functionality that it makes sense to keep in a single contract, or at a single contract address. A diamond does not have a max contract size. -1. **A diamond provides a way to organize contract code and data.** You may want to build a contract system with a lot of functionality. A diamond provides a systematic way to isolate different functionality and connect them together and share data between them as needed in a gas-efficient way. -1. **A diamond provides a way to upgrade functionality.** Upgradeable diamonds can be upgraded to add/replace/remove functionality. Because diamonds have no max contract size, there is no limit to the amount of functionality that can be added to diamonds over time. Diamonds can be upgradeable or immutable. It is also possible to make an upgradeable diamond and then at a later time remove its upgrade capability. - -### Diamonds Support Transparency - -To find out what functions a regular smart contract has it is only necessary to look at its verified source code. - -The verified source code of a diamond does not include what functions it has so a different mechanism is needed. - -A diamond has four standard functions called the loupe functions that are used to show what functions a diamond has. - -The loupe functions can be used for many things including: -1. To show all functions used by a diamond. -1. To query services like Etherscan or files to retrieve and show all source code used by a diamond. -1. To query services like Etherscan or files to retrieve ABI information for a diamond. -1. To test or verify that a transaction that adds/replaces/removes functions on a diamond succeeded. -1. To find out what functions a diamond has before calling functions on it. -1. To be used by tools and programming libraries to deploy and upgrade diamonds. -1. To be used by user interfaces to show information about diamonds. -1. To be used by user interfaces to enable users to call functions on diamonds. - -Diamonds support another form of transparency which is a historical record of all upgrades on a diamond. This is done with the DiamondCut event which is used to record all functions that are added, replaced or removed on a diamond. - -This standard is an improvement of [EIP-1538 Transparent Contract Standard](https://eips.ethereum.org/EIPS/eip-1538). The same motivations of that standard apply to this standard. - -See the [Learning & References section](https://eips.ethereum.org/EIPS/eip-2535#learning--references) for additional information and uses of diamonds. - -## What is a Diamond? - -A diamond is a contract with external functions that are supplied by contracts called **facets**. - -Facets are separate, independent contracts that can share internal functions, libraries and state variables. - -## How a Diamond Works - -A diamond stores within it a mapping of function selector to facet address, for example `selectorToFacet`. - -When an external function is called on a diamond its fallback function is executed. The fallback function finds in the `selectorToFacet` mapping which facet has the function that has been called and then executes that function from the facet using `delegatecall`. - -A diamond's fallback function and `delegatecall` enable a diamond to execute a facet's external function as its own external function. The `msg.sender` and `msg.value` values do not change and only the diamond's contract storage is read and written to. - -Here is a simple example of a diamond's fallback function: - -```Solidity -// Find facet for function that is called and execute the -// function if a facet is found and return any value. -fallback() external payable { - address facet = selectorTofacet[msg.sig]; - require(facet != address(0)); - // Execute external function from facet using delegatecall and return any value. - assembly { - calldatacopy(0, 0, calldatasize()) - let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) - returndatacopy(0, 0, returndatasize()) - switch result - case 0 {revert(0, returndatasize())} - default {return (0, returndatasize())} - } -} -``` - -A diamond can use a `diamondCut` function to add/replace/remove any number of functions from any number of facets in a single transaction. `diamondCut` updates the mapping of function selector to facet address. Other such functions can be used. - -An event is emitted any time external functions are added, replaced or removed to report what changed. - -A diamond has four standard external functions that can be called to show what facets and functions it currently has. - -## Upgrades and Immutability - -A diamond can be immutable from inception by not adding any external functions that can add/replace/remove functions. [There are number of reasons to do this.](#different-kinds-of-diamonds) - -A diamond that is mutable can be made immutable by removing such functions. - -A diamond can be upgraded if it has a diamondCut external function or other function(s) that can add/replace/remove functions. - -## Organizing State Variables in Diamonds - -A state variable or storage layout organizational pattern is needed because Solidity's builtin storage layout system doesn't support proxy contracts or diamonds. - -Described below are diamond storage and AppStorage which are two state variable organizational patterns that have been successfully used in diamonds. - -Another successful pattern has been to write a storage contract that contains all state variables and is inherited by all facets. - -## Facets, State Variables and Diamond Storage - -A facet defines external functions and can define or use internal functions, libraries, and state variables. - -A facet can declare state variables in structs. Each struct is given a specific position in contract storage. This technique is called **Diamond Storage**. - -Here is a simple example that shows diamond storage and its use in a facet: - -```Solidity -// A contract that implements diamond storage. -library LibA { - - // This struct contains state variables we care about. - struct DiamondStorage { - address owner; - bytes32 dataA; - } - - // Returns the struct from a specified position in contract storage - // ds is short for DiamondStorage - function diamondStorage() internal pure returns(DiamondStorage storage ds) { - // Specifies a random position from a hash of a string - bytes32 storagePosition = keccak256("diamond.storage.LibA") - // Set the position of our struct in contract storage - assembly {ds.slot := storagePosition} - } -} - -// Our facet uses the diamond storage defined above. -contract FacetA { - - function setDataA(bytes32 _dataA) external { - LibA.DiamondStorage storage ds = LibA.diamondStorage(); - require(ds.owner == msg.sender, "Must be owner."); - ds.dataA = _dataA - } - - function getDataA() external view returns (bytes32) { - return LibA.diamondStorage().dataA - } -} -``` - -Any number of structs, each with a different storage position, can be used by a facet. - -By using diamond storage facets can declare their own state variables that do not conflict with the storage locations of state variables declared in other facets. - -By using diamond storage facets can be developed independently, without connection or concern for other facets. - -## AppStorage - -A specialized version of diamond storage is AppStorage. This pattern is used to more conveniently and easily share state variables between facets. - -The AppStorage pattern is implemented by defining a struct called AppStorage that contains the state variables of your application. It can contain any number of state variables of any type, including arrays and mappings, and more can be added in upgrades. - -The AppStorage struct is defined or imported and declared as the first and only state variable directly (or via inheritance) in any facet that uses it. This means that AppStorage is always located at position 0 in contract storage. - -The AppStorage state variable is often named `s` to provide easy access to it and to distinguish state variables from function arguments, function names, and local variables. - -Here is a simple example of a contract that uses AppStorage: - -```Solidity -import "./AppStorage.sol" - -contract StakingFacet { - AppStorage internal s; - - function myFacetFunction(uint256 _nextVar) external { - s.total = s.firstVar + _nextVar; - } - -``` - -The above example accesses the `s.firstVar` state variable and stores a computation in the `s.total` state variable. - -Read this article to learn more about AppStorage: [AppStorage Pattern for State Variables in Solidity](https://dev.to/mudgen/appstorage-pattern-for-state-variables-in-solidity-3lki). - - -## Diamonds Can Use Other Contract Storage Strategies - -Diamonds and facets don't have to use diamond storage or AppStorage. They can use or mix with other contract storage strategies such as contract inheritance. - -Diamonds only need to implement the [Specification section](#specification) of this standard. - -## Facets Can Share State and Functionality - -Facets can share state variables by using the same structs at the same storage positions. - -Facets can share internal functions and libraries by inheriting the same contracts or using the same libraries. - -In these ways facets are separate, independent units but can share state and functionality. - -## Facets are Reusable and Composable - -A deployed facet can be used by any number of diamonds. - -Different combinations of facets can be used with different diamonds. - -It is possible to create and deploy a set of facets that are reused by different diamonds over time. - -The ability to use the same deployed facets for many diamonds reduces deployment costs. - -A limitation is that two external functions with the same function signature can't be added to a diamond at the same time because a diamond, or any contract, cannot have two external functions with the same function signature. - -## Diagrams - -### Diamond Structure - -This diagram shows the structure of a diamond: - - - -### Diamond Storage - -The diagram below shows facets with their own data and data shared between them. - -Notice that all data is stored in the diamond. But different facets have different access to data. - -In this diagram - -- Only FacetA can access DataA -- Only FacetB can access DataB -- Only the diamond's own code can access DataD. -- FacetA and FacetB share access to DataAB. -- The diamond's own code, FacetA and FacetB share access to DataABD. - - - -### Deployed Facets Can Be Reused - -A deployed facet can be used by any number of diamonds. - -The diagram below shows two diamonds using the same two facets. - -- FacetA is used by Diamond1 -- FacetA is used by Diamond2 -- FacetB is used by Diamond1 -- FacetB is used by Diamond2 - - - -## Some Diamond Benefits - -1. A stable contract address that provides needed functionality. -1. A single address with the functionality of multiple contracts (facets) that are independent from each other but can share internal functions, libraries and state variables. -1. A way to add, replace and remove multiple external functions atomically (in the same transaction). -1. Fine-grained upgrades, so you can change just the parts of a diamond that need to be changed. -1. Have greater control over when and what functions exist. -1. Decentralized Autonomous Organizations (DAOs) and other governance systems can be used to upgrade diamonds. -1. An event that shows what functions are added, replaced and removed. -1. The ability to show all changes made to a diamond. -1. Increase trust over time by showing all changes made to a diamond. -1. A way to look at a diamond to see its current facets and functions. -1. Have an immutable, trustless diamond. -1. Solves the 24KB maximum contract size limitation. Diamonds can be any size. -1. Separate functionality can be implemented in separate facets and used together in a diamond. -1. Larger contracts have to reduce their size by removing error messages and other things. You can keep your error messages and the full functionality that you need by implementing a diamond. -1. Enables zero, partial or full diamond immutability as desired, and when desired. -1. The ability to develop and improve an application over time with an upgradeable diamond and then make it immutable and trustless if desired. -1. Develop incrementally and let your diamond grow with your application. -1. Upgrade diamonds to fix bugs, add functionality and implement new standards. -1. Organize your code with a diamond and facets. -1. Diamonds can be large (have many functions) but still be modular because they are compartmented with facets. -1. Contract architectures that call multiple contracts in a single transaction can save gas by condensing those contracts into a single diamond and accessing state variables directly. -1. Save gas by creating external functions for specific use cases, such as bulk transfers. -1. Diamonds are designed for tooling and user-interface software. - -### New User-Interface Software & Libraries - -User-interface software can be written to show all documentation, functions and source code used by a diamond. - -Diamond events can be filtered from the Ethereum blockchain to show all changes to a diamond. - -Existing and new programming libraries and software can be used to deploy, show, upgrade and use diamonds. - -### Upgradeable Diamond vs. Centralized Private Database - -Why have an upgradeable diamond instead of a centralized, private, mutable database? - -1. Decentralized Autonomous Organizations (DAOs) and other governance systems can be used to upgrade diamonds. -1. Wide interaction and integration with the Ethereum ecosystem. -1. With open storage data and verified source code it is possible to show a provable history of trustworthiness. -1. With openness bad behavior can be spotted and reported when it happens. -1. Independent security and domain experts can review the change history of contracts and vouch for their history of trustworthiness. -1. It is possible for an upgradeable diamond to become immutable and trustless. - -### Different Kinds of Diamonds - -Many designs of diamonds are possible. Here are a few kinds of diamonds and their uses. - -**Upgradeable Diamond** -An upgradeable diamond has the `diamondCut` function and/or possibly other functions to add/replace/remove functions. It is useful for iterative development or improving an application over time. - -**Finished Diamond** -A finished diamond was an upgradeable diamond and had a number of upgrades. Then its `diamondCut` function and/or other upgrade functions were removed and upgrades are no longer possible. It is no longer possible to add/replace/remove functions. It has become an immutable diamond. - -**Single Cut Diamond** -A single cut diamond adds all functions to itself in its constructor function, but it does not add the `diamondCut` function or any other function that can add/replace/remove functions. This means that a single cut diamond is fully created in its constructor and once created can never be upgraded. It has the same immutability and trustless guarantees as a regular vanilla contract. Why would someone do this? There may be a number of reasons. The two use cases below are good reasons. - -1. Your contract hits the max contract size limit. Make it into a single cut diamond. You still break your big contract into smaller facets, modularizing your code. -2. You start with an upgradeable diamond in your development and testing and upgrade it to your heart's delight. Reap the advantages of easy upgrading and a stable address as you work out new features, bugs and kinks. Release the upgradeable diamond on a test network with your application for beta testing and upgrade it when needed. This is iterative development. When it is solid then deploy it as a single cut diamond on the main network. - -## 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 contract storage of the calling contract, not the contract where the functions are defined. - -> **Note:** This specification specifies what needs to be implemented for a contract to be a diamond. - -### Terms - -1. A **diamond** is a contract that uses functions from its facets to execute function calls. A diamond can have one or more facets. -2. The word **facet** comes from the diamond industry. It is a side, or flat surface of a diamond. A diamond can have many facets. In this standard a facet is a contract with one or more functions that executes functionality of a diamond. -3. A **loupe** is a magnifying glass that is used to look at diamonds. In this standard a loupe is a facet that provides functions to look at a diamond and its facets. -4. An **immutable function** is a function that is defined directly in a diamond and so cannot be replaced or removed. Or it is a function that is defined in a facet that cannot be replaced or removed because all upgrade functions have been removed from a diamond. - -### General Summary - -A diamond calls functions from its facets using `delegatecall`. - -In the diamond industry diamonds are created and shaped by being cut, creating facets. In this standard diamonds are cut by adding, replacing or removing facets and their functions. - -#### The diamondCut Function - -The standard `diamondCut` function specified below can be used to add/replace/remove any number of functions from/to a diamond in a single transaction. - -The standard `diamondCut` function below is specified for the purpose of interoperability. Diamond tools, software and user-interfaces should expect and use the standard `diamondCut` function. Diamonds that might work with diamond specific tooling to add/replace/remove functions should implement the standard `diamondCut` function. - -The `diamondCut` function is optional. It does not have to be implemented in a diamond. For example an immutable diamond wouldn't have this function. - -You can implement your own custom functions that add or replace or remove functions. You can also implement your own non-standard versions of `diamondCut` that have different parameters. - -If you want to create your own custom function(s) for adding/replacing/removing functions you might also want to implement the standard `diamondCut` function for interoperability with tools. - -**In ALL cases any function or code that adds or replaces or removes one or more functions MUST emit the standard DiamondCut event specified below.** - -The `DiamondCut` event records all changes to a diamond. - -### Diamond Interface - -```Solidity -interface IDiamondCut { - enum FacetCutAction {Add, Replace, Remove} - // Add=0, Replace=1, Remove=2 - - struct FacetCut { - address facetAddress; - FacetCutAction action; - bytes4[] functionSelectors; - } - - /// @notice Add/replace/remove any number of functions and optionally execute - /// a function with delegatecall - /// @param _diamondCut Contains the facet addresses and function selectors - /// @param _init The address of the contract or facet to execute _calldata - /// @param _calldata A function call, including function selector and arguments - /// _calldata is executed with delegatecall on _init - function diamondCut( - FacetCut[] calldata _diamondCut, - address _init, - bytes calldata _calldata - ) external; - - event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); -} -``` - -#### Adding/Replacing/Removing Functions - -A diamond contains within it a mapping of function selectors to facet addresses. Functions are added/replaced/removed by modifying this mapping. - -The `_diamondCut` argument is an array of FacetCut structs. - -Each FacetCut struct contains a facet address and array of function selectors that are updated in a diamond. - -To add new functions create a FacetCut struct with `facetAddress` set to the facet that has the new functions and `functionSelectors` set with the function selectors to add. Set the `action` enum to `Add`. - -To replace functions create a FacetCut struct with `facetAddress` set to the facet that has the replacement functions and `functionSelectors` set with the function selectors to replace. Set the `action` enum to `Replace`. - -To remove functions create a FacetCut struct with `facetAddress` set to `address(0)` and `functionSelectors` set with the function selectors to remove. Set the `action` enum to `Remove`. - -It is the design of the `diamondCut` function that cuts are explicit and intentional. - -The `diamondCut` function reverts when attempting to add a function that already exists. - -The `diamondCut` function reverts when attempting to replace a function with a facet it is already using. - -The `diamondCut` function reverts when attempting to remove a function that already does not exist. - -#### Executing \_calldata - -After adding/replacing/removing functions the `_calldata` argument is executed with `delegatecall` on `_init`. This execution is done to initialize data or setup or remove anything needed or no longer needed after adding, replacing and/or removing functions. - -If the `_init` value is `address(0)` then `_calldata` must contain 0 bytes or the transaction reverts. - -If the `_init` value is not `address(0)` then `_calldata` must contain more than 0 bytes or the transaction reverts. - -If `_init` is `address(0)` and `_calldata` contains 0 bytes then `_calldata` execution is skipped. `_calldata` is not executed and the `diamondCut` call can complete successfully. - -#### DiamondCut Event - -The `_diamondCut`, `_init`, and `_calldata` arguments are passed directly to the `DiamondCut` event. - -Any time one or more functions are added, replaced or removed the `DiamondCut` event MUST be emitted to record changes. - -### Diamond Loupe - -> A loupe is a small magnifying glass used to look at diamonds. -> These functions look at diamonds. - -The function selectors used by a diamond are queried to get what functions the diamond has and what facets are used. - -A diamond loupe is a facet that implements this interface: - -```Solidity -// A loupe is a small magnifying glass used to look at diamonds. -// These functions look at diamonds -interface IDiamondLoupe { - /// These functions are expected to be called frequently - /// by tools. - - struct Facet { - address facetAddress; - bytes4[] functionSelectors; - } - - /// @notice Gets all facet addresses and their four byte function selectors. - /// @return facets_ Facet - function facets() external view returns (Facet[] memory facets_); - - /// @notice Gets all the function selectors supported by a specific facet. - /// @param _facet The facet address. - /// @return facetFunctionSelectors_ - function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); - - /// @notice Get all the facet addresses used by a diamond. - /// @return facetAddresses_ - function facetAddresses() external view returns (address[] memory facetAddresses_); - - /// @notice Gets the facet that supports the given selector. - /// @dev If facet is not found return address(0). - /// @param _functionSelector The function selector. - /// @return facetAddress_ The facet address. - function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); -} -``` - -See an [example implementation](https://github.com/mudgen/Diamond) to see how this can be implemented. - -The loupe functions can be used in user-interface software. A user interface calls these functions to provide information about and visualize diamonds. - -The loupe functions can be used in deployment functionality, upgrade functionality, testing and other software. - -Some loupe implementations are not gas efficient and should not be called in on-chain transactions. Some loupe implementations may be gas efficient and can be called in on-chain transactions. Read the documentation of the loupe implementation you use. - -### Implementation Points - -A diamond implements the following implementation points: - -1. A diamond contains a fallback function and zero or more immutable functions that are defined within it. -1. A diamond associates function selectors with facets. -1. When a function is called on a diamond it executes immediately if it is an "immutable function" defined in the diamond. Otherwise the diamond's fallback function is executed. The fallback function finds the facet associated with the function and executes the function using `delegatecall`. If there is no facet for the function and no other mechanism to handle it then execution reverts. -1. Each time functions are added, replaced or removed a `DiamondCut` event is emitted to record it. -1. A diamond implements the DiamondLoupe interface. -1. All immutable functions must be emitted in the `DiamondCut` event as new functions added. And the loupe functions must return information about immutable functions if they exist. The facet address for an immutable function is the diamond's address. -1. Optionally a diamond implements ERC165. If a diamond has the `diamondCut` function then the interface ID used for it is `IDiamondCut.diamondCut.selector`. The interface ID used for the diamond loupe interface is `IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector`. - -The diamond address is the address that users interact with. The diamond address does not change. Only facet addresses can change by using the `diamondCut` function, or other function. - -## Implementation - -Example diamond implementations exist in the [Diamond repository](https://github.com/mudgen/Diamond). - -## Rationale - -### Using Function Selectors - -User interface software can be used to retrieve function selectors and face addresses from a diamond in order show what functions a diamond has. - -This standard is designed to make diamonds work well with user-interface software. Function selectors with the ABI of a contract provide enough information about functions to be useful for user-interface software. - -### Gas Considerations - -Delegating function calls does have some gas overhead. This is mitigated in several ways: - -1. Because diamonds do not have a max size limitation it is possible to add gas optimizing functions for use cases. For example someone could use a diamond to implement the ERC721 standard and implement batch transfer functions from the [ERC1412 standard](https://github.com/ethereum/EIPs/issues/1412) to reduce gas (and make batch transfers more convenient). -1. Some contract architectures require calling many contracts in one transaction. Gas savings can be realized by condensing those contracts into a single diamond and accessing contract storage directly. -1. Facets 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. -1. The Solidity optimizer can be set to a high setting causing more bytecode to be generated but the facets will use less gas when executed. - -### Diamond Storage - -Since Solidity 0.6.4 it is possible to create pointers to structs in arbitrary places in contract storage. This enables diamonds and their facets to create their own storage layouts that are separate from each other and do not conflict with each other, but can still be shared between them. See this blog post for more information: [New Storage Layout For Proxy Contracts and Diamonds](https://medium.com/1milliondevs/new-storage-layout-for-proxy-contracts-and-diamonds-98d01d0eadb). The example implementation for EIP-2535 uses diamond storage. - -Diamond storage is not the same thing as unstructured storage. Unstructured storage reads and writes specific values like unsigned integers and addresses at specified locations in contract storage. Diamond storage uses structs at specified locations in contract storage for reading and writing. Structs can hold any number of state variables of any type. - -### Versions of Functions - -Software or a user can verify what version of a function is called by getting the facet address of the function. This can be done by calling the `facetAddress` function from the DiamondLoupe interface. This function takes a function selector as an argument and returns the facet address where it is implemented. - -### Sharing Functions Between Facets - -In some cases it might be necessary to call a function defined in a different facet. -Here are some solutions to this: - -1. Copy internal function code in one facet to the other facet. -1. Put common internal functions in a contract that is inherited by multiple facets. -1. Put common internal functions in a Solidity library and use the library in facets. -1. A type safe way to call an external function defined in another facet is to do this: MyOtherFacet(this).myFunction(arg1, arg2) -1. A more gas-efficient way to call an external function defined in another facet is to use `delegatecall`. Here is an example of doing that: -```Solidity -DiamondStorage storage ds = diamondStorage(); -bytes4 functionSelector = bytes4(keccak256("myFunction(uint256)")); -// get facet address of function -address facet = ds.selectorToFacet[functionSelector]; -bytes memory myFunctionCall = abi.encodeWithSelector(functionSelector, 4); -(bool success, uint result) = address(facet).delegatecall(myFunctionCall); -require(success, "myFunction failed"); -``` -6. Instead of calling an external function defined in another facet you can instead create an internal function version of the external function. Add the internal version of the function to the facet that needs to use it. - -## Security Considerations - -### Ownership and Authentication - -> **Note:** The design and implementation of diamond ownership/authentication 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. - -It is possible to create many different authentication or ownership schemes with EIP-2535. Authentication schemes can be very simple or complex, fine grained or coarse. EIP-2535 does not limit it in any way. For example ownership/authentication could be as simple as a single account address having the authority to add/replace/remove functions. Or a decentralized autonomous organization could have the authority to only add/replace/remove certain functions. - -Consensus functionality could be implemented such as an approval function that multiple different people call to approve changes before they are executed with the `diamondCut` function. These are just examples. - -The development of standards and implementations of ownership, control and authentication of diamonds is encouraged. - -### Security of Diamond Storage - -If a person can add/replace functions then that person can alter storage willy-nilly. This is very powerful and very dangerous. However the capability can be used while eliminating or reducing the danger. The danger is eliminated or reduced by limiting **who** can add/replace/remove functions, limiting **when** functions can be added/replaced/removed and by **transparency**. - -**Who** -Here are some ways **who** can be limited: - -1. Only allow a trusted individual or organization to make diamond upgrades. -1. Only allow a distributed autonomous organization to make diamond upgrades. -1. Only allow multi-signature upgrades. -1. Only allow the end user who owns his own diamond to make upgrades. This enables users to opt-in to upgrades. -1. Don't allow anybody to make upgrades by making a single cut diamond. - -**When** -Here are some ways **when** can be limited: - -1. Only allow upgrades during development and testing. Make a single cut diamond for main network release. -1. Use an upgradeable diamond until it is certain that no new features are needed and then make it a finished diamond by removing the ability to add/replace/remove functions. -1. Program into the `diamondCut` function certain periods of time that the diamond can be upgraded. For example the `diamondCut` function could be programmed so that a diamond could only be upgraded during a specific five hour period each year. Attention and transparency could be applied to that five hour period to ensure upgrades are done right. - -**Transparency** -Transparency provides certainty and proof that upgrades are done correctly and honestly. - -1. Publish and make available verified source code used by diamonds and facets. -1. Provide documentation for diamonds, facets, upgrade plans, and results of upgrades. -1. Provide tools and/or user interfaces that make your diamonds more visible and understandable. - -### Function Selector Clash - -A function selector clash occurs when two different function signatures hash to the same four-byte hash. This has the unintended consequence of replacing an existing function in a diamond when the intention was to add a new function. This scenario is not possible with the `diamondCut` function because it prevents adding function selectors that already exist. - -### Transparency - -Diamonds emit an event every time one or more functions are added, replaced or removed. All source code can be verified. This enables people and software to monitor changes to a contract. If any bad acting function is added to a diamond then it can be seen. - -Security and domain experts can review the history of change of a diamond to detect any history of foul play. - -## Backwards Compatibility - -This standard makes upgradeable diamonds compatible with future standards and functionality because new functions can be added and existing functions can be replaced or removed. - -## Learning & References - -### Diamond Articles - -[Why Ethereum Diamonds Need A Standard](https://dev.to/mudgen/why-diamonds-need-a-standard-1i1h) - -[Ethereum's Maximum Contract Size Limit is Solved with EIP-2535 Diamonds](https://dev.to/mudgen/ethereum-s-maximum-contract-size-limit-is-solved-with-the-diamond-standard-2189) - -[Understanding Diamonds](https://dev.to/mudgen/understanding-diamonds-on-ethereum-1fb) - -[Why Ethereum Diamonds Need A Standard](https://dev.to/mudgen/why-diamonds-need-a-standard-1i1h) - -[Diamond Loupe Functions?](https://dev.to/mudgen/why-loupe-functions-for-diamonds-1kc3) - -[EIP-2535 Diamonds: A new paradigm for upgradeability](https://medium.com/derivadex/the-diamond-standard-a-new-paradigm-for-upgradeability-569121a08954) - -[Upgradeable smart contracts using EIP-2535 Diamonds](https://hiddentao.com/archives/2020/05/28/upgradeable-smart-contracts-using-diamond-standard) - -[Ethereum Diamonds for On-Chain Decentralized Governance](https://dev.to/mudgen/ethereum-diamonds-for-on-chain-decentralized-governance-39op) - -[How to Share Functions Between Facets of a Diamond](https://dev.to/mudgen/how-to-share-functions-between-facets-of-a-diamond-1njb) - -### Diamond Storage Articles - -[How Diamond Storage Works](https://dev.to/mudgen/how-diamond-storage-works-90e) - -[AppStorage Pattern for State Variables in Solidity](https://dev.to/mudgen/appstorage-pattern-for-state-variables-in-solidity-3lki) - -[New Storage Layout For Proxy Contracts and Diamonds](https://medium.com/1milliondevs/new-storage-layout-for-proxy-contracts-and-diamonds-98d01d0eadb) - -[Solidity Libraries Can't Have State Variables -- Oh Yes They Can!](https://dev.to/mudgen/solidity-libraries-can-t-have-state-variables-oh-yes-they-can-3ke9) - -[ Smart Contracts Sharing Common Data](https://medium.com/coinmonks/smart-contracts-sharing-common-data-777310263ac0?source=friends_link&sk=b462ff3559ae9c8da243ba31a557e4f4) - -[Sharing Common Data Using Libraries](https://medium.com/coinmonks/sharing-common-data-using-libraries-6573857d328c?source=friends_link&sk=1da1ef153b8d15f3f7bb9f4ce429890a) - -### Diamond Tools - -[Louper](https://louper.dev/) A user interface for all diamonds. - -[buidler-deploy](https://github.com/wighawag/buidler-deploy#diamonds-and-facets) - -### Implementations - -[Diamond example implementations](https://github.com/mudgen/Diamond) - -[GHST Staking](https://github.com/aavegotchi/ghst-staking) - -[pie-dao / ExperiPie](https://github.com/pie-dao/ExperiPie) - -[Nayms Contracts](https://github.com/nayms/contracts) - -[Aavegotchi Diamond](https://github.com/aavegotchi/aavegotchi-contracts) - -### Help - -[EIP-2535 Diamonds Discord](https://discord.gg/kQewPw2) - -## Inspiration & Development - -EIP-2535 is an improved design over [EIP-1538](./eip-1538.md) using ABIEncoderV2 and function selectors. - -EIP-2535 replaces EIP-1538. - -This standard was inspired by [EIP-1538](./eip-1538.md) and 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). - -## 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-2535.md diff --git a/EIPS/eip-2537.md b/EIPS/eip-2537.md index df7d5bdbdc2898..20275da7b2bff8 100644 --- a/EIPS/eip-2537.md +++ b/EIPS/eip-2537.md @@ -1,7 +1,8 @@ --- eip: 2537 title: Precompile for BLS12-381 curve operations -author: Alex Vlasov (@shamatar), Kelly Olson (@ineffectualproperty) +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: Review type: Standards Track @@ -9,59 +10,57 @@ category: Core created: 2020-02-21 --- -## Simple Summary - -This precompile adds operation on BLS12-381 curve as a precompile in a set necessary to *efficiently* perform operations such as BLS signature verification and perform SNARKs verifications. - ## Abstract -If `block.number >= X` we introduce *nine* separate precompiles to perform the following operations: +Add functionality to efficiently perform operations over the BLS12-381 curve, including those for BLS signature verification. -- BLS12_G1ADD - to perform point addition in G1 (curve over base prime field) with a gas cost of `500` gas -- BLS12_G1MUL - to perform point multiplication in G1 (curve over base prime field) with a gas cost of `12000` gas -- BLS12_G1MULTIEXP - to perform multiexponentiation 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 `800` gas -- BLS12_G2MUL - to perform point multiplication in G2 (curve over quadratic extension of the base prime field) with a gas cost of `45000` gas -- BLS12_G2MULTIEXP - to perform multiexponentiation in G2 (curve over quadratic extension of the base prime field) with a gas cost formula defined in the corresponding section -- BLS12_PAIRING - 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 gast cost of `5500` gas -- BLS12_MAP_FP2_TO_G2 - maps extension field element into the G2 point with a gas cost of `75000` gas +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. -Mapping functions specification is included as a separate [document](../assets/eip-2537/field_to_curve.md). Mapping function does NOT perform mapping of the byte string into 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 field element into curve point. Such functionality is required for signature schemes. +## Motivation -Multiexponentiation operation is included to efficiently aggregate public keys or individual signer's signatures during BLS signature verification. +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. -### Proposed addresses table +## Specification -|Precompile |Address | -|---|---| -|BLS12_G1ADD | 0x0a | -|BLS12_G1MUL | 0x0b | -|BLS12_G1MULTIEXP | 0x0c | -|BLS12_G2ADD | 0x0d | -|BLS12_G2MUL | 0x0e | -|BLS12_G2MULTIEXP | 0x0f | -|BLS12_PAIRING | 0x10 | -|BLS12_MAP_FP_TO_G1 | 0x11 | -|BLS12_MAP_FP2_TO_G2 | 0x12 | +### Constants -## Motivation +| 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 | -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. +We introduce *seven* separate precompiles to perform the following operations: -## Specification +- 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: +### Curve parameters -BLS12 curve is fully defined by the following set of parameters (coefficient `A=0` for all BLS12 curves): +The BLS12 curve is fully defined by the following set of parameters (coefficient `A=0` for all BLS12 curves): ``` -Base field modulus = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +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 = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 +Main subgroup order = q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 Extension tower Fp2 construction: -Fp quadratic non-residue = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa +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 @@ -70,10 +69,10 @@ Twist type: M B coefficient for twist c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 B coefficient for twist c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 Generators: -G1: +H1: X = 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb Y = 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1 -G2: +H2: X c0 = 0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8 X c1 = 0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e Y c0 = 0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801 @@ -83,37 +82,47 @@ Pairing parameters: x is negative = true ``` -One should note that base field modulus 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`. +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: -To encode points involved in the operation one has to encode elements of the base field and the extension field. +In order to produce inputs to an operation, one encodes 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. +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 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). +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's required that encoded element is "in a field" that means strictly `< modulus`. In BigEndian encoding it automatically means that for a modulus that is just `381` bit long top `16` bytes in `64` bytes encoding are zeroes and it **must** be checked if only a subslice of input data is used for actual decoding. +*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. -If encodings do not follow this spec anywhere during parsing in the precompile the precompile *must* return an error. +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 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. +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 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. +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: -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. +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 multiexponentiations (takes a list of pairs `(point, scalar)`), or pairing (takes a list of `(G1, G2)` points). While their behavior is well-defined (from arithmetic perspective) on empty inputs, this EIP discourages such use cases and variable input length operations must return an error if input is empty. +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 @@ -122,103 +131,106 @@ Certain operations have variable length input, such as multiexponentiations (tak 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 +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point +- Input has invalid length -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). +Note: -Error cases: -- Point being not on the curve must result in error -- Field elements encoding rules apply (obviously) -- Input has invalid length +There is no subgroup check for the G1 addition precompile. -#### ABI for G1 multiexponentiation +#### ABI for G1 MSM -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). +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: -- Any of G1 points being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- 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 -- Input is empty #### 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). +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: -- Either of points being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point - Input has invalid length -#### ABI for G2 multiplication +Note: -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). +There is no subgroup check for the G2 addition precompile. -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 MSM -#### 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). +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: -- Any of G2 points being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- 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 -- Input is empty -#### ABI for pairing +#### 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: -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. +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: -- 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) + +- 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 -- Input is empty + +Note: + +If any input is the infinity point, pairing result will be 1. Protocols may want to check and reject infinity points prior to calling the precompile. #### ABI for mapping Fp element to G1 point -Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field. Output of this call is `128` bytes and is G1 point following respective encoding rules. +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 a valid field element +- Input is not correctly encoded #### ABI for mapping Fp2 element to G2 point -Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field. Output of this call is `256` bytes and is G2 point following respective encoding rules. +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 a valid field element +- Input is not correctly encoded -### Gas burinig on error +### Gas burning on error -Following the current state of all other precompiles if 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. +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 -Sane implementation of this EIP *should not* contain infinite cycles (it is possible and not even hard to implement all the functionality without `while` cycles) and gas schedule accurately reflects a time spent on computations of the corresponding function (precompiles pricing reflects an amount of gas consumed in the worst case where such case exists). +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 a constant `30 MGas/second` following prices are suggested. +Assuming `EcRecover` precompile as a baseline. #### G1 addition -`500` gas +`375` gas #### G1 multiplication @@ -226,106 +238,123 @@ Assuming a constant `30 MGas/second` following prices are suggested. #### G2 addition -`800` gas +`600` gas #### G2 multiplication -`45000` gas +`22500` gas + +#### G1/G2 MSM -#### G1/G2 Multiexponentiation +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`. -Multiexponentiations are expected to be performed by the Peppinger algorithm (we can also say that is **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 cup `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. -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. +G1 and G2 are priced separately, each having their own discount table and `max_discount`. -Discounts table as a vector of pairs `[k, discount]`: +##### G1 discounts + +Discounts table for G1 MSM 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]] +[[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 = 174` +`max_discount = 519` -#### Pairing operation +##### G2 discounts -Cost of the pairing operation is `43000*k + 65000` where `k` is a number of pairs. +Discounts table for G2 MSM as a vector of pairs `[k, discount]`: -#### Fp-to-G1 mappign operation +``` +[[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 mappign operation +#### Fp2-to-G2 mapping operation -Fp2 -> G2 mapping is `75000` gas +Fp2 -> G2 mapping is `23800` gas #### Gas schedule clarifications for the variable-length input -For multiexponentiation and pairing functions gas cost depends on the input length. The current state of how gas schedule is implemented in major clients (at the time of writing) is that 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 gas cost functions **must** be implemented to ensure consistency between clients and safety. +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 Multiexponentiation +##### 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; +``` +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 number of pairs. If length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on precompile will return an error. Also, case when `k = 0` is safe: `CALL` or `STATICCALL` cost is non-zero, and case with formal zero gas cost is already used in `Blake2f` precompile. In any case, main precompile routine **must** produce an error on such an input because it violated encoding rules. +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 = 23000*k + 115000; - - return gas_cost; +``` +k = floor(len(input) / LEN_PER_PAIR); +gas_cost = 32600*k + 37700; +return gas_cost; ``` -We use floor division to get number of pairs. If length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on precompile will return an error (precompile routine **must** produce an error on such an input because it violated encoding rules). +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 -Motivation section covers a total motivation to have operations over BLS12-381 curve available. We also extend a rationale for move specific fine points. +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 -### Multiexponentiation 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). -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). +### 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. -## 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). +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 -Algorithms and set of parameters for SWU mapping method is provided by a separate [document](../assets/eip-2537/field_to_curve.md) +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. 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. +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. -Requeired properties for basic ops (add/multiply): +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` @@ -334,8 +363,13 @@ Requeired properties for basic ops (add/multiply): - 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) + +- 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 @@ -344,7 +378,8 @@ A set of test vectors for quick benchmarking on new implementations is located i ## Reference Implementation There are two fully spec compatible implementations on the day of writing: -- One in Rust language that is based on the EIP1962 code and integrated with OpenEthereum for this library + +- 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 @@ -354,4 +389,5 @@ Strictly following the spec will eliminate security implications or consensus im 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](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2539.md b/EIPS/eip-2539.md index 8977521b907d8c..3e4f850a592dfd 100644 --- a/EIPS/eip-2539.md +++ b/EIPS/eip-2539.md @@ -1,7 +1,8 @@ --- eip: 2539 title: BLS12-377 curve operations -author: Alex Vlasov (@shamatar) +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: Draft type: Standards Track @@ -10,11 +11,10 @@ created: 2020-02-26 requires: 1109, 2046 --- -## Simple Summary -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. - ## 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 @@ -24,22 +24,27 @@ If `block.number >= X` we introduce *nine* separate precompiles to perform the f - 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 | 0x13 | -|BLS12_377_G1MUL | 0x14 | -|BLS12_377_G1MULTIEXP | 0x15 | -|BLS12_377_G2ADD | 0x16 | -|BLS12_377_G2MUL | 0x17 | -|BLS12_377_G2MULTIEXP | 0x18 | -|BLS12_377_PAIRING | 0x19 | +| 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 @@ -76,9 +81,9 @@ Pairing parameters: x is negative = false ``` -#### Fine points and encoding of base elements +### Fine points and encoding of base elements -##### Field elements encoding: +#### Field elements encoding: To encode points involved in the operation one has to encode elements of the base field and the extension field. @@ -88,114 +93,130 @@ For elements of the quadratic extension field (Fp2) encoding is byte concatenati 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: +#### 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: +#### 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: +#### 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 operations -##### ABI for G1 addition +#### 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 + - 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 +#### 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 + - Point being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for G1 multiexponentiation +#### 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 + - 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 +#### 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 + - 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 +#### 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 + - Point being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for G2 multiexponentiation +#### 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 + - 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 +#### 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 + - `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 + - 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 an an input that is interpreted as a 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 -#### Prevention of DDoS on error handling +#### ABI for mapping Fp2 element to G2 point + +Field-to-curve call expects `128` bytes an an input that is interpreted as a 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 -This precompile performs extensive computations and in case of any errors during execution it MUST consume all gas from the the gas schedule for the corresponding operation. +### Prevention of DDoS on error handling -#### Gas schedule +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 +#### G1 addition `600` gas -##### G1 multiplication +#### G1 multiplication `12000` gas -##### G2 addition +#### G2 addition `4500` gas -##### G2 multiplication +#### G2 multiplication `55000` gas -##### G1/G2 Multiexponentiation +#### G1/G2 Multiexponentiation Multiexponentiations are expected to be performed by the Peppinger algorithm (we can also say that is **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 cup `max_discount` for `k > 128`. @@ -209,23 +230,33 @@ Discounts table as a vector of pairs `[k, discount]`: `max_discount = 174` -##### Pairing operation +#### 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 +### 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 +### Important notes -### Subgroup checks +#### 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). @@ -234,33 +265,35 @@ Subgroup check **is mandatory** during the pairing call. Implementations *should 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` + - 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) + - 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. -Test vector for all operations are expanded in this `csv` files in [repo](https://github.com/matter-labs/eip1962/tree/master/src/test/test_vectors/eip2537). +## Reference Implementation -## Implementation There is a various choice of existing implementations of the curve operations. It may require extra work to add an ABI: -- EIP1962 code bases with fixed parameters - - [Rust](https://github.com/matter-labs/eip1962) - - [C++](https://github.com/matter-labs/eip1962_cpp) -- Original implementation linked in Zexe paper in [Rust](https://github.com/scipr-lab/zexe) -- Standalone in [Go](https://github.com/kilic/bls12-377) + - 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](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-2542.md b/EIPS/eip-2542.md index 833546ab8d54e6..5580dca0503dba 100644 --- a/EIPS/eip-2542.md +++ b/EIPS/eip-2542.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-02-29 @@ -84,4 +84,4 @@ Smart contracts that will use proposed opcodes must not use them for the core of 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-2544.md b/EIPS/eip-2544.md index 46d971fc6f3c0f..98dbdbe943eb3d 100644 --- a/EIPS/eip-2544.md +++ b/EIPS/eip-2544.md @@ -1,110 +1,7 @@ --- eip: 2544 -title: ENS Wildcard Resolution -author: Nick Johnson (@arachnid), 0age (@0age) -discussions-to: https://ethereum-magicians.org/t/eip-2544-ens-wildcard-resolution -status: Draft -type: Standards Track category: ERC -created: 2020-02-28 -requires: 137 +status: Moved --- -## Simple Summary - -EIP-2544 extends ENS client behavior to support "wildcard" resolution of subdomains. This is accomplished by using a parent domain's resolver if none is set on a given subdomain. - -## Abstract - -The Ethereum Name Service Specification (EIP-137) establishes a two-step name resolution process. First, an ENS client takes a provided name, performs the namehash algorithm to determine the associated "node", and supplies that node to the ENS Registry contract to determine the resolver. Then, if a resolver has been set on the Registry, the client supplies that same node to the resolver contract, which will return the associated address or other record. - -As currently specified, this process terminates if a resolver is not set on the ENS Registry for a given node. This EIP extends the existing name resolution process by adding an additional step if a resolver is not set for subdomain. This step strips out the leftmost label from the name, derives the node of the new fragment, and supplies that node to the ENS Registry. If a resolver is located for that node, the client supplies the original, complete node to that resolver contract to derive the relevant records. - -## Motivation - -Many applications such as wallet providers, exchanges, and dapps have expressed a desire to issue ENS names for their users via custom subdomains on a shared parent domain. However, the cost of doing so is currently prohibitive for large user bases, as a distinct record must be set on the ENS Registry for each subdomain. - -Furthermore, users cannot immediately utilize these subdomains upon account creation, as the transaction to assign a resolver for the node of the subdomain must first be submitted and mined on-chain. This adds unnecessary friction when onboarding new users, who coincidentally would often benefit greatly from the usability improvements afforded by an ENS name. - -Enabling wildcard support allows for the design of more advanced resolvers that deterministically generate addresses and other records for unassigned subdomains. The generated addresses could map to counterfactual contract deployment addresses (i.e. `CREATE2` addresses), to designated "fallback" addresses, or other schemes. Additionally, individual resolvers would still be assignable to any given subdomain, which would supersede the wildcard resolution using the parent resolver. - -Another critical motivation with EIP-2544 is to enable wildcard resolution in a backwards-compatible fashion. It does not require modifying the current ENS Registry contract or any assigned resolvers, and continues to support existing ENS records — legacy ENS clients would simply fail to resolve wildcard records. - -## 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. - -EIP-2544-compliant ENS clients MUST perform the following sequence when determining the resolver for a given name: - -1. Apply the namehash algorithm to the supplied name as specified in EIP-137 to derive the `node`. -2. Call the ENS Registry contract, supplying the node as the argument to `function resolver(bytes32 node) constant returns (address)`. -3. If an address other than the null address is returned, the client MUST use the returned address as the resolver. -4. If the null address is returned, the client MUST strip the leftmost label from the name to derive a new name. -5. If the only remaining label is a top-level domain, or if no labels remain, the client MUST refuse to interact with the resolver. -6. Apply the namehash algorithm to the new name as specified in EIP-137 to derive the `parentNode`. -7. Call the ENS Registry contract, supplying the parent node as the argument to `function resolver(bytes32 node) constant returns (address)` to determine the resolver. -8. If the null address is returned from this second request, the client MUST refuse to interact with the resolver. - -In the event that a non-null resolver is located via this process, the client MUST supply the full, original `node` to the resolver to derive the address or other records. As with EIP-137, clients attempting to resolve an address via `function addr(bytes32 node) constant returns (address)` MUST refuse to interact with the returned address when the null address is returned. - -### Pseudocode -``` -function getNodeAndResolver(name) { - // 1. Apply the namehash algorithm to supplied name to determine the node. - const node = namehash(name); - - // 2. Attempt to retrieve a resolver from the ENS Registry using the node. - let resolver = ENS_REGISTRY.methods.resolver(node).call(); - - // 3. Use the resolver if a non-null result is returned from the registry. - if (resolver != "0x0000000000000000000000000000000000000000") { - return (node, resolver); - } - - // 4. Remove the leftmost label from the name. - const labelsWithoutLeftmost = name.split(".").slice(1); - - // 5. Do not continue if only the top-level domain (or no domain) remains. - if (labelsWithoutLeftmost.length < 2) { - throw new Error("ENS resolver not found."); - } - - // 6. Apply the namehash algorithm to new name to determine the parent node. - const parentNode = namehash(labelsWithoutLeftmost.join(".")); - - // 7. Attempt to retrieve a resolver from registry using the parent node. - resolver = ENS_REGISTRY.methods.resolver(parentNode).call(); - - // 8. Do not continue if a null result is returned from the registry. - if (resolver == "0x0000000000000000000000000000000000000000") { - throw new Error("ENS resolver not found."); - } - - // Return the located resolver along with the original node. - return (node, resolver); -}; -``` - -## Rationale - -The proposed implementation supports wildcard resolution in a manner that minimizes the impact to existing systems. It also reuses existing algorithms and procedures to the greatest possible extent, thereby easing the burden placed on authors and maintainers of various ENS clients. - -It also recognizes an existing consensus concerning the desirability of wildcard resolution for ENS, enabling more widespread adoption of the original specification by solving for a key scalability obstacle. - -By not recursively applying the namehash operation after removing successive leftmost subdomains, round-trip requests are reduced and edge cases around overriding ownership of nested subdomains are adequately handled. ENS clients may optimize further for reduced latency by utilizing a helper contract that performs the logic necessary to support wildcard resolution. - -## Backwards Compatibility - -There are no backwards compatibility concerns — existing ENS clients that are compliant with EIP-137 will fail to resolve wildcard records and refuse to interact with them, while those compliant with EIP-2544 will continue to correctly resolve, or reject, existing ENS records. - -## Security Considerations - -While compliant ENS clients will continue to refuse to resolve records without a resolver, there is still the risk that an improperly-configured client will refer to an incorrect resolver, or will not reject interactions with the null address when a resolver cannot be located. - -Additionally, resolvers supporting completely arbitrary wildcard subdomain resolution will increase the likelihood of funds being sent to unintended recipients as a result of typos. Applications that implement such resolvers should consider making additional name validation available to clients depending on the context, or implementing features that support recoverability of funds. - -There is also the possibility that some applications might require that no resolver be set for certain subdomains. For this to be problematic, the parent domain would need to successfully resolve the given subdomain node — to the knowledge of the authors, no application currently supports this feature or expects that subdomains should not resolve to a record. - -## 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-2544.md diff --git a/EIPS/eip-2565.md b/EIPS/eip-2565.md index 2ad443c00798aa..bfd83317efc59a 100644 --- a/EIPS/eip-2565.md +++ b/EIPS/eip-2565.md @@ -3,8 +3,7 @@ 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: Last Call -review-period-end: 2020-10-09 +status: Final type: Standards Track category: Core created: 2020-03-20 @@ -102,4 +101,4 @@ The biggest security consideration for this EIP is creating a potential DoS vect [EIP-198](./eip-198.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-2566.md b/EIPS/eip-2566.md index 00a1cb6fb3dda9..27ad65af53f3e1 100644 --- a/EIPS/eip-2566.md +++ b/EIPS/eip-2566.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-03-23 @@ -103,4 +103,4 @@ With backwards compatibility in mind, this EIP proposes augmenting the set of Et 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2569.md b/EIPS/eip-2569.md index 482e769765726a..280c82a66eeaa4 100644 --- a/EIPS/eip-2569.md +++ b/EIPS/eip-2569.md @@ -1,366 +1,7 @@ --- eip: 2569 -title: Saving and Displaying Image Onchain for Universal Tokens -author: Hua Zhang (@dgczhh), Yuefei Tan (@whtyfhas), Derek Zhou (@zhous) -discussions-to: https://ethereum-magicians.org/t/erc-2569-saving-and-displaying-image-onchain-for-universal-tokens/4167 -status: Draft -type: Standards Track category: ERC -created: 2020-03-28 +status: Moved --- -## Simple Summary -A set of interfaces to save an SVG image in Ethereum, and to retrieve the image file from Ethereum for universal tokens. - -## Abstract -This set of interfaces allow a smart contract to save an SVG image in Ethereum and to retrieve an SVG image from Ethereum for fungible tokens, non-fungible tokens and tokens based on standards that will be developed in the future. - -The interface set has two interfaces: one to save an SVG file in Ethereum and the other to retrieve an SVG file from Ethereum. - -Typical applications include but not limited to: -* A solution for storage of a fungible token's icon. -* A solution for storage of a non-fungible token's icon. -* A solution for storage of the icon/logo of a DAO's reputation token. - -## Motivation -The ERC-721 token standard is a popular standard to define a non-fungible token in Ethereum. This standard is widely used to specify a crypto gift, crypto medal, crypto collectible etc. The most famous use case is the [cryptokitty](https://www.cryptokitties.co/). - -In most of these applications an image is attached to an ERC-721 token. For example, in the cryptokitty case each kitty has a unique image. While the token's code is saved in Ethereum permanently, the image attached to the token is not. - -The existing solutions still keep such an image in a centralized server instead of Ethereum. When these applications display an image for a token they retrieve the token's information from Ethereum and search the centralized server for the token's associated image by using the token's information. - -Although this is an applicable way to display an image for a token, the image is still vulnerable to risks of being damaged or lost when saved in a centralized server. - -Hence we propose a set of interfaces to save an image for a universal token in Ethereum to keep the image permanent and tamper-resistant, and to retrieve an image for a universal token from Ethereum. - -## Specification - -An EIP-2569 compatible contract MUST have a method with the signature getTokenImageSvg(uint256) view returns (string memory) and a method with the signature setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal. - -These methods define how a smart contract saves an image for a universal token in Ethereum which keeps the image permanent and tamper-resistant, and how a smart contract retrieves an image from Ethereum for a universal token. - -By calling the methods users should access an SVG image. - -* getTokenImageSvg(uint256 tokenId) external view returns (string memory): for an ERC-721 or ERC-1155 token or a token implemented by a contract which has a member "ID" to specify its token type or token index we define an interface to get an SVG image by using the token's ID number. For an ERC-20 token or a token implemented by a contract which doesn't have a member "ID" to specify its token type or token index we define an interface to get an SVG image for it if the token has a member variable string to save the image. - -It has the following parameter: - -tokenId: for a non-fungible token such as an ERC-721 token or a multi-token such as an ERC-1155 token which has a member "ID" to specify its token type or token index our proposed interface assigns an SVG image's file content to a string variable of the token's contract and associates the SVG image to this "ID" number. This unique ID is used to access its SVG image in both a "set" operation and a "get" operation. -For a fungible token such as an ERC-20 token no such an ID is needed and our proposed interface just assigns an SVG image's file content to a string variable of the token's contract. - -* setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal: for an ERC-721 or ERC-1155 token or a token implemented by a contract which has a member "ID" to specify its token type or token index we define an interface to associate an SVG image to the token's ID number. For an ERC-20 token or a token implemented by a contract which doesn't have a member "ID" to specify its token type or token index we define an interface to assign an SVG image to a member variable string of this token's contract. - -It has the following two parameters: - -tokenId: for a non-fungible token such as an ERC-721 token or a multi-token such as an ERC-1155 token which has a member "ID" to specify its token type or token index our proposed interface assigns an SVG image's file content to a string variable of the token's contract and associates the SVG image to this "ID" number. This unique ID is used to access its SVG image in both a "set" operation and a "get" operation. -For a fungible token such as an ERC-20 token no such an ID is needed and our proposed interface just assigns an SVG image's file content to a string variable of the token's contract. - -imageSvg: we use a string variable to save an SVG image file's content. -An SVG image that will be saved in the imageSvg string should include at least two attributes:"name", "desc"(description). - -The procedure to save an image for a token in Ethereum is as follows: - -**Step1:** define a string variable or an array of strings to hold an image or an array of images. - -**Step 2:** define a function to set an (SVG) image's file content or an array of image file's contents to the string variable or the array of strings. - -Step 1: for a token such as an ERC-721 or ERC-1155 token which has a member variable "ID" to specify a token type or index and a member variable string to keep an (SVG) image associated with the "ID", retrieve the (SVG) image from Ethereum by calling our proposed "get" interface with the token's ID; -for a token which doesn't have a member variable "ID" to specify a token type of index but has a member variable string to keep an (SVG) image, retrieve the (SVG) image from Ethereum by calling our proposed "get" without an "ID". - -## Rationale -After Bitcoin was created people have found ways to keep information permanent and tamper-resistant by encoding text messages they want to preserve permanently and tamper-resistantly in blockchain transactions. However existing applications only do this for text information and there are no solutions to keep an image permanent and tamper-resistant. - -One of the most significant reasons for not doing so is that in general the size of an image is much bigger than the size of a text file, thus the gas needed to save an image in Ethereum would exceed a block's gas limit. - -However this changed a lot after the SVG(Scalable Vector Graphics) specification was developed by W3C since 1999. - -The SVG specification offers several advantages (for more details about the advantages please refer to a reference link:https://en.wikipedia.org/wiki/Scalable_Vector_Graphics) over raster images. One of these advantages is its compact file-size. - -"Compact file-size – Pixel-based images are saved at a large size from the start because you can only retain the quality when you make the image smaller, but not when you make it larger. This can impact a site’s download speed. Since SVGs are scalable, they can be saved at a minimal file size". - -This feature well fixes the painpoint of saving an image file in Ethereum, therefore we think saving an SVG image in Ethereum is a good solution for keep the image permanent and tamper-resistant. - -In most ERC-721 related DAPPs they display an image for a non-fungible token. In most ERC-20 related DAPPs they don't have an image for a fungible token. We think displaying an image for a token either based on existing token standards such as ERC-20, ERC-721, ERC-1155 or based on future standards is needed in many use cases. Therefore those DAPPs which currently don't display an image for a token will eventually need such a function. - -However with regard to most of the existing DAPPs which can display an image for a token they save such an image in a centralized server which, we think, is just a compromised solution. By utilizing the SVG specification we think converting a token's image to an SVG image and saving it in Ethereum provides a better solution for DAPPs to access an image for a token. - -This solution not only works for tokens based on ERC-721, ERC-1155 and ERC-20 but will work for tokens based on future standards. - -## Backwards Compatibility -There are no backward compatibility issues. - -## Test Cases -[DHonor](https://dhonor.io/) - -[1155](http://dhonor.io/1155) - -[DeMe](https://www.deme.app/) - -## Implementation -`tokenId`: a token index in an ERC-721 token or a token type/index in an ERC-1155 token. It is a uint256 variable. - -`imageSvg`: an SVG image's file content. It is a string variable. Note: the SVG image should include at least three attributes:"name", "description" and "issuer". - -`setTokenImageSvg`: interface to set an SVG image to a token with or without an ID number. - -`getTokenImageSvg`: interface to get an SVG image for a token with or without an ID number. - -We propose to add three sol files in the existing ERC-721 implementation. -Here are the details for the proposed sol files. - -```solidity -// ----- IERC721GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; - -/** - * @title ERC-721 Non-Fungible Token Standard, optional retrieving SVG image extension - * @dev See https://eips.ethereum.org/EIPS/eip-721 - */ -contract IERC721GetImageSvg is IERC721 { - function getTokenImageSvg(uint256 tokenId) external view returns (string memory); -} - - -// ----- ERC721GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "@openzeppelin/contracts/GSN/Context.sol"; -import "@openzeppelin/contracts/token/ERC721/./ERC721.sol"; -import "@openzeppelin/contracts/introspection/ERC165.sol"; -import "./IERC721GetImageSvg.sol"; - -contract ERC721GetImageSvg is Context, ERC165, ERC721, IERC721GetImageSvg { - // Mapping for token Images - mapping(uint256 => string) private _tokenImageSvgs; - - /* - * bytes4(keccak256('getTokenImageSvg(uint256)')) == 0x87d2f48c - * - * => 0x87d2f48c == 0x87d2f48c - */ - bytes4 private constant _INTERFACE_ID_ERC721_GET_TOKEN_IMAGE_SVG = 0x87d2f48c; - - /** - * @dev Constructor function - */ - constructor () public { - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(_INTERFACE_ID_ERC721_GET_TOKEN_IMAGE_SVG); - } - - /** - * @dev Returns an SVG Image for a given token ID. - * Throws if the token ID does not exist. May return an empty string. - * @param tokenId uint256 ID of the token to query - */ - function getTokenImageSvg(uint256 tokenId) external view returns (string memory) { - require(_exists(tokenId), "ERC721GetImageSvg: SVG Image query for nonexistent token"); - return _tokenImageSvgs[tokenId]; - } - - /** - * @dev Internal function to set the token SVG image for a given token. - * Reverts if the token ID does not exist. - * @param tokenId uint256 ID of the token to set its SVG image - * @param imagesvg string SVG to assign - */ - function setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal { - require(_exists(tokenId), "ERC721GetImageSvg: SVG image set of nonexistent token"); - _tokenImageSvgs[tokenId] = imagesvg; - } - -} - - -// ----- ERC721ImageSvgMintable.sol ------------------------- - -pragma solidity ^0.5.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721Metadata.sol"; -import "@openzeppelin/contracts/access/roles/MinterRole.sol"; -import "./ERC721GetImageSvg.sol"; - -/** - * @title ERC721ImageSvgMintable - * @dev ERC721 minting logic with imagesvg. - */ -contract ERC721ImageSvgMintable is ERC721, ERC721Metadata, ERC721GetImageSvg, MinterRole { - /** - * @dev Function to mint tokens. - * @param to The address that will receive the minted tokens. - * @param tokenId The token id to mint. - * @param tokenImageSvg The token SVG image of the minted token. - * @return A boolean that indicates if the operation was successful. - */ - function mintWithTokenImageSvg(address to, uint256 tokenId, string memory tokenImageSvg) public onlyMinter returns (bool) { - _mint(to, tokenId); - setTokenImageSvg(tokenId, tokenImageSvg); - return true; - } -} - - -We propose to add three sol files in the existing ERC-1155 implementation. -Here are the details for the proposed sol files. - -// ----- IERC1155GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "./IERC1155.sol"; - -/** - * @title ERC-1155 Multi Token Standard, retrieving SVG image for a token - * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md - */ -contract IERC1155GetImageSvg is IERC1155 { - function getTokenImageSvg(uint256 tokenId) external view returns (string memory); -} - - -// ----- ERC1155GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "./ERC1155.sol"; -import "./IERC1155GetImageSvg.sol"; - -contract ERC1155GetImageSvg is ERC165, ERC1155, IERC1155GetImageSvg { - // Mapping for token Images - mapping(uint256 => string) private _tokenImageSvgs; - - /* - * bytes4(keccak256('getTokenImageSvg(uint256)')) == 0x87d2f48c - * - * => 0x87d2f48c == 0x87d2f48c - */ - bytes4 private constant _INTERFACE_ID_ERC1155_GET_TOKEN_IMAGE_SVG = 0x87d2f48c; - - /** - * @dev Constructor function - */ - constructor () public { - // register the supported interfaces to conform to ERC1155 via ERC165 - _registerInterface(_INTERFACE_ID_ERC1155_GET_TOKEN_IMAGE_SVG); - } - - - /** - * @dev Returns an SVG Image for a given token ID. - * Throws if the token ID does not exist. May return an empty string. - * @param tokenId uint256 ID of the token to query - */ - function getTokenImageSvg(uint256 tokenId) external view returns (string memory) { - require(_exists(tokenId), "ERC1155GetImageSvg: SVG Image query for nonexistent token"); - return _tokenImageSvgs[tokenId]; - } - - /** - * @dev Internal function to set the token SVG image for a given token. - * Reverts if the token ID does not exist. - * @param tokenId uint256 ID of the token to set its SVG image - * @param imagesvg string SVG to assign - */ - function setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal { - require(_exists(tokenId), "ERC1155GetImageSvg: SVG image set of nonexistent token"); - _tokenImageSvgs[tokenId] = imagesvg; - } - -} - - - -// ----- ERC1155MixedFungibleWithSvgMintable.sol ------------------------- - -pragma solidity ^0.5.0; - -import "./ERC1155MixedFungibleMintable.sol"; -import "./ERC1155GetImageSvg.sol"; - -/** - @dev Mintable form of ERC1155 with SVG images - Shows how easy it is to mint new items with SVG images -*/ - -contract ERC1155MixedFungibleWithSvgMintable is ERC1155, ERC1155MixedFungibleMintable, ERC1155GetImageSvg { - /** - * @dev Function to mint non-fungible tokens. - * @param _to The address that will receive the minted tokens. - * @param _type The token type to mint. - * @param tokenImageSvg The token SVG image of the minted token. - */ - function mintNonFungibleWithImageSvg(uint256 _type, address[] calldata _to, string memory tokenImageSvg) external creatorOnly(_type) { - mintNonFungible(_type, _to); - setTokenImageSvg(_type, tokenImageSvg); - } - - - /** - * @dev Function to mint fungible tokens. - * @param _to The address that will receive the minted tokens. - * @param _id The token type to mint. - * @param _quantities The number of tokens for a type to mint. - * @param tokenImageSvg The token SVG image of the minted token. - */ - function mintFungibleWithImageSvg(uint256 _id, address[] calldata _to, uint256[] calldata _quantities, string memory tokenImageSvg) external creatorOnly(_id) { - mintFungible(_id, _to, _quantities, tokenImageSvg) { - setTokenImageSvg(_id, tokenImageSvg); - } -} - - - -We propose to add three sol files in the existing ERC-20 implementation. -Here are the details for the proposed sol files. - - -// ----- IERC20GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; - -/** - * @title ERC-20 Fungible Token Standard, retrieving SVG image for a token - * @dev See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol - */ -contract IERC20GetImageSvg is IERC20 { - function getTokenImageSvg() external view returns (string memory); -} - - -// ----- ERC20GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import "./IERC20GetImageSvg.sol"; - -contract ERC20GetImageSvg is ERC20, IERC20GetImageSvg { - string private _tokenImageSvg; -//将图片实现写在构造器中 - constructor(string calldata svgCode) public { -_tokenImageSvg = svgCode -} - - /** - * @dev Returns an SVG Image. - */ - function getTokenImageSvg() external view returns (string memory) { - return _tokenImageSvg; - } - -} - - -``` - -## Articles & Discussions - -[Image Storage Solution Based on Ethereum Sharding](https://naturaldao.io/en/collaboration/blog/65-storage-shading.html) - -## 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-2569.md diff --git a/EIPS/eip-2583.md b/EIPS/eip-2583.md index 6514d9c9b92a3e..12689ee89f8e20 100644 --- a/EIPS/eip-2583.md +++ b/EIPS/eip-2583.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-02-21 @@ -291,4 +291,4 @@ Downside: ## 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-2584.md b/EIPS/eip-2584.md index 1e7b6e9978e8bf..e2a6293027ddd5 100644 --- a/EIPS/eip-2584.md +++ b/EIPS/eip-2584.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-04-03 @@ -111,4 +111,4 @@ There are three attack vectors that I can foresee: * 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2593.md b/EIPS/eip-2593.md index 4fb7f0da7a96d1..c5e1cc6169da6a 100644 --- a/EIPS/eip-2593.md +++ b/EIPS/eip-2593.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-03-13 @@ -128,4 +128,4 @@ The security considerations for this EIP are: - None currently known. ## 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-2612.md b/EIPS/eip-2612.md index d23fa0931778af..416c494fd2824e 100644 --- a/EIPS/eip-2612.md +++ b/EIPS/eip-2612.md @@ -1,204 +1,7 @@ --- eip: 2612 -title: permit – 712-signed approvals -author: Martin Lundfall (@Mrchico) -discussions-to: https://github.com/ethereum/EIPs/issues/2613 -status: Draft -type: Standards Track category: ERC -created: 2020-04-13 -requires: 20, 712 +status: Moved --- -## Simple Summary -A function `permit` extending [ERC-20](./eip-20.md) which allows for approvals to be made via `secp256k1` signatures. This kind of "account abstraction for ERC-20" brings about two main benefits: - -- transactions involving ERC-20 operations can be paid using the token itself rather than ETH, -- approve and pull operations can happen in a single transaction instead of two consecutive transactions, - -while adding as little as possible over the existing ERC-20 standard. - -## Abstract -Arguably one of the main reasons for the success of ERC-20 tokens lies in the interplay between `approve` and `transferFrom`, -which allows for tokens to not only be transferred between externally owned accounts (EOA), but to be used in other contracts under application specific conditions by abstracting away `msg.sender` as the defining mechanism for token access control. - -However, a limiting factor in this design stems from the fact that the ERC-20 `approve` function itself is defined in terms of `msg.sender`. This means that user's _initial action_ involving ERC-20 tokens must be performed by an EOA [1]. If the user needs to interact with a smart contract, then they need to make 2 transactions (`approve` and the smart contract call which will internally call `transferFrom`). Even in the simple use case of paying another person, they need to hold ETH to pay for transaction gas costs. - -This ERC extends the ERC-20 standard with a new function `permit`, which allows users to modify the `allowance` mapping using a signed message, instead of through `msg.sender`. - -For an improved user experience, the signed data is structured following [ERC-712](./eip-712.md), which already has wide spread adoption in major RPC providers. - - -## Motivation -While ERC-20 tokens have become ubiquotous in the Ethereum ecosystem, their status remains that of second class tokens from the perspective of the protocol. The ability for users to interact with Ethereum without holding any ETH has been a [long outstanding goal](https://github.com/ethereum/EIPs/blob/ed621645c8f3bc5756492f327cda015f35d9f8da/EIPS/eip-101.md) and the [subject](./eip-1077.md) [of](./eip-777.md) [many](https://github.com/ethereum/EIPs/issues/1776#) [EIPs](https://eips.ethereum.org/EIPS/eip-1271). - -So far, many of these proposals have seen very little adoption, and the ones that have been adopted (such as [ERC-777](./eip-777.md)), introduce a lot of additional functionality, causing [unexpected behavior in mainstream contracts](https://medium.com/consensys-diligence/uniswap-audit-b90335ac007). - -This ERC proposes an alternative solution which is designed to be as minimal as possible and to only address _one problem_: the lack of abstraction in the ERC-20 `approve` method. - -While it may be tempting to introduce `*_by_signature` counterparts for every ERC-20 function, they are intentionally left out of this ERC-20 for two reasons: - - - the desired specifics of such functions, such as decision regarding fees for `transfer_by_signature`, possible batching algorithms, varies depending on the use case, and, - - they can be implemented using a combination of `permit` and additional helper contracts without loss of generality. - - -## Specification -Three new functions are added to the ERC20 ABI: -```sol -function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external -function nonces(address owner) external view returns (uint) -function DOMAIN_SEPARATOR() external view returns (bytes32) -``` -The semantics of which are as follows: - -For all addresses `owner`, `spender`, uint256s `value`, `deadline` and `nonce`, uint8 `v`, bytes32 `r` and `s`, -a call to `permit(owner, spender, value, deadline, v, r, s)` will set -`approval[owner][spender]` to `value`, -increment `nonces[owner]` by 1, -and emit a corresponding `Approval` event, -if and only if the following conditions are met: - - -- The current blocktime is less than or equal to `deadline`. -- `owner` is not the zero address. -- `nonces[owner]` (before the state update) is equal to `nonce`. -- `r`, `s` and `v` is a valid `secp256k1` signature from `owner` of the message: - -```sol -keccak256(abi.encodePacked( - hex"1901", - DOMAIN_SEPARATOR, - keccak256(abi.encode( - keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"), - owner, - spender, - value, - nonce, - deadline)) -)) -``` -where `DOMAIN_SEPARATOR` is defined according to EIP-712. The `DOMAIN_SEPARATOR` should be unique to the contract and chain to prevent replay attacks from other domains, -and satisfy the requirements of EIP-712, but is otherwise unconstrained. -A common choice for `DOMAIN_SEPARATOR` is: -```solidity -DOMAIN_SEPARATOR = keccak256( - abi.encode( - keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), - keccak256(bytes(name)), - keccak256(bytes(version)), - chainid, - address(this) -)); -``` - -In other words, the message is the ERC-712 typed structure: - -```js -{ - "types": { - "EIP712Domain": [ - { - "name": "name", - "type": "string" - }, - { - "name": "version", - "type": "string" - }, - { - "name": "chainId", - "type": "uint256" - }, - { - "name": "verifyingContract", - "type": "address" - } - ], - "Permit": [{ - "name": "owner", - "type": "address" - }, - { - "name": "spender", - "type": "address" - }, - { - "name": "value", - "type": "uint256" - }, - { - "name": "nonce", - "type": "uint256" - }, - { - "name": "deadline", - "type": "uint256" - } - ], - "primaryType": "Permit", - "domain": { - "name": erc20name, - "version": version, - "chainId": chainid, - "verifyingContract": tokenAddress - }, - "message": { - "owner": owner, - "spender": spender, - "value": value, - "nonce": nonce, - "deadline": deadline - } -}} -``` - -Note that nowhere in this definition we refer to `msg.sender`. The caller of the `permit` function can be any address. - - -## Rationale -The `permit` function is sufficient for enabling any operation involving ERC-20 tokens to be paid for using the token itself, rather than using ETH. -An example of a contract which enables gasless token transactions can be found [here](https://github.com/dapphub/ds-dach). - -It avoids any calls to unknown code. - -The `nonces` mapping is given for replay protection. - -A common use case of `permit` has a relayer submit a `Permit` on behalf of the `owner`. In this scenario, the relaying party is essentially given a free option to submit or withhold the `Permit`. If this is a cause of concern, the `owner` can limit the time a `Permit` is valid for by setting `deadline` to a value in the near future. The `deadline` argument can be set to `uint(-1)` to create `Permit`s that effectively never expire. - -ERC-712 typed messages are included because of its wide spread adoption in many wallet providers. - - -## Backwards Compatibility -There are already a couple of `permit` functions in token contracts implemented in contracts in the wild, most notably the one introduced in the `dai.sol`. - -Its implementation differs slightly from the presentation here in that: -- instead of taking a `value` argument, it takes a bool `allowed`, setting approval to 0 or `uint(-1)`. -- the `deadline` argument is instead called `expiry`. This is not just a syntactic change, as it effects the contents of the signed message. - -There is also an implementation in the token [`Stake`](https://etherscan.io/address/0x0Ae055097C6d159879521C384F1D2123D1f195e6#code) with the same ABI as `dai` but with different semantics: it lets users issue "expiring approvals", that only allow `transferFrom` to occur while `expiry >= block.timestamp`. - -The specification presented here is in line with the implementation in [Uniswap-v2](https://github.com/uniswap/uniswap-v2-core). - -## Test Cases - -Some basic tests can be found here https://github.com/Uniswap/uniswap-v2-core/blob/master/test/UniswapV2ERC20.spec.ts. - -## Implementation -[UniswapV2ERC20.sol](https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) - -## Security Considerations - -Though the signer of a `Permit` may have a certain party in mind to submit their transaction, another party can always front run this transaction and call `permit` before the intended party. The end result is the same for the `Permit` signer, however. - -Since the ecrecover precompile fails silently and just returns the zero address as `signer` when given malformed messages, it is important to ensure `owner != address(0)` to avoid `permit` from creating an approval to spend "zombie funds" belong to the zero address. - -Signed `Permit` messages are censorable. The relaying party can always choose to not submit the `Permit` after having received it, withholding the option to submit it. The `deadline` parameter is one mitigation to this. If the signing party holds ETH they can also just submit the `Permit` themselves, which can render previously signed `Permit`s invalid. - -The standard [ERC-20 race condition for approvals](https://swcregistry.io/docs/SWC-114) applies to `permit` as well. - -If the `DOMAIN_SEPARATOR` contains the `chainId` and is defined at contract deployment instead of reconstructed for every signature, there is a risk of possible replay attacks between chains in the event of a fututre chain split. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - -[1] - Unless the address owning the token is actually a contract wallet. Although contract wallets solves many of the same problems that motivates this EIP, they are currently only scarcely adopted in the ecosystem. Contract wallets suffer from a UX problem -- since they separate the EOA `owner` of the contract wallet from the contract wallet itself (which is meant to carry out actions on the `owner`s behalf and holds all of their funds), user interfaces need to be specifically designed to support them. The `permit` pattern reaps many of the same benefits while requiring little to no change in user interfaces. +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 index 8f24badb673107..34ed14f5f0a143 100644 --- a/EIPS/eip-2615.md +++ b/EIPS/eip-2615.md @@ -1,241 +1,7 @@ --- eip: 2615 -title: Non-Fungible Token with mortgage and rental functions -author: Kohshi Shiba -discussions-to: https://github.com/ethereum/EIPs/issues/2616 -status: Draft -type: Standards Track category: ERC -created: 2020-04-25 -requires: 165, 721 +status: Moved --- -## Simple Summary - -This standard proposes an extension to ERC721 Non-Fungible Tokens (NFTs) to support rental and mortgage functions. These functions are necessary for NFTs to emulate real property, just like those in the real world. - -## Abstract - -This standard is an extension of ERC721. It proposes additional roles, the right of tenants to enable rentals, and the right of lien. - -With ERC2615, NFT owners will be able to rent out their NFTs and take out a mortgage by collateralizing their NFTs. For example, this standard can apply to: - -- Virtual items (in-game assets, virtual artwork, etc.) -- Physical items (houses, automobiles, etc.) -- Intellectual property rights -- DAO membership tokens - -NFT developers are also able to easily integrate ERC2615 since it is fully backwards-compatible with the ERC721 standard. - -One notable point is that the person who has the right to use an application is not the owner but the user (i.e. tenant). Application developers must implement this specification into their applications. - -## Motivation - -It has been challenging to implement rental and mortgage functions with the ERC721 standard because it only has one role defined (which is the Owner). - -Currently, a security deposit is needed for trustless renting with ERC721, and ownership lockup within a contract is necessary whenever one chooses to mortgage their ERC721 property. The tracking and facilitation of these relationships must be done separately from the ERC721 standard. - -This proposal eliminates these requirements by integrating basic rights of tenantship and liens. By standardizing these functions, developers can more easily integrate rental and mortgage functions for their applications. - -## Specification - -This standard proposes three user roles: the **Lien Holder**, the **Owner**, and the **User**. Their rights are as follows: - -- A **Lien Holder** has the right to: - - 1. Transfer the **Owner** role - 2. Transfer the **User** role - -- An **Owner** has the right to: - - 1. Transfer the **Owner** role - 2. Transfer the **User** role - -- A **User** has the right to: - 1. Transfer the **User** role - -### ERC-2615 Interface - -```solidity -event TransferUser(address indexed from, address indexed to, uint256 indexed itemId, address operator); -event ApprovalForUser(address indexed user, address indexed approved, uint256 itemId); -event TransferOwner(address indexed from, address indexed to, uint256 indexed itemId, address operator); -event ApprovalForOwner(address indexed owner, address indexed approved, uint256 itemId); -event ApprovalForAll(address indexed owner, address indexed operator, bool approved); -event LienApproval(address indexed to, uint256 indexed itemId); -event TenantRightApproval(address indexed to, uint256 indexed itemId); -event LienSet(address indexed to, uint256 indexed itemId, bool status); -event TenantRightSet(address indexed to, uint256 indexed itemId,bool status); - -function balanceOfOwner(address owner) public view returns (uint256); -function balanceOfUser(address user) public view returns (uint256); -function userOf(uint256 itemId) public view returns (address); -function ownerOf(uint256 itemId) public view returns (address); - -function safeTransferOwner(address from, address to, uint256 itemId) public; -function safeTransferOwner(address from, address to, uint256 itemId, bytes memory data) public; -function safeTransferUser(address from, address to, uint256 itemId) public; -function safeTransferUser(address from, address to, uint256 itemId, bytes memory data) public; - -function approveForOwner(address to, uint256 itemId) public; -function getApprovedForOwner(uint256 itemId) public view returns (address); -function approveForUser(address to, uint256 itemId) public; -function getApprovedForUser(uint256 itemId) public view returns (address); -function setApprovalForAll(address operator, bool approved) public; -function isApprovedForAll(address requester, address operator) public view returns (bool); - -function approveLien(address to, uint256 itemId) public; -function getApprovedLien(uint256 itemId) public view returns (address); -function setLien(uint256 itemId) public; -function getCurrentLien(uint256 itemId) public view returns (address); -function revokeLien(uint256 itemId) public; - -function approveTenantRight(address to, uint256 itemId) public; -function getApprovedTenantRight(uint256 itemId) public view returns (address); -function setTenantRight(uint256 itemId) public; -function getCurrentTenantRight(uint256 itemId) public view returns (address); -function revokeTenantRight(uint256 itemId) public; -``` - -### ERC-2615 Receiver - -```solidity -function onERCXReceived(address operator, address from, uint256 itemId, uint256 layer, bytes memory data) public returns(bytes4); -``` - -### ERC-2615 Extensions - -Extensions here are provided to help developers build with this standard. - -#### 1. ERC721 Compatible functions - -This extension makes this standard compatible with ERC721. By adding the following functions, developers can take advantage of the existing tools for ERC721. - -Transfer functions in this extension will transfer both the **Owner** and **User** roles when the tenant right has not been set. Conversely, when the tenant right has been set, only the **Owner** role will be transferred. - -```solidity -function balanceOf(address owner) public view returns (uint256) -function ownerOf(uint256 itemId) public view returns (address) -function approve(address to, uint256 itemId) public -function getApproved(uint256 itemId) public view returns (address) -function transferFrom(address from, address to, uint256 itemId) public -function safeTransferFrom(address from, address to, uint256 itemId) public -function safeTransferFrom(address from, address to, uint256 itemId, bytes memory data) pubic -``` - -#### 2. Enumerable - -This extension is analogous to the enumerable extension of the ERC721 standard. - -```solidity -function totalNumberOfItems() public view returns (uint256); -function itemOfOwnerByIndex(address owner, uint256 index, uint256 layer)public view returns (uint256 itemId); -function itemByIndex(uint256 index) public view returns (uint256); -``` - -#### 3. Metadata - -This extension is analogous to the metadata extension of the ERC721 standard. - -```solidity -function itemURI(uint256 itemId) public view returns (string memory); -function name() external view returns (string memory); -function symbol() external view returns (string memory); -``` - -## How rentals and mortgages work - -This standard does not deal with token or value transfer. Other logic (outside the scope of this standard) must be used to orchestrate these transfers and to implement validation of payment. - -### Mortgage functions - -The following diagram demonstrates the mortgaging functionality. - -![concept image](../assets/eip-2615/mortgage-sequential.jpg "mortgage") - -Suppose Alice owns an NFT and wants to take out a mortgage, and Bob wants to earn interest by lending tokens to Alice. - -1. Alice approves the setting of a lien for the NFT Alice owns. -2. Alice sends a loan request to the mortgage contract. -3. Bob fills the loan request and transfers tokens to the mortgage contract. The lien is then set on the NFT by the mortgage contract. -4. Alice can now withdraw the borrowed tokens from the mortgage contract. -5. Alice registers repayment (anyone can pay the repayment). -6. Bob can finish the agreement if the agreement period ends and the agreement is kept (i.e. repayment is paid without delay). -7. Bob can revoke the agreement if the agreement is breached (e.g. repayment is not paid on time) and execute the lien and take over the ownership of the NFT. - -### Rental functions - -The following diagram demonstrates the rental functionality. - -![concept image](../assets/eip-2615/rental-sequential.jpg "rental") - -Suppose Alice owns NFTs and wants to rent out a NFT, and Bob wants to lease a NFT. - -1. Alice approves the setting of a tenant-right for the NFT Alice owns. -2. Alice sends a rental listing to the rental contract. -3. Bob fills the rental request, and the right to use the NFT is transferred to Bob. At the same time, the tenant-right is set, and Alice becomes not able to transfer the right to use the NFT. -4. Bob registers rent (anyone can pay the rent). -5. Alice can withdraw the rent from the rental contract. -6. Alice can finish the agreement if the agreement period has ended and the agreement is kept (i.e. rent is paid without delay). -7. Alice can revoke the agreement if the agreement is breached (e.g. rent is not paid on time) and revoke the tenant-right and take over the right to use the NFT. - -## Rationale - -There have been some attempts to achieve rentals or mortgages with ERC721. However, as I noted before, it has been challenging to achieve. I will explain the reasons and advantages of this standard below. - -### No security lockup for rentals - -To achieve trustless rental of NFTs with ERC721, it has been necessary to deposit funds as security. This is required to prevent malicious activity from tenants, as it is impossible to take back ownership once it is transferred. - -With this standard, security deposits are no longer needed since the standard natively supports rental and tenantship functions. - -### No ownership escrow when taking out a mortgage - -In order to take out a mortgage on NFTs, it has been necessary to transfer the NFTs to a contract as collateral. This is required to prevent the potential default risk of the mortgage. - -However, secured collateral with ERC721 hurts the utility of the NFT. Since most NFT applications provide services to the canonical owner of a NFT, the NFT essentially cannot be utilized under escrow. - -With ERC2615, it is possible to collateralize NFTs and use them at the same time. - -### Easy integration - -Because of the above reasons, a great deal of effort is required to implement rental and mortgage functions with ERC721. Adopting this standard is a much easier way to integrate rental and mortgage functionality. - -### No money/token transactions within tokens - -A NFT itself does not handle lending or rental functions directly. This standard is open-source, and there is no platform lockup. Developers can integrate it without having to worry about those risks. - -## Backward compatibility - -As mentioned in the specifications section, this standard can be fully ERC721 compatible by adding an extension function set. - -In addition, new functions introduced in this standard have many similarities with the existing functions in ERC721. This allows developers to easily adopt the standard quickly. - -## Test Cases - -When running the tests, you need to create a test network with Ganache-CLI: - -``` -ganache-cli -a 15 --gasLimit=0x1fffffffffffff -e 1000000000 -``` - -And then run the tests using Truffle: - -``` -truffle test -e development -``` - -Powered by Truffle and Openzeppelin test helper. - -## Implementation - -[Github Reposotory](https://github.com/kohshiba/ERC-X). - -## Security Considerations - -Since the external contract will control lien or tenant rights, flaws within the external contract directly lead to the standard's unexpected behavior. - -## 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-2615.md diff --git a/EIPS/eip-2645.md b/EIPS/eip-2645.md index bdbe0349a6e929..f3cfeef686499d 100644 --- a/EIPS/eip-2645.md +++ b/EIPS/eip-2645.md @@ -1,71 +1,7 @@ --- eip: 2645 -title: Hierarchical Deterministic Wallet for Layer-2 -author: Tom Brand , Louis Guthmann -discussions-to: https://ethereum-magicians.org/t/hierarchical-deterministic-wallet-for-computation-integrity-proof-cip-layer-2/4286 -status: Draft -type: Standards Track category: ERC -created: 2020-05-13 +status: Moved --- -## Simple Summary -In the context of Computation Integrity Proof (CIP) Layer-2 solutions such as ZK-Rollups, users are required to sign messages on new elliptic curves optimized for those environnements. We leverage existing work on Key Derivation ([BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) to define an efficient way to securely produce CIP L2s private keys, as well as creating domain separation between Layer-2 applications. - -## Abstract -We provide a Derivation Path allowing a user to derive hierarchical keys for Layer-2 solutions depending on the zk-technology, the application, the user’s Layer-1 address, as well as an efficient grinding method to enforce the private key distribution within the curve domain. The propose Derivation Path is defined as follow -``` -m / purpose' / layer' / application' / eth_address_1' / eth_address_2' / index -``` - -## Motivation -In the context of Computation Integrity Proof (CIP) Layer-2 solutions such as ZK-Rollups, users are required to sign messages on new elliptic curves optimized for those environnements. Extensive work has been done to make it secure on Bitcoin via [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki). Those protosals have become the standard for wallets in the entire industry, independently on the associated blockchain. As Layer-2 solutions are taking off, it is a necessary requirement to maintain the same standard and security in this new space. - -## Specification -Starkware keys are derived with the following [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)-compatible derivation path, with direct inspiration from [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki): -``` -m / purpose' / layer' / application' / eth_address_1' / eth_address_2' / index -``` -where: -* `m` - the seed. -* `purpose` - `2645` (the number of this EIP). -* `layer` - the 31 lowest bits of sha256 on the layer name. Serve as a domain separator between different technologies. In the context of `starkex`, the value would be `579218131`. -* `application` - the 31 lowest bits of sha256 of the application name. Serve as a domain separator between different applications. In the context of DeversiFi in June 2020, it is the 31 lowest bits of sha256(starkexdvf) and the value would be `1393043894`. -* `eth_address_1 / eth_address_2` - the first and second 31 lowest bits of the corresponding eth_address. -* `index` - to allow multiple keys per eth_address. - -As example, the expected path for address 0x0000....0000 assuming seed `m` and index 0 in the context of DeversiFi in June 2020: `m/2645'/579218131'/1393043894'/0'/0'/0` - -The key derivation should follow the following algorithm -``` -N = 2**256 -n = Layer2 curve order -path = stark derivation path -BIP32() = Official BIP-0032 derivation function on secp256k1 -hash = SHA256 -i = 0 -root_key = BIP32(path) -while True: - key = hash(root_key|i) - if (key < (N - (N % n))): - return key % n - i++ -``` -This algorithm has been defined to maintain efficiency on existing restricted devices. - -Nota Bene: At each round, the probability for a key to be greater than (N - (N % n)) is < 2^(-5). - -## Rationale -This EIP specifies two aspects of keys derivation in the context of Hierarchical Wallets: -- Derivation Path -- Grinding Algorithm to enforce a uniform distribution over the elliptic curve. -The derivation path is defined to allow efficient keys separation based on technology and application while maintaining a 1-1 relation with the Layer-1 wallet. In such a way, losing EIP-2645 wallets falls back to losing the Layer-1 wallet. - -## Backwards Compatibility -This standard complies with BIP43. - -## Security Considerations -This EIP has been defined to maintain separation of keys while providing foolproof logic on key derivation. - -## 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-2645.md diff --git a/EIPS/eip-2657.md b/EIPS/eip-2657.md index 182380482ce110..83b1c215c78bca 100644 --- a/EIPS/eip-2657.md +++ b/EIPS/eip-2657.md @@ -3,7 +3,7 @@ eip: 2657 title: Ephemeral Testnet Yolo author: James Hancock (@madeoftin) discussions-to: https://gitter.im/ethereum/AllCoreDevs -status: Draft +status: Stagnant type: Meta created: 2020-04-19 --- @@ -63,4 +63,4 @@ Client syncs with the network - Faucet is unauthenticated, you can reach it from the dashboard ## 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-2666.md b/EIPS/eip-2666.md index 1c2de46647404e..3bd458a40aec09 100644 --- a/EIPS/eip-2666.md +++ b/EIPS/eip-2666.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-05-22 @@ -130,4 +130,4 @@ There is no reference implementation at the time of writing as it requires just 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2677.md b/EIPS/eip-2677.md index 749464a9ec7938..7bf2473d7766ab 100644 --- a/EIPS/eip-2677.md +++ b/EIPS/eip-2677.md @@ -1,12 +1,13 @@ --- eip: 2677 title: Limit size of `initcode` -author: Martin Holst Swende (@holiman), Pawel Bylica (@chfast), Alex Beregszazi (@axic) +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: Draft +status: Withdrawn type: Standards Track category: Core created: 2020-05-18 +withdrawal-reason: Replaced by EIP-3860. --- ## Simple Summary @@ -73,4 +74,4 @@ Test cases should include the following cases, 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-2678.md b/EIPS/eip-2678.md index 9d183b0fd115e2..9d9d8d2c4d1b58 100644 --- a/EIPS/eip-2678.md +++ b/EIPS/eip-2678.md @@ -1,1043 +1,7 @@ --- eip: 2678 -title: Revised Ethereum Smart Contract Packaging Standard (EthPM v3) -author: g. nicholas d’andrea (@gnidan), Piper Merriam (@pipermerriam), Nick Gheorghita (@njgheorghita), Christian Reitwiessner (@chriseth), Ben Hauser (@iamdefinitelyahuman), Bryant Eisenbach (@fubuloubu) -discussions-to: https://ethereum-magicians.org/t/ethpm-v3-specification-working-group/4086 -status: Final -review-period-end: 2021-04-14 -type: Standards Track category: ERC -created: 2020-05-26 +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. Packages -are then published to on-chain EthPM registries, defined in -[EIP-1319](./eip-1319.md), from where they can be freely accessed. - -This document presents a natural language description of a formal -specification for version **3** 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. - -- Updates the schema for a *package manifest* to be compatible with - the [metadata](https://solidity.readthedocs.io/en/latest/metadata.html) output for compilers. -- Updates the `"sources"` object definition to support a wider range of source file types and serve as [JSON input](https://solidity.readthedocs.io/en/latest/using-the-compiler.html#compiler-input-and-output-json-description) for a compiler. -- Moves compiler definitions to a top-level `"compilers"` array in order to: - - Simplify the links between a compiler version, sources, and the - compiled assets. - - Simplify packages that use multiple compiler versions. -- Updates key formatting from `snake_case` to `camelCase` to be - more consistent with [JSON convention](https://google.github.io/styleguide/jsoncstyleguide.xml?showone=Property_Name_Format#Property_Name_Format). - -### 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. - -4. Package manifests can be used to verify public deployments of source - contracts. - -### Use Cases - -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. -* **simple-auction**: Compiler `"metadata"` field output. - -## Package Specification - -### 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](#prefixed) hexadecimal value begins with `0x`. -[Unprefixed](#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. - -- To ensure backwards compatibility, `manifest_version` is a forbidden - top-level key. - - -### 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](https://json-schema.org)) version of this specification: [package.spec.json](../assets/eip-2678/package.spec.json) -* **Jump To**: [Definitions](#object-definitions) - -### EthPM Manifest Version - -The `manifest` field defines the specification version that this -document conforms to. - -- Packages **must** include this field. - -* **Required**: Yes -* **Key**: `manifest` -* **Type**: String -* **Allowed Values**: `ethpm/3` - -### Package Name - -The `name` field defines a human readable name for this package. - -- Packages **should** include this field to be released on an EthPM - registry. - -- Package names **must** begin with a lowercase letter and be - comprised of only the lowercase letters `a-z`, numeric characters `0-9`, and the - dash character `-`. - -- Package names **must** not exceed 255 characters in length. - -* **Required**: If `version` is included. -* **Key**: `name` -* **Type**: String -* **Format**: **must** match the regular expression `^[a-z][-a-z0-9]{0,255}$` - -### Package Version - -The `version` field declares the version number of this release. - -- Packages **should** include this field to be released on an EthPM - registry. - -- This value **should** conform to the - [semver](http://semver.org/) version numbering - specification. - -* **Required**: If `name` is included. -* **Key**: `version` -* **Type**: String - -### Package Metadata - -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](#the-package-meta-object) - -### Sources - -The `sources` field defines a source tree that **should** comprise the -full source tree necessary to recompile the contracts contained in this -release. - -* **Required**: No -* **Key**: `sources` -* **Type**: Object (String: [Sources Object](#the-source-object)) - -### Contract Types - -The `contractTypes` field hosts the [Contract -Types](#contract-type) which have been included in this release. - -- Packages **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. - -* **Required**: No -* **Key**: `contractTypes` -* **Type**: Object (String: [Contract Type Object](#the-contract-type-object)) -* **Format**: Keys **must** be valid [Contract Aliases](#contract-alias).
Values **must** conform to the [Contract Type Object](#the-contract-type-object) definition. - -### Compilers - -The `compilers` field holds the information about the compilers and -their settings that have been used to generate the various -`contractTypes` included in this release. - -* **Required**: No -* **Key**: `compilers` -* **Type**: Array ([Compiler Information Object](#the-compiler-information-object)) - -### Deployments - -The `deployments` field holds the information for the chains on which -this release has [Contract Instances](#contract-instance) as well -as the [Contract Types](#contract-type) and other deployment -details for those deployed contract instances. The set of chains defined -by the [BIP122 URI](#bip122-uri) keys for this object **must** be -unique. There cannot be two different URI keys in a deployments field -representing the same blockchain. - -* **Required**: No -* **Key**: `deployments` -* **Type**: Object (String: Object(String: [Contract Instance Object](#the-contract-instance-object))) -* **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](#contract-instance-name)
- Values **must** be a valid [Contract Instance Object](#the-contract-instance-object) - -### Build Dependencies - -The `buildDependencies` field defines a key/value mapping of EthPM -packages that this project depends on. - -* **Required**: No -* **Key**: `buildDependencies` -* **Type**: Object (String: String) -* **Format**: Keys **must** be valid [package names](#package-name).
Values **must** be a [Content Addressable URI](#content-addressable-uri) which resolves to a valid package that conforms the same EthPM manifest version as its parent. - -### Object 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](#link-reference) object has the following -key/value pairs. All link references are assumed to be associated with -some corresponding [Bytecode](#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](#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](#identifier) format. - -### The *Link Value* Object - -Describes a single [Link Value](#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](#linking) the corresponding bytecode. - -* **Required**: Yes -* **Type**: String -* **Allowed Values**: `"literal"` for bytecode literals.
`"reference"` for named references to a particular [Contract Instance](#contract-instance) - -#### Value: `value` - -The `value` field defines the value which should be written when [linking](#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 0x-prefixed -hexadecimal string representing bytes. - - -To reference the address of a [Contract -Instance](#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](#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](#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 `buildDependencies` for the - current package. - -- For every `pn` where `n > 1`, `pn` **must** be present in the keys - of the `buildDependencies` 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](#contract-name). - -- The `` value **must** be a valid [Contract - Instance Name](#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: `linkReferences` - -The `linkReferences` field defines the locations in the corresponding -bytecode which require [linking](#linking). - -* **Required**: No -* **Type**: Array -* **Format**: All values **must** be valid [Link Reference objects](#the-link-reference-object). See also below. - -Format - -This field is considered invalid if *any* of the [Link -References](#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: `linkDependencies` - -The `linkDependencies` defines the [Link Values](#link-value) that -have been used to link the corresponding bytecode. - -* **Required**: No -* **Type**: Array -* **Format**: All values **must** be valid [Link Value objects](#the-link-value-object). 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](#the-link-value-object) **must** have a - corresponding [link reference object](#the-link-reference-object) under - the `linkReferences` field. - -- The length of the resolved `value` **must** be equal to the `length` - of the corresponding [Link Reference](#link-reference). - - -### The *Package Meta* Object - -The *Package Meta* object is defined to have the following key/value -pairs. - -#### 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 - -The `license` field declares the license associated with this package. -This value **should** conform to the -[SPDX](https://spdx.org/licenses/) -format. Packages **should** include this field. If a file [Source -Object](#the-source-object) defines its own license, that license takes -precedence for that particular file over this package-scoped `meta` -license. - -* **Required**: No -* **Key**: `license` -* **Type**: String - -#### 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 - -The `keywords` field provides relevant keywords related to this package. - -* **Required**: No -* **Key**: `keywords` -* **Type**: Array(String) - -#### 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. - -* **Required**: No -* **Key**: `links` -* **Type**: Object (String: String) - -### The *Sources* Object - -A *Sources* object is defined to have the following fields. - -* **Key**: A unique identifier for the source file. (String) -* **Value**: [Source Object](#the-source-object) - -### The *Source* Object - -#### Checksum: `checksum` - -Hash of the source file. - -* **Required**: Only **if** the `content` field is missing and none of the provided URLs contain a content hash. -* **Key**: `checksum` -* **Value**: [Checksum Object](#the-checksum-object) - -#### URLS: `urls` - -Array of urls that resolve to the same source file. -- Urls **should** be stored on a content-addressable filesystem. - **If** they are not, then either `content` or `checksum` **must** be - included. - -- Urls **must** be prefixed with a scheme. - -- 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. - -* **Required**: If `content` is not included. -* **Key**: `urls` -* **Value**: Array(String) - -#### Content: `content` - -Inlined contract source. If both `urls` and `content` are provided, the `content` value -**must** match the content of the files identified in `urls`. - -* **Required**: If `urls` is not included. -* **Key**: `content` -* **Value**: String - -#### Install Path: `installPath` - -Filesystem path of source file. -- **Must** be a relative filesystem path that begins with a `./`. - -- **Must** resolve to a path that is within the current virtual - working directory. - -- **Must** be unique across all included sources. - -- **Must not** contain `../` to avoid accessing files outside of - the source folder in improper implementations. - -* **Required**: This field **must** be included for the package to be writable to disk. -* **Key**: `installPath` -* **Value**: String - -#### Type: `type` - -The `type` field declares the type of the source file. The field -**should** be one of the following values: `solidity`, `vyper`, -`abi-json`, `solidity-ast-json`. - -* **Required**: No -* **Key**: `type` -* **Value**: String - -#### License: `license` - -The `license` field declares the type of license associated with -this source file. When defined, this license overrides the -package-scoped [meta license](#license). - -* **Required**: No -* **Key**: `license` -* **Value**: String - -### The *Checksum* Object - -A *Checksum* object is defined to have the following key/value pairs. - -#### Algorithm: `algorithm` - -The `algorithm` used to generate the corresponding hash. Possible -algorithms include, but are not limited to `sha3`, `sha256`, `md5`, -`keccak256`. - -* **Required**: Yes -* **Type**: String - -#### Hash: `hash` - -The `hash` of a source files contents generated with the corresponding -algorithm. - -* **Required**: Yes -* **Type**: String - -### The *Contract Type* Object - -A *Contract Type* object is defined to have the following key/value -pairs. - -#### Contract Name: `contractName` - -The `contractName` field defines the [Contract -Name](#contract-name) for this [Contract -Type](#contract-type). - -* **Required**: If the [Contract Name](#contract-name) and [Contract Alias](#contract-alias) are not the same. -* **Type**: String -* **Format**: **Must** be a valid [Contract Name](#contract-name) - -#### Source ID: `sourceId` - -The global source identifier for the source file from which this -contract type was generated. - -* **Required**: No -* **Type**: String -* **Format**: **Must** match a unique source ID included in the [Sources Object](#the-sources-object) for this package. - -#### Deployment Bytecode: `deploymentBytecode` - -The `deploymentBytecode` field defines the bytecode for this [Contract -Type](#contract-type). - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [Bytecode object](#the-bytecode-object) format. - -#### Runtime Bytecode: `runtimeBytecode` - -The `runtimeBytecode` field defines the unlinked `0x`-prefixed runtime -portion of [Bytecode](#bytecode) for this [Contract -Type](#contract-type). - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [Bytecode object](#the-bytecode-object) format. - -#### ABI: `abi` - -* **Required**: No -* **Type**: Array -* **Format**: **Must** conform to the [Ethereum Contract ABI JSON](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#json) format. - -#### UserDoc: `userdoc` - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [UserDoc](https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format#user-documentation) format. - -#### DevDoc: `devdoc` - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [DevDoc](https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format#developer-documentation) format. - -### The *Contract Instance* Object - -A **Contract Instance Object** represents a single deployed [Contract -Instance](#contract-instance) and is defined to have the following -key/value pairs. - -#### Contract Type: `contractType` - -The `contractType` field defines the [Contract -Type](#contract-type) for this [Contract -Instance](#contract-instance). This can reference any of the -contract types included in this [Package](#package) *or* any of the -contract types found in any of the package dependencies from the -`buildDependencies` section of the [Package -Manifest](#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](#contract-alias). - -- The value **must** be present in the keys of the `contractTypes` - 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 - `buildDependencies` of this Package. - -- The `` value **must** be be a valid [Contract - Alias](#contract-alias). - -- The resolved package for `` must contain the - `` value in the keys of the `contractTypes` section. - -#### Address: `address` - -The `address` field defines the [Address](#address) of the -[Contract Instance](#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](#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: `runtimeBytecode` - -The `runtimeBytecode` field defines the runtime portion of bytecode for -this [Contract Instance](#contract-instance). When present, the -value from this field supersedes the `runtimeBytecode` from the -[Contract Type](#contract-type) for this [Contract -Instance](#contract-instance). - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [Bytecode Object](#the-bytecode-object) format. - -Every entry in the `linkReferences` for this bytecode **must** have a -corresponding entry in the `linkDependencies` section. - -### The *Compiler Information* Object - -The `compilers` field defines the various compilers and settings used -during compilation of any [Contract Types](#contract-type) or -[Contract Instance](#contract-instance) included in this package. - -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](http://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](http://solidity.readthedocs.io/en/latest/using-the-compiler.html#compiler-input-and-output-json-description). - -* **Required**: No -* **Key**: `settings` -* **Type**: Object - -#### Contract Types: `contractTypes` - -A list of the [Contract Alias](#contract-alias) or [Contract Types](#contract-type) in this package -that used this compiler to generate its outputs. - -- All `contractTypes` that locally declare `runtimeBytecode` - **should** be attributed for by a compiler object. - -- A single `contractTypes` **must** not be attributed to more than one - compiler. - -* **Required**: No -* **Key**: `contractTypes` -* **Type**: Array([Contract Alias](#contract-alias)) - - -### BIP122 URI - -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). - -### Glossary - -The terms in this glossary have been updated to reflect the changes made -in V3. - -#### 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](#prefixed) with `0x`. - -Bytecode can either be linked or unlinked. (see -[Linking](#linking)) - -* **Unlinked Bytecode**: The hexadecimal representation of a contract’s EVM instructions that contains sections of code that requires [linking](#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](#link-reference) replaced with the desired [Link Values](#link-value). **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](#contract-type). Contract aliases **must** be unique within a -single [Package](#package). - -The contract alias **must** use *one of* the following naming schemes: - -- `` - -- `` - -The `` portion **must** be the same as the [Contract -Name](#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](#contract-type). - -All contract instances have an [Address](#address) on some specific -chain. - -#### Contract Instance Name -A name which refers to a specific [Contract -Instance](#contract-instance) on a specific chain from the -deployments of a single [Package](#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](#contract-type), package managers **should** use the -[Contract Alias](#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](#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](#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](#link-reference) - -#### Linking -The act of replacing [Link References](#link-reference) with [Link -Values](#link-value) within some [Bytecode](#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](#package-manifest). - -#### Package Manifest -A machine-readable description of a package. - -#### Prefixed -[Bytecode](#bytecode) string with leading `0x`. - -* **Example**: `0xdeadbeef` - -#### Unprefixed -Not [Prefixed](#prefixed). - -* **Example**: `deadbeef` - -## Rationale - -### Minification - -EthPM packages are distributed as alphabetically-ordered & minified JSON to ensure consistency. -Since packages are published on content-addressable filesystems (eg. IPFS), this restriction -guarantees that any given set of contract assets will always resolve to the same content-addressed URI. - -### Package Names - -Package names are restricted to lower-case characters, numbers, and `-` to improve the readability -of the package name, in turn improving the security properties for a package. A user is more likely -to accurately identify their target package with this restricted set of characters, and not confuse -a malicious package that disguises itself as a trusted package with similar but different -characters (e.g. `O` and `0`). - -### BIP122 - -The BIP-122 standard has been used since EthPM v1 since it is an industry standard URI scheme for -identifying different blockchains and distinguishing between forks. - -### Compilers - -Compilers are now defined in a top-level array, simplifying the task for tooling to identify the compiler types -needed to interact with or validate the contract assets. This also removes unnecessarily duplicated -information, should multiple `contractTypes` share the same compiler type. - -## Backwards Compatibility - -To improve understanding and readability of the EthPM spec, the -`manifest_version` field was updated to `manifest` in v3. To ensure -backwards compatibility, v3 packages **must** define a top-level -`"manifest"` with a value of `"ethpm/3"`. Additionally, -`"manifest_version"` is a forbidden top-level key in v3 packages. - - -## Security Considerations - -Using EthPM packages implicitly requires importing &/or executing code written by others. The EthPM spec -guarantees that when using a properly constructed and released EthPM package, the user will have the exact same -code that was included in the package by the package author. However, it is impossible to guarantee that this code -is safe to interact with. Therefore, it is critical that end users only interact with EthPM packages authored and -released by individuals or organizations that they trust to include non-malicious code. - - -## 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-2678.md diff --git a/EIPS/eip-2680.md b/EIPS/eip-2680.md index 50e9d9b59466b4..637cab1e90dde0 100644 --- a/EIPS/eip-2680.md +++ b/EIPS/eip-2680.md @@ -1,136 +1,7 @@ --- eip: 2680 -title: Ethereum 2 wallet layout -author: Jim McDonald -discussions-to: https://ethereum-magicians.org/t/eip-2680-ethereum-2-wallet-layout/4323 -status: Draft -type: Standards Track category: ERC -created: 2020-05-29 +status: Moved --- -## Simple Summary - -A standard layout and naming format for walletstore and keystore for both hierarchical (e.g. filesystem, Amazon S3) and non-hierarchical (key/value) storage systems. - -## Abstract - -Ethereum wallets have no standards for their layout in persistent storage, making different wallet implementations incompatible. This defines a standard for the placement of Ethereum walletstores and keystores, making it possible for different software to work with the same wallets and keys. - -## Motivation - -A standard layout for wallets and accounts allows interoperability between validators. This benefits users, as they can move from one validator software to another (and back) without requiring movement of files. This is important because any movement of files containing keys involves danger of either deleting them or duplicating them, both of which could cause loss of access to funds. - -## Specification - -There are four elements for a wallet that need to be addressed. These are defined below. - -### Base location -The base location is required to be well-known, either pre-defined or defined by the storage system's connection parameters. - -For filesystems the pre-defined base location for different operating systems is as follows: - - - Windows: `%APPDATA%\ethereum2\wallets` - - MacOSX: `${HOME}/Library/Application Support/ethereum2/wallets` - - Linux: `${HOME}/.config/ethereum2/wallets` - -For other hierarchical stores, for example Amazon S3, the base location MUST be the lower-case hex string representing the [SHA-256](../assets/eip-2680/sha256-384-512.pdf) hash of the string "Ethereum 2 wallet:" appended with the identifier for the hierarchical store. For example, if the account ID for a user's Amazon S3 account is "AbC0438EB" then: - - - string would be `Ethereum 2 wallet:AbC0438EB` - - SHA-256 hash of string would be the byte array `0x991ec14a8d13836b10d8c3039c9e30876491cb8aa9c9c16967578afc815c9229` - - base location would be the string `991ec14a8d13836b10d8c3039c9e30876491cb8aa9c9c16967578afc815c9229` - -For non-hierarchical stores there is no base location. - -### Wallet container -The wallet container holds the walletstore and related keystores. - -The wallet container is identified by the wallet's UUID. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -### Walletstore -The walletstore element contains the walletstore and is held within the wallet container. It is identified by the wallet's UUID. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -### Keystore -The keystore element contains the keystore for a given key and is held within the wallet container. It is identified by the key's UUID. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -## Hierarchical store example -Hierarchical stores are a common way to store and organize information. The most common example is the filesystem, but a number of object-based stores such as Amazon S3 also provide hierarchical naming. - -Putting these elements together for a sample wallet with wallet UUID `1f031fff-c51d-44fc-8baf-d6b304cb70a7` and key UUIDs `1302106c-8441-4e2e-b687-6c77f49fc624` and `4a320100-83fd-4db7-8126-6d6d205ba834` gives the following layout: - -``` -- 1f031fff-c51d-44fc-8baf-d6b304cb70a7 -+- 1302106c-8441-4e2e-b687-6c77f49fc624 -+- 1f031fff-c51d-44fc-8baf-d6b304cb70a7 -+- 4a320100-83fd-4db7-8126-6d6d205ba834 -``` - -### Non-hierarchical store example -Non-hierarchical stores use a simplified approach where the wallet UUID and key UUIDs are concatenated using the ':' character. Using the same example wallet and key UUIDs as above would result in objects with the following keys: - -``` -1f031fff-c51d-44fc-8baf-d6b304cb70a7:1302106c-8441-4e2e-b687-6c77f49fc624 -1f031fff-c51d-44fc-8baf-d6b304cb70a7:1f031fff-c51d-44fc-8baf-d6b304cb70a7 -1f031fff-c51d-44fc-8baf-d6b304cb70a7:4a320100-83fd-4db7-8126-6d6d205ba834 -``` - -### Protecting against concurrent write access -TBD - -### Iterating over wallets -In the case of hierarchical stores and iteration-capable non-hierarchical stores iteration over wallets is a matter of iterating over the files in the root container. - -An implementer MAY include an index in the base location. If so then it MUST follow the structure as specified in the following "Index format" section. - -### Iterating over accounts -In the case of hierarchical stores iteration over accounts is a matter of iterating over the files in the wallet container. - -An implementer MAY include an index within a wallet container for accounts within that wallet. If so then it MUST follow the structure as specified in the following "Index format" section. - -### Index format -The index format is the same for both wallets and accounts, following a standard JSON schema. - -```json -{ - "type": "array", - "items": { - "type": "object", - "properties": { - "uuid": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "uuid", - "name" - ] - } -} -``` - -The index MUST use the identifier 'index'. - -Public keys must NOT be stored in the index. - -## Rationale - -A standard for walletstores, similar to that for keystores, provides a higher level of compatibility between wallets and allows for simpler wallet and key interchange between them. - -## Implementation - -A Go implementation of the filesystem layout can be found at [https://github.com/wealdtech/go-eth2-wallet-filesystem](https://github.com/wealdtech/go-eth2-wallet-filesystem). - -A Go implementation of the Amazon S3 layout can be found at [https://github.com/wealdtech/go-eth2-wallet-s3](https://github.com/wealdtech/go-eth2-wallet-s3). - -## Security Considerations - -Locations for wallet stores are defined to be within each user's personal space, reducing the possibility of accidental exposure of information. It is, however, still possible for permissions to be set such that this data is world-readable, and applications implementing this EIP should attempt to set, and reset, permissions to ensure that only the relevant user has access to the information. - -The names for both wallet and key stores are UUIDs, ensuring that no data is leaked from the metadata. - -## 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-2680.md diff --git a/EIPS/eip-2681.md b/EIPS/eip-2681.md index 9e5972f49be38b..db9e1ffc38de76 100644 --- a/EIPS/eip-2681.md +++ b/EIPS/eip-2681.md @@ -3,7 +3,7 @@ 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: Review +status: Final type: Standards Track category: Core created: 2020-04-25 @@ -23,10 +23,10 @@ Lastly, this facilitates a minor optimisation in clients, because the nonce no l ## Specification -If `block.number >= FORK_BLOCK` introduce two new restrictions: +Introduce two new restrictions retroactively from genesis: -1. Consider any transaction invalid, where the nonce exceeds `2^64-1`. -2. The `CREATE` instruction to abort with an exceptional halt, where the account nonce is `2^64-1`. +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 @@ -37,13 +37,15 @@ This mode of replay protection is out of fashion since [EIP-155](./eip-155.md) i 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 in place (`state.Account.Nonce` and `types.txdata.AccountNonce` it as a 64-bit number). +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 @@ -51,4 +53,4 @@ None. ## 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-2696.md b/EIPS/eip-2696.md index 9b50efb0fcfa23..555d5178967d85 100644 --- a/EIPS/eip-2696.md +++ b/EIPS/eip-2696.md @@ -97,4 +97,4 @@ While this standard is perhaps not the greatest mechanism for communicating betw 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2700.md b/EIPS/eip-2700.md index 31e9f408f5c176..bd7c590b259a77 100644 --- a/EIPS/eip-2700.md +++ b/EIPS/eip-2700.md @@ -44,4 +44,4 @@ This EIP is mostly a retrospective EIP meaning it codifies an already existing s 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2711.md b/EIPS/eip-2711.md index 5d7e16a4014c1b..4c733e9dc9dd57 100644 --- a/EIPS/eip-2711.md +++ b/EIPS/eip-2711.md @@ -3,7 +3,7 @@ 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: Draft +status: Withdrawn type: Standards Track category: Core created: 2020-06-11 @@ -96,7 +96,7 @@ While we could save one byte in the common case by bundling the y-parity bit of ### 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 transcations to simply have a `0` (1 byte in RLP) value for this field. +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` @@ -133,4 +133,4 @@ No known issues. ## Security Considerations ## 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-2718.md b/EIPS/eip-2718.md index e5501aefb27fe8..83a19b0fa865dc 100644 --- a/EIPS/eip-2718.md +++ b/EIPS/eip-2718.md @@ -1,18 +1,15 @@ --- 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: Last Call -review-period-end: 2021-04-15 +status: Final type: Standards Track category: Core created: 2020-06-13 --- -## Simple Summary -Defines a new transaction type that is an envelope for future transaction types. - ## 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. @@ -22,7 +19,7 @@ This was seen in [EIP-155](./eip-155.md) where the new value was bit-packed into 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 envolope 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. +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 @@ -32,7 +29,7 @@ By introducing an envolope transaction type, we only need to ensure backward com 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 transcation +* `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])` @@ -43,7 +40,7 @@ This makes it so we do not have to worry about signatures for one transaction ty 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 transcation +* `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])` @@ -79,4 +76,4 @@ If it starts with a value in the range `[0, 0x7f]` then it is a new transaction 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2733.md b/EIPS/eip-2733.md index 57d6d0a749a224..067265651ba557 100644 --- a/EIPS/eip-2733.md +++ b/EIPS/eip-2733.md @@ -3,11 +3,12 @@ eip: 2733 title: Transaction Package author: Matt Garnett (@lightclient) discussions-to: https://ethereum-magicians.org/t/eip-transaction-package/4365 -status: Draft +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 @@ -248,7 +249,7 @@ limit. 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, simplifing clients and downstream infrastructure. The +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. @@ -288,4 +289,4 @@ 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2746.md b/EIPS/eip-2746.md index fc006be63b0731..ef688895dcf679 100644 --- a/EIPS/eip-2746.md +++ b/EIPS/eip-2746.md @@ -1,220 +1,7 @@ --- eip: 2746 -title: Rules Engine Standard -author: Aaron Kendall (@jaerith), Juan Blanco (@juanfranblanco) -discussions-to: https://ethereum-magicians.org/t/eip-2746-rules-engine-interface/4435 -status: Draft -type: Standards Track category: ERC -created: 2020-06-20 +status: Moved --- -## Simple Summary -An interface for using a smart contract as a rules engine. A single deployed contract can register a data domain, create sets of rules that perform actions on that domain, and then invoke a set as an atomic transaction. - -## Abstract -This standard proposes an interface that will allow the creation of hierarchal sets of rules (i.e., RuleTrees) that can be invoked to evaluate and manipulate a registered data domain. At the time of this draft, all intentions to insert additional functionality onto the blockchain requires the coding and creation of a newly deployed contract. However, this standard will allow users to deploy a contract just once, one which will then allow them to create (and invoke) pipelines of commands within that contract. - -## Motivation -At the time of this draft, all development for Ethereum requires writing the code that forms smart contracts and then deploying those contracts to Ethereum. In order to create a proper contract, many considerations must be taken into account when designing and implementing the code, especially in terms of efficiency (i.e., gas cost) and security. Even the simplest contracts require a certain amount of vigilance and examination, before and after deployment. These requirements pertain to all cases, even for simple cases of examining a value and/or altering it. - -These technical challenges might form an obstacle for many others who might wish to create software around Ethereum. Less technical companies and users might also want to configure and deploy simple functionality onto the chain, without knowing the relevant languages or details necessary. By having the data domain and the predefined actions (i.e., types of rules) implemented along with this interface, a deployed instance of such a rules engine contract can provide efficient and safe functionality to no-code or little-code clients, allowing more users of various technical proficiency to interact with the Ethereum ecosystem. - -## Specification -For the clarification of terminology, an Attribute is a registered data point within the data domain, representing data that exists either in the rules engine contract or elsewhere. A Rule is an predefined action that occurs upon a single data point (i.e., Attribute) in the predefined data domain. For example, a Rule could check whether the Attribute 'TokenAmt' has a value less than the RHL (i.e., right-hand value) of 10. A RuleSet is a collection of Rules, where their collection invocation creates a boolean result that determines the navigational flow of execution between RuleSets. A RuleTree is a collection of RuleSets that are organized within a hierarchy, where RuleSets can contain other RuleSets. - -```solidity -pragma solidity ^0.6.0; - -/** - @title ERC-2746 Rules Engine Standard - @dev See https://eips.ethereum.org/EIPS/eip-2746 - */ - interface ERCRulesEngine { - - /** - @dev Should emit when a RuleTree is invoked. - The `ruler` is the ID and owner of the RuleTree being invoked. It is also likely msg.sender. - */ - event CallRuleTree( - address indexed ruler - ); - - /** - @dev Should emit when a RuleSet is invoked. - The `ruler` is the ID and owner of the RuleTree in which the RuleSet is stored. It is also likely msg.sender. - The 'ruleSetId' is the ID of the RuleSet being invoked. - */ - event CallRuleSet( - address indexed ruler, - bytes32 indexed tmpRuleSetId - ); - - /** - @dev Should emit when a Rule is invoked. - The `ruler` is the ID and owner of the RuleTree in which the RuleSet is stored. It is also likely msg.sender. - The 'ruleSetId' is the ID of the RuleSet being invoked. - The 'ruleId' is the ID of the Rule being invoked. - The 'ruleType' is the type of the rule being invoked. - */ - event CallRule( - address indexed ruler, - bytes32 indexed ruleSetId, - bytes32 indexed ruleId, - uint ruleType - ); - - /** - @dev Should emit when a RuleSet fails. - The `ruler` is the ID and owner of the RuleTree in which the RuleSet is stored. It is also likely msg.sender. - The 'ruleSetId' is the ID of the RuleSet being invoked. - The 'severeFailure' is the indicator of whether or not the RuleSet is a leaf with a 'severe' error flag. - */ - event RuleSetError ( - address indexed ruler, - bytes32 indexed ruleSetId, - bool severeFailure - ); - - /** - @notice Adds a new Attribute to the data domain. - @dev Caller should be the deployer/owner of the rules engine contract. An Attribute value can be an optional alternative if it's not a string or numeric. - @param _attrName Name/ID of the Attribute - @param _maxLen Maximum length of the Attribute (if it is a string) - @param _maxNumVal Maximum numeric value of the Attribute (if it is numeric) - @param _defaultVal The default value for the Attribute (if one is not found from the source) - @param _isString Indicator of whether or not the Attribute is a string - @param _isNumeric Indicator of whether or not the Attribute is numeric - */ - function addAttribute(bytes32 _attrName, uint _maxLen, uint _maxNumVal, string calldata _defaultVal, bool _isString, bool _isNumeric) external; - - /** - @notice Adds a new RuleTree. - @param _owner Owner/ID of the RuleTree - @param _ruleTreeName Name of the RuleTree - @param _desc Verbose description of the RuleTree's purpose - */ - function addRuleTree(address _owner, bytes32 _ruleTreeName, string calldata _desc) external; - - /** - @notice Adds a new RuleSet onto the hierarchy of a RuleTree. - @dev RuleSets can have child RuleSets, but they will only be called if the parent's Rules execute to create boolean 'true'. - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet - @param _desc Verbose description of the RuleSet - @param _parentRSName ID/Name of the parent RuleSet, to which this will be added as a child - @param _severalFailFlag Indicator of whether or not the RuleSet's execution (as failure) will result in a failure of the RuleTree. (This flag only applies to leaves in the RuleTree.) - @param _useAndOp Indicator of whether or not the rules in the RuleSet will execute with 'AND' between them. (Otherwise, it will be 'OR'.) - @param _failQuickFlag Indicator of whether or not the RuleSet's execution (as failure) should immediately stop the RuleTree. - */ - function addRuleSet(address _owner, bytes32 _ruleSetName, string calldata _desc, bytes32 _parentRSName, bool _severalFailFlag, bool _useAndOp, bool _failQuickFlag) external; - - /** - @notice Adds a new Rule into a RuleSet. - @dev Rule types can be implemented as any type of action (greater than, less than, etc.) - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet to which the Rule will be added - @param _ruleName ID/Name of the Rule being added - @param _attrName ID/Name of the Attribute upon which the Rule is invoked - @param _ruleType ID of the type of Rule - @param _rightHandValue The registered value to be used by the Rule when performing its action upon the Attribute - @param _notFlag Indicator of whether or not the NOT operator should be performed on this Rule. - */ - function addRule(address _owner, bytes32 _ruleSetName, bytes32 _ruleName, bytes32 _attrName, uint _ruleType, string calldata _rightHandValue, bool _notFlag) external; - - /** - @notice Executes a RuleTree. - @param _owner Owner/ID of the RuleTree - */ - function executeRuleTree(address _owner) external returns (bool); - - /** - @notice Retrieves the properties of a Rule. - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet where the Rule resides - @param _ruleIdx Index of the rule in the RuleSet's listing - @return bytes32 ID/Name of Rule - @return uint Type of Rule - @return bytes32 Target Attribute of Rule - @return string Value mentioned in Rule - @return bool Flag for NOT operator in Rule - @return bytes32[] Values that should be provided in delegated call (if Rule is custom operator) - */ - function getRuleProps(address _owner, bytes32 _ruleSetName, uint _ruleIdx) external returns (bytes32, uint, bytes32, string memory, bool, bytes32[] memory); - - /** - @notice Retrieves the properties of a RuleSet - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet - @return string Verbose description of the RuleSet - @return bool Flag that indicates whether this RuleSet's failure (if a leaf) will cause the RuleTree to fail - @return bool Flag that indicates whether this RuleSet uses the AND operator when executing rules collectively - @return uint Indicates the number of rules hosted by this RuleSet - @return bytes32[] The list of RuleSets that are children of this RuleSet - */ - function getRuleSetProps(address _owner, bytes32 _ruleSetName) external returns (string memory, bool, bool, uint, uint, bytes32[] memory); - - /** - @notice Retrieves the properties of a RuleSet - @param _owner Owner/ID of the RuleTree - @return bytes32 Name of the RuleTree - @return string Verbose description of the RuleTree - @return bytes32 ID/Name of the RuleSet that serves as the root node for the RuleTree - */ - function getRuleTreeProps(address _owner) external returns (bytes32, string memory, bytes32); - - /** - @notice Removes a RuleTree. - @param _owner Owner/ID of the RuleTree - */ - function removeRuleTree(address _owner) external returns (bool); -} -``` - -### Considerations - -An argument could be made for interface functions that allow a RuleTree's owner to include others users as executors of the RuleTree. - -Another argument could be made for interface functions that allow an administrator to configure the origin point of an Attribute, such as whether the Attribute's value comes from a data structure (internal to the rules engine contract) or from calling a contract method (like an implementation of the [Diamond Standard](https://github.com/ethereum/EIPs/issues/2535)). - -Yet another argument could be made for interface functions that allow an administrator to extend the functionality catalog provided by the rules engine, by allowing other contracts' methods to be added as a rule operation. - -Also, an argument could be made for functions that calculate and report the range of potential cost for invoking a RuleTree. Unlike the normal execution of a contract method, the Ethereum transaction costs of invoking a RuleTree are more dynamic, depending on its depth/breadth and the navigational flow during invocation. Since the general cost of a RuleTree is unknown until the time of invocation, these functions could report the minimal amount of gas for a transaction (i.e., none of the Rules in a RuleTree are invoked) and the maximum amount for a transaction (i.e., all Rules in a RuleTree are invoked). - -### Example - -A company wishes to deploy a contract with data points and functionality that are predefined and/or under the control of an administrator, and it aims to build a no-code client that will allow less-technical users to define actions within the rules engine contract. In this example, the company wants one of its users to write the rules in a proprietary markup language, in order for the calculation of a VAT to be determined. For the sake of transparency, [these rules](https://ipfs.infura.io/ipfs/QmPrZ9959c7SzzqdLkVgX28xM7ZrqLeT3ydvRAHCaL1Hsn) are published onto IPFS, so that they are accessible to auditors and possibly government officials. The no-code client will then know how to parse the rules from the markup and communicate with the rules engine contract, establishing the RuleTree to be invoked later by the company's user(s) or off-chain programs. - -In order to calculate the value of the VAT, these provided rules invoke simple mathematical operations that can perform the calculation. However, the implementation of the rules engine contract could possess other functionality called by rules, ones that could execute more complicated logic or call the methods of other contracts. - -## Rationale - -### Attributes - -The data points are abstracted in order to let the implementation provide the mechanism for retrieving/populating the data. Data can be held by an internal data structure, another contract's method, or any number of other options. - -### Events - -The events specified will help the caller of the RuleTree after execution, so that they may ascertain the navigational flow of RuleSet execution within the RuleTree and so that they may understand which RuleSets failed. - -### Right-Hand Value - -In the function addRule(), the data type for the right-hand value is 'string' since the rule's action depends on its type, meaning that the value must be provided in a generic form. In the case of a Rule that performs numerical operations, the provided value could be transformed into a number when stored in the Rule. - -## Implementation -- [Wonka](https://github.com/Nethereum/Wonka/tree/master/Solidity/WonkaEngine) -- [Wonka Rules Editor](https://github.com/jaerith/WonkaRulesBlazorEditor) - -The Wonka implementation supports this proposed interface and also implements all of the additional considerations mentioned above. - -## Security Considerations - -The deployer of the contract should be the owner and administrator, allowing for the addition of Attributes and RuleTrees. Since a RuleTree is owned by a particular EOA (or contract address), the only accounts that should be able to execute the RuleTree should be its owner or the contract's owner/administrator. If Attributes are defined to exist as data within other contracts, the implementation must take into account the possibility that RuleTree owners must have the security to access the data in those contracts. - -## References - -**Standards** -- [EIP-2535 Diamond Standard](./eip-2535.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-2746.md diff --git a/EIPS/eip-2767.md b/EIPS/eip-2767.md index bec3ccc440b141..e78cf4776e1ff8 100644 --- a/EIPS/eip-2767.md +++ b/EIPS/eip-2767.md @@ -1,123 +1,7 @@ --- eip: 2767 -title: Contract Ownership Governance -author: Soham Zemse (@zemse), Nick Mudge (@mudgen) -discussions-to: https://github.com/ethereum/EIPs/issues/2766 -status: Draft -type: Standards Track category: ERC -created: 2020-07-04 -requires: 20, 165, 173 +status: Moved --- -## Simple Summary - -A standard for Governance contracts that holds the administrative ownership of other smart contracts with voting power distributed as `ERC-20` tokens. - -## Abstract - -The following standard defines the implementation of a standard API for a Governance smart contract based on `ERC-20`. Existing `ERC-173` compatible contracts can upgrade from private key wallet ownership to a Governance smart contract. Adhering to a standard API enables general tools to populate governance information of various projects, thus increasing transparency. - -## Motivation - -Traditionally, many contracts that require that they be owned or controlled in some way use `ERC-173` which standardized the use of ownership in the smart contracts. For example to withdraw funds or perform administrative actions. - -```solidity -contract dApp { - function doSomethingAdministrative() external onlyOwner { - // admin logic that can be performed by a single wallet - } -} -``` - -Often, such administrative rights for a contract are written for maintenance purpose but users need to trust the owner. Rescue operations by an owner have raised questions on decentralised nature of the projects. Also, there is a possibility of compromise of an owner's private key. - -At present, many governance implementations by ambitious projects need users to visit a specific UI to see governance information about their project. Some examples of live implementations having different API that does the same thing are [Compound Governance](https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol#L27), [Uniswap Governance](https://github.com/Uniswap/governance/blob/master/contracts/GovernorAlpha.sol#L27) and [Sushiswap Governance](https://github.com/sushiswap/sushiswap/blob/master/contracts/GovernorAlpha.sol#L45). It's just like if the ERC-20 standard wasn't finalized, then token projects would have their own block explorer. Adhering to a standard API would enable general tools (like Etherscan) to populate governance information, thus increasing transparency to users. Using widely popular `ERC-20` token as a governance token, existing tools built to work with `ERC-20` can already display voters. This can result in a wide adoption for contract governance over private key based ownership. - -## Specification - -A Governance contract that is compliant with `ERC-2767` shall implement the following interfaces: - -```solidity -/// @title ERC-2767 Governance -/// @dev ERC-165 InterfaceID: 0xd8b04e0e -interface ERC2767 is ERC165 { - /// @notice Gets number votes required for achieving consensus - /// @dev Should cost less than 30000 gas - /// @return Required number of votes for achieving consensus - function quorumVotes() external view returns (uint256); - - /// @notice The address of the Governance ERC20 token - function token() external view returns (address); -} -``` - -### `ERC-20` Governance Token - -An `ERC-2767` Governance Contract should reference an address through `token()` that implements `ERC-20` interface. `token()` is allowed to return self address (`address(this)`), if `ERC-20` functionalities are implemented in the same contract (one can consider checking out Diamond Standard [`ERC-2535`](https://eips.ethereum.org/EIPS/eip-2535) to optimise contract size). - -Implementations are allowed to have varying `ERC-20`'s `totalSupply()` (through any standard of minting or burning). But having a fixed `quorumVotes()` return value in this case would cause required votes consensus in `%` with respect to `totalSupply()` to change. To automatically account for this, any custom logic under `quorumVotes()` is allowed to return for e.g. `51%` of `totalSupply()`. - -### `ERC-165` Interface Identification - -An `ERC-2767` Governance Contract should also implement `ERC-165`. This helps general tools to identify whether a contract is a `ERC-2767` Governance contract. - -```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 - -The goals of this EIP have been the following: - -- Standardize API of Governance contracts to make it easy for analysis tools to be built. -- Encourage use of `ERC-20` based weighted governance over existing multi-sig (_generally limited to 50 max owners_) for big projects. -- Encourage existing `ERC-173` ownership smart contracts / projects to move to Governance based ownership by removing the effort needed to host custom UI for their project. -- Encourage availability of publicly audited governance contracts, just like `ERC-20` which anyone can use. -- Make it possible to utilize existing `ERC-20` tools for owners of governance token analysis. -- Make future protocols possible that need to interact with governances of multiple projects. -- Keep this EIP minimal and allow another EIPs to standardize any specific functionalities. - -## Backwards Compatibility - -Smart contracts that are `ERC-173` compliant can transfer their ownership to a Governance contract. This enables such contracts to become compatible with `ERC-2767` Governance. - -However, there are some existing projects with governance implementations and most of them have custom APIs ([Compound Governance](https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol#L27), [Uniswap Governance](https://github.com/Uniswap/governance/blob/master/contracts/GovernorAlpha.sol#L27) and [Sushiswap Governance](https://github.com/sushiswap/sushiswap/blob/master/contracts/GovernorAlpha.sol#L45)), since a standard did not exist. Not having an `ERC-2767` compatible governance contract means only that general tools might not be able to populate their governance information without including some special code for the project. - -For existing governance contracts to get compatible with `ERC-2767`: - -1. Projects can deploy a new governance contract and transfer ownership to it to be `ERC-2767` compatible. This is suitable for those who use Multi-sig wallets for Governance. -2. It is understood that redeploying governance contracts would be a troublesome task, and contracts who already have functionality similar to `ERC-20` based (weighted votes) have a bit advanced way to avoid it. Basically, they can create a forwarder contract implements `ERC-2767` and forwards all calls to the actual non-standard methods. Projects can list the forwarder contract to display the information project's governance info without requiring any custom code in analysys tool, but this might have certain limitations depending on the project's existing governance implementation. Specification of forwarder contract is out of scope for this EIP and it may be addressed in another EIP if required. - - - -## Implementation - -The reference implementations are available in this [repository](https://github.com/zemse/contract-ownership-governance). Publicly audited implementations will be included in future. - -## Security Considerations - -Implementers are free to choose between On-chain and Off-chain consensus. Exact specification is out of scope for this standard (open for other EIPs to standardize). However, this section mentions points that implementers can consider. - -#### On-chain - -In such implementations, community can create transaction proposals and vote on it by sending on-chain transactions. - -- OpenZeppelin Snapshots can be used to prevent double voting. - -#### Off-chain - -- The signatures in off-chain governance implementation can follow recommendations of `ERC-191` or `ERC-712`. -- To prevent replaying signatures, it'd be best if executer is required to sort the signatures based on increasing addresses. - -## 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-2767.md diff --git a/EIPS/eip-2770.md b/EIPS/eip-2770.md index c8ba49abf93df8..85c594e1ec4b01 100644 --- a/EIPS/eip-2770.md +++ b/EIPS/eip-2770.md @@ -1,207 +1,7 @@ --- eip: 2770 -title: Meta-Transactions Forwarder Contract -author: Alex Forshtat (@forshtat), Dror Tirosh (@drortirosh) -discussions-to: https://ethereum-magicians.org/t/erc-2770-meta-transactions-forwarder-contract/5391 -status: Draft -type: Standards Track category: ERC -created: 2020-07-01 -requires: 712, 2771 +status: Moved --- -## Simple Summary -Standardized contract interface for extensible meta-transaction forwarding. - -## Abstract - -This proposal defines an external API of an extensible Forwarder whose responsibility is to validate transaction -signatures on-chain and expose the signer to the destination contract, that is expected to accommodate all use-cases. -The ERC-712 structure of the forwarding request can be extended allowing wallets to display readable data even -for types not known during the Forwarder contract deployment. - -## Motivation - -There is a growing interest in making it possible for Ethereum contracts to -accept calls from externally owned accounts that do not have ETH to pay for -gas. - -This can be accomplished with meta-transactions, which are transactions that have been signed as plain data by one -externally owned account first and then wrapped into an Ethereum transaction by a different account. - -`msg.sender` is a transaction parameter that can be inspected by a contract to -determine who signed the transaction. The integrity of this parameter is -guaranteed by the Ethereum EVM, but for a meta-transaction verifying -`msg.sender` is insufficient, and signer address must be recovered as well. - -The Forwarder contract described here allows multiple Gas Relays and Relay Recipient contracts to rely -on a single instance of the signature verifying code, improving reliability and security -of any participating meta-transaction framework, as well as avoiding on-chain code duplication. - -## Specification -The Forwarder contract operates by accepting a signed typed data together with it's ERC-712 signature, -performing signature verification of incoming data, appending the signer address to the data field and -performing a call to the target. - -### Forwarder data type registration -Request struct MUST contain the following fields in this exact order: -``` -struct ForwardRequest { - address from; - address to; - uint256 value; - uint256 gas; - uint256 nonce; - bytes data; - uint256 validUntil; -} -``` -`from` - an externally-owned account making the request \ -`to` - a destination address, normally a smart-contract\ -`value` - an amount of Ether to transfer to the destination\ -`gas` - an amount of gas limit to set for the execution\ -`nonce` - an on-chain tracked nonce of a transaction\ -`data` - the data to be sent to the destination\ -`validUntil` - the highest block number the request can be forwarded in, or 0 if request validity is not time-limited - -The request struct MAY include any other fields, including nested structs, if necessary. -In order for the Forwarder to be able to enforce the names of the fields of this struct, only registered types are allowed. - -Registration MUST be performed in advance by a call to the following method: -``` -function registerRequestType(string typeName, string typeSuffix) -``` -`typeName` - a name of a type being registered\ -`typeSuffix` - an ERC-712 compatible description of a type - -For example, after calling -``` -registerRequestType("ExtendedRequest", "uint256 x,bytes z,ExtraData extraData)ExtraData(uint256 a,uint256 b,uint256 c)") -``` -the following ERC-712 type will be registered with forwarder: -``` -/* primary type */ -struct ExtendedRequest { - address from; - address to; - uint256 value; - uint256 gas; - uint256 nonce; - bytes data; - uint256 validUntil; - uint256 x; - bytes z; - ExtraData extraData; -} - -/* subtype */ -struct ExtraData { - uint256 a; - uint256 b; - uint256 c; -} -``` - -### Signature verification - -The following method performs an ERC-712 signature check on a request: -``` -function verify( - ForwardRequest forwardRequest, - bytes32 domainSeparator, - bytes32 requestTypeHash, - bytes suffixData, - bytes signature -) view; -``` -`forwardRequest` - an instance of the `ForwardRequest` struct -`domainSeparator` - caller-provided domain separator to prevent signature reuse across dapps (refer to ERC-712) -`requestTypeHash` - hash of the registered relay request type -`suffixData` - RLP-encoding of the remainder of the request struct -`signature` - an ERC-712 signature on the concatenation of `forwardRequest` and `suffixData` - -### Command execution - -In order for the Forwarder to perform an operation, the following method is to be called: -``` -function execute( - ForwardRequest forwardRequest, - bytes32 domainSeparator, - bytes32 requestTypeHash, - bytes suffixData, - bytes signature -) -public -payable -returns ( - bool success, - bytes memory ret -) -``` - -Performs the ‘verify’ internally and if it succeeds performs the following call: -``` -bytes memory data = abi.encodePacked(forwardRequest.data, forwardRequest.from); -... -(success, ret) = forwardRequest.to.call{gas: forwardRequest.gas, value: forwardRequest.value}(data); -``` -Regardless of whether the inner call succeeds or reverts, the nonce is incremented, invalidating the signature and preventing a replay of the request. - -Note that `gas` parameter behaves according to EVM rules, specifically EIP-150. The forwarder validates internally that -there is enough gas for the inner call. In case the `forwardRequest` specifies non-zero value, extra `40000 gas` is -reserved in case inner call reverts or there is a remaining Ether so there is a need to transfer value from the `Forwarder`: -```solidity -uint gasForTransfer = 0; -if ( req.value != 0 ) { - gasForTransfer = 40000; // buffer in case we need to move Ether after the transaction. -} -... -require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas"); -``` -In case there is not enough `value` in the Forwarder the execution of the inner call fails.\ -Be aware that if the inner call ends up transferring Ether to the `Forwarder` in a call that did not originally have `value`, this -Ether will remain inside `Forwarder` after the transaction is complete. - -### ERC-712 and 'suffixData' parameter -`suffixData` field must provide a valid 'tail' of an ERC-712 typed data. -For instance, in order to sign on the `ExtendedRequest` struct, the data will be a concatenation of the following chunks: -* `forwardRequest` fields will be RLP-encoded as-is, and variable-length `data` field will be hashed -* `uint256 x` will be appended entirely as-is -* `bytes z` will be hashed first -* `ExtraData extraData` will be hashed as a typed data - -So a valid `suffixData` is calculated as following: -``` -function calculateSuffixData(ExtendedRequest request) internal pure returns (bytes) { - return abi.encode(request.x, keccak256(request.z), hashExtraData(request.extraData)); -} - -function hashExtraData(ExtraData extraData) internal pure returns (bytes32) { - return keccak256(abi.encode( - keccak256("ExtraData(uint256 a,uint256 b,uint256 c)"), - extraData.a, - extraData.b, - extraData.c - )); -} -``` - -### Accepting Forwarded calls -In order to support calls performed via the Forwarder, the Recipient contract must read the signer address from the -last 20 bytes of `msg.data`, as described in ERC-2771. - -## Rationale -Further relying on `msg.sender` to authenticate end users by their externally-owned accounts is taking the Ethereum dapp ecosystem to a dead end. - -A need for users to own Ether before they can interact with any contract has made a huge portion of use-cases for smart contracts non-viable, -which in turn limits the mass adoption and enforces this vicious cycle. - -`validUntil` field uses a block number instead of timestamp in order to allow for better precision and integration -with other common block-based timers. - -## Security Considerations -All contracts introducing support for the Forwarded requests thereby authorize this contract to perform any operation under any account. -It is critical that this contract has no vulnerabilities or centralization issues. - -## 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-2770.md diff --git a/EIPS/eip-2771.md b/EIPS/eip-2771.md index 0ea7c33f9fe18f..4d87023ef42f2b 100644 --- a/EIPS/eip-2771.md +++ b/EIPS/eip-2771.md @@ -1,211 +1,7 @@ --- eip: 2771 -title: Secure Protocol for Native Meta Transactions -author: Ronan Sandford (@wighawag), Liraz Siri (@lirazsiri), Dror Tirosh (@drortirosh), Yoav Weiss (@yoavw), Alex Forshtat (@forshtat), Hadrien Croubois (@Amxx), Sachin Tomar (@tomarsachin2271), Patrick McCorry (@stonecoldpat), Nicolas Venturo (@nventuro), Fabian Vogelsteller (@frozeman) -discussions-to: https://ethereum-magicians.org/t/erc-2771-secure-protocol-for-native-meta-transactions/4488 -status: Draft -type: Standards Track category: ERC -created: 2020-07-01 +status: Moved --- -## Simple Summary - -A contract interface for receiving meta transactions through a trusted -forwarder. - -## Abstract - -This ERC defines a minimal contract-level protocol that a compliant Recipient -contract needs to support in order to be capable of accepting a meta -transaction through a compliant Forwarder contract that it trusts to help it -identify the address of the Transaction Signer. - -No EVM-level protocol changes are proposed or required. - -## Motivation - -There is a growing interest in making it possible for Ethereum contracts to -accept calls from externally owned accounts that do not have ETH to pay for -gas. - -This can be accomplished with meta transactions, which are transactions that -have been: - -1. Authorized by the **Transaction Signer**. For example, signed by an - externally owned account. -2. Relayed by an untrusted third party that pays for the gas (the **Gas - Relay**) - -`msg.sender` is a transaction parameter that can be inspected by a contract to -determine who signed the transaction. The integrity of this parameter is -guaranteed by the Ethereum EVM, but for a meta transaction securing -`msg.sender` is insufficient. - -The problem is that for a contract that is not natively aware of meta -transactions, the `msg.sender` of the transaction will make it appear to be -coming from the **Gas Relay** and not the **Transaction Signer**. A secure -protocol for a contract to accept meta transactions needs to prevent the **Gas -Relay** from forging, modifying or duplicating requests by the **Transaction -Signer**. - -## Specification - -The keywords "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)). - -Here is an example flow: - -![Example flow](../assets/eip-2771/example-flow.png) - - -* **Transaction Signer** - entity that signs & sends to request to **Gas - Relay** -* **Gas Relay** - receives a signed request off-chain from **Transaction - Signer** and pays gas to turn it into a valid transaction that goes through -**Trusted Forwarder** -* **Trusted Forwarder** - a contract that is trusted by the `Recipient` to - correctly verify the signature and nonce before forwarding the request from -**Transaction Signer** -* **Recipient** - a contract that can securely accept meta-transactions - through a **Trusted Forwarder** by being compliant with this standard. - -### Extracting The Transaction Signer address - -The **Trusted Forwarder** is responsible for calling the **Recipient** contract -and MUST append the address of the **Transaction Signer** (20 bytes of data) to -the end of the call data. - -For example : - -```solidity -(bool success, bytes memory returnData) = to.call.value(value)(abi.encodePacked(data, from)); -``` - -The **Recipient** contract can then extract the **Transaction Signer** address -by performing 3 operations: - -1. Check that the **Forwarder** is trusted. How this is implemented is out of - the scope of this proposal. -2. Extract the **Transaction Signer** address from the last 20 bytes of the - call data and use that as the original `sender` of the transaction (instead of `msg.sender`) -3. If the `msg.sender` is not a trusted forwarder (or if the msg.data is - shorter than 20 bytes), then return the original `msg.sender` as it is. - -The **Recipient** MUST check that it trusts the Forwarder to prevent it from -extracting address data appended from an untrusted contract. This could result -in a forged address. - -### Protocol Support Discovery Mechanism - -Unless a **Recipient** contract is being used by a particular frontend that -knows that this contract has support for native meta transactions, it would not -be possible to offer the user the choice of using meta-transaction to interact -with the contract. We thus need a mechanism by which the **Recipient** can let -the world know that it supports meta transactions. - -This is especially important for meta transactions to be supported at the Web3 -wallet level. Such wallets may not necessarily know anything about the -**Recipient** contract users may wish to interact with. - -As a **Recipient** could trust forwarders with different interfaces and -capabilities (e.g., transaction batching, different message signing formats), -we need to allow wallets to discover which Forwarder is trusted. - -To provide this discovery mechanism a **Recipient** contract MUST implement -this function: - -```solidity -function isTrustedForwarder(address forwarder) external returns(bool); -``` - -* That function MUST return true if the forwarder is trusted by the - Recipient. -* That function MUST return false if the forwarder is not trusted. -* That function MUST NOT throw a revert. - -Internally, the **Recipient** MUST then accept a request from forwarder - -That function can be called on-chain and as such gas restriction needs to be -put in place. - -A Gas limit of 50k is enough for making the decision either inside the -contract, or delegating it to another contract and doing some memory access -calculations, like querying a mapping. - -### Recipient example - -```solidity -contract RecipientExample { - - function purchaseItem(uint256 itemId) external { - address sender = _msgSender(); - ... perform the purchase for sender - } - - address immutable _trustedForwarder; - constructor(address trustedForwarder) internal { - _trustedForwarder = trustedForwarder; - } - - function isTrustedForwarder(address forwarder) public returns(bool) { - return forwarder == _trustedForwarder; - } - - function _msgSender() internal view returns (address payable signer) { - signer = msg.sender; - if (msg.data.length>=20 && isTrustedForwarder(signer)) { - assembly { - signer := shr(96,calldataload(sub(calldatasize(),20))) - } - } - } - -} -``` - -## Rationale - -* Make it easy for contract developers to add support for meta - transactions by standardizing the simplest viable contract interface. - -* Without support for meta transactions in the recipient contract, an externally owned - account can not use meta transactions to interact with the recipient contract. - -* Without a standard contract interface, there is no standard way for a client - to discover whether a recipient supports meta transactions. - -* Without a standard contract interface, there is no standard way to send a - meta transaction to a recipient. - -* Without the ability to leverage a trusted forwarder every recipient contract - has to internally implement the logic required to accept meta transactions securely. - -* Without a discovery protocol, there is no mechanism for a client to discover - whether a recipient supports a specific forwarder. - -* Making the contract interface agnostic to the internal implementation - details of the trusted forwarder, makes it possible for a recipient contract - to support multiple forwarders with no change to code. - -## Security Considerations - -A bad forwarder may allow forgery of the `msg.sender` returned from -`_msgSender()` and allow transactions to appear to be coming from any address. - -This means a recipient contract should be very careful which forwarder it -trusts and whether this can be modified. The power to change the forwarder -trusted by a recipient is equivalent to giving full control over the contract. -If this kind of control over the recipient is acceptable, it is recommended -that only the owner of the recipient contract be able to modify which forwarder -is trusted. Otherwise best to leave it unmodifiable, as in the example above. - -## Implementations - -An implementation of a base class for a recipient: [BaseRelayRecipient.sol](https://github.com/opengsn/forwarder/blob/master/contracts/BaseRelayRecipient.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-2771.md diff --git a/EIPS/eip-2780.md b/EIPS/eip-2780.md index e1b2c65ba0c348..175d1e541c90cf 100644 --- a/EIPS/eip-2780.md +++ b/EIPS/eip-2780.md @@ -42,7 +42,7 @@ not by imposing artificial restrictions to encourage it. Reducing the intrinsic cost of a transaction from `21,000` to `7,000` gas will make sending transactions cheaper, is easily achievable, and does not incur technical debt. -However, such a change should only be made after it is determined that it does not impose non-negligble externalities, specifically: +However, such a change should only be made after it is determined that it does not impose non-negligible externalities, specifically: * Increases uncle-rate. @@ -113,4 +113,4 @@ The table below captures the effect of this proposal on the savings multiplier i ## 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-2786.md b/EIPS/eip-2786.md index f192d335bef354..2c8d944931ee6c 100644 --- a/EIPS/eip-2786.md +++ b/EIPS/eip-2786.md @@ -4,7 +4,6 @@ title: Ethereum Provider Connect/Disconnect Events author: Micah Zoltu (@MicahZoltu), Erik Marks (@rekmarks) discussions-to: https://github.com/ethereum/EIPs/issues/2787 status: Withdrawn -review-period-end: 2020-07-31 type: Standards Track category: Interface created: 2020-07-15 @@ -59,7 +58,7 @@ The relationship between Ethereum Provider and client is a trusted one, where 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). ## Appendix I: Examples diff --git a/EIPS/eip-2803.md b/EIPS/eip-2803.md index 0f1dc7ccbd1704..4804c8d5aefb0a 100644 --- a/EIPS/eip-2803.md +++ b/EIPS/eip-2803.md @@ -1,26 +1,24 @@ --- 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-07-18 --- -## Simple Summary -Support 'rich transactions' by allowing transactions from externally owned accounts to execute bytecode directly. - ## Abstract -If a transaction has a `to` of address `x`, then the `data` of the transaction will be treated as EVM bytecode and executed from the context of the `CALLER` of the transaction (aka: the transaction signer at the moment). +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. We propose this EIP as a way of enhancing the utility of existing EOAs, in the spirit of "don't let the perfect be the enemy of the good". +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: @@ -30,10 +28,10 @@ A new reserved address is specified at `x`, in the range used for precompiles. W - `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 do not return the transaction payload. + - 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 transfers the balance of the EOA to the specified address, and at the end of the transaction zeroes out the account's state storage, but does not zero the account's nonce. No refund is applied for the `SELFDESTRUCT` at the end of the transaction. + - 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. @@ -48,11 +46,5 @@ This EIP introduces a new feature that will need to be implemented in a future h 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. -## Test Cases -TBD. - -## Implementation -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-2831.md b/EIPS/eip-2831.md index 04208503a94f81..3a07fba8b28848 100644 --- a/EIPS/eip-2831.md +++ b/EIPS/eip-2831.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-07-26 @@ -126,7 +126,7 @@ None at the current time. ## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). ## Appendix I: Examples diff --git a/EIPS/eip-2844.md b/EIPS/eip-2844.md index 9edc9c64eed582..6546ba3f79bc65 100644 --- a/EIPS/eip-2844.md +++ b/EIPS/eip-2844.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-08-01 @@ -129,4 +129,4 @@ Both JOSE and DIDs are standards that have gone though a lot of scrutiny. Their 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2848.md b/EIPS/eip-2848.md index a71b4fc14116c0..e1bf77a5c8cf0e 100644 --- a/EIPS/eip-2848.md +++ b/EIPS/eip-2848.md @@ -1,195 +1,7 @@ --- eip: 2848 -title: My Own Messages (MOM) -author: Giuseppe Bertone (@Neurone) -discussions-to: https://github.com/InternetOfPeers/EIPs/issues/1 -status: Draft -type: Standards Track category: ERC -created: 2020-08-02 +status: Moved --- -## Simple Summary - -My Own Messages (MOM) is a standard to create your very own public, always updated, unstoppable, verifiable, message board. - -## Abstract - -My Own Messages (MOM) use Ethereum as a certification layer for commands and multihash of your messages. It don't use smart contracts but simple self-send transactions with specific payload attached. - -## Motivation - -_Note: contents are all here but I'm trying to improve this section to be clearer_ - -As a _developer_ or _pool's owner_, I'd like to send messages to my users in a decentralized way. They must be able to easily verify my role in the smart contract context (owner, user, and so on) and they must be able to do it without relying on external, insecure and hackable social media sites (Facebook, Twitter, you name it). Also, I'd like to read messages from my userbase, in the same secure and verifiable manner. - -As a _user_, I want a method to easily share my thoughts and idea, publish content, send messages, receive feedback, receive tips, and so on, without dealing with any complexity: just write a message, send it and it's done. Also, I want to write to some smart contract's owner or to the sender of some transaction. - -As an _explorer service_, I want to give my users an effective way to read information by smart contract owners and a place to share ideas and information without using third party services (i.e. Etherscan uses Disqus, and so on) - -And in _any role_, I want a method that does not allow scams - transactions without values, no smart contract's address to remember or to fake - and it does not allow spam - it's cheap but not free, and even if you can link/refer other accounts, you cannot send them messages directly, and others must explicitly follow and listen to your transactions if they want to read your messages. - -Main advantages: -- You can send messages to users of your ÐApp or Smart Contract, and they always know it is a voice reliable as the smart contract is. -- Create your Ethereum account dedicated to your personal messages, say something only once and it can be seen on every social platform (no more reply of the same post/opinion on dozens of sites like Reddit, Twitter, Facebook, Medium, Disqus, and so on...) -- Small fee to be free: pay just few cents of dollar to notarize your messages, and distribute them with IPFS, Swarm or any other storage you prefer. Because the multihash of the content is notarized, you can always check the integrity of the message you download even from centralized storage services. -- Finally, you can ask and get tips for your words directly into your wallet. - -I know, My Own Messages (MOM) sounds like _mom_. And yes, pun intended :) - -## 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) when, and only when, they appear in all capitals as shown here. - -Clients following MOM standard **MUST** allow users to send and to read MOM transaction, creating an _updated message list_ for each address the users are interested in. - -Reading MOM transactions, MOM clients **MUST** be able to show the current and updated message list, and they **SHOULD** be able to show also all the message history if users ask for it. - -Apart from message list, MOM clients **SHOULD** be able to download the content of the messages and to show them to the user. - -Clients **SHOULD** allow users to choose and set the source to download content from, and they **SHOULD** be able to use common Content Addressable Networks - i.e. IPFS or Swarm - or HTTP servers. If content is downloaded from HTTP servers, clients **MUST** check the content against the declared multihash. - -As the default setting, clients **MUST** consider `text/markdown` ([RFC 7763](https://www.ietf.org/rfc/rfc7763.txt)) as the media type of the content represented by a multihash, and in particular [Markdown](https://en.wikipedia.org/wiki/Markdown) text in [UTF-8](https://en.wikipedia.org/wiki/UTF-8) without [BOM](https://en.wikipedia.org/wiki/Byte_order_mark). - -Clients **MAY** let users choose to parse messages considering other content types. In this case they **SHOULD** cast a warning to users stating that a content type other than `text/markdown` is used while processing messages. - -It's **RECOMMENDED** that clients inform users about the actual setting of the default content type. - -### MOM transactions -Clients **MUST** assume that **invalid MOM transactions don't exist**. If a transaction does not strictly follow the MOM standard, clients **MUST** ignore it and they **MUST NOT** consider it a MOM transaction at all. - -Because there can be security implications parsing data sent by users, clients **SHOULD NOT** try to keep track or interpret transactions as _invalid_ MOM transactions. - -#### Valid MOM transaction's data structure - -| ATTRIBUTE | VALUE | -|:--------|:------------| -| `to` | **MUST** be the same account signing the transaction. | -| `value` | **MUST** be `0` wei. | -| `data` | **MUST** be at least `2` bytes. The first byte **MUST** be operational code and following bytes **MUST** be based on the operational codes listed below. | - -#### List of supported operations and messages - -Each operational code has one or more parameters, and all parameters **MUST** be considered mandatory. - -Optional parameters don't exist: if parameters for the specific operational code are not all present or they don't follow the rules, clients **MUST** ignore the transaction completely. - -Messages **MUST** be always referenced with the multihash of their content. - -Operations are divided into two sets: **CORE** and **EXTENDED** operations. - -- Clients **MUST** support all core operations and they **SHOULD** support as much extended operations as possible. -- Clients **SHOULD** support and implement as much extended operations as possible, but they **MAY** choose to implement only some specific extended operations they are interested in. - -#### Core operations - -| OPERATION | CODE | PARAMETERS | MEANING | EFFECT | -|-----------|:--------:|------------|---------|--------| -| ADD | `0x00` | multihash | Add a message. The parameter **MUST** be the multihash of the message. | Clients **MUST** add the message to the message list of the sender. | -| UPDATE | `0x01` | multihash, multihash | Update a message. The first parameter **MUST** be the multihash of the message to be updated. The second parameter **MUST** be the multihash of the updated message. | Clients **MUST** update the message list to show the updated message. | -| REPLY | `0x02` | multihash, multihash | Reply to a message. The first parameter **MUST** be the multihash of the message to reply to. The second parameter **MUST** the multihash of the message. | Clients **MUST** insert a new message in the message list and they **MUST** preserve the relationship with the referenced message. | -| DELETE | `0x03` | multihash | Delete a message. The parameter **MUST** be the multihash of the message to delete. | Clients **MUST** remove the message from the message list. | -| CLOSE ACCOUNT | `0xFD` | multihash | Close an account. The parameter **MUST** be the multihash of the message with the motivations for closing the account. | Clients **MUST** add the message with motivations to the message list and they **MUST NOT** consider MOM messages sent by that address to be valid anymore, ever. In other words, MOM clients **MUST** ignore any other transaction sent by that address while creating the message list. This is useful when users want to change account, for example because the private key seems compromised. | -| RAW | `0xFF` | any | The parameter **MUST** be at least `1` byte. Content type is not disclosed and it **MUST NOT** be considered as `text/markdown`. | Clients **MUST** add the message to the message list but they **MUST NOT** try to decode the content. Clients **SHOULD** allow users to see this message only if explicitly asked for. This operation can be used for _blind_ notarization that general client can ignore. | - -#### Note about `DELETE` operational code - -Please note that sending a `DELETE` command users are not asking to actually delete anything from the blockchain, they are just asking clients to hide that specific message because it's not valid anymore for some reasons. You can think of it like if users say: _I changed my mind so please ÐApps don't show this anymore_. As already stated in the specifications above, clients **MUST** follow this request by the author, unless expressly asked otherwise by the user. - -Please also note that, because it's usually up to the author of a message to be sure the content is available to everyone, if a `DELETE` message was sent it's very likely the content referenced by the multihash isn't available anymore, simply because probably it's not shared by anyone. - -#### Extended operations - -| OPERATION | CODE | PARAMETERS | MEANING | EFFECT | -|-----------|:--------:|------------|---------|--------| -| ADD & REFER | `0x04` | multihash, address | Add a message and refer an account. The first parameter **MUST** be the multihash of the message. The second parameter **MUST** be an address referenced by the message. | Clients **MUST** add the message to the message list and they **MUST** track the reference to the specified account. This can be useful _to invite_ the owner of the referenced account to read this specific message. | -| UPDATE & REFER | `0x05` | multihash, multihash, address | Update a message. The first parameter **MUST** be the multihash of the message to be updated. The second parameter **MUST** be the multihash of the updated message. The third parameter **MUST** be an address referenced by the message.| Clients **MUST** update the message list to show the updated message and they **MUST** track the reference to the specified account. This can be useful _to invite_ the owner of the referenced account to read this specific message. | -| ENDORSE | `0x06` | multihash | Endorse a message identified by the specified multihash. The parameter **MUST** be the multihash of the message to be endorsed. | Clients **MUST** record and track the endorsement for that specific message. Think it as a _like_, a _retwitt_, etc. | -| REMOVE ENDORSEMENT | `0x07` | multihash | Remove endorsement to the message identified by the specified multihash. The parameter **MUST** be the multihash of the message. | Clients **MUST** remove the endorsement for that specific message. | -| DISAPPROVE | `0x08` | multihash | Disapprove a message identified by the specified multihash. The parameter **MUST** be the multihash of the message to disapprove. | Clients **MUST** record and track the disapproval for that specific message. Think it as a _I don't like it_. | -| REMOVE DISAPPROVAL | `0x09` | multihash | Remove disapproval of a message identified by the specified multihash. The parameter **MUST** be the multihash of the message. | Clients **MUST** remove the disapproval for that specific message. | -| ENDORSE & REPLY | `0x0A` | multihash, multihash | Endorse a message and reply to it. The first parameter **MUST** be the multihash of the message to reply to. The second parameter **MUST** be the multihash of the message. | Clients **MUST** insert a new message in the message list and they **MUST** preserve the relationship with the referenced message. Clients **MUST** also record and track the endorsement for that specific message. | -| DISAPPROVE & REPLY | `0x0B` | multihash, multihash | Disapprove a message and reply to it. The first parameter **MUST** be the multihash of the message to reply to. The second parameter **MUST** be the multihash of the message. | Clients **MUST** insert a new message in the message list and they **MUST** preserve the relationship with the referenced message. Clients **MUST** also record and track the disapproval for that specific message. | - -## Rationale - -Ethereum is _account based_, so it's good to be identified as a single source of information. - -It is also able of doing notarization very well and to impose some restrictions on transaction's structure, so it's good for commands. - -IPFS, Swarm or other CANs (Content Addressable Networks) or storage methods are good to store a lot of information. So, the union of both worlds it's a good solution to achieve the objectives of this message standard. - -The objective is also to avoid in the first place any kind of scam and malicious behaviors, so MOM don't allow to send transactions to other accounts and the value of a MOM transaction is always 0. - -### Why not using a smart contract? - -MOM wants to be useful, easy to implement and read, error proof, fast and cheap, but: -- using a smart contract for messages can leads more easily to errors and misunderstandings: - - address of the contract can be wrong - - smart contract must be deployed on that specific network to send messages -- executing a smart contract costs much more than sending transactions -- executing a smart contract just to store static data is the best example of an anti-pattern (expensive and almost useless) - -Without a specific smart contract to rely on, the MOM standard can be implemented and used right now in any existing networks, and even in future ones. - -Finally, if you can achieve exactly the same result without a smart contract, you didn't need a smart contract at the first place. - -### Why not storing messages directly on-chain? - -There's no benefit to store _static_ messages on-chain, if they are not related to some smart contract's state or if they don't represent exchange of value. The cost of storing data on-chain is also very high. - -### Why not storing op codes inside the message? - -While cost effectiveness is a very important feature in a blockchain related standard, there's also a compromise to reach with usability and usefulness. - -Storing commands inside the messages forces the client to actually download messages to understand what to do with them. This is very inefficient, bandwidth and time consuming. - -Being able to see the commands before downloading the content, it allows the client to recreate the history of all messages and then, at the end, download only updated messages. - -Creating a structure for the content of the messages leads to many issues and considerations in parsing the content, if it's correct, misspelled, and so on. - -Finally, the **content must remain clean**. You really want to notarize the content and not to refer to a data structure, because this can lead to possible false-negative when checking if a content is the same of another. - -### Why multihash? - -[Multihash](https://github.com/multiformats/multihash) is flexible, future-proof and there are already tons of library supporting it. Ethereum must be easily integrable with many different platforms and architectures, so MOM standard follows that idea. - -## Backwards Compatibility - -You can already find few transactions over the Ethereum network that use a pattern similar to this EIP. Sometimes it's done to invalidate a previous transaction in memory pool, using the same nonce but with more gas price, so that transaction is mined cancelling the previous one still in the memory pool. This kind of transactions can be easily ignored if created before the approval of this EIP or just checking if the payload follows the correct syntax. - -## Test Cases - -A MOM-compliant client can be found and tested on [GitHub](https://github.com/InternetOfPeers/mom-client). - -You can use the latest version of MOM client directly via [GitHub Pages](https://internetofpeers.github.io/mom-client) or via IPFS (see the [client repo](https://github.com/InternetOfPeers/mom-client) for the latest updated address). - -## Implementation - -You can use an already working MOM JavaScript package on [GitHub Packages](https://github.com/InternetOfPeers/mom-js/packages/323930) or [npmjs](https://www.npmjs.com/package/@internetofpeers/mom-js). The package is already used by the MOM client above, and you can use it in your ÐApps too with: -``` -npm install @internetofpeers/mom-js -``` - -Transaction [`0x8e49485c56897757a6f2707b92cd5dad06126afed92261b9fe1a19b110bc34e6`](https://etherscan.io/tx/0x8e49485c56897757a6f2707b92cd5dad06126afed92261b9fe1a19b110bc34e6) is an example of a valid MOM transaction already mined on the Main net; it's an `ADD` message. - -## Security Considerations - -MOM is very simple and it has no real security concerns by itself. The standard already considers valid only transactions with `0` value and where `from` and `to` addresses are equals. - -The only concerns can come from the payload, but it is more related to the client and not to the standard itself, so here you can find some security suggestions related to clients implementing the standard. - -### Parsing commands -MOM standard involves parsing payloads generated by potentially malicious clients, so attention must be made to avoid unwanted code execution. - -- Strictly follow only the standard codes -- Don't execute any commands outside of the standard ones, unless expressly acknowledged by the user -- Ignore malformed transactions (transactions that don't strictly follow the rules) - -### Messages -Default content-type of a message following the MOM standard is Markdown text in UTF8 without BOM. It is highly recommended to disallow the reading of any not-text content-type, unless expressly acknowledged by the user. - -Because content multihash is always stored into the chain, clients can download that content from Content Addressable Network (like IPFS or Swarm) or from central servers. In the latter case, a client should always check the integrity of the received messages, or it must warn the user if it cannot do that (feature not implemented or in error). - -## 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-2848.md diff --git a/EIPS/eip-2876.md b/EIPS/eip-2876.md index 3db042e096ed9a..0edca2a8be05ce 100644 --- a/EIPS/eip-2876.md +++ b/EIPS/eip-2876.md @@ -1,184 +1,7 @@ --- eip: 2876 -title: Deposit contract and address standard -author: Jonathan Underwood (@junderw) -discussions-to: https://github.com/junderw/deposit-contract-poc/issues/1 -status: Draft -type: Standards Track category: ERC -created: 2020-08-13 +status: Moved --- -## Simple Summary -This ERC defines a simple contract interface for managing deposits. It also defines a new address format that encodes the extra data passed into the interface's main deposit function. - -## Abstract -An ERC-2876 compatible **deposit system** can accept ETH payments from multiple depositors without the need for managing multiple keys or requiring use of a hot wallet. - -An ERC-2876 compatible **wallet application** can send ETH to ERC-2876 compatible **deposit systems** in a way that the **deposit system** can differentiate their payment using the 8 byte id specified in this standard. - -Adoption of ERC-2876 by all exchanges (as a deposit system and as a wallet for their withdrawal systems), merchants, and all wallet applications/libraries will likely decrease total network gas usage by these systems, since two value transactions cost 42000 gas while a simple ETH forwarding contract will cost closer to 30000 gas depending on the underlying implementation. - -This also has the benefit for deposit system administrators of allowing for all deposits to be forwarded to a cold wallet directly without any manual operations to gather deposits from multiple external accounts. - -## Motivation -Centralized exchanges and merchants (Below: "apps") require an address format for accepting deposits. Currently the address format used refers to an account (external or contract), but this creates a problem. It requires that apps create a new account for every invoice / user. If the account is external, that means the app must have the deposit addresses be hot wallets, or have increased workload for cold wallet operators (as each deposit account will create 1 value tx to sweep). If the account is contract, generating an account costs at least 60k gas for a simple proxy, which is cost-prohibitive. - -Therefore, merchant and centralized exchange apps are forced between taking on one of the following: - -- Large security risk (deposit accounts are hot wallets) -- Large manual labor cost (cold account manager spends time sweeping thousands of cold accounts) -- Large service cost (deploying a contract-per-deposit-address model). - -The timing of this proposal is within the context of increased network gas prices. During times like this, more and more services who enter the space are being forced into hot wallets for deposits, which is a large security risk. - -The motivation for this proposal is to lower the cost of deploying and managing a system that accepts deposits from many users, and by standardizing the methodology for this, services across the world can easily use this interface to send value to and from each other without the need to create multiple accounts. - -## Specification - -### Definitions -- 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. -- `The contract interface` is the contract component of this ERC. -- `The deposit address format` is the newly made format described in "Deposit Address Format" for encoding the 20 byte account address and the 8 byte id. -- `The contract` refers to the contract that implements `the contract interface` of this ERC. -- `The 8 byte "id"` is an 8 byte id used as the input parameter for the contract interface. -- `The 5 byte "nonce"` is the first 5 most significant bytes of the `"id"`. -- `The 3 byte "checksum"` is the last 3 least significant bytes of the `"id"` -- `deposit(bytes8)` refers to the function of that signature, which is defined in `the contract interface`. -- `The parent application` refers to the application that will use the information gained within the `deposit(bytes8)` function. (ie. an exchange backend or a non-custodial merchant application) -- `The depositor` refers to the person that will send value to `the contract` via the `deposit(bytes8)` call. -- `The wallet` refers to any application or library that sends value transactions upon the request of `the depositor`. (ie. MyEtherWallet, Ledger, blockchain.com, various libraries) - -### Deposit Address Format - -In order to add the 8 byte "id" data, we need to encode it along with the 20 byte -account address. The 8 bytes are appended to the 20 byte address. - -A 3 byte checksum is included in the id, which is the first 3 bytes of the keccak256 -hash of the 20 byte address and first 5 byte nonce of the id concatenated (25 bytes). - -The Deposit Address format can be generated with the following JavaScript code: - -```js -/** - * Converts a 20 byte account address and a 5 byte nonce to a deposit address. - * The format of the return value is 28 bytes as follows. The + operator is byte - * concatenation. - * (baseAddress + nonce + keccak256(baseAddress + nonce)[:3]) - * - * @param {String} baseAddress the given HEX address (20 byte hex string with 0x prepended) - * @param {String} nonce the given HEX nonce (5 byte hex string with 0x prepended) - * @return {String} - */ -function generateAddress (baseAddress, nonce) { - if ( - !baseAddress.match(/^0x[0-9a-fA-F]{40}$/) || - !nonce.match(/^0x[0-9a-fA-F]{10}$/) - ) { - throw new Error('Base Address and nonce must be 0x hex strings'); - } - const ret = - baseAddress.toLowerCase() + nonce.toLowerCase().replace(/^0x/, ''); - const myHash = web3.utils.keccak256(ret); - return ret + myHash.slice(2, 8); // first 3 bytes from the 0x hex string -}; -``` - -The checksum can be verified within the deposit contract itself using the following: - -```solidity -function checksumMatch(bytes8 id) internal view returns (bool) { - bytes32 chkhash = keccak256( - abi.encodePacked(address(this), bytes5(id)) - ); - bytes3 chkh = bytes3(chkhash); - bytes3 chki = bytes3(bytes8(uint64(id) << 40)); - return chkh == chki; -} -``` - -### The Contract Interface - -A contract that follows this ERC: - -- `The contract` MUST revert if sent a transaction where `msg.data` is null (A pure value transaction). -- `The contract` MUST have a deposit function as follows: - -```solidity -interface DepositEIP { - function deposit(bytes8 id) external payable returns (bool); -} -``` - -- `deposit(bytes8)` MUST return `false` when the contract needs to keep the value, but signal to the depositor that the deposit (in terms of the parent application) itself has not yet succeeded. (This can be used for partial payment, ie. the invoice is for 5 ETH, sending 3 ETH returns false, but sending a second tx with 2 ETH will return true.) -- `deposit(bytes8)` MUST revert if the deposit somehow failed and the contract does not need to keep the value sent. -- `deposit(bytes8)` MUST return `true` if the value will be kept and the payment is logically considered complete by the parent application (exchange/merchant). -- `deposit(bytes8)` SHOULD check the checksum contained within the 8 byte id. (See "Deposit Address Format" for an example) -- `The parent application` SHOULD return any excess value received if the deposit id is a one-time-use invoice that has a set value and the value received is higher than the set value. However, this SHOULD NOT be done by sending back to `msg.sender` directly, but rather should be noted in the parent application and the depositor should be contacted out-of-band to the best of the application manager's ability. - -### Depositing Value to the Contract from a Wallet - -- `The wallet` MUST accept `the deposit address format` anywhere the 20-byte address format is accepted for transaction destination. -- `The wallet` MUST verify the 3 byte checksum and fail if the checksum doesn't match. -- `The wallet` MUST fail if the destination address is `the deposit address format` and the `data` field is set to anything besides null. -- `The wallet` MUST set the `to` field of the underlying transaction to the first 20 bytes of the deposit address format, and set the `data` field to `0x3ef8e69aNNNNNNNNNNNNNNNN000000000000000000000000000000000000000000000000` where `NNNNNNNNNNNNNNNN` is the last 8 bytes of the deposit address format. (ie. if the deposit address format is set to `0x433e064c42e87325fb6ffa9575a34862e0052f26913fd924f056cd15` then the `to` field is `0x433e064c42e87325fb6ffa9575a34862e0052f26` and the `data` field is `0x3ef8e69a913fd924f056cd15000000000000000000000000000000000000000000000000`) - -## Rationale -The contract interface and address format combination has one notable drawback, which was brought up in discussion. This ERC can only handle deposits for native value (ETH) and not other protocols such as ERC-20. However, this is not considered a problem, because it is best practice to logically AND key-wise separate wallets for separate currencies in any exchange/merchant application for accounting reasons and also for security reasons. Therefore, using this method for the native value currency (ETH) and another method for ERC-20 tokens etc. is acceptable. Any attempt at doing something similar for ERC-20 would require modifying the ERC itself (by adding the id data as a new input argument to the transfer method etc.) which would grow the scope of this ERC too large to manage. However, if this address format catches on, it would be trivial to add the bytes8 id to any updated protocols (though adoption might be tough due to network effects). - -The 8 byte size of the id and the checksum 3 : nonce 5 ratio were decided with the following considerations: - -- 24 bit checksum is better than the average 15 bit checksum of an EIP-55 address. -- 40 bit nonce allows for over 1 trillion nonces. -- 64 bit length of the id was chosen as to be long enough to support a decent checksum and plenty of nonces, but not be too long. (Staying under 256 bits makes hashing cheaper in gas costs as well.) - -## Backwards Compatibility -An address generated with the deposit address format will not be considered a valid address for applications that don't support it. If the user is technical enough, they can get around lack of support by verifying the checksum themselves, creating the needed data field by hand, and manually input the data field. (assuming the wallet app allows for arbitrary data input on transactions) A tool could be hosted on github for users to get the needed 20 byte address and msg.data field from a deposit address. - -Since a contract following this ERC will reject any plain value transactions, there is no risk of extracting the 20 byte address and sending to it without the calldata. - -However, this is a simple format, and easy to implement, so the author of this ERC will first implement in web3.js and encourage adoption with the major wallet applications. - -## Test Cases -``` -[ - { - "address": "0x083d6b05729c58289eb2d6d7c1bb1228d1e3f795", - "nonce": "0xbdd769c69b", - "depositAddress": "0x083d6b05729c58289eb2d6d7c1bb1228d1e3f795bdd769c69b3b97b9" - }, - { - "address": "0x433e064c42e87325fb6ffa9575a34862e0052f26", - "nonce": "0x913fd924f0", - "depositAddress": "0x433e064c42e87325fb6ffa9575a34862e0052f26913fd924f056cd15" - }, - { - "address": "0xbbc6597a834ef72570bfe5bb07030877c130e4be", - "nonce": "0x2c8f5b3348", - "depositAddress": "0xbbc6597a834ef72570bfe5bb07030877c130e4be2c8f5b3348023045" - }, - { - "address": "0x17627b07889cd22e9fae4c6abebb9a9ad0a904ee", - "nonce": "0xe619dbb618", - "depositAddress": "0x17627b07889cd22e9fae4c6abebb9a9ad0a904eee619dbb618732ef0" - }, - { - "address": "0x492cdf7701d3ebeaab63b4c7c0e66947c3d20247", - "nonce": "0x6808043984", - "depositAddress": "0x492cdf7701d3ebeaab63b4c7c0e66947c3d202476808043984183dbe" - } -] -``` - -## Implementation -A sample implementation with an example contract and address generation (in the tests) is located here: - -https://github.com/junderw/deposit-contract-poc - -## Security Considerations -In general, contracts that implement the contract interface should forward funds received to the deposit(bytes8) function to their cold wallet account. This address SHOULD be hard coded as a constant OR take advantage of the `immutable` keyword in solidity versions `>=0.6.5`. - -To prevent problems with deposits being sent after the parent application is shut down, a contract SHOULD have a kill switch that will revert all calls to deposit(bytes8) rather than using `selfdestruct(address)` (since users who deposit will still succeed, since an external account will receive value regardless of the calldata, and essentially the self-destructed contract would become a black hole for any new deposits) - -## 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-2876.md diff --git a/EIPS/eip-2917.md b/EIPS/eip-2917.md index 84e9b4d33e9f76..8ff04516b1ce20 100644 --- a/EIPS/eip-2917.md +++ b/EIPS/eip-2917.md @@ -1,165 +1,7 @@ --- eip: 2917 -title: Staking Reward Calculation -author: Tony Carson , Mehmet Sabir Kiraz , Süleyman Kardaş -discussions-to: https://github.com/ethereum/EIPs/issues/2925 -status: Draft -type: Standards Track category: ERC -created: 2020-08-28 +status: Moved --- -## Simple Summary -ERC2917 is a new standardization for on-chain calculation of staking reward. - -## Abstract -Based on the product of effective collateral and time, ERC2917 calculates the reward a user can get at any time, and realize the real decentralized DeFi. Here below is the formula for the calculation of reward for a user U: - -![concept image](../assets/eip-2917/erc-reward-formula.png "erc-reward-formula") - -where ∆pi denotes individual productivity of the user U between the consecutive block numbers ti-1 and ti, ∆Pi denotes global productivity between the consecutive block numbers ti-1 and ti, and ∆Gi denotes gross product between the consecutive block numbers ti-1 and ti. The formula ensures that there is no benefit in case of exiting earlier or entering later in the computation. The reward a user can get for a period is based on his total productivity during that specific time. The formula has been simplified through Solidity and generalized design to make it available across all DeFi products. -We note that the smart contract can be triggered for every computation of on the following events: -- whenever the productivity of a user changes (increase/decrease), -- whenever a user withdraws. - -## Motivation - -One of the main drawbacks of many DeFi projects is the reward distribution mechanism within the smart contract. In fact, there are two main mechanisms are adopted so far. -1. Distribution of rewards is only given when all users exit the contract -2. The project collects on-chain data, conducts calculation off-chain, and sends the results -to the chain before starting rewards distribution accordingly - -The first approach conducts all calculation in an on-chain fashion, the cycle of its rewards distribution is too long. Furthermore, users need to remove their collateral before getting the rewards, which can be harmful for their rewards. The second approach is a semi-decentralized model since the main algorithm involves an off-chain computation. Therefore, the fairness and transparency properties cannot be reflected and this can even create the investment barrier for users. - -Since there is more DeFi projects coming out everyday, users could not find a proper way to get to know: -1) amount of interests he/she would get -2) how the interest calculated -3) what is his/her contribution compare to the overall - -By standardizing ERC2917, it abstracts the interface for interests generation process. Making wallet applications easier to collect each DeFi's metrics, user friendlier. - -## Specification - -Every ERC-2917 compliant contract must implement the ERC2917 and ERC20 interfaces (if necessary): - -```solidity -interface IERC2917 is IERC20 { - - /// @dev This emit when interests amount per block is changed by the owner of the contract. - /// It emits with the old interests amount and the new interests amount. - event InterestRatePerBlockChanged (uint oldValue, uint newValue); - - /// @dev This emit when a users' productivity has changed - /// It emits with the user's address and the the value after the change. - event ProductivityIncreased (address indexed user, uint value); - - /// @dev This emit when a users' productivity has changed - /// It emits with the user's address and the the value after the change. - event ProductivityDecreased (address indexed user, uint value); - - - /// @dev Return the current contract's interests rate per block. - /// @return The amount of interests currently producing per each block. - function interestsPerBlock() external view returns (uint); - - /// @notice Change the current contract's interests rate. - /// @dev Note the best practice will be restrict the gross product provider's contract address to call this. - /// @return The true/false to notice that the value has successfully changed or not, when it succeed, it will emite the InterestRatePerBlockChanged event. - function changeInterestRatePerBlock(uint value) external returns (bool); - - /// @notice It will get the productivity of given user. - /// @dev it will return 0 if user has no productivity proved in the contract. - /// @return user's productivity and overall productivity. - function getProductivity(address user) external view returns (uint, uint); - - /// @notice increase a user's productivity. - /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. - /// @return true to confirm that the productivity added success. - function increaseProductivity(address user, uint value) external returns (bool); - - /// @notice decrease a user's productivity. - /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. - /// @return true to confirm that the productivity removed success. - function decreaseProductivity(address user, uint value) external returns (bool); - - /// @notice take() will return the interests that callee will get at current block height. - /// @dev it will always calculated by block.number, so it will change when block height changes. - /// @return amount of the interests that user are able to mint() at current block height. - function take() external view returns (uint); - - /// @notice similar to take(), but with the block height joined to calculate return. - /// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests. - /// @return amount of interests and the block height. - function takeWithBlock() external view returns (uint, uint); - - /// @notice mint the available interests to callee. - /// @dev once it mint, the amount of interests will transfer to callee's address. - /// @return the amount of interests minted. - function mint() external returns (uint); -} -``` - -### InterestRatePerBlockChanged - -This emit when interests amount per block is changed by the owner of the contract. It emits with the old interests amount and the new interests amount. - - -### ProductivityIncreased - -It emits with the user's address and the the value after the change. - - -### ProductivityDecreased - -It emits with the user's address and the the value after the change. - -### interestsPerBlock - -It returns the amount of interests currently producing per each block. - -### changeInterestRatePerBlock - -Note the best practice will be restrict the gross product provider's contract address to call this. - -The true/false to notice that the value has successfully changed or not, when it succeed, it will emite the InterestRatePerBlockChanged event. - -### getProductivity - -It returns user's productivity and overall productivity. It returns 0 if user has no productivity proved in the contract. - -### increaseProductivity - -It increases a user's productivity. - -### decreaseProductivity - -It decreases a user's productivity. - -### take - -It returns the interests that callee will get at current block height. - -### takeWithBlock - -Similar to take(), but with the block height joined to calculate return. - -For instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests. - -It returns amount of interests and the block height. - -### mint -it mints the amount of interests will transfer to callee's address. It returns the amount of interests minted. - -## Rationale -TBD - -## Implementation -The implementation code is on the github: - -- [ERC2917 Demo](https://github.com/gnufoo/ERC3000-Proposal) - -## Security Considerations -TBD - -## 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-2917.md diff --git a/EIPS/eip-2926.md b/EIPS/eip-2926.md index 70aa5b1e3f4b19..bb1562d5a56cc7 100644 --- a/EIPS/eip-2926.md +++ b/EIPS/eip-2926.md @@ -3,7 +3,7 @@ eip: 2926 title: Chunk-Based Code Merkleization author: Sina Mahmoodi (@s1na), Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/eip-2926-chunk-based-code-merkleization/4555 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2020-08-25 @@ -158,4 +158,4 @@ The implementation of the chunking and merkleization logic in Typescript can be 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-2929.md b/EIPS/eip-2929.md index e2940a9567017e..0e11417265a623 100644 --- a/EIPS/eip-2929.md +++ b/EIPS/eip-2929.md @@ -37,7 +37,7 @@ In the further future, there are similar benefits in the case of SNARK/STARK wit | Constant | Value | | - | - | -| `FORK_BLOCK` | TBD | +| `FORK_BLOCK` | 12244000 | | `COLD_SLOAD_COST` | 2100 | | `COLD_ACCOUNT_ACCESS_COST` | 2600 | | `WARM_STORAGE_READ_COST` | 100 | @@ -169,4 +169,4 @@ But there are ways to further expand the usability of this pattern. One possibil 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2930.md b/EIPS/eip-2930.md index bb507969989b0a..c9db53a936c5c9 100644 --- a/EIPS/eip-2930.md +++ b/EIPS/eip-2930.md @@ -16,9 +16,9 @@ Adds a transaction type which contains an access list, a list of addresses and s ## Abstract -We introduce a new [EIP-2718](./eip-2718.md) transaction type, with the format `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, access_list, yParity, senderR, senderS])`. +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 `access_list` 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. +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 @@ -42,19 +42,19 @@ This EIP serves two functions: | Constant | Value | | - | - | -| `FORK_BLOCK` | TBD | +| `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, access_list, yParity, senderR, senderS])`. +The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is `rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, signatureYParity, signatureR, signatureS])`. -The `yParity, senderR, senderS` elements of this transaction represent a secp256k1 signature over `keccak256(0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, access_list]))`. +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, `access_list` 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): +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): ``` [ @@ -72,7 +72,7 @@ For the transaction to be valid, `access_list` must be of type `[[{20 bytes}, [{ ] ``` -At the beginning of execution (ie. at the same time as the `21000 + 4 * zeroes + 12 * nonzeroes` start gas is charged), 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. +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. @@ -137,4 +137,4 @@ However, this EIP proposes only a 10% initial discount to access lists, so there 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2935.md b/EIPS/eip-2935.md index 22383207384d50..198affb72399bf 100644 --- a/EIPS/eip-2935.md +++ b/EIPS/eip-2935.md @@ -1,7 +1,8 @@ --- eip: 2935 -title: Save historical block hashes in state -author: Vitalik Buterin (@vbuterin), Tomasz Stanczak (@tkstanczak) +title: Serve historical block hashes from state +description: Store and serve last 8192 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: Review type: Standards Track @@ -9,55 +10,216 @@ category: Core created: 2020-09-03 --- -## Simple Summary +## Abstract -Store historical block hashes in a contract, and modify the `BLOCKHASH (0x40)` opcode to read this contract. +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 -There is increasingly a desire to remove the need for most clients to store history older than some relatively short duration (often between 1 week and 1 year) to save disk space. This requires some form of layer-2 network to help clients access historical information. These protocols can be made much simpler if blocks contained a quick Merkle path to historical blocks. +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. -Additional secondary motivations include: +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. -* The protocol can be used to make more secure efficient light clients with flyclient-like technology (while the "optimal" flyclient protocol is fairly complex, large security gains over the status quo (trusted "canonical hash trees") can be made cheaply) -* Improving cleanness of the protocol, as the BLOCKHASH opcode would then access state and not history. +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 | | - | - | -| `FORK_BLKNUM` | TBD | -| `HISTORY_STORAGE_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe`| - -At the start of processing any block where `block.number > FORK_BLKNUM` (ie. before processing any transactions), run `sstore(HISTORY_STORAGE_ADDRESS, block.number - 1, block.prevhash)`. - -When `block.number > FORK_BLKNUM + 256`, change the logic of the `BLOCKHASH` opcode as follows: if `FORK_BLKNUM <= arg < block.number`, return `sload(HISTORY_STORAGE_ADDRESS, arg)`. Otherwise return 0. +| `BLOCKHASH_SERVE_WINDOW` | `256` | +| `HISTORY_SERVE_WINDOW` | `8191` | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | +| `HISTORY_STORAGE_ADDRESS` | `0x0F792be4B0c0cb4DAE440Ef133E90C0eCD48CCCC` | + +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": "0xbaefe09f0109759", + "hash": "0x8c7bd2d3713a0b2bb693463d2a78c4d612ac47dd38ecb74f8996a4b6fc96f03c" +} +``` + +Note, the input in the transaction has a simple constructor prefixing the desired runtime code. + +The sender of the transaction can be calculated as `0xE9f0662359Bb2c8111840eFFD73B9AFA77CbDE10`. The address of the first contract deployed from the account is `rlp([sender, 0])` which equals `0x0F792be4B0c0cb4DAE440Ef133E90C0eCD48CCCC`. 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 in EIP-98 and EIP-210. This EIP is a simplification, removing two sources of needless complexity: +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 -The former was intended to save space. Since then, however, storage usage has increased massively, to the point where even eg. 5 million new storage slots are fairly negligible compared to existing usage. The latter was intended as a first step toward "writing the Ethereum protocol in EVM" as much as possible, but this goal has since been de-facto abandoned. +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. -## Backwards Compatibility +Second concern was how to best transition the BLOCKHASH resolution logic post fork by: -The range of `BLOCKHASH` is increased by this opcode, but behavior within the previous 256-block range remains unchanged. +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. -## Test Cases +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. -TBD +### 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 definied outside of the EIP + state.insert_slot(HISTORY_STORAGE_ADDRESS, (block.number-1) % HISTORY_SERVE_WINDOW , block.parent.hash) +``` -## Implementation +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 TBD ## Security Considerations -Adding ~2.5 million storage slots per year bloats the state somewhat (but not much relative to the hundreds of millions of existing state objects). However, this EIP is not intended to be permanent; when eth1 is merged into eth2, the BLOCKHASH opcode would likely be repurposed to use eth2's built-in history accumulator structure (see [phase 0 spec](https://github.com/ethereum/annotated-spec/blob/master/phase0/beacon-chain.md#slots_per_historical_root)). +Having contracts (system or otherwise) with hot update paths (branches) poses a risk of "branch" poisioning 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2936.md b/EIPS/eip-2936.md index 92f5e18ccf1170..daad2d0bf28d4b 100644 --- a/EIPS/eip-2936.md +++ b/EIPS/eip-2936.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-09-03 @@ -57,4 +57,4 @@ Implementation is required on all major clients to add the opcode. 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2937.md b/EIPS/eip-2937.md index 17e79f2f540a4a..4122d7c7d02fc7 100644 --- a/EIPS/eip-2937.md +++ b/EIPS/eip-2937.md @@ -3,7 +3,7 @@ eip: 2937 title: SET_INDESTRUCTIBLE opcode author: Vitalik Buterin (@vbuterin) discussions-to: https://ethereum-magicians.org/t/eip-2937-set-indestructible/4571 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2020-09-04 @@ -45,4 +45,4 @@ This breaks forward compatibility with _some_ forms of state rent, which would s If `SELFDESTRUCT` is ever removed in the future, this EIP would simply become a no-op. ## 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-2938.md b/EIPS/eip-2938.md index e6c242237f55c1..2d208f4a2c87b5 100644 --- a/EIPS/eip-2938.md +++ b/EIPS/eip-2938.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-09-04 @@ -16,11 +16,11 @@ Account abstraction (AA) allows a contract to be the top-level account that pays ## Abstract -**See also: https://ethereum-magicians.org/t/implementing-account-abstraction-as-part-of-eth1-x/4020 and the links therein for historical work and motivation.** +**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.) +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 @@ -32,7 +32,7 @@ The existing limitations preclude innovation in a number of important areas, par 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. +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. @@ -162,7 +162,7 @@ While processing a new block, take note of which accounts were the `target` of a ### 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`) to any contract whose first byte is the `SET_INDESTRUCTIBLE` opcode is no longer banned. However, calls other than `CALLCODE` and `DELEGATECALL` (ie. calls that change the `callee`) to anything but the `target` or a precompile are still not permitted. +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. @@ -184,7 +184,7 @@ 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 includeable 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. +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. @@ -208,13 +208,13 @@ This is done to allow signature checking done in validation code to validate the ### Replay Protection -Whichever option (requiring `SET_INDESTRUCTIBLE` or modifying `SELFDESTRUCT` behavior) is necessary 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. +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...) 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. +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. @@ -241,9 +241,9 @@ The tornado.cash workflow is as follows: 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 nulllifier, publish the transaction using their own ETH to pay for gas, and collects the fee back from the user from the TC contract. +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 us to do this without relayers: the user could simply send an AA transaction targeting the TC contract, and the ZK-SNARK verification and the nullifier checking can be done as 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. +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). @@ -261,17 +261,17 @@ This AA implementation preserves the existing transaction type. The use of `asse 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). -All AA contracts may also potentially 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). +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 +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 +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 for an analysis of DoS issues. +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 @@ -281,7 +281,7 @@ There are, however, cases where an attacker can publish a transaction that inval #### 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 increased allotment of validation work allowed to AA, it's important 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. +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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2942.md b/EIPS/eip-2942.md index 3a3df32b728f44..265660ceaee3b1 100644 --- a/EIPS/eip-2942.md +++ b/EIPS/eip-2942.md @@ -1,66 +1,7 @@ --- eip: 2942 -title: EthPM URI Specification -author: Nick Gheorghita (@njgheorghita), Piper Merriam (@pipermerriam), g. nicholas d'andrea (@gnidan), Benjamin Hauser (@iamdefinitelyahuman) -discussions-to: https://ethereum-magicians.org/t/ethpm-v3-specification-working-group/4086/7 -status: Draft -type: Standards Track category: ERC -created: 2020-09-04 -requires: 2678 +status: Moved --- -## Simple Summary -A custom URI scheme to identify an EthPM registry, package, release, or specific contract asset within a release. - -## Abstract -When interacting with the EthPM ecosystem, users and tooling can benefit from a URI scheme to identify EthPM assets. Being able to specify a package, registry, or release with a single string makes simplifies the steps required to install, publish, or distribute EthPM packages. - -## Specification -`scheme://registry_address[:chain_id][/package_name[@package_version[/json_pointer]]]` - -#### `scheme` -- Required -- Must be one of `ethpm` or `erc1319`. If future versions of the EthPM registry standard are designed and published via the ERC process, those ERCs will also be valid schemes. - -#### `registry_address` -- Required -- This **SHOULD** be either an ENS name or a 0x-prefixed, checksummed address. ENS names are more suitable for cases where mutability of the underlying asset is acceptable and there is implicit trust in the owner of the name. 0x prefixed addresses are more preferable in higher security cases to avoid needing to trust the controller of the name. - -#### `chain_id` -- Optional -- Integer representing the chain id on which the registry is located -- If omitted, defaults to `1` (mainnet). - -#### `package_name` -- Optional -- String of the target package name - -#### `package_version` -- Optional -- String of the target package version -- If the package version contains any [url unsafe characters](https://en.wikipedia.org/wiki/Percent-encoding), they **MUST** be safely escaped -- Since semver is not strictly enforced by the ethpm spec, if the `package_version` is omitted from a uri, tooling **SHOULD** avoid guessing in the face of any ambiguity and present the user with a choice from the available versions. - -#### `json_pointer` -- Optional -- A path that identifies a specific asset within a versioned package release. -- This path **MUST** conform to the [JSON pointer](https://tools.ietf.org/html/rfc6901) spec and resolve to an available asset within the package. - -## Rationale -Most interactions within the EthPM ecosystem benefit from a single-string representation of EthPM assets; from installing a package, to identifying a registry, to distributing a package. A single string that can faithfully represent any kind of EthPM asset, across the mainnet or testnets, reduces the mental overload for new users, minimizes configuration requirements for frameworks, and simplifies distribution of packages for package authors. - -## Test Cases -A JSON file for testing various URIs can be found in the [`ethpm-spec`](https://github.com/ethpm/ethpm-spec/) repository fixtures. - -## Implementation -The EthPM URI scheme has been implemented in the following libraries: -- [Brownie](https://eth-brownie.readthedocs.io/en/stable/) -- [Truffle](https://www.trufflesuite.com/docs/truffle/overview) -- [EthPM CLI](https://ethpm-cli.readthedocs.io/en/latest/) - -## Security Considerations -In most cases, an EthPM URI points to an immutable asset, giving full security that the target asset has not been modified. However, in the case where an EthPM URI uses an ENS name as its registry address, it is possible that the ENS name has been redirected to a new registry, in which case the guarantee of immutability no longer exists. - -## 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-2942.md diff --git a/EIPS/eip-2970.md b/EIPS/eip-2970.md index 92f2463f791933..0d58fe4d4ffe9a 100644 --- a/EIPS/eip-2970.md +++ b/EIPS/eip-2970.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-09-13 @@ -36,4 +36,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-2972.md b/EIPS/eip-2972.md index 4fd3ef616145ec..0db0c868d1bac8 100644 --- a/EIPS/eip-2972.md +++ b/EIPS/eip-2972.md @@ -124,4 +124,4 @@ Luckily, [EIP-2718](./eip-2718.md) also excludes transaction types `0xc0` to `0x 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2976.md b/EIPS/eip-2976.md index 04ad6dae9117c6..36bd2d463a7f48 100644 --- a/EIPS/eip-2976.md +++ b/EIPS/eip-2976.md @@ -1,18 +1,16 @@ --- eip: 2976 -title: 'Typed Transactions over Gossip' +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: Review +status: Final type: Standards Track category: Networking created: 2020-09-13 requires: 2718 --- -## Simple Summary -Adds support for transmission of typed transactions over devp2p. - ## 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. @@ -36,7 +34,7 @@ All changes specified below apply to all protocol/versions retroactively. * `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 transcation +* `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))` @@ -96,4 +94,4 @@ If a client chooses to ignore the **SHOULD** recommendation for disconnecting pe 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2980.md b/EIPS/eip-2980.md index 459c34858e6f1d..84cdaf8aa83904 100644 --- a/EIPS/eip-2980.md +++ b/EIPS/eip-2980.md @@ -1,204 +1,7 @@ --- eip: 2980 -title: Swiss Compliant Asset Token -author: Gianluca Perletti (@Perlets9), Alan Scarpellini (@alanscarpellini), Roberto Gorini (@robertogorini), Manuel Olivi (@manvel79) -discussions-to: https://github.com/ethereum/EIPs/issues/2983 -status: Draft -type: Standards Track category: ERC -created: 2020-09-08 -requires: 20 +status: Moved --- -## Simple Summary - -An interface for asset tokens, compliant with Swiss Law and compatible with [ERC-20](./eip-20.md). - -## Abstract - -This new standard is an [ERC-20](./eip-20.md) compatible token with restrictions that comply with the following Swiss laws: the [Stock Exchange Act](../assets/eip-2980/Swiss-Confederation-SESTA.pdf), the [Banking Act](../assets/eip-2980/Swiss-Confederation-BA.pdf), the [Financial Market Infrastructure Act](../assets/eip-2980/Swiss-Confederation-FMIA.pdf), the [Act on Collective Investment Schemes](../assets/eip-2980/Swiss-Confederation-CISA.pdf) and the [Anti-Money Laundering Act](../assets/eip-2980/Swiss-Confederation-AMLA.pdf). The [Financial Services Act](../assets/eip-2980/Swiss-Confederation-FINSA.pdf) and the [Financial Institutions Act](../assets/eip-2980/Swiss-Confederation-FINIA.pdf) must also be considered. The solution achieved meet also the European jurisdiction. - -This new standard meets the new era of asset tokens (known also as "security tokens"). These new methods manage securities ownership during issuance and trading. The issuer is the only role that can manage a white-listing and the only one that is allowed to execute “freeze” or “revoke” functions. - -## Motivation - -In its ICO guidance dated February 16, 2018, FINMA (Swiss Financial Market Supervisory Authority) defines asset tokens as tokens representing assets and/or relative rights ([FINMA ICO Guidelines](../assets/eip-2980/Finma-ICO-Guidelines.pdf)). It explicitly mentions that asset tokens are analogous to and can economically represent shares, bonds, or derivatives. The long list of relevant financial market laws mentioned above reveal that we need more methods than with Payment and Utility Token. - -## 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. - -The words "asset tokens" and "security tokens" can be considered synonymous. - -Every ERC-2980 compliant contract MUST implement the ERC-2980 interface. - -### ERC-2980 (Token Contract) - -``` solidity -interface ERC2980 extends ERC20 { - - /// @dev This emits when funds are reassigned - event FundsReassigned(address from, address to, uint256 amount); - - /// @dev This emits when funds are revoked - event FundsRevoked(address from, uint256 amount); - - /// @dev This emits when an address is frozen - event FundsFrozen(address target); - - /** - * @dev getter to determine if address is in frozenlist - */ - function frozenlist(address _operator) external view returns (bool); - - /** - * @dev getter to determine if address is in whitelist - */ - function whitelist(address _operator) external view returns (bool); - -} -``` - -The ERC-2980 extends [ERC-20](./eip-20.md). Due to the indivisible nature of asset tokens, the decimals number MUST be zero. - -### Whitelist and Frozenlist - -The accomplishment of the Swiss Law requirements is achieved by the use of two distinct lists of address: the Whitelist and the Frozenlist. -Addresses can be added to one or the other list at any time by operators with special privileges, called Issuers, and described below. -Although these lists may look similar, they differ for the following reasons: the Whitelist members are the only ones who can receive tokens from other addresses. There is no restriction on the possibility that these addresses can transfer the tokens already in their ownership. -This can occur when an address, present in the Whitelist, is removed from this list, without however being put in the Frozenlist and remaining in possession of its tokens. -On the other hand, the addresses assigned to the Frozenlist, as suggested by the name itself, have to be considered "frozen", so they cannot either receive tokens or send tokens to anyone. - -Below is an example interface for the implementation of a whitelist-compatible and a frozenlist-compratible contract. - -``` solidity -Interface Whitelistable { - - /** - * @dev add an address to the whitelist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to add - * @return true if the address was added to the whitelist, false if the address was already in the whitelist - */ - function addAddressToWhitelist(address _operator) external returns (bool); - - /** - * @dev remove an address from the whitelist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to remove - * @return true if the address was removed from the whitelist, false if the address wasn't in the whitelist in the first place - */ - function removeAddressFromWhitelist(address _operator) external returns (bool); - -} - -Interface Freezable { - - /** - * @dev add an address to the frozenlist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to add - * @return true if the address was added to the frozenlist, false if the address was already in the frozenlist - */ - function addAddressToFrozenlist(address _operator) external returns (bool); - - /** - * @dev remove an address from the frozenlist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to remove - * @return true if the address was removed from the frozenlist, false if the address wasn't in the frozenlist in the first place - */ - function removeAddressFromFrozenlist(address _operator) external returns (bool); - -} -``` - -### Issuers - -A key role is played by the Issuer. This figure has the permission to manage Whitelists and Frozenlists, to revoke tokens and reassign them and to transfer the role to another address. No restrictions on the possibility to have more than one Issuer per contract. Issuers are nominated by the Owner of the contract, who also is in charge of remove the role. The possibility of nominating the Owner itself as Issuer at the time of contract creation (or immediately after) is not excluded. - -Below is an example interface for the implementation of the Issuer functionalities. - -``` solidity -Interface Issuable { - - /** - * @dev getter to determine if address has issuer role - */ - function isIssuer(address _addr) external view returns (bool); - - /** - * @dev add a new issuer address - * Throws unless `msg.sender` is the contract owner - * @param _operator address - * @return true if the address was not an issuer, false if the address was already an issuer - */ - function addIssuer(address _operator) external returns (bool); - - /** - * @dev remove an address from issuers - * Throws unless `msg.sender` is the contract owner - * @param _operator address - * @return true if the address has been removed from issuers, false if the address wasn't in the issuer list in the first place - */ - function removeIssuer(address _operator) external returns (bool); - - /** - * @dev Allows the current issuer to transfer its role to a newIssuer - * Throws unless `msg.sender` is an Issuer operator - * @param _newIssuer The address to transfer the issuer role to - */ - function transferIssuer(address _newIssuer) external; - -} -``` - -### Revoke and Reassign - -Revoke and Reassign methods allow Issuers to move tokens from addresses, even if they are in the Frozenlist. The Revoke method transfers the entire balance of the target address to the Issuer who invoked the method. The Reassign method transfers the entire balance of the target address to another address. These rights for these operations MUST be allowed only to Issuers. - -Below is an example interface for the implementation of the Revoke and Reassign functionalities. - -``` solidity -Interface RevokableAndReassignable { - - /** - * @dev Allows the current Issuer to transfer token from an address to itself - * Throws unless `msg.sender` is an Issuer operator - * @param _from The address from which the tokens are withdrawn - */ - function revoke(address _from) external; - - /** - * @dev Allows the current Issuer to transfer token from an address to another - * Throws unless `msg.sender` is an Issuer operator - * @param _from The address from which the tokens are withdrawn - * @param _to The address who receives the tokens - */ - function reassign(address _from, address _to) external; - -} -``` - -## Rationale - -There are currently no token standards that expressly facilitate conformity to securities law and related regulations. EIP-1404 (Simple Restricted Token Standard) it’s not enough to address FINMA requirements around re-issuing securities to Investors. -In Swiss law, an issuer must eventually enforce the restrictions of their token transfer with a “freeze” function. The token must be “revocable”, and we need to apply a white-list method for AML/KYC checks. - -## Backwards Compatibility - -This EIP does not introduce backward incompatibilities and is backward compatible with the older ERC-20 token standard. -This standard allows the implementation of ERC-20 functions transfer, transferFrom, approve and allowance alongside to make a token fully compatible with ERC-20. -The token MAY implement decimals() for backward compatibility with ERC-20. If implemented, it MUST always return 0. - -## Implementations - -Although an official implementation of the ERC-2980 has not been presented, in the Specifications section some interfaces have been reported which, once implemented correctly and according to the reccomandations, allow to create an asset token compliant with this ERC. - -## Security Considerations - -The security considerations mainly concern the role played by the Issuers. This figure, in fact, is not generally present in common ERC-20 tokens but has very powerful rights that allow him to move tokens without being in possession and freeze other addresses, preventing them from transferring tokens. It must be the responsibility of the owner to ensure that the addresses that receive this charge remain in possession of it only for the time for which they have been designated to do so, thus preventing any abuse. - -## 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-2980.md diff --git a/EIPS/eip-2981.md b/EIPS/eip-2981.md index 1e8c91681deb9e..9b6e89e7e50d44 100644 --- a/EIPS/eip-2981.md +++ b/EIPS/eip-2981.md @@ -1,206 +1,7 @@ --- eip: 2981 -title: ERC-721 Royalty Standard -author: Zach Burks (@vexycats), James Morgan (@jamesmorgan), Blaine Malone (@blmalone), James Seibel (@seibelj) -discussions-to: https://github.com/ethereum/EIPs/issues/2907 -status: Draft -type: Standards Track category: ERC -created: 2020-09-15 -requires: 165 +status: Moved --- -## Simple Summary - -A standardized way to handle royalty payments for ERC-721 tokens, including publicly viewable royalty information and notification using a royalty payment event. - -## Abstract - -This standard extends the [ERC-721 specification](./eip-721.md) to enable setting a royalty amount paid to the NFT creator or rights holder every time an NFT is sold and re-sold. This is intended for NFT marketplaces that want to support the ongoing funding of artists and other NFT creators. The royalty payment must be voluntary as required by the EIP-721 standard, as `transferFrom()` includes NFT transfers between wallets, and executing `transferFrom()` does not always imply a sale occurred. Marketplaces and individuals implement this standard by retrieving the royalty payment information with `royaltyInfo()`, paying the proper royalty amount to the royalty recipient address, and calling `onRoyaltiesReceived()` to notify the NFT contract of the royalty payment. Payments are simple and sent only to a single address. This ERC should be considered a minimal, gas-efficient building block for further innovation in NFT royalty payments. - -## Motivation -There are many marketplaces for NFTs with multiple unique royalty payment implementations that are not easily compatible or usable by other marketplaces. Just like the early days of ERC-20 tokens, ERC-721 marketplace smart contracts are varied by ecosystem and not standardized. This EIP enables all marketplaces to pay the royalties that NFT creators specify and are entitled to, enabling accurate royalty payments regardless of which marketplace the NFT is sold or re-sold at. - -Many of the largest ERC-721 marketplaces have implemented royalty payments that are incompatible with other platforms and therefore make it much harder to enforce when the NFT is sold on another marketplace, not fulfilling the potential of any implemented royalty system. This standard is a way to implement royalties that can be accepted across any type of NFT marketplace. This minimalist proposal allows for standardized royalties to be accepted on all marketplaces - leaving the actual funds transfer up to the marketplace itself, and only providing a means to fetch the royalty amounts and an event to be emitted when the transfer has happened. - -This standard extends the [ERC-721 specification](./eip-721.md) to enable setting a royalty amount paid to the NFT creator or rights holder every time an NFT is sold and re-sold. If a marketplace chooses *not* to implement this EIP, then obviously no funds are paid for secondary sales. But as most NFT marketplaces have developed some unique royalty system themselves - and all of them are singular and only work within their own contracts - there should be an accepted standard for paying royalties, if the creator chooses to set royalties on their NFTs. We believe the NFT marketplace ecosystem will voluntarily implement royalty payments to provide ongoing funding for artists and other creators, and NFT buyers will assess the royalty payment as a factor when making NFT purchasing decisions. - -Without an agreed royalty payment standard, the NFT ecosystem will lack an effective means to collect royalties across all marketplaces and artists and other creators will not receive ongoing funding. This will hamper the growth and adoption of NFTs and demotivate artists and other NFT creators from minting new and innovative tokens. - -*"Yes we have royalties, but if your NFT is sold on another marketplace, we cannot provide royalties" ... "But can't I sell my NFT anywhere with a click of my wallet?" ... "Yes... but we don't have a standard for royalties so you'll lose out."* - -This EIP fixes this issue, enabling all NFT marketplaces to unify on a single royalty payment standard and benefiting the entire NFT ecosystem. - -## 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. - -**ERC-721 compliant contracts MAY implement this ERC for royalties to provide a standard method of accepting royalty payments and receiving royalty information.** - -The `amount` returned by `royaltyInfo()` **MUST** be a percentage fixed point with a scaling factor of 100000 `(X/100000)` - such as "500000" - for 5% (i.e. 5 decimals). This is **REQUIRED** to maintain uniformity across the standard. The max and min values would be 10000000 (100%) and 1 (0.00001%). This fits snugly into the `uint24` type to minimize storage costs, and can easily be cast to other `uint` types as needed (i.e. `uint256(0x1234)`). - -Marketplaces that support this standard **MAY** implement any method of calculating or transferring royalties to the royalty recipient. - -Marketplaces that support this standard **MUST** call the `onRoyaltiesReceived()` function on the NFT contract after sending a payment, which will automatically emit the `RoyaltiesReceived` event. - -Implementers of this standard **MUST** emit the `RoyaltiesReceived` event when `onRoyaltiesReceived()` is called. Implementers may do any other logic inside of this call, provided the `RoyaltiesReceived` event is emitted. - -Implementers of this standard **MUST** have all of the following events and functions: - -```solidity -pragma solidity ^0.6.0; -import "./ERC165.sol"; - -/// -/// @dev Implementation of royalties for 721s -/// -interface IERC2981 is ERC165 { - /// ERC165 bytes to add to interface array - set in parent contract - /// implementing this standard - /// - /// bytes4(keccak256("royaltyInfo(uint256)")) == 0xcef6d368 - /// bytes4(keccak256("onRoyaltiesReceived(address,address,uint256,address,uint256,bytes32)")) == 0xe8cb9d99 - /// bytes4(0xcef6d368) ^ bytes4(0xe8cb9d99) == 0x263d4ef1 - /// bytes4 private constant _INTERFACE_ID_ERC721ROYALTIES = 0x263d4ef1; - /// _registerInterface(_INTERFACE_ID_ERC721ROYALTIES); - - /// @notice Called to return both the creator's address and the royalty percentage - /// @param _tokenId - the NFT asset queried for royalty information - /// @return receiver - address of who should be sent the royalty payment - /// @return amount - a percentage calculated as a fixed point - /// with a scaling factor of 100000 (5 decimals), such that - /// 100% would be the value 10000000, as 10000000/100000 = 100. - /// 1% would be the value 100000, as 100000/100000 = 1 - function royaltyInfo(uint256 _tokenId) external returns (address receiver, uint24 amount); - - /// @notice Called when royalty is transferred to the receiver. This - /// emits the RoyaltiesReceived event as we want the NFT contract - /// itself to contain the event for easy tracking by royalty receivers. - /// @param _royaltyRecipient - The address of who is entitled to the - /// royalties as specified by royaltyInfo(). - /// @param _buyer - If known, the address buying the NFT on a secondary - /// sale. 0x0 if not known. - /// @param _tokenId - the ID of the ERC-721 token that was sold - /// @param _tokenPaid - The address of the ERC-20 token used to pay the - /// royalty fee amount. Set to 0x0 if paid in the - /// native asset (ETH). - /// @param _amount - The amount being paid to the creator using the - /// correct decimals from _tokenPaid's ERC-20 contract - /// (i.e. if 7 decimals, 10000000 for 1 token paid) - /// @param _metadata - Arbitrary data attached to this payment - /// @return `bytes4(keccak256("onRoyaltiesReceived(address,address,uint256,address,uint256,bytes32)"))` - function onRoyaltiesReceived(address _royaltyRecipient, address _buyer, uint256 _tokenId, address _tokenPaid, uint256 _amount, bytes32 _metadata) external returns (bytes4); - - /// @dev This event MUST be emitted by `onRoyaltiesReceived()`. - event RoyaltiesReceived( - address indexed _royaltyRecipient, - address indexed _buyer, - uint256 indexed _tokenId, - address _tokenPaid, - uint256 _amount, - bytes32 _metadata - ); - - /// @notice Informs callers that this ERC721 supports ERC2981 - /// @dev If `_registerInterface(_INTERFACE_ID_ERC721ROYALTIES)` is called - /// in the initializer, this should be automatic - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @return `true` if the contract implements - /// `_INTERFACE_ID_ERC721ROYALTIES` and `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} - -``` - -### Examples - -This standard being used on an ERC-721 during deployment: - -#### Deploying an ERC-721 and setting the royalty amount and creator - -```solidity -constructor (string memory name, string memory symbol, string memory baseURI) public Royalties(royalty_amount, msg.sender) { - _name = name; - _symbol = symbol; - _setBaseURI(baseURI); - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(_INTERFACE_ID_ERC721); - _registerInterface(_INTERFACE_ID_ERC721_METADATA); - _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); - // Royalties interface - _registerInterface(_INTERFACE_ID_ERC721ROYALTIES); - } -``` - -#### Checking if the NFT being sold on your marketplace implemented royalties - -Note: using address.call() is completely **OPTIONAL** and is just one method. - -```solidity -function checkRoyalties(address _token) internal returns (bool) { - (bool success) = address(_token).call(abi.encodeWithSignature("royaltyInfo(uint256)")); - return success; - } -``` - -**Transferring funds (ETH) and calling function to emit the RoyaltiesReceived event inside the NFT contract** - -```solidity - _recipient.transfer(amount); - IERC2981(_tokenAddress).onRoyaltiesReceived(_recipient, _buyer, _tokenId, address(0), amount, _metadata); -``` - -**Transferring funds (USDC) and calling function to emit the RoyaltiesReceived event inside the NFT contract** - -```solidity - IERC20(0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48).transfer(_recipient, amount); - IERC2981(_tokenAddress).onRoyaltiesReceived(_recipient, _buyer, _tokenId, address(0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48), amount, _metadata); -``` - -## Rationale - -### Optional royalty payments - -It is impossible to know which NFT transfers are the result of sales, and which are merely wallets moving or consolidating their NFTs. Therefore, we cannot force every `transferFrom()` call to involve a royalty payment, as not every transfer is a sale that would require such payment. We believe the NFT marketplace ecosystem will voluntarily implement this royalty payment standard to provide ongoing funding for artists and other creators, and NFT buyers will assess the royalty payment percentage as a factor when making NFT purchasing decisions. - -### Simple royalty payments to a single address - -It is impossible to fully know and efficiently implement all possible types of royalty payments and logic, so it is on the royalty payment receiver to implement all additional complexity and logic for fee splitting, multiple receivers, taxes, accounting, etc. in their own receiving contract or off-chain. If we attempted to do this as part of this standard, it would dramatically increase the implementation complexity, increase gas costs, and could not possibly cover every potential use-case. Therefore, implementers desiring more complex royalty payment logic should create their own smart contract that implements their own requirements upon the receipt of ETH or ERC20 tokens and / or the execution of `onRoyaltiesReceived()`. This ERC should be considered a minimal, gas-efficient building block for further innovation in NFT royalty payments. - -### Fixed percentage to 10^5 (100000) - -Having the flexibility to set any percentage a creator likes is important - although the reality of having users want a 0.00000000001% fee is not very likely. Instead the value can be limited to 5 decimal places with the lowest percentage being 0.00001% and the cap at 100%. It also allows us to store the value in a `uint24`, reducing storage costs. - -### Emitting event for payment on the NFT contract itself - -Choosing to emit an event for payment is important as each NFT contract is standalone, and while a marketplace contract can emit events that an NFT is sold, the royalty recipient might not be aware or watching the marketplace for a secondary sale of their NFT and therefore would never know they received a payment except for having an increased amount of ETH or ERC20 tokens in their wallet randomly. Watching for a royalty event only on the contract of the NFT being sold is an easy way for the recipient to check on payments received by their secondary sales without needing to watch every marketplace contract in existence. - -### Structure of the RoyaltiesReceived event - -The `RoyaltiesReceived` event will help future-proof this standard and allow potential enhancements in future EIPs. - -`royaltyRecipient` allows multiple royalty recipients to exist in the same ERC-721 contract, and indexing it allows a receiver to track payments to themselves easily. - -`buyer` enables tracking specific buyers of NFTs for analytics purposes. - -`tokenId` allows easy tracking of specific NFT sales. - -`tokenPaid` enables ERC-20 tokens to be used in addition to native ETH. - -`metadata` helps more advanced use-cases, perhaps described in future EIPs. `onRoyaltiesReceived()` is assumed to be called within the same transaction of the royalty payment, making the knowledge of the transaction hash and total amount of the sale easy to know. But if there are many small sales, sending many tiny transfers of ERC-20 tokens and calling `onRoyaltiesReceived()` for each could get expensive. This field could potentially enable a batched payment standard (monthly, quarterly, etc.), with some sort of data stored here that helps identify which sales this payment was for. - - -## Backwards Compatibility - -This standard is completely compatible with current ERC-721 standards - in fact it requires it. - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard. - -## 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-2981.md diff --git a/EIPS/eip-2982.md b/EIPS/eip-2982.md index 3deec8f744e4f9..6a6d00063329d7 100644 --- a/EIPS/eip-2982.md +++ b/EIPS/eip-2982.md @@ -1,28 +1,25 @@ --- 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: Review +status: Final type: Informational created: 2020-09-15 --- -## Simple Summary - -Serenity, aka eth2, is the [long-planned](https://blog.ethereum.org/2015/03/03/ethereum-launch-process) upgrade of Ethereum to a scalable, proof-of-stake (PoS) consensus. Specifications, development, and releases are divided into phases to iteratively manage the complexity of the upgrade. This EIP addresses Phase 0 of the release schedule. - -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. - ## 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](https://github.com/ethereum/eth2.0-specs) from this EIP, and safety and liveness proofs can be found in the [Combining GHOST and Casper](https://arxiv.org/abs/2003.03052) paper. To avoid duplication, this EIP just references relevant spec files and releases. +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](https://blog.ethereum.org/2015/03/03/ethereum-launch-process/) of Ethereum to support an efficient, global-scale, general-purpose transactional platform while retaining high cryptoeconomic security and decentralization. +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. @@ -34,26 +31,23 @@ As the Ethereum network and the applications built upon it have seen increasing 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. -See the [Ethereum wiki sharding FAQ](https://eth.wiki/sharding/Sharding-FAQs) for an excellent introduction and discussion of scaling through sharding. - ### Decentralization and economic finality through proof-of-stake -Since the [early days](https://blog.ethereum.org/2015/12/28/understanding-serenity-part-2-casper/) of Ethereum, proof-of-stake has been a long-awaited desideratum for the following: +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"](https://eth.wiki/sharding/Sharding-FAQs#how-do-you-actually-do-this-sampling-in-proof-of-work-and-in-proof-of-stake) than PoW and thus allows for a more direct sharded protocol construction. +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. -See the [Ethereum wiki proof-of-stake FAQ](https://eth.wiki/en/concepts/proof-of-stake-faqs) for an excellent introduction and discussion of proof-of-stake consensus. ## Specification -Phase 0 is designed to require _no breaking consensus changes_ to existing Ethereum mainnet. Instead, this is the bootstraping a new PoS consensus that can, once stable, supplant the current PoW consensus. +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](https://github.com/ethereum/eth2.0-specs) independent of this EIP. `SPEC_RELEASE_VERSION` release (TBD) of the specs at `SPEC_RELEASE_COMMIT` are considered the canonical Phase 0 specs for this EIP. +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 [specs repository](https://github.com/ethereum/eth2.0-specs). +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 @@ -68,42 +62,31 @@ This EIP provides a high level view on the Phase 0 mechanisms, especially those | `PROPORTIONAL_SLASHING_MULTIPLIER` | `1` | | `MIN_SLASHING_PENALTY_QUOTIENT` | `2**7` (128) | -_Note:_ Eth2 has many more [Phase 0 configuration parameters](https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/configs/mainnet/phase0.yaml) but the majority are left out of this EIP for brevity. +_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](https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/deposit-contract.md) -- at `DEPOSIT_CONTRACT_ADDRESS` to onboard validators into the PoS consensus of the beacon chain. +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. -More on this mechanism: -* [Deposit Contract](https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/deposit-contract.md) -* [Beacon Chain -- `Deposit` processing](https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#deposits) -* [Validator -- Becoming a validator](https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/validator.md#becoming-a-validator) - ### Beacon chain and validator mechanics -Users who choose to participate in eth2 consensus deposit ETH collateral into the [deposit contract](https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/deposit-contract.md) 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). +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"). -More on the beacon chain and validator mechanics: -* [Beacon Chain -- State transition function](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/beacon-chain.md#beacon-chain-state-transition-function) -* [Beacon chain -- Operations](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/beacon-chain.md#operations) -* [Beacon chain -- Rewards and Penalties](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/beacon-chain.md#rewards-and-penalties-1) -* [Validator -- Beacon chain responsibilities](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/validator.md#beacon-chain-responsibilities) - ### 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](https://github.com/ethereum/research/blob/master/papers/discouragement/discouragement.pdf). +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. -![](https://storage.googleapis.com/ethereum-hackmd/upload_953c502d09928c0b306cc078268945c1.png) +![](../assets/eip-2982/2982-issuance.png) | Active Deposits | Max Annual Validator Reward\* | Max Annual ETH Issued\* | | -------- | -------: | --------: | @@ -119,11 +102,9 @@ In eth2, this curve is parameterized by `BASE_REWARD_FACTOR` in the context of s _\*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._ -For more details, see this [eth2 calculator](https://docs.google.com/spreadsheets/d/15tmPOvOgi3wKxJw7KQJKoUe-uonbYR6HF7u83LR5Mj4/edit#gid=842896204) maintained by _ConsenSys Activate_. - ### Initial punitive parameters -For PoS protocols to be crypto-economically secure, in-protocol penalties are required (see discussion of ["Nothing at Stake"](https://blog.ethereum.org/2014/11/25/proof-stake-learned-love-weak-subjectivity/)). Small offline penalties incentivize validator liveness, whereas (potentially) much larger penalties provide protocol security in the event of tail-risk scenarios. +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. @@ -137,58 +118,326 @@ _`PROPORTIONAL_SLASHING_MULTIPLIER` is configured initially to one-third of its _`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. -___A hard fork of the eth2 beacon chain is planned for 5 months after genesis. This hard fork will adjust `INACTIVITY_PENALTY_QUOTIENT`, `PROPORTIONAL_SLASHING_MULTIPLIER`, and `MIN_SLASHING_PENALTY_QUOTIENT` to their final, more secure values.___ - ## Rationale -For details regarding specification design rationale and decisions, see the following: -* [Serenity Design Rationale](https://notes.ethereum.org/@vbuterin/rkhCgQteN) -* [Ben Edgington's Eth2 Annotated Spec](https://benjaminion.xyz/eth2-annotated-spec/) -* [Vitalik Buterin's Eth2 Annotated Spec](https://github.com/ethereum/annotated-spec/blob/master/phase0/beacon-chain.md) +### Principles -## Backwards Compatibility +* **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) -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. +### The Layer 1 vs Layer 2 Tradeoff -## Implementation +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 following implementations of eth2 Phase 0 exist. At the time of writing at least five are near production-ready and in testnet/audit phase: +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. -* [Cortex](https://github.com/NethermindEth/cortex) (.net) -* [Lighthouse](https://github.com/sigp/lighthouse) (rust) -* [Lodestar](https://github.com/ChainSafe/lodestar) (javascript) -* [Nimbus](https://github.com/status-im/nim-beacon-chain) (nim) -* [Prysm](https://github.com/prysmaticlabs/prysm/) (go) -* [Teku](https://github.com/pegasyseng/teku) (java) -* [Trinity](https://github.com/ethereum/trinity/) (python) +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. -In addition to implementations of the spec, the deposit contract is [implemented in Solidity](), along with a [formal verification](https://github.com/runtimeverification/verified-smart-contracts/blob/master/deposit/deposit-formal-verification.pdf) of the bytecode. +### Why proof of stake -## Security Considerations +In short: -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:_ +* **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". -* [Casper FFG](https://arxiv.org/abs/1710.09437) -* [Combining GHOST and Casper](https://arxiv.org/abs/2003.03052) -* [Sharding FAQ](https://eth.wiki/sharding/Sharding-FAQs) -* [PoS FAQ](https://eth.wiki/en/concepts/proof-of-stake-faqs) -* [Eth2 research compendium](https://notes.ethereum.org/@serenity/H1PGqDhpm?type=view) +### Why Casper -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._ +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 dury 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. -* [Eth2 Phase 0 Spec audit by Least Authority](https://leastauthority.com/blog/ethereum-2-0-specifications/) -* [Gossipsub v1.1 audit by Least Authority](https://leastauthority.com/blog/audit-of-gossipsub-v1-1-protocol-design-implementation-for-protocol-labs/) -* [Discv5 audit by Least Authority](https://leastauthority.com/blog/audit-of-gossipsub-v1-1-protocol-design-implementation-for-protocol-labs/) -* [Formal Verification of Finality in eth2 by Runtime Verification](https://runtimeverification.com/blog/formally-verifying-finality-in-gasper-the-core-of-the-beacon-chain/) -* [Formal Verification of Deposit Contract by Runtime Verification](https://github.com/runtimeverification/deposit-contract-verification/blob/master/deposit-contract-verification.pdf) -* [Prysm client audit by Quantstamp](https://quantstamp.com/blog/ethereum-2-0-moves-closer-to-launch-with-quantstamp-audit-of-prysm) and [the results](https://medium.com/prysmatic-labs/quantstamp-security-audit-results-for-the-prysm-eth2-client-7f949c6c866f) -* [Lodestar utility libraries audit by Least Authority](https://leastauthority.com/blog/audit-of-chainsafe-utility-libraries/) +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: -Finally, the EF maintains bounty programs for the eth2 spec, attacknets, and clients. +$$\omega \ge \frac{2 * n}{f}$$ -* [Eth2 Phase 0 bug bounty program](https://notes.ethereum.org/@djrtwo/phase0-bounty) -* [Eth2 public attacknets](https://github.com/ethresearch/public-attacknets) -* _Eth2 Client Bounty Program to be released soon_ +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 do 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2997.md b/EIPS/eip-2997.md index 13197c2f4e0d90..ee1152b5406c89 100644 --- a/EIPS/eip-2997.md +++ b/EIPS/eip-2997.md @@ -5,7 +5,7 @@ author: Sergio Demian Lerner (@SergioDemianLerner) discussions-to: https://ethresear.ch/t/impersonatecall-opcode/8020 category: Core type: Standards Track -status: Draft +status: Stagnant created: 2020-09-24 --- @@ -100,4 +100,4 @@ The address derivation scheme prevents address collision with another deployed c ## 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-3000.md b/EIPS/eip-3000.md index 9f3f17c5799725..fd185a40d8b10d 100644 --- a/EIPS/eip-3000.md +++ b/EIPS/eip-3000.md @@ -1,154 +1,7 @@ --- eip: 3000 -title: Optimistic enactment governance standard -author: Jorge Izquierdo (@izqui), Fabien Marino (@bonustrack) -discussions-to: https://github.com/ethereum/EIPs/issues/3042 -status: Draft -type: Standards Track category: ERC -created: 2020-09-24 +status: Moved --- -## Simple Summary - -Interface for scheduling, executing and challenging contract executions based on off-chain approval - -## Abstract - -ERC-3000 presents a basic on-chain spec for contracts to optimistically enact governance decisions made off-chain. - -The standard is opinionated in defining the 6 entrypoint functions to contracts supporting the standard. But it allows for any sort of resolver mechanism for the challenge/response games characteristic of optimistic contracts. - -While the authors currently believe resolving challenges [using a subjective oracle](https://aragon.org/blog/snapshot) is the right tradeoff, the standard has been designed such that changing to another mechanism is possible (a deterministic resolver like [Optimism's OVM](https://optimism.io) uses), even allowing to hot-swap it in the same live instance. - -## Specification - -### Data structures - -Some data structures are defined which are later used in the standard interfaces: - -```solidity -library ERC3000Data { - struct Container { - Payload payload; - Config config; - } - - struct Payload { - uint256 nonce; - uint256 executionTime; - address submitter; - IERC3000Executor executor; - Action[] actions; - bytes proof; - } - - struct Action { - address to; - uint256 value; - bytes data; - } - - struct Config { - uint256 executionDelay; - Collateral scheduleDeposit; - Collateral challengeDeposit; - Collateral vetoDeposit; - address resolver; - bytes rules; - } - - struct Collateral { - address token; - uint256 amount; - } -} -``` - -### Interface and events - -Given the data structures above, by taking advantage of the Solidity ABI encoder v2, we define four required functions and two optional functions as the interface for contracts to comply with ERC-3000. - -All standard functions are expected to revert (whether to include error messages/revert reasons as part of the standard is yet to be determined) when pre-conditions are not met or an unexpected error occurs. On success, each function must emit its associated event once and only once. - -```solidity -abstract contract IERC3000 { - /** - * @notice Schedules an action for execution, allowing for challenges and vetos on a defined time window - * @param container A Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - */ - function schedule(ERC3000Data.Container memory container) virtual public returns (bytes32 containerHash); - event Scheduled(bytes32 indexed containerHash, ERC3000Data.Payload payload, ERC3000Data.Collateral collateral); - - /** - * @notice Executes an action after its execution delayed has passed and its state hasn't been altered by a challenge or veto - * @param container A ERC3000Data.Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - * should be a MUST payload.executor.exec(payload.actions) - */ - function execute(ERC3000Data.Container memory container) virtual public returns (bytes[] memory execResults); - event Executed(bytes32 indexed containerHash, address indexed actor, bytes[] execResults); - - /** - * @notice Challenge a container in case its scheduling is illegal as per Config.rules. Pulls collateral and dispute fees from sender into contract - * @param container A ERC3000Data.Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - * @param reason Hint for case reviewers as to why the scheduled container is illegal - */ - function challenge(ERC3000Data.Container memory container, bytes memory reason) virtual public returns (uint256 resolverId); - event Challenged(bytes32 indexed containerHash, address indexed actor, bytes reason, uint256 resolverId, ERC3000Data.Collateral collateral); - - /** - * @notice Apply arbitrator's ruling over a challenge once it has come to a final ruling - * @param container A ERC3000Data.Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - * @param resolverId disputeId in the arbitrator in which the dispute over the container was created - */ - function resolve(ERC3000Data.Container memory container, uint256 resolverId) virtual public returns (bytes[] memory execResults); - event Resolved(bytes32 indexed containerHash, address indexed actor, bool approved); - - /** - * @dev OPTIONAL - * @notice Apply arbitrator's ruling over a challenge once it has come to a final ruling - * @param payloadHash Hash of the payload being vetoed - * @param config A ERC3000Data.Config struct holding the config attached to the payload being vetod - */ - function veto(bytes32 payloadHash, ERC3000Data.Config memory config, bytes memory reason) virtual public; - event Vetoed(bytes32 indexed containerHash, address indexed actor, bytes reason, ERC3000Data.Collateral collateral); - - /** - * @dev OPTIONAL: implementer might choose not to implement (initial Configured event MUST be emitted) - * @notice Apply a new configuration for all *new* containers to be scheduled - * @param config A ERC3000Data.Config struct holding all the new params that will control the queue - */ - function configure(ERC3000Data.Config memory config) virtual public returns (bytes32 configHash); - event Configured(bytes32 indexed containerHash, address indexed actor, ERC3000Data.Config config); -} -``` - -## Rationale - -The authors believe that it is very important that this standard leaves the other open to any resolver mechanism to be implemented and adopted. - -That's why a lot of the function and variable names were left intentionally bogus to be compatible with future resolvers without changing the standard. - -ERC-3000 should be seen as a public good of top of which public infrastrastructure will be built, being way more important than any particular implementation or the interests of specific companies or projects. - -## Security Considerations - -The standard allows for the resolver for challenges to be configured, and even have different resolvers for coexisting scheduled payloads. Choosing the right resolver requires making the right tradeoff between security, time to finality, implementation complexity, and external dependencies. - -Using a subjective oracle as resolver has its risks, since security depends on the crypto-economic properties of the system. For an analysis of crypto-economic considerations of Aragon Court, you can check [the following doc](https://github.com/aragon/aragon-court/tree/master/docs/3-cryptoeconomic-considerations). - -On the other hand, implementing a deterministic resolver is prone to dangerous bugs given its complexity, and will rely on a specific version of the off-chain protocol, which could rapidly evolve while the standard matures and gets adopted. - -## Implementations - -### 1. Aragon Govern - -- [ERC-3000 interface (MIT license)](https://github.com/aragon/govern/blob/master/packages/erc3k) -- [Implementation (GPL-3.0 license)](https://github.com/aragon/govern/blob/master/packages/govern-core) - -## 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-3000.md diff --git a/EIPS/eip-3005.md b/EIPS/eip-3005.md index 58c8b85e9f63ee..1b8dc33c0f8ba9 100644 --- a/EIPS/eip-3005.md +++ b/EIPS/eip-3005.md @@ -1,416 +1,7 @@ --- eip: 3005 -title: Batched meta transactions -author: Matt (@defifuture) -discussions-to: https://ethereum-magicians.org/t/eip-3005-the-economic-viability-of-batched-meta-transactions/4673 -status: Draft -type: Standards Track category: ERC -created: 2020-09-25 +status: Moved --- -## Simple Summary - -Defines an extension function for ERC-20 (and other fungible token standards), which allows receiving and processing a batch of meta transactions. - -## Abstract - -This EIP defines a new function called `processMetaBatch()` that extends any fungible token standard, and enables batched meta transactions coming from many senders in one on-chain transaction. - -The function must be able to receive multiple meta transactions data and process it. This means validating the data and the signature, before proceeding with token transfers based on the data. - -The function enables senders to make gasless transactions, while reducing the relayer's gas cost due to batching. - -## Motivation - -Meta transactions have proven useful as a solution for Ethereum accounts that don't have any ether, but hold ERC-20 tokens and would like to transfer them (gasless transactions). - -The current meta transaction relayer implementations only allow relaying one meta transaction at a time. Some also allow batched meta transactions from the same sender. But none offers batched meta transactions from **multiple** senders. - -The motivation behind this EIP is to find a way to allow relaying batched meta transactions from **many senders** in **one on-chain transaction**, which also **reduces the total gas cost** that a relayer needs to cover. - -![](../assets/eip-3005/meta-txs-directly-to-token-smart-contract.png) - -## 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. - -The key words "MUST (BUT WE KNOW YOU WON'T)", "SHOULD CONSIDER", "REALLY SHOULD NOT", "OUGHT TO", "WOULD PROBABLY", "MAY WISH TO", "COULD", "POSSIBLE", and "MIGHT" in this document are to be interpreted as described in RFC 6919. - -### Meta transaction data - -In order to successfully validate and transfer tokens, the `processMetaBatch()` function MUST process the following data about a meta transaction: - -- sender address -- receiver address -- token amount -- relayer fee -- a (meta tx) nonce -- an expiration date (this COULD be a block number, or it COULD be a block timestamp) -- a token address -- a relayer address -- a signature - -Not all of the data needs to be sent to the function by the relayer (see the function interface specification). Some of the data can be deduced or extracted from other sources (from transaction data and contract state). - -### `processMetaBatch()` function input data - -The `processMetaBatch()` function MUST receive the following data: - -- sender address -- receiver address -- token amount -- relayer fee -- an expiration date (this COULD be a block number, or it COULD be a block timestamp) -- a signature - -The following data is OPTIONAL to be sent to the function, because it can be extracted or derived from other sources: - -- a (meta tx) nonce -- a token address -- a relayer address - -### Meta transaction data hash - -The pseudocode for creating a hash of meta transaction data is the following: - -``` -keccak256(address(sender) - ++ address(recipient) - ++ uint256(amount) - ++ uint256(relayerFee) - ++ uint256(nonce) - ++ uint256(expirationDate) - ++ address(tokenContract) - ++ address(relayer) -) -``` - -The created hash MUST then be signed with the sender's private key. - -### Validation rules - -- Nonce of a new transaction MUST always be bigger by exactly 1 from the nonce of the last successfully processed meta transaction of the same sender to the same token contract. -- Sending to and from a 0x0 address MUST be prohibited. -- A meta transaction MUST be processed before the expiration date. -- Each sender's token balance MUST be equal or greater than the sum of their respective meta transaction token amount and relayer fee. -- A transaction where at least one meta transaction in the batch does not satisfy the above requirements MUST not be reverted. Instead, a failed meta transaction MUST be skipped or ignored. - -### `processMetaBatch()` function interface - -The `processMetaBatch()` function MUST have the following interface: - -```solidity -function processMetaBatch(address[] memory senders, - address[] memory recipients, - uint256[] memory amounts, - uint256[] memory relayerFees, - uint256[] memory blocks, - uint8[] memory sigV, - bytes32[] memory sigR, - bytes32[] memory sigS) public returns (bool); -``` - -The overview of parameters that are passed: - -- `senders`: an array of meta transaction sender addresses (token senders) -- `recipients `: an array of token recipients addresses -- `amounts`: an array of token amounts that are sent from each sender to each recipient, respectively -- `relayerFees`: an array of the relayer fees paid in tokens by senders. The fee receiver is a relayer (`msg.address`) -- `blocks`: an array of block numbers that represent an expiration date by which the meta transaction must be processed (alternatively, a timestamp could be used instead of a block number) -- `sigV`, `sigR`, `sigS`: three arrays that represent parts of meta transaction signatures - -Each entry in each of the arrays MUST represent data from one meta transaction. The order of the data is very important. Data from a single meta transaction MUST have the same index in every array. - -### Meta transaction nonce - -The token smart contract must keep track of a meta transaction nonce for each token holder. - -```solidity -mapping (address => uint256) private _metaNonces; -``` - -The interface for the `nonceOf()` function is the following: - -```solidity -function nonceOf(address account) public view returns (uint256); -``` - -### Token transfers - -After a meta transaction is successfully validated, the meta nonce of the meta transaction sender MUST be increased by 1. - -Then two token transfers MUST occur: - -- The specified token amount MUST go to the recipient. -- The relayer fee MUST go to the relayer (`msg.sender`). - -## Implementation - -The **reference implementation** adds a couple of functions to the existing ERC-20 token standard: - -- `processMetaBatch()` -- `nonceOf()` - -You can see the implementation of both functions in this file: [ERC20MetaBatch.sol](https://github.com/defifuture/erc20-batched-meta-transactions/blob/master/contracts/ERC20MetaBatch.sol). This is an extended ERC-20 contract with added meta transaction batch transfer capabilities. - -### `processMetaBatch()` - -The `processMetaBatch()` function is responsible for receiving and processing a batch of meta transactions that change token balances. - -```solidity -function processMetaBatch(address[] memory senders, - address[] memory recipients, - uint256[] memory amounts, - uint256[] memory relayerFees, - uint256[] memory blocks, - uint8[] memory sigV, - bytes32[] memory sigR, - bytes32[] memory sigS) public returns (bool) { - - address sender; - uint256 newNonce; - uint256 relayerFeesSum = 0; - bytes32 msgHash; - uint256 i; - - // loop through all meta txs - for (i = 0; i < senders.length; i++) { - sender = senders[i]; - newNonce = _metaNonces[sender] + 1; - - if(sender == address(0) || recipients[i] == address(0)) { - continue; // sender or recipient is 0x0 address, skip this meta tx - } - - // the meta tx should be processed until (including) the specified block number, otherwise it is invalid - if(block.number > blocks[i]) { - continue; // if current block number is bigger than the requested number, skip this meta tx - } - - // check if meta tx sender's balance is big enough - if(_balances[sender] < (amounts[i] + relayerFees[i])) { - continue; // if sender's balance is less than the amount and the relayer fee, skip this meta tx - } - - // check if the signature is valid - msgHash = keccak256(abi.encode(sender, recipients[i], amounts[i], relayerFees[i], newNonce, blocks[i], address(this), msg.sender)); - if(sender != ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)), sigV[i], sigR[i], sigS[i])) { - continue; // if sig is not valid, skip to the next meta tx - } - - // set a new nonce for the sender - _metaNonces[sender] = newNonce; - - // transfer tokens - _balances[sender] -= (amounts[i] + relayerFees[i]); - _balances[recipients[i]] += amounts[i]; - relayerFeesSum += relayerFees[i]; - } - - // give the relayer the sum of all relayer fees - _balances[msg.sender] += relayerFeesSum; - - return true; -} -``` - -### `nonceOf()` - -Nonces are needed due to the replay protection (see *Replay attacks* under *Security Considerations*). - -```solidity -mapping (address => uint256) private _metaNonces; - -// ... - -function nonceOf(address account) public view returns (uint256) { - return _metaNonces[account]; -} -``` - -The link to the complete implementation (along with gas usage results) is here: [https://github.com/defifuture/erc20-batched-meta-transactions](https://github.com/defifuture/erc20-batched-meta-transactions). - -> Note that the OpenZeppelin ERC-20 implementation was used here. Some other implementation may have named the `_balances` mapping differently, which would require minor changes in the `processMetaBatch()` function. - -## Rationale - -### All-in-one - -Alternative implementations (like GSN) use multiple smart contracts to enable meta transactions, although this increases gas usage. This implementation (EIP-3005) intentionally keeps everything within one function which reduces complexity and gas cost. - -The `processMetaBatch()` function thus does the job of receiving a batch of meta transactions, validating them, and then transferring tokens from one address to another. - -### Function parameters - -As you can see, the `processMetaBatch()` function in the reference implementation takes the following parameters: - -- an array of **sender addresses** (meta txs senders, not relayers) -- an array of **receiver addresses** -- an array of **amounts** -- an array of **relayer fees** (relayer is `msg.sender`) -- an array of **block numbers** (a due "date" for meta tx to be processed) -- Three arrays that represent parts of a **signature** (v, r, s) - -**Each item** in these arrays represents **data of one meta transaction**. That's why the **correct order** in the arrays is very important. - -If a relayer gets the order wrong, the `processMetaBatch()` function would notice that (when validating a signature), because the hash of the meta transaction values would not match the signed hash. A meta transaction with an invalid signature is **skipped**. - -### The alternative way of passing meta transaction data into the function - -The reference implementation takes parameters as arrays. There's a separate array for each meta transaction data category (the ones that cannot be deduced or extracted from other sources). - -A different approach would be to bitpack all data of a meta transaction into one value and then unpack it within the smart contract. The data for a batch of meta transactions would be sent in an array, but there would need to be only one array (of packed data), instead of multiple arrays. - -### Why is nonce not one of the parameters in the reference implementation? - -Meta nonce is used for constructing a signed hash (see the `msgHash` line where a `keccak256` hash is constructed - you'll find a nonce there). - -Since a new nonce has to always be bigger than the previous one by exactly 1, there's no need to include it as a parameter array in the `processMetaBatch()` function, because its value can be deduced. - -This also helps avoid the "Stack too deep" error. - -### Can EIP-2612 nonces mapping be re-used? - -The EIP-2612 (`permit()` function) also requires a nonce mapping. At this point, I'm not sure yet if this mapping should be **re-used** in case a smart contract implements both EIP-3005 and EIP-2612. - -At the first glance, it seems the `nonces` mapping from EIP-2612 could be re-used, but this should be thought through (and tested) for possible security implications. - -### Token transfers - -Token transfers in the reference implementation could alternatively be done by calling the `_transfer()` function (part of the OpenZeppelin ERC-20 implementation), but it would increase the gas usage and it would also revert the whole batch if some meta transaction was invalid (the current implementation just skips it). - -Another gas usage optimization is to assign total relayer fees to the relayer at the end of the function, and not with every token transfer inside the for loop (thus avoiding multiple SSTORE calls that cost 5'000 gas). - -## Backwards Compatibility - -The code implementation of batched meta transactions is backwards compatible with any fungible token standard, for example, ERC-20 (it only extends it with one function). - -## Test Cases - -Link to tests: [https://github.com/defifuture/erc20-batched-meta-transactions/tree/master/test](https://github.com/defifuture/erc20-batched-meta-transactions/tree/master/test). - -## Security Considerations - -Here is a list of potential security issues and how are they addressed in this implementation. - -### Forging a meta transaction - -The solution against a relayer forging a meta transaction is for a user to sign the meta transaction with their private key. - -The `processMetaBatch()` function then verifies the signature using `ecrecover()`. - -### Replay attacks - -The `processMetaBatch()` function is secure against two types of a replay attack: - -**Using the same meta transaction twice in the same token smart contract** - -A nonce prevents a replay attack where a relayer would send the same meta transaction more than once. - -**Using the same meta transaction twice in different token smart contracts** - -A token smart contract address must be added into the signed hash (of a meta transaction). - -This address does not need to be sent as a parameter into the `processMetaBatch()` function. Instead, the function uses `address(this)` when constructing a hash in order to verify the signature. This way a meta transaction not intended for the token smart contract would be rejected (skipped). - -### Signature validation - -Signing a meta transaction and validating the signature is crucial for this whole scheme to work. - -The `processMetaBatch()` function validates a meta transaction signature, and if it's **invalid**, the meta transaction is **skipped** (but the whole on-chain transaction is **not reverted**). - -```solidity -msgHash = keccak256(abi.encode(sender, recipients[i], amounts[i], relayerFees[i], newNonce, blocks[i], address(this), msg.sender)); - -if(sender != ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)), sigV[i], sigR[i], sigS[i])) { - continue; // if sig is not valid, skip to the next meta tx -} -``` - -Why not reverting the whole on-chain transaction? Because there could be only one problematic meta transaction, and the others should not be dropped just because of one rotten apple. - -That said, it is expected of relayers to validate meta transactions in advance before relaying them. That's why relayers are not entitled to a relayer fee for an invalid meta transaction. - -### Malicious relayer forcing a user into over-spending - -A malicious relayer could delay sending some user's meta transaction until the user would decide to make the token transaction on-chain. - -After that, the relayer would relay the delayed meta transaction which would mean that the user would have made two token transactions (over-spending). - -**Solution:** Each meta transaction should have an "expiry date". This is defined in a form of a block number by which the meta transaction must be relayed on-chain. - -```solidity -function processMetaBatch(... - uint256[] memory blocks, - ...) public returns (bool) { - - //... - - // loop through all meta txs - for (i = 0; i < senders.length; i++) { - - // the meta tx should be processed until (including) the specified block number, otherwise it is invalid - if(block.number > blocks[i]) { - continue; // if current block number is bigger than the requested number, skip this meta tx - } - - //... -``` - -### Front-running attack - -A malicious relayer could scout the Ethereum mempool to steal meta transactions and front-run the original relayer. - -**Solution:** The protection that `processMetaBatch()` function uses is that it requires the meta transaction sender to add the relayer's Ethereum address as one of the values in the hash (which is then signed). - -When the `processMetaBatch()` function generates a hash it includes the `msg.sender` address in it: - -```solidity -msgHash = keccak256(abi.encode(sender, recipients[i], amounts[i], relayerFees[i], newNonce, blocks[i], address(this), msg.sender)); - -if(sender != ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)), sigV[i], sigR[i], sigS[i])) { - continue; // if sig is not valid, skip to the next meta tx -} -``` - -If the meta transaction was "stolen", the signature check would fail because the `msg.sender` address would not be the same as the intended relayer's address. - -### A malicious (or too impatient) user sending a meta transaction with the same nonce through multiple relayers at once - -A user that is either malicious or just impatient could submit a meta transaction with the same nonce (for the same token contract) to various relayers. Only one of them would get the relayer fee (the first one on-chain), while the others would get an invalid meta transaction. - -**Solution:** Relayers could **share a list of their pending meta transactions** between each other (sort of an info mempool). - -The relayers don't have to fear that someone would steal their respective pending transactions, due to the front-running protection (see above). - -If relayers see meta transactions from a certain sender address that have the same nonce and are supposed to be relayed to the same token smart contract, they can decide that only the first registered meta transaction goes through and others are dropped (or in case meta transactions were registered at the same time, the remaining meta transaction could be randomly picked). - -At a minimum, relayers need to share this meta transaction data (in order to detect meta transaction collision): - -- sender address -- token address -- nonce - -### Too big due block number - -The relayer could trick the meta transaction sender into adding too big due block number - this means a block by which the meta transaction must be processed. The block number could be far in the future, for example, 10 years in the future. This means that the relayer would have 10 years to submit the meta transaction. - -**One way** to solve this problem is by adding an upper bound constraint for a block number within the smart contract. For example, we could say that the specified due block number must not be bigger than 100'000 blocks from the current one (this is around 17 days in the future if we assume 15 seconds block time). - -```solidity -// the meta tx should be processed until (including) the specified block number, otherwise it is invalid -if(block.number > blocks[i] || blocks[i] > (block.number + 100000)) { - // If current block number is bigger than the requested due block number, skip this meta tx. - // Also skip if the due block number is too big (bigger than 100'000 blocks in the future). - continue; -} -``` - -This addition could open new security implications, that's why it is left out of this proof-of-concept. But anyone who wishes to implement it should know about this potential constraint, too. - -**The other way** is to keep the `processMetaBatch()` function as it is and rather check for the too big due block number **on the relayer level**. In this case, the user could be notified about the problem and could issue a new meta transaction with another relayer that would have a much lower block parameter (and the same nonce). - -## Copyright - -Copyright and related rights are 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-3005.md diff --git a/EIPS/eip-3009.md b/EIPS/eip-3009.md index 588a4a3bb257ff..66ff691c786e23 100644 --- a/EIPS/eip-3009.md +++ b/EIPS/eip-3009.md @@ -1,536 +1,7 @@ --- eip: 3009 -title: Transfer With Authorization -author: Peter Jihoon Kim (@petejkim), Kevin Britz (@kbrizzle), David Knott (@DavidLKnott) -discussions-to: https://github.com/ethereum/EIPs/issues/3010 -status: Draft -type: Standards Track category: ERC -created: 2020-09-28 -requires: 20, 712 +status: Moved --- -## Simple Summary - -A contract interface that enables transferring of fungible assets via a signed authorization. - -## Abstract - -A set of functions to enable meta-transactions and atomic interactions with [ERC-20](./eip-20.md) token contracts via signatures conforming to the [EIP-712](./eip-712.md) typed message signing specification. - -This enables the user to: - -- delegate the gas payment to someone else, -- pay for gas in the token itself rather than in ETH, -- perform one or more token transfers and other operations in a single atomic transaction, -- transfer ERC-20 tokens to another address, and have the recipient submit the transaction, -- batch multiple transactions with minimal overhead, and -- create and perform multiple transactions without having to worry about them failing due to accidental nonce-reuse or improper ordering by the miner. - -## Motivation - -There is an existing spec, [EIP-2612](./eip-2612), that also allows meta-transactions, and it is encouraged that a contract implements both for maximum compatibility. The two primary differences between this spec and EIP-2612 are that: - -- EIP-2612 uses sequential nonces, but this uses random 32-byte nonces, and that -- EIP-2612 relies on the ERC-20 `approve`/`transferFrom` ("ERC-20 allowance") pattern. - -The biggest issue with the use of sequential nonces is that it does not allow users to perform more than one transaction at time without risking their transactions failing, because: - -- DApps may unintentionally reuse nonces that have not yet been processed in the blockchain. -- Miners may process the transactions in the incorrect order. - -This can be especially problematic if the gas prices are very high and transactions often get queued up and remain unconfirmed for a long time. Non-sequential nonces allow users to create as many transactions as they want at the same time. - -The ERC-20 allowance mechanism is susceptible to the [multiple withdrawal attack](https://blockchain-projects.readthedocs.io/multiple_withdrawal.html)/[SWC-114](https://swcregistry.io/docs/SWC-114), and encourages antipatterns such as the use of the "infinite" allowance. The wide-prevalence of upgradeable contracts have made the conditions favorable for these attacks to happen in the wild. - -The deficiencies of the ERC-20 allowance pattern brought about the development of alternative token standards such as the [ERC-777](./eip-777) and [ERC-677](https://github.com/ethereum/EIPs/issues/677). However, they haven't been able to gain much adoption due to compatibility and potential security issues. - -## Specification - -### Event - -```solidity -event AuthorizationUsed( - address indexed authorizer, - bytes32 indexed nonce -); - -// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") -bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; - -// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") -bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; - -/** - * @notice Returns the state of an authorization - * @dev Nonces are randomly generated 32-byte data unique to the authorizer's - * address - * @param authorizer Authorizer's address - * @param nonce Nonce of the authorization - * @return True if the nonce is used - */ -function authorizationState( - address authorizer, - bytes32 nonce -) external view returns (bool); - -/** - * @notice Execute a transfer with a signed authorization - * @param from Payer's address (Authorizer) - * @param to Payee's address - * @param value Amount to be transferred - * @param validAfter The time after which this is valid (unix time) - * @param validBefore The time before which this is valid (unix time) - * @param nonce Unique nonce - * @param v v of the signature - * @param r r of the signature - * @param s s of the signature - */ -function transferWithAuthorization( - address from, - address to, - uint256 value, - uint256 validAfter, - uint256 validBefore, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s -) external; - -/** - * @notice Receive a transfer with a signed authorization from the payer - * @dev This has an additional check to ensure that the payee's address matches - * the caller of this function to prevent front-running attacks. (See security - * considerations) - * @param from Payer's address (Authorizer) - * @param to Payee's address - * @param value Amount to be transferred - * @param validAfter The time after which this is valid (unix time) - * @param validBefore The time before which this is valid (unix time) - * @param nonce Unique nonce - * @param v v of the signature - * @param r r of the signature - * @param s s of the signature - */ -function receiveWithAuthorization( - address from, - address to, - uint256 value, - uint256 validAfter, - uint256 validBefore, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s -) external; -``` - -**Optional:** - -``` -event AuthorizationCanceled( - address indexed authorizer, - bytes32 indexed nonce -); - -// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") -bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; - -/** - * @notice Attempt to cancel an authorization - * @param authorizer Authorizer's address - * @param nonce Nonce of the authorization - * @param v v of the signature - * @param r r of the signature - * @param s s of the signature - */ -function cancelAuthorization( - address authorizer, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s -) external; -``` - - -The arguments `v`, `r`, and `s` must be obtained using the [EIP-712](./eip-712.md) typed message signing spec. - -**Example:** - -``` -DomainSeparator := Keccak256(ABIEncode( - Keccak256( - "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" - ), - Keccak256("USD Coin"), // name - Keccak256("2"), // version - 1, // chainId - 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 // verifyingContract -)) -``` - -With the domain separator, the typehash, which is used to identify the type of the EIP-712 message being used, and the values of the parameters, you are able to derive a Keccak-256 hash digest which can then be signed using the token holder's private key. - -**Example:** - -``` -// Transfer With Authorization -TypeHash := Keccak256( - "TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)" -) -Params := { From, To, Value, ValidAfter, ValidBefore, Nonce } - -// ReceiveWithAuthorization -TypeHash := Keccak256( - "ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)" -) -Params := { From, To, Value, ValidAfter, ValidBefore, Nonce } - -// CancelAuthorization -TypeHash := Keccak256( - "CancelAuthorization(address authorizer,bytes32 nonce)" -) -Params := { Authorizer, Nonce } -``` - -``` -// "‖" denotes concatenation. -Digest := Keecak256( - 0x1901 ‖ DomainSeparator ‖ Keccak256(ABIEncode(TypeHash, Params...)) -) - -{ v, r, s } := Sign(Digest, PrivateKey) -``` - -Smart contract functions that wrap `receiveWithAuthorization` call may choose to reduce the number of arguments by accepting the full ABI-encoded set of arguments for the `receiveWithAuthorization` call as a single argument of the type `bytes`. - -**Example:** - -```solidity -// keccak256("receiveWithAuthorization(address,address,uint256,uint256,uint256,bytes32,uint8,bytes32,bytes32)")[0:4] -bytes4 private constant _RECEIVE_WITH_AUTHORIZATION_SELECTOR = 0xef55bec6; - -function deposit(address token, bytes calldata receiveAuthorization) - external - nonReentrant -{ - (address from, address to, uint256 amount) = abi.decode( - receiveAuthorization[0:96], - (address, address, uint256) - ); - require(to == address(this), "Recipient is not this contract"); - - (bool success, ) = token.call( - abi.encodePacked( - _RECEIVE_WITH_AUTHORIZATION_SELECTOR, - receiveAuthorization - ) - ); - require(success, "Failed to transfer tokens"); - - ... -} -``` - -### Use with web3 providers - -The signature for an authorization can be obtained using a web3 provider with the `eth_signTypedData{_v4}` method. - -**Example:** - -```javascript -const data = { - types: { - EIP712Domain: [ - { name: "name", type: "string" }, - { name: "version", type: "string" }, - { name: "chainId", type: "uint256" }, - { name: "verifyingContract", type: "address" }, - ], - TransferWithAuthorization: [ - { name: "from", type: "address" }, - { name: "to", type: "address" }, - { name: "value", type: "uint256" }, - { name: "validAfter", type: "uint256" }, - { name: "validBefore", type: "uint256" }, - { name: "nonce", type: "bytes32" }, - ], - }, - domain: { - name: tokenName, - version: tokenVersion, - chainId: selectedChainId, - verifyingContract: tokenAddress, - }, - primaryType: "TransferWithAuthorization", - message: { - from: userAddress, - to: recipientAddress, - value: amountBN.toString(10), - validAfter: 0, - validBefore: Math.floor(Date.now() / 1000) + 3600, // Valid for an hour - nonce: Web3.utils.randomHex(32), - }, -}; - -const signature = await ethereum.request({ - method: "eth_signTypedData_v4", - params: [userAddress, JSON.stringify(data)], -}); - -const v = "0x" + signature.slice(130, 132); -const r = signature.slice(0, 66); -const s = "0x" + signature.slice(66, 130); -``` - -## Rationale - -### Unique Random Nonce, Instead of Sequential Nonce - -One might say transaction ordering is one reason why sequential nonces are preferred. However, sequential nonces do not actually help achieve transaction ordering for meta transactions in practice: - -- For native Ethereum transactions, when a transaction with a nonce value that is too-high is submitted to the network, it will stay pending until the transactions consuming the lower unused nonces are confirmed. -- However, for meta-transactions, when a transaction containing a sequential nonce value that is too high is submitted, instead of staying pending, it will revert and fail immediately, resulting in wasted gas. -- The fact that miners can also reorder transactions and include them in the block in the order they want (assuming each transaction was submitted to the network by different meta-transaction relayers) also makes it possible for the meta-transactions to fail even if the nonces used were correct. (e.g. User submits nonces 3, 4 and 5, but miner ends up including them in the block as 4,5,3, resulting in only 3 succeeding) -- Lastly, when using different applications simultaneously, in absence of some sort of an off-chain nonce-tracker, it is not possible to determine what the correct next nonce value is if there exists nonces that are used but haven't been submitted and confirmed by the network. -- Under high gas price conditions, transactions can often "get stuck" in the pool for a long time. Under such a situation, it is much more likely for the same nonce to be unintentionally reused twice. For example, if you make a meta-transaction that uses a sequential nonce from one app, and switch to another app to make another meta-transaction before the previous one confirms, the same nonce will be used if the app relies purely on the data available on-chain, resulting in one of the transactions failing. -- In conclusion, the only way to guarantee transaction ordering is for relayers to submit transactions one at a time, waiting for confirmation between each submission (and the order in which they should be submitted can be part of some off-chain metadata), rendering sequential nonce irrelevant. - -### Valid After and Valid Before - -- Relying on relayers to submit transactions for you means you may not have exact control over the timing of transaction submission. -- These parameters allow the user to schedule a transaction to be only valid in the future or before a specific deadline, protecting the user from potential undesirable effects that may be caused by the submission being made either too late or too early. - -### EIP-712 - -- EIP-712 ensures that the signatures generated are valid only for this specific instance of the token contract and cannot be replayed on a different network with a different chain ID. -- This is achieved by incorporating the contract address and the chain ID in a Keccak-256 hash digest called the domain separator. The actual set of parameters used to derive the domain separator is up to the implementing contract, but it is highly recommended that the fields `verifyingContract` and `chainId` are included. - -## Backwards Compatibility - -New contracts benefit from being able to directly utilize EIP-3009 in order to create atomic transactions, but existing contracts may still rely on the conventional ERC-20 allowance pattern (`approve`/`transferFrom`). - -In order to add support for EIP-3009 to existing contracts ("parent contract") that use the ERC-20 allowance pattern, a forwarding contract ("forwarder") can be constructed that takes an authorization and does the following: - -1. Extract the user and deposit amount from the authorization -2. Call `receiveWithAuthorization` to transfer specified funds from the user to the forwarder -3. Approve the parent contract to spend funds from the forwarder -4. Call the method on the parent contract that spends the allowance set from the forwarder -5. Transfer the ownership of any resulting tokens back to the user - -**Example:** - -```solidity -interface IDeFiToken { - function deposit(uint256 amount) external returns (uint256); - - function transfer(address account, uint256 amount) - external - returns (bool); -} - -contract DepositForwarder { - bytes4 private constant _RECEIVE_WITH_AUTHORIZATION_SELECTOR = 0xef55bec6; - - IDeFiToken private _parent; - IERC20 private _token; - - constructor(IDeFiToken parent, IERC20 token) public { - _parent = parent; - _token = token; - } - - function deposit(bytes calldata receiveAuthorization) - external - nonReentrant - returns (uint256) - { - (address from, address to, uint256 amount) = abi.decode( - receiveAuthorization[0:96], - (address, address, uint256) - ); - require(to == address(this), "Recipient is not this contract"); - - (bool success, ) = address(_token).call( - abi.encodePacked( - _RECEIVE_WITH_AUTHORIZATION_SELECTOR, - receiveAuthorization - ) - ); - require(success, "Failed to transfer to the forwarder"); - - require( - _token.approve(address(_parent), amount), - "Failed to set the allowance" - ); - - uint256 tokensMinted = _parent.deposit(amount); - require( - _parent.transfer(from, tokensMinted), - "Failed to transfer the minted tokens" - ); - - uint256 remainder = _token.balanceOf(address(this); - if (remainder > 0) { - require( - _token.transfer(from, remainder), - "Failed to refund the remainder" - ); - } - - return tokensMinted; - } -} -``` - -## Test Cases - -See [EIP3009.test.ts](https://github.com/CoinbaseStablecoin/eip-3009/blob/master/test/EIP3009.test.ts). - -## Implementation - -**EIP3009.sol** -```solidity -abstract contract EIP3009 is IERC20Transfer, EIP712Domain { - // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") - bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; - - // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") - bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; - - mapping(address => mapping(bytes32 => bool)) internal _authorizationStates; - - event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); - - string internal constant _INVALID_SIGNATURE_ERROR = "EIP3009: invalid signature"; - - function authorizationState(address authorizer, bytes32 nonce) - external - view - returns (bool) - { - return _authorizationStates[authorizer][nonce]; - } - - function transferWithAuthorization( - address from, - address to, - uint256 value, - uint256 validAfter, - uint256 validBefore, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s - ) external { - require(now > validAfter, "EIP3009: authorization is not yet valid"); - require(now < validBefore, "EIP3009: authorization is expired"); - require( - !_authorizationStates[from][nonce], - "EIP3009: authorization is used" - ); - - bytes memory data = abi.encode( - TRANSFER_WITH_AUTHORIZATION_TYPEHASH, - from, - to, - value, - validAfter, - validBefore, - nonce - ); - require( - EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, - "EIP3009: invalid signature" - ); - - _authorizationStates[from][nonce] = true; - emit AuthorizationUsed(from, nonce); - - _transfer(from, to, value); - } -} -``` - -**IERC20Transfer.sol** -```solidity -abstract contract IERC20Transfer { - function _transfer( - address sender, - address recipient, - uint256 amount - ) internal virtual; -} -``` - -**EIP712Domain.sol** -```solidity -abstract contract EIP712Domain { - bytes32 public DOMAIN_SEPARATOR; -} -``` - -**EIP712.sol** -```solidity -library EIP712 { - // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") - bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; - - function makeDomainSeparator(string memory name, string memory version) - internal - view - returns (bytes32) - { - uint256 chainId; - assembly { - chainId := chainid() - } - - return - keccak256( - abi.encode( - EIP712_DOMAIN_TYPEHASH, - keccak256(bytes(name)), - keccak256(bytes(version)), - address(this), - bytes32(chainId) - ) - ); - } - - function recover( - bytes32 domainSeparator, - uint8 v, - bytes32 r, - bytes32 s, - bytes memory typeHashAndData - ) internal pure returns (address) { - bytes32 digest = keccak256( - abi.encodePacked( - "\x19\x01", - domainSeparator, - keccak256(typeHashAndData) - ) - ); - address recovered = ecrecover(digest, v, r, s); - require(recovered != address(0), "EIP712: invalid signature"); - return recovered; - } -} -``` - -A fully working implementation of EIP-3009 can be found in [this repository](https://github.com/CoinbaseStablecoin/eip-3009/blob/master/contracts/lib/EIP3009.sol). The repository also includes [an implementation of EIP-2612](https://github.com/CoinbaseStablecoin/eip-3009/blob/master/contracts/lib/EI32612.sol) that uses the EIP-712 library code presented above. - -## Security Considerations - -Use `receiveWithAuthorization` instead of `transferWithAuthorization` when calling from other smart contracts. It is possible for an attacker watching the transaction pool to extract the transfer authorization and front-run the `transferWithAuthorization` call to execute the transfer without invoking the wrapper function. This could potentially result in unprocessed, locked up deposits. `receiveWithAuthorization` prevents this by performing an additional check that ensures that the caller is the payee. Additionally, if there are multiple contract functions accepting receive authorizations, the app developer could dedicate some leading bytes of the nonce could as the identifier to prevent cross-use. - -When submitting multiple transfers simultaneously, be mindful of the fact that relayers and miners will decide the order in which they are processed. This is generally not a problem if the transactions are not dependent on each other, but for transactions that are highly dependent on each other, it is recommended that the signed authorizations are submitted one at a time. - -The zero address must be rejected when using `ecrecover` to prevent unauthorized transfers and approvals of funds from the zero address. The built-in `ecrecover` returns the zero address when a malformed signature is provided. - -## 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-3009.md diff --git a/EIPS/eip-3014.md b/EIPS/eip-3014.md index b43e21ad6a5450..408d992c0f5c74 100644 --- a/EIPS/eip-3014.md +++ b/EIPS/eip-3014.md @@ -1,9 +1,9 @@ --- eip: 3014 -title: `eth_symbol` JSON-RPC method +title: eth_symbol JSON-RPC method author: Peter Grassberger (@PeterTheOne) discussions-to: https://github.com/ethereum/EIPs/issues/3012 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-09-30 @@ -45,4 +45,4 @@ This endpoint is similar to [EIP-695](./eip-695.md) but it provides the symbol i 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3026.md b/EIPS/eip-3026.md index 6af4f5d59df72a..560f13bc63a465 100644 --- a/EIPS/eip-3026.md +++ b/EIPS/eip-3026.md @@ -1,20 +1,19 @@ --- eip: 3026 title: BW6-761 curve operations -author: Youssef El Housni (@yelhousni), Michael Connor (@iAmMichaelConnor), Aurore Guillevic +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: Draft +status: Stagnant type: Standards Track category: Core -requires: 2539 created: 2020-10-05 +requires: 2539 --- -## Simple Summary -This precompile adds operations for the BW6-761 curve (from the EY/Inria [research paper](https://eprint.iacr.org/2020/351.pdf)) as a precompile in a set necessary to *efficiently* perform verification of one-layer composed zkSNARKs proofs. - ## 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 @@ -29,20 +28,20 @@ The multiexponentiation operations are a generalization of point multiplication, ## Motivation -This EIP is based on and tends to replace [EIP-2541](https://github.com/matter-labs/EIPs/blob/sw6_wrapping/EIPS/eip-2541.md) for significant performance reasons. In most applications, BW6-761 is used as an outer curve to BLS12-377 considered in [EIP-2539](https://github.com/ethereum/EIPs/pull/2539). +This EIP is based on and tends to replace matter-labs' proposol 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 | 0x13 | -|BW6_G1_MUL | 0x14 | -|BW6_G1_MULTIEXP | 0x15 | -|BW6_G2_ADD | 0x16 | -|BW6_G2_MUL | 0x17 | -|BW6_G2_MULTIEXP | 0x18 | -|BW6_PAIRING | 0x19 | +| 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 @@ -79,9 +78,9 @@ loop_count_1 is negative = false loop_count_2 is negative = false ``` -#### Encoding +### Encoding -##### Field elements encoding: +#### Field elements encoding: To encode points involved in the operation one has to encode elements of only the base field. @@ -89,16 +88,16 @@ The base field element (Fp) is encoded as `96` bytes by performing BigEndian enc If encodings do not follow this spec anywhere during parsing in the precompile, the precompile **MUST** revert with "endoding error". -##### Encoding of uncompressed points: +#### 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: +#### 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: +#### 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. @@ -106,65 +105,74 @@ Note that the main subgroup order for BW6-761 is actually only `377` bits (`48` The corresponding integer **MAY** be greater than the main subgroup order. -#### ABI for operations +### ABI for operations -##### ABI for G1 addition +#### 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 +#### 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 +#### 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 +#### 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 +#### 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 +#### 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 +#### 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 @@ -174,46 +182,55 @@ Output is `32` bytes representing a boolean: - `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 +### 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 -This precompile performs extensive computations and in case of any errors during execution it **MUST** consume all gas from the the gas schedule for the corresponding operation. +`180` gas -#### Gas schedule +#### G1 multiplication -##### G1 addition -`` gas +`64000` gas -##### G1 multiplication -`` gas +#### G2 addition -##### G2 addition -`` gas +`180` gas -##### G2 multiplication -`` gas +#### G2 multiplication + +`64000` gas + +#### G1/G2 Multiexponentiation -##### 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 = ` +`max_discount = 150` -##### Pairing operation -Base cost of the pairing operation is `*k + ` where `k` is a number of pairs. +#### 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 EIP1962 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](https://github.com/matter-labs/eip1962/blob/master/run_bn_pairing_estimate.sh) and [BNPAIR](https://github.com/matter-labs/eip1962/blob/master/run_bn_pairing_estimate.sh) 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: +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) @@ -222,13 +239,16 @@ Gas cost is derived by taking the average timing of the same operations over dif - 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 +### 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). -#### Explicit subgroup checks +### 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 @@ -246,32 +266,39 @@ Requeired properties for basic ops (add/multiply): - 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 [gist](https://gist.github.com/shamatar/506ab3193a7932fe9302a2f3a31a23e8) until it's final. +## Reference Implementation -## Implementation There is a various choice of existing implementations: **Libraries:** -- Rust implementation (EY/Zexe): https://github.com/yelhousni/zexe/tree/youssef/BW6-761-Fq-ABLR-2ML-M -- C++ implementation (EY/libff): https://github.com/EYBlockchain/zk-swap-libff -- Golang implementation (Consensys/gurvy): https://github.com/ConsenSys/gurvy + +- 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): https://github.com/kilic/bw6 + +- Golang implementation with Intel assembly (Onur Kilic): github.com/kilic/bw6 **Precompiles:** -- OpenEthereum (EY/Parity): https://github.com/EYBlockchain/solidity-elliptic-curves -**Sripts:** -- SageMath and Magma scripts: https://gitlab.inria.fr/zk-curves/bw6-761/ +- 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](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3030.md b/EIPS/eip-3030.md index 25da7195c9be2d..7d3ecba3d8de80 100644 --- a/EIPS/eip-3030.md +++ b/EIPS/eip-3030.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-09-30 @@ -358,4 +358,4 @@ An attacker can dump the memory in the remote signer to disclose a secret key. | An attacker can DoS the remote signer. | Implement IP filtering.
_or_
Implement Rate limiting. ## 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-3041.md b/EIPS/eip-3041.md index 20fb247014f386..3a21c44d1b91b3 100644 --- a/EIPS/eip-3041.md +++ b/EIPS/eip-3041.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-10-13 @@ -91,4 +91,4 @@ Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) The added field (`baseFee`) is informational and does not introduce technical security issues. ## 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-3044.md b/EIPS/eip-3044.md index 9dcd9870214c6d..73af4b98df9dc7 100644 --- a/EIPS/eip-3044.md +++ b/EIPS/eip-3044.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-10-14 @@ -91,4 +91,4 @@ Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) The added field (`baseFee`) is informational and does not introduce technical security issues. ## 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-3045.md b/EIPS/eip-3045.md index 07f0c4ab9945fd..f3a2f2c40603b2 100644 --- a/EIPS/eip-3045.md +++ b/EIPS/eip-3045.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-10-14 @@ -91,4 +91,4 @@ Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) The added field (`baseFee`) is informational and does not introduce technical security issues. ## 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-3046.md b/EIPS/eip-3046.md index 0804a25defda1e..d5ca817043c80a 100644 --- a/EIPS/eip-3046.md +++ b/EIPS/eip-3046.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-10-14 @@ -91,4 +91,4 @@ Backwards compatible. Calls related to block prior to [EIP-1559](./eip-1559.md) The added field (`baseFee`) is informational and does not introduce technical security issues. ## 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-3068.md b/EIPS/eip-3068.md index 6a27b8bbf416dc..8283305613fd99 100644 --- a/EIPS/eip-3068.md +++ b/EIPS/eip-3068.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-10-23 @@ -293,5 +293,4 @@ related to the elliptic curve pairing; they are independent of this EIP. ## 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-3074.md b/EIPS/eip-3074.md index 7e141f8ac2fcae..aeb5b3d186def2 100644 --- a/EIPS/eip-3074.md +++ b/EIPS/eip-3074.md @@ -1,27 +1,25 @@ --- 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: Review +status: Stagnant type: Standards Track category: Core created: 2020-10-15 +requires: 155 --- -## Simple Summary - -Allow externally owned accounts (EOAs) to delegate control of their account to a contract. - ## 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`. This essentially delegates control of the EOA to smart contract. +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 functionlity 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. +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 good analogy for the benefit this EIP provides is that it's similar to allowing any EOA to become a smart contract wallet *without* deploying a contract. +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. @@ -39,9 +37,9 @@ With the extraordinary growth of tokens on Ethereum, it has become common for EO | Constant | Value | | ---------------- | ------ | -| `MAGIC` | `0x03` | +| `MAGIC` | `0x04` | -`MAGIC` is used for EIP-3074 signatures to prevent signature collisions with other signing formats. +`MAGIC` is used for [EIP-3074](./eip-3074.md) signatures to prevent signature collisions with other signing formats. ### Context Variables @@ -55,42 +53,73 @@ The variable has the same scope as the program counter -- `authorized` persists ### `AUTH` (`0xf6`) -A new opcode `AUTH` shall be created at `0xf6`. It shall take four stack element inputs and returns one stack element. +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` | `commit` | -| `top - 1` | `yParity` | -| `top - 2` | `r` | -| `top - 3` | `s` | +| `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` | `authorized` | +| `top - 0` | `success` | + +##### Memory + +Memory is not modified by this instruction. #### Behavior -The arguments (`yParity`, `r`, `s`) are interpreted as an ECDSA signature on the secp256k1 curve over the message `keccak256(MAGIC || paddedInvokerAddress || commit)`, where: - - `paddedInvokerAddress` is the address of the contract executing `AUTH`, 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 (e.g. a nonce for replay protection). +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. -Signature validity and signer recovery is handled analogous to transaction signatures, including the stricter `s` range for preventing ECDSA malleability. Note that `yParity` is expected to be `0` or `1`. +`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`. -If the signature is valid, the context variable `authorized` is set to the signer address. In particular, this is also true if `signerAddress == tx.origin`, which used to be handled separately in earlier versions of this EIP (see Security Considerations). If the signature is instead invalid, `authorized` is reset to an unset value. +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: -`AUTH` returns the new `authorized` if set, or `0` otherwise. + - `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 `3100`. This is equal to the cost for the `ecrecover` precompile, plus a bit extra to cover a keccak256 hash and some additional logic. +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 eight stack elements and return one stack element. It matches the behavior of the existing `CALL` (`0xF1`) instruction, except where noted below. +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 @@ -99,11 +128,10 @@ A new opcode `AUTHCALL` shall be created at `0xf7`. It shall take eight stack el | `top - 0` | `gas` | | `top - 1` | `addr` | | `top - 2` | `value` | -| `top - 3` | `valueExt` | -| `top - 4` | `argsOffset` | -| `top - 5` | `argsLength` | -| `top - 6` | `retOffset` | -| `top - 7` | `retLength` | +| `top - 3` | `argsOffset` | +| `top - 4` | `argsLength` | +| `top - 5` | `retOffset` | +| `top - 6` | `retLength` | #### Output @@ -113,14 +141,14 @@ A new opcode `AUTHCALL` shall be created at `0xf7`. It shall take eight stack el #### Behavior -`AUTHCALL` is interpreted the same as `CALL`, except for: +`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 the executing contract. It is not paid by `authorized`. If `value` is higher than the balance of the executing contract, execution is invalid. - - If `valueExt` is not zero, the instruction immediately returns 0. In this case the gas that would have been passed into the call is refunded, but not the gas consumed by the `AUTHCALL` opcode itself. In the future, this restriction may be relaxed to externally transfer value out of the `authorized` account. + - `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. @@ -167,6 +195,16 @@ As with `CALL`, the full gas cost is charged immediately, independently of actua ## 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). @@ -179,9 +217,9 @@ A well-behaved contract should never reach an `AUTHCALL` without having successf There are two general approaches to separating the "fee payer" from the "action originator". -The first is introducing a new transaction. 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 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 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. +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. @@ -191,7 +229,7 @@ More logic can be implemented around the `AUTHCALL` instruction, giving more con ### 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. +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`. @@ -199,22 +237,26 @@ The `invoker` binds a particular signed message to a single invoker. If invoker 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 they 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. +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 mult-tx flows, such as ERC-20 `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. +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 they transaction to be processed only by a contract they trust. This allows them to interact with sponsors without needing to trust them. +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 wallet using its code could be compromised. +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 @@ -224,12 +266,11 @@ It is, therefore, sufficient for the invoker to guarantee a minimum amount of ga ### Source of `value` -Any non-zero `value` passed into an `AUTHCALL` is deducted from the invoker's balance. A natural alternative source for `value` would be the `authorized` account. However, deducting value from an EOA mid-execution is problematic, as it breaks important invariants for handling pending transactions. Specifically: +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. -* Transaction pools expect transactions for a given EOA to only turn invalid when other transactions from the same EOA are included into a block, increasing its nonce and (possibly) decreasing its balance. Deducting `value` from the `authorized` account would make transaction invalidation an unpredictable side effect of any smart contract execution. -* Similarly, miners rely on the ability to statically pick a set of valid transactions from their transaction pool to include into a new block. Deducting `value` from the `authorized` account would break this ability, increasing the overhead and thus the time for block creation. +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. -At the same time, the ability to directly take ether out of the `authorized` account is an important piece of functionality and thus a desired future addition via an additional opcode similar to `AUTHCALL`. For this reason, it is included as `valueExt`, an operand of `AUTHCALL`, which may be activated in a future fork. The prerequisite for that would be to find satisfying mitigations to the transaction invalidation concerns outlined above. One potential avenue for that could be the addition of account access lists similar to EIP-2930, used to signal accounts whose balance can be reduced as a side effect of the transaction (without on their own constituting authorization to do so). +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 @@ -239,58 +280,75 @@ Allowing `authorized` to equal `tx.origin` enables simple transaction batching, 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 re-entrancy. + 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 re-entrancy protection, though the search was non-exhaustive. +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 re-entrancy (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 re-entrancy, rather than other more common approaches. + - 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. + - 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. -## Backwards Compatibility +### `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 -No known issues. +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. -## Test Cases +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. -TODO +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. -## Implementation +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. -https://github.com/quilt/go-ethereum/tree/eip-3074 +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: +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. - - The current chain id should be included in `commit` and checked against `CHAINID` on *every transaction*. Without it, a malicious sponsor could replay a signature on a different chain. - `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_. +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 re-entrancy guards of the style `require(tx.origin == msg.sender)`. + - 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3076.md b/EIPS/eip-3076.md index c55c8ae9dbbd0a..24b8245676872d 100644 --- a/EIPS/eip-3076.md +++ b/EIPS/eip-3076.md @@ -1,22 +1,19 @@ --- 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/ -status: Review +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: Core +category: Interface created: 2020-10-27 -updated: 2021-02-08 --- -## Simple Summary - -A JSON interchange format for proof of stake validators to migrate slashing protection data between clients. - ## 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](https://eips.ethereum.org/EIPS/eip-2335) 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. +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 @@ -24,7 +21,7 @@ The proof of stake (PoS) protocol penalises validators for voting in ways that c 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 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. +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. @@ -171,12 +168,14 @@ A valid interchange file is one that adheres to the following JSON schema, and i 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][pps]. 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. +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][isad]. +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 @@ -184,7 +183,8 @@ source.epoch < if att.pubkey == attester_pubkey) ``` -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`). In pseudocode: +{: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 <= @@ -199,14 +199,9 @@ target_epoch <= - 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)`][csr]: 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)`][cd]. - -- The `signed_attestations` `signing_root`s are calculated using [`compute_signing_root(attestation, domain)`][csr]: 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)`][cd]. +- 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)`. -[pps]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#proposer-slashings -[isad]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#is_slashable_attestation_data -[csr]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#compute_signing_root -[cd]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#compute_domain +- 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 @@ -246,21 +241,21 @@ In order to minimise risk and complexity, the format has been designed to map cl 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. +- 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. +- 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. +- 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3085.md b/EIPS/eip-3085.md index 964d3697a95aa8..22a576b13e2035 100644 --- a/EIPS/eip-3085.md +++ b/EIPS/eip-3085.md @@ -1,49 +1,33 @@ --- eip: 3085 -title: Wallet Add Ethereum Chain RPC Method (`wallet_addEthereumChain`) -author: Erik Marks (@rekmarks), Pedro Gomes (@pedrouid) +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: Review +status: Stagnant type: Standards Track category: Interface created: 2020-11-01 -requires: 155, 695 +requires: 155 --- -## Simple Summary - -An RPC method for adding Ethereum chains to wallet applications. - ## Abstract -The `wallet_addEthereumChain` RPC method allows Ethereum applications ("dapps") to suggest chains to be added to the user's wallet application. -The caller must specify a chain ID and some chain metadata. -The wallet application may arbitrarily refuse or accept the request. -`null` is returned if the chain was added, and an error otherwise. - -## Motivation - -All dapps require the user to interact with one or more Ethereum chains in order to function. -Any given chain may or may not be supported by the user's wallet application. -`wallet_addEthereumChain` enables dapps to request chains to be added to the user's wallet. -This enables UX improvements for both dapps and wallets. +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](https://www.ietf.org/rfc/rfc2119.txt). - -### `wallet_addEthereumChain` +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. -The method accepts a single object parameter, with a `chainId` and some chain metadata. -The method returns `null` if the chain was added to the wallet, and an error otherwise. +This proposal defines a new RPC method, `wallet_addEthereumChain`. -The wallet **MAY** reject the request for any reason. +### `wallet_addEthereumChain` -> Note that this method makes **no** statement about whether the wallet should change the user's currently selected chain, if the wallet has a concept thereof. +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. -#### Parameters +#### `wallet_addEthereumChain` Parameters -`wallet_addEthereumChain` accepts a single object parameter, specified by the following TypeScript interface: +The `wallet_addEthereumChain` method takes a single parameter, an `EthereumChainAddRequest` object, which is defined as follows: ```typescript interface AddEthereumChainParameter { @@ -60,115 +44,33 @@ interface AddEthereumChainParameter { } ``` -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. - -- `chainId` - - **MUST** specify the integer ID of the chain as a hexadecimal string, per the [`eth_chainId`](./eip-695.md) Ethereum RPC method. - - The wallet **SHOULD** compare the specified `chainId` value with the `eth_chainId` return value from the endpoint. - If these values are not identical, the wallet **MUST** reject the request. -- `blockExplorerUrls` - - If provided, **MUST** specify one or more URLs pointing to block explorer web sites for the chain. -- `chainName` - - If provided, **MUST** specify a human-readable name for the chain. -- `iconUrls` - - If provided, **MUST** specify one or more URLs pointing to reasonably sized images that can be used to visually identify the chain. -- `nativeCurrency` - - If provided, **MUST** describe the native currency of the chain using the `name`, `symbol`, and `decimals` fields. - - `decimals` **MUST** be a non-negative integer. - - `name` and `symbol` **SHOULD** be human-readable strings. -- `rpcUrls` - - If provided, **MUST** specify one or more URLs pointing to RPC endpoints that can be used to communicate with the chain. - -All URL strings **MUST** include the protocol component of the URL. -HTTPS **SHOULD** always be used over HTTP. - -#### Returns - -The method **MUST** return `null` if the request was successful, and an error otherwise. - -A request to add a chain that was already added **SHOULD** be considered successful. - -The wallet **MUST NOT** allow the same `chainId` to be added multiple times. -See [Security Considerations](#security-considerations) for more information. - -### Examples - -These examples use JSON-RPC, but the method could be implemented using other RPC protocols. - -To add the Goerli test chain: - -```json -{ - "id": 1, - "jsonrpc": "2.0", - "method": "wallet_addEthereumChain", - "params": [ - { - "chainId": "0x5", - "chainName": "Goerli", - "rpcUrls": ["https://goerli.infura.io/v3/INSERT_API_KEY_HERE"], - "nativeCurrency": { - "name": "Goerli ETH", - "symbol": "gorETH", - "decimals": 18 - }, - "blockExplorerUrls": ["https://goerli.etherscan.io"] - } - ] -} -``` +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. -To add POA Network's xDAI chain: - -```json -{ - "id": 1, - "jsonrpc": "2.0", - "method": "wallet_addEthereumChain", - "params": [ - { - "chainId": "0x64", - "chainName": "xDAI Chain", - "rpcUrls": ["https://dai.poa.network"], - "iconUrls": [ - "https://xdaichain.com/fake/example/url/xdai.svg", - "https://xdaichain.com/fake/example/url/xdai.png" - ], - "nativeCurrency": { - "name": "xDAI", - "symbol": "xDAI", - "decimals": 18 - } - } - ] -} -``` +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. -In the above example, notice that the `iconUrls` array contains URLs pointing to two different image formats. +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. -A success response: +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. -```json -{ - "id": 1, - "jsonrpc": "2.0", - "result": null -} -``` +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. -A failure response: +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. -```json -{ - "id": 1, - "jsonrpc": "2.0", - "error": { - "code": 4001, - "message": "The user rejected the request." - } -} -``` +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 @@ -186,8 +88,6 @@ Therefore, all parameters except `chainId` are specified as optional, even thoug 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. -For related work, see [EIP-2015](./eip-2015.md). - ## Security Considerations `wallet_addEthereumChain` is a powerful method that exposes the end user to serious risks if implemented incorrectly. @@ -204,7 +104,7 @@ The wallet should: - 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](#parameters). +- Verify that the specified chain ID matches the return value of `eth_chainId` from the endpoint, as described above. ### RPC Endpoints and RPC URLs @@ -246,4 +146,4 @@ If the user denies the request, the wallet should return the same user rejection ## 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-3091.md b/EIPS/eip-3091.md index 24495eef755e30..a2174d3c52d2da 100644 --- a/EIPS/eip-3091.md +++ b/EIPS/eip-3091.md @@ -1,45 +1,55 @@ --- eip: 3091 title: Block Explorer API Routes -author: Pedro Gomes (@pedrouid) +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: Draft +status: Stagnant type: Standards Track category: Interface created: 2020-11-02 --- -## Simple Summary -Standard API Routes for Blockchain explorers - ## Abstract + This proposal brings standardization between block explorers API routes when linking transactions, blocks, accounts and tokens. ## Motivation -Currently wallets will link transactions and accounts to block explorers 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. This EIP makes RPC endpoints like [EIP-2015](./eip-2015.md) more feasible. + +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/ +`/block/` ### Transactions -/tx/ + +`/tx/` ### Accounts -/address/ +`/address/` + +### Tokens -### ERC-20 Tokens -/token/ +`/token/` -## Backward Compatibility -This EIP was designed with existing API routes in mind to reduce disruption. Incompatible block explorers should include either 301 redirects to their existing API routes to match this EIP. +## 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 -TBD + +None ## 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-3102.md b/EIPS/eip-3102.md index 54442ddd2d1bc1..376a91b14f8412 100644 --- a/EIPS/eip-3102.md +++ b/EIPS/eip-3102.md @@ -2,9 +2,8 @@ eip: 3102 title: Binary trie structure author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin) -status: Draft discussions-to: https://ethresear.ch/t/binary-trie-format/7621 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2020-09-01 @@ -180,4 +179,4 @@ Issues could arise when performing the transition. In particular, a heavy conver ## 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-3135.md b/EIPS/eip-3135.md index 5dbe26b3773e45..357486d011dcbc 100644 --- a/EIPS/eip-3135.md +++ b/EIPS/eip-3135.md @@ -1,268 +1,7 @@ --- eip: 3135 -title: Exclusive Claimable Token -author: Zhenyu Sun (@Ungigdu) -discussions-to: https://github.com/ethereum/EIPs/issues/3132 -status: Draft -type: Standards Track category: ERC -created: 2020-08-10 -requires: 20 +status: Moved --- -## Simple Summary - -This standard defines a token which can be claimed only by token issuer with payer's signature. - -## Abstract - -This EIP defines a set of additions to the default token standard such as ERC-20, that allows online/offline service providers establish micropayment channels with any number of users by signing and verifying messages about the consumption of token off chain. Using this mechanism will reduce interactions with blockchain to minimal for both participants, thus saving gas and improve performance. - -## Motivation - -There are two main purposes of this EIP, one is to reduce interactions with blockchain, the second is to link Ethereum to real-world payment problems. - -Many small businesses want to build payment system based on blockchain but find it difficult. There are basically two ways: - -1. Directly pay with token. There are many wallet can receive and transfer token but transactions on Ethereum cost gas and take time to confirm. -2. User lock token on payment smart contract and service provider use payment messages signed by user to release token, establishing a micropayment channel. The advantage is interactions with blockchain is reduced and the signing/verifying process is off-chain. But interact with payment contract needs service provider to build a DApp, which require resources many small businesses do not have. Even if they managed to build DApps, they are all different, not standardized. Also, user should have a wallet with DApp browser and has to learn how to use it. - -This EIP helps to standardize the interactions of micropayment system, and make it possible for wallet build a universal UI in the future. - -## Specification - -```solidity - -/// @return Image url of this token or descriptive resources -function iconUrl() external view returns (string memory); - -/// @return Issuer of this token. Only issuer can execute claim function -function issuer() external view returns (address); - -/** - * @notice Remove consumption from payer's deposite - * @dev Check if msg.sender == issuer - * @param from Payer's address - * @param consumption How many token is consumed in this epoch, specified - * @param epoch Epoch increased by 1 after claim or withdraw, at the beginning of each epoch, consumption goes back to 0 - * @param signature Signature of payment message signed by payer -*/ -function claim(address from, uint256 consumption, uint256 epoch, bytes calldata signature) external; - -function transferIssuer(address newIssuer) external; - -/// @notice Move amount from payer's token balance to deposite balance to ensure payment is sufficient -function deposit(uint256 amount) external; - -/** - * @notice Give remaining deposite balance back to "to" account, act as "refund" function - * @dev In prepayment module, withdraw is executed from issuer account - * In lock-release module, withdraw is executed from user account - * @param to the account receiving remaining deposite - * @param amount how many token is returned -*/ -function withdraw(address to, uint256 amount) external; - -function depositBalanceOf(address user) external view returns(uint256 depositBalance, uint256 epoch); - -event Deposit( - address indexed from, - uint256 amount -); - -event Withdraw( - address indexed to, - uint256 amount -); - -event TransferIssuer( - address indexed oldIssuer, - address indexed newIssuer -); - -event Claim( - address indexed from, - address indexed to, - uint256 epoch, - uint256 consumption -); - -``` - -### signature - -the pseudo code generating an ECDSA signature: -``` -sign(keccak256(abi_encode( - "\x19Ethereum Signed Message:\n32", - keccak256(abi_encode( - token_address, - payer_address, - token_issuer, - token_consumption, //calculated by user client - epoch - )) - )) -,private_key) - -``` - -### verification process - -the verification contains check about both signature and token_consumption - -the pseudo code run by verification server is as follows: - -``` - -serving_loop: - - for { - /** - * unpaied_consumption is calculated by provider - * signed_consumption is claimable amount - * tolerance allows payer "owes" provider to a certain degree - */ - //getSignedConsumption returns amount that are already claimable - if(unpaied_consumption < signed_consumption + tolerance){ - informUser("user need charge", unpaied_consumption) - interruptService() - }else{ - isServing() || recoverService() - } - } - -verification_loop: - - for { - message = incomingMessage() - if(recover_signer(message, signature) != payer_address){ - informUser("check signature failed", hash(message)) - continue - } - - /** - * optional: when using echo server to sync messages between verification servers - * more info about this in Security Considerations section - */ - if(query(message) != message){ - informUser("message outdate", hash(message)) - continue - } - - if(epoch != message.epoch || message.consumption > getDepositBalance()){ - informUser("invalid message", epoch, unpaied_consumption) - continue - } - - signed_consumption = message.consumption - save(message) - } - -claim_process: - - if(claim()){ - unpaied_consumption -= signed_consumption - signed_consumption = 0 - epoch+=1 - } - -``` -### About withdraw - -The withdraw function is slightly different based on business models - -1. prepayment model - -In prepayment business model such as using token as recharge card of general store, the user pays (crypto)currency to store in advance for claimable token as recharge card (with bonus or discount). When checking out, the customer signs a message with updated consumption (old consumption + consumption this time) to store and store verifies this message off chain. The shopping process loops without any blockchain involved, until the customer wants to return the card and get money back. Because the store already holds all currency, the withdraw function should be executed by token issuer (store) to return remaining deposit balance after claim. The prepayment model can easily be built into a wallet with QR-code scanning function. - -2. lock-release model - -If we run a paid end-to-end encrypted e-mail service that accepts token as payment, we can use lock-release model. Unlike prepayment, we charge X * N token for an e-mail sent to N recipients. In this "pay for usage" scenario, the counting of services happens on both client and server side. The client should not trust charge amount given by server in case the it's malfunctioning or malicious. When client decide not to trust server, it stops signing messages, but some of token is taken hostage in deposit balance. To fix this problem, the withdraw function should be executed by payer account with limitation such as epoch didn't change in a month. - -## Rationale - -This EIP targets on ERC-20 tokens due to its widespread adoption. However, this extension is designed to be compatible with other token standard. - -The reason we chose to implement those functions in token contract rather than a separate record contract is as follows: -- Token can transfer is more convenient and more general than interact with DApp -- Token is more standardized and has better UI support -- Token is equal to service, make token economy more prosperous -- Remove the approve process - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-20](./eip-20.md). - -## Implementation - -```solidity - -mapping (address => StampBalance) private _depositBalance; - -struct StampBalance{ - uint256 balance; - uint256 epoch; -} - -function deposit(uint256 value) override external{ - require(value <= _balances[msg.sender]); - _balances[msg.sender] = _balances[msg.sender].sub(value); - _depositBalance[msg.sender].balance = _depositBalance[msg.sender].balance.add(value); - emit Deposit(msg.sender, value); -} - -function withdraw(address to, uint256 value) override onlyIssuer external{ - require(value <= _depositBalance[to].balance); - _depositBalance[to].balance = _depositBalance[to].balance.sub(value); - _depositBalance[to].epoch += 1; - _balances[to] = _balances[to].add(value); - emit Withdraw(to, value); -} - -function depositBalanceOf(address user) override public view returns(uint256 depositBalance, uint256 epoch){ - return (_depositBalance[user].balance, _depositBalance[user].epoch); -} - -// prepayment model -function claim(address from, uint credit, uint epoch, bytes memory signature) override onlyIssuer external{ - require(credit > 0); - require(_depositBalance[from].epoch + 1 == epoch); - require(_depositBalance[from].balance >= credit); - bytes32 message = keccak256(abi.encode(this, from, _issuer, credit, epoch)); - bytes32 msgHash = prefixed(message); - require(recoverSigner(msgHash, signature) == from); - _depositBalance[from].balance = _depositBalance[from].balance.sub(credit); - _balances[_issuer] = _balances[_issuer].add(credit); - _depositBalance[from].epoch += 1; - emit Claim(from, msg.sender, credit, epoch); -} - -function prefixed(bytes32 hash) internal pure returns (bytes32) { - return keccak256(abi.encode("\x19Ethereum Signed Message:\n32", hash)); -} - -function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { - (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig); - return ecrecover(message, v, r, s); -} - -function splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s) { - require(sig.length == 65); - assembly { - r := mload(add(sig, 32)) - s := mload(add(sig, 64)) - v := byte(0, mload(add(sig, 96))) - } - return (v, r, s); -} - -``` - -## Security Considerations - -By restricting claim function to issuer, there is no race condition on chain layer. However double spending problem may occur when the issuer use multiple verifiers and payer signs many payment messages simultaneously. Some of those messages may get chance to be checked valid though only the message with the largest consumption can be claimed. This problem can be fixed by introducing an echo server which accepts messages from verifiers, returns the message sequentially with largest consumption and biggest epoch number. If a verifier gets an answer different from the message he send, it updates the message from echo server as the last message it receives along with local storage of the status about this payer. Then the verifier asks the payer again for a new message. - -## 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-3135.md diff --git a/EIPS/eip-3143.md b/EIPS/eip-3143.md index af60a8a77d5b79..1b48eac57f9836 100644 --- a/EIPS/eip-3143.md +++ b/EIPS/eip-3143.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-12-01 @@ -50,4 +50,4 @@ There are no known backward compatibility issues with the introduction of this E There are no known security issues presented by this change. ## 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-3155.md b/EIPS/eip-3155.md index 5bf68b5d03a140..009bc77d78fd82 100644 --- a/EIPS/eip-3155.md +++ b/EIPS/eip-3155.md @@ -1,167 +1,177 @@ --- 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: Draft +status: Review type: Standards Track category: Interface created: 2020-12-07 --- +## Abstract -## Simple Summary -Introduce a new JSON standard for EVM traces during execution of state tests. +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, 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 objectives: +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 finding differences in execution quickly in the case of a chain split. +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. +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-ethereums `evm` binary for code examples. + +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 | +| 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 | -| `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 | -| `memSize` | Number | Size of memory array | - -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 | -| `returnStack` | Array of Hex-Numbers | Array of values, Stack of the called function | - -*Example:* +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`, `returnStack`, `memory`) MUST be initialized to empty arrays ("stack":[],) NOT to null. -If the CUT will not output 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 `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:* + +*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 +### Summary and Error Handling -At the end of execution, the CUT MUST print some summerical info, this info SHOULD have the following fields. +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: +#### 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 | -| 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 -OptionalFields: +| Name | Type | Explanation | +|--------|--------|-------------------------------------------------------| +| `time` | Number | Time in nanoseconds needed to execute the transaction | +| `fork` | String | Name of the fork rules used for execution | + +*Example*: -| Name | Type | Explanation | -|---|---|---| -| `time` | Number | Time in nanoseconds needed to execute the transaction | -| `fork` | String | Name of the fork rules used for execution | ``` -{"stateRoot":"0xd4c577737f5d20207d338c360c42d3af78de54812720e3339f7b27293ef195b7","output":"","gasUsed":"0x3","successful":"true","time":141485} +{"stateRoot":"0xd4c577737f5d20207d338c360c42d3af78de54812720e3339f7b27293ef195b7","output":"","gasUsed":"0x3","pass":"true","time":141485} ``` ## Rationale -This EIP is largely based on the previous non-official documentation for EVM tracing. + +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. + +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 - ~/go/src/github.com/ethereum/go-ethereum/build/bin/evm --code 604080536040604055604060006040600060025afa6040f3 --json run -{"pc":0,"op":96,"gas":"0x2540be400","gasCost":"0x3","memory":"0x","memSize":0,"stack":[],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":2,"op":128,"gas":"0x2540be3fd","gasCost":"0x3","memory":"0x","memSize":0,"stack":["0x40"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"DUP1","error":""} -{"pc":3,"op":83,"gas":"0x2540be3fa","gasCost":"0xc","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x40"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"MSTORE8","error":""} -{"pc":4,"op":96,"gas":"0x2540be3ee","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":[],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":6,"op":96,"gas":"0x2540be3eb","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":8,"op":85,"gas":"0x2540be3e8","gasCost":"0x4e20","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x40"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SSTORE","error":""} -{"pc":9,"op":96,"gas":"0x2540b95c8","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":[],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":11,"op":96,"gas":"0x2540b95c5","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":13,"op":96,"gas":"0x2540b95c2","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":15,"op":96,"gas":"0x2540b95bf","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":17,"op":96,"gas":"0x2540b95bc","gasCost":"0x3","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40","0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":19,"op":90,"gas":"0x2540b95b9","gasCost":"0x2","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40","0x0","0x2"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"GAS","error":""} -{"pc":20,"op":250,"gas":"0x2540b95b7","gasCost":"0x24abb676c","memory":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x40","0x0","0x40","0x0","0x2","0x2540b95b7"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"STATICCALL","error":""} -{"pc":21,"op":96,"gas":"0x2540b92a7","gasCost":"0x3","memory":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b00000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x1"],"returnStack":[],"returnData":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b","depth":1,"refund":0,"opName":"PUSH1","error":""} -{"pc":23,"op":243,"gas":"0x2540b92a4","gasCost":"0x0","memory":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b00000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000","memSize":96,"stack":["0x1","0x40"],"returnStack":[],"returnData":"0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b","depth":1,"refund":0,"opName":"RETURN","error":""} -{"stateRoot":"2eef130ec61805516c1f050720b520619787704a5dd826a39aeefb850f83acfd", "output":"40","gasUsed":"0x515c","time":350855} -``` - - -## Implementation -Implementation in [go-ethereum](https://github.com/ethereum/go-ethereum/tree/master/cmd/evm) -Implementation in [OpenEthereum](https://github.com/openethereum/openethereum/tree/master/evmbin) -Implementation in [Besu](https://github.com/hyperledger/besu/tree/master/ethereum/evmtool) -Implementation in [Nethermind](https://github.com/NethermindEth/nethermind/tree/master/src/Nethermind/Nethermind.State.Test.Runner) - +${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. + +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](https://creativecommons.org/publicdomain/zero/1.0/). + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3156.md b/EIPS/eip-3156.md index 1da3825ad8efe8..b3f20e5d49f318 100644 --- a/EIPS/eip-3156.md +++ b/EIPS/eip-3156.md @@ -1,515 +1,7 @@ --- eip: 3156 -title: Flash Loans -author: Alberto Cuesta Cañada (@albertocuestacanada), Fiona Kobayashi (@fifikobayashi), fubuloubu (@fubuloubu), Austin Williams (@onewayfunction) -discussions-to: https://ethereum-magicians.org/t/erc-3156-flash-loans-review-discussion/5077 -status: Final -type: Standards Track category: ERC -created: 2020-11-15 +status: Moved --- -## Simple Summary - -This ERC provides standard interfaces and processes for single-asset flash loans. - -## Abstract - -A flash loan is a smart contract transaction in which a lender smart contract lends assets to a borrower smart contract with the condition that the assets are returned, plus an optional fee, before the end of the transaction. This ERC specifies interfaces for lenders to accept flash loan requests, and for borrowers to take temporary control of the transaction within the lender execution. The process for the safe execution of flash loans is also specified. - -## Motivation - -Flash loans allow smart contracts to lend an amount of tokens without a requirement for collateral, with the condition that they must be returned within the same transaction. - -Early adopters of the flash loan pattern have produced different interfaces and different use patterns. The diversification is expected to intensify, and with it the technical debt required to integrate with diverse flash lending patterns. - -Some of the high level diferences in the approaches across the protocols include: -- Repayment approaches at the end of the transaction, where some pull the principal plus the fee from the loan receiver, and others where the loan receiver needs to manually return the principal and the fee to the lender. -- Some lenders offer the ability to repay the loan using a token that is different to what was originally borrowed, which can reduce the overall complexity of the flash transaction and gas fees. -- Some lenders offer a single entry point into the protocol regardless of whether you're buying, selling, depositing or chaining them together as a flash loan, whereas other protocols offer discrete entry points. -- Some lenders allow to flash mint any amount of their native token without charging a fee, effectively allowing flash loans bounded by computational constraints instead of asset ownership constraints. - -## Specification - -A flash lending feature integrates two smart contracts using a callback pattern. These are called the LENDER and the RECEIVER in this EIP. - -### Lender Specification - -A `lender` MUST implement the IERC3156FlashLender interface. -``` -pragma solidity ^0.7.0 || ^0.8.0; -import "./IERC3156FlashBorrower.sol"; - - -interface IERC3156FlashLender { - - /** - * @dev The amount of currency available to be lent. - * @param token The loan currency. - * @return The amount of `token` that can be borrowed. - */ - function maxFlashLoan( - address token - ) external view returns (uint256); - - /** - * @dev The fee to be charged for a given loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function flashFee( - address token, - uint256 amount - ) external view returns (uint256); - - /** - * @dev Initiate a flash loan. - * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) external returns (bool); -} -``` - -The `maxFlashLoan` function MUST return the maximum loan possible for `token`. If a `token` is not currently supported `maxFlashLoan` MUST return 0, instead of reverting. - -The `flashFee` function MUST return the fee charged for a loan of `amount` `token`. If the token is not supported `flashFee` MUST revert. - -The `flashLoan` function MUST include a callback to the `onFlashLoan` function in a `IERC3156FlashBorrower` contract. - -``` -function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data -) external returns (bool) { - ... - require( - receiver.onFlashLoan(msg.sender, token, amount, fee, data) == keccak256("ERC3156FlashBorrower.onFlashLoan"), - "IERC3156: Callback failed" - ); - ... -} -``` - -The `flashLoan` function MUST transfer `amount` of `token` to `receiver` before the callback to the borrower. - -The `flashLoan` function MUST include `msg.sender` as the `initiator` to `onFlashLoan`. - -The `flashLoan` function MUST NOT modify the `token`, `amount` and `data` parameter received, and MUST pass them on to `onFlashLoan`. - -The `flashLoan` function MUST include a `fee` argument to `onFlashLoan` with the fee to pay for the loan on top of the principal, ensuring that `fee == flashFee(token, amount)`. - -The `lender` MUST verify that the `onFlashLoan` callback returns the keccak256 hash of "ERC3156FlashBorrower.onFlashLoan". - -After the callback, the `flashLoan` function MUST take the `amount + fee` `token` from the `receiver`, or revert if this is not successful. - -If successful, `flashLoan` MUST return `true`. - -### Receiver Specification - -A `receiver` of flash loans MUST implement the IERC3156FlashBorrower interface: - -``` -pragma solidity ^0.7.0 || ^0.8.0; - - -interface IERC3156FlashBorrower { - - /** - * @dev Receive a flash loan. - * @param initiator The initiator of the loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param fee The additional amount of tokens to repay. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" - */ - function onFlashLoan( - address initiator, - address token, - uint256 amount, - uint256 fee, - bytes calldata data - ) external returns (bytes32); -} -``` - -For the transaction to not revert, `receiver` MUST approve `amount + fee` of `token` to be taken by `msg.sender` before the end of `onFlashLoan`. - -If successful, `onFlashLoan` MUST return the keccak256 hash of "ERC3156FlashBorrower.onFlashLoan". - -## Rationale - -The interfaces described in this ERC have been chosen as to cover the known flash lending use cases, while allowing for safe and gas efficient implementations. - -`flashFee` reverts on unsupported tokens, because returning a numerical value would be incorrect. - -`flashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the lender, and including both the use cases in which the tokens lent are held or minted by the lender. - -`receiver` is taken as a parameter to allow flexibility on the implementation of separate loan initiators and receivers. - -Existing flash lenders all provide flash loans of several token types from the same contract. Providing a `token` parameter in both the `flashLoan` and `onFlashLoan` functions matches closely the observed functionality. - -A `bytes calldata data` parameter is included for the caller to pass arbitrary information to the `receiver`, without impacting the utility of the `flashLoan` standard. - -`onFlashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the `receiver`, and following the `onAction` naming pattern used as well in EIP-667. - -A `initiator` will often be required in the `onFlashLoan` function, which the lender knows as `msg.sender`. An alternative implementation which would embed the `initiator` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -The `amount` will be required in the `onFlashLoan` function, which the lender took as a parameter. An alternative implementation which would embed the `amount` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -A `fee` will often be calculated in the `flashLoan` function, which the `receiver` must be aware of for repayment. Passing the `fee` as a parameter instead of appended to `data` is simple and effective. - -The `amount + fee` are pulled from the `receiver` to allow the `lender` to implement other features that depend on using `transferFrom`, without having to lock them for the duration of a flash loan. An alternative implementation where the repayment is transferred to the `lender` is also possible, but would need all other features in the lender to be also based in using `transfer` instead of `transferFrom`. Given the lower complexity and prevalence of a "pull" architecture over a "push" architecture, "pull" was chosen. - -## Backwards Compatibility - -No backwards compatibility issues identified. - -## Implementation - -### Flash Borrower Reference Implementation - -``` -pragma solidity ^0.8.0; - -import "./interfaces/IERC20.sol"; -import "./interfaces/IERC3156FlashBorrower.sol"; -import "./interfaces/IERC3156FlashLender.sol"; - - -contract FlashBorrower is IERC3156FlashBorrower { - enum Action {NORMAL, OTHER} - - IERC3156FlashLender lender; - - constructor ( - IERC3156FlashLender lender_ - ) { - lender = lender_; - } - - /// @dev ERC-3156 Flash loan callback - function onFlashLoan( - address initiator, - address token, - uint256 amount, - uint256 fee, - bytes calldata data - ) external override returns(bool) { - require( - msg.sender == address(lender), - "FlashBorrower: Untrusted lender" - ); - require( - initiator == address(this), - "FlashBorrower: Untrusted loan initiator" - ); - (Action action) = abi.decode(data, (Action)); - if (action == Action.NORMAL) { - // do one thing - } else if (action == Action.OTHER) { - // do another - } - return keccak256("ERC3156FlashBorrower.onFlashLoan"); - } - - /// @dev Initiate a flash loan - function flashBorrow( - address token, - uint256 amount - ) public { - bytes memory data = abi.encode(Action.NORMAL); - uint256 _allowance = IERC20(token).allowance(address(this), address(lender)); - uint256 _fee = lender.flashFee(token, amount); - uint256 _repayment = amount + _fee; - IERC20(token).approve(address(lender), _allowance + _repayment); - lender.flashLoan(this, token, amount, data); - } -} -``` - -### Flash Mint Reference Implementation - -``` -pragma solidity ^0.8.0; - -import "../ERC20.sol"; -import "../interfaces/IERC20.sol"; -import "../interfaces/IERC3156FlashBorrower.sol"; -import "../interfaces/IERC3156FlashLender.sol"; - - -/** - * @author Alberto Cuesta Cañada - * @dev Extension of {ERC20} that allows flash minting. - */ -contract FlashMinter is ERC20, IERC3156FlashLender { - - bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); - uint256 public fee; // 1 == 0.0001 %. - - /** - * @param fee_ The percentage of the loan `amount` that needs to be repaid, in addition to `amount`. - */ - constructor ( - string memory name, - string memory symbol, - uint256 fee_ - ) ERC20(name, symbol) { - fee = fee_; - } - - /** - * @dev The amount of currency available to be lent. - * @param token The loan currency. - * @return The amount of `token` that can be borrowed. - */ - function maxFlashLoan( - address token - ) external view override returns (uint256) { - return type(uint256).max - totalSupply(); - } - - /** - * @dev The fee to be charged for a given loan. - * @param token The loan currency. Must match the address of this contract. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function flashFee( - address token, - uint256 amount - ) external view override returns (uint256) { - require( - token == address(this), - "FlashMinter: Unsupported currency" - ); - return _flashFee(token, amount); - } - - /** - * @dev Loan `amount` tokens to `receiver`, and takes it back plus a `flashFee` after the ERC3156 callback. - * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface. - * @param token The loan currency. Must match the address of this contract. - * @param amount The amount of tokens lent. - * @param data A data parameter to be passed on to the `receiver` for any custom use. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) external override returns (bool){ - require( - token == address(this), - "FlashMinter: Unsupported currency" - ); - uint256 fee = _flashFee(token, amount); - _mint(address(receiver), amount); - require( - receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS, - "FlashMinter: Callback failed" - ); - uint256 _allowance = allowance(address(receiver), address(this)); - require( - _allowance >= (amount + fee), - "FlashMinter: Repay not approved" - ); - _approve(address(receiver), address(this), _allowance - (amount + fee)); - _burn(address(receiver), amount + fee); - return true; - } - - /** - * @dev The fee to be charged for a given loan. Internal function with no checks. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function _flashFee( - address token, - uint256 amount - ) internal view returns (uint256) { - return amount * fee / 10000; - } -} -``` - -### Flash Loan Reference Implementation - -``` -pragma solidity ^0.8.0; - -import "../interfaces/IERC20.sol"; -import "../interfaces/IERC3156FlashBorrower.sol"; -import "../interfaces/IERC3156FlashLender.sol"; - - -/** - * @author Alberto Cuesta Cañada - * @dev Extension of {ERC20} that allows flash lending. - */ -contract FlashLender is IERC3156FlashLender { - - bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); - mapping(address => bool) public supportedTokens; - uint256 public fee; // 1 == 0.0001 %. - - - /** - * @param supportedTokens_ Token contracts supported for flash lending. - * @param fee_ The percentage of the loan `amount` that needs to be repaid, in addition to `amount`. - */ - constructor( - address[] memory supportedTokens_, - uint256 fee_ - ) { - for (uint256 i = 0; i < supportedTokens_.length; i++) { - supportedTokens[supportedTokens_[i]] = true; - } - fee = fee_; - } - - /** - * @dev Loan `amount` tokens to `receiver`, and takes it back plus a `flashFee` after the callback. - * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param data A data parameter to be passed on to the `receiver` for any custom use. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) external override returns(bool) { - require( - supportedTokens[token], - "FlashLender: Unsupported currency" - ); - uint256 fee = _flashFee(token, amount); - require( - IERC20(token).transfer(address(receiver), amount), - "FlashLender: Transfer failed" - ); - require( - receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS, - "FlashLender: Callback failed" - ); - require( - IERC20(token).transferFrom(address(receiver), address(this), amount + fee), - "FlashLender: Repay failed" - ); - return true; - } - - /** - * @dev The fee to be charged for a given loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function flashFee( - address token, - uint256 amount - ) external view override returns (uint256) { - require( - supportedTokens[token], - "FlashLender: Unsupported currency" - ); - return _flashFee(token, amount); - } - - /** - * @dev The fee to be charged for a given loan. Internal function with no checks. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function _flashFee( - address token, - uint256 amount - ) internal view returns (uint256) { - return amount * fee / 10000; - } - - /** - * @dev The amount of currency available to be lent. - * @param token The loan currency. - * @return The amount of `token` that can be borrowed. - */ - function maxFlashLoan( - address token - ) external view override returns (uint256) { - return supportedTokens[token] ? IERC20(token).balanceOf(address(this)) : 0; - } -} - -``` - -## Security Considerations - - -### Verification of callback arguments - -The arguments of `onFlashLoan` are expected to reflect the conditions of the flash loan, but cannot be trusted unconditionally. They can be divided in two groups, that require different checks before they can be trusted to be genuine. - -0. No arguments can be assumed to be genuine without some kind of verification. `initiator`, `token` and `amount` refer to a past transaction that might not have happened if the caller of `onFlashLoan` decides to lie. `fee` might be false or calculated incorrectly. `data` might have been manipulated by the caller. -1. To trust that the value of `initiator`, `token`, `amount` and `fee` are genuine a reasonable pattern is to verify that the `onFlashLoan` caller is in a whitelist of verified flash lenders. Since often the caller of `flashLoan` will also be receiving the `onFlashLoan` callback this will be trivial. In all other cases flash lenders will need to be approved if the arguments in `onFlashLoan` are to be trusted. -2. To trust that the value of `data` is genuine, in addition to the check in point 1, it is recommended to verify that the `initiator` belongs to a group of trusted addresses. Trusting the `lender` and the `initiator` is enough to trust that the contents of `data` are genuine. - -### Flash lending security considerations - -#### Automatic approvals for untrusted borrowers -The safest approach is to implement an approval for `amount+fee` before the `flashLoan` is executed. - -Including in `onFlashLoan` the approval for the `lender` to take the `amount + fee` needs to be combined with a mechanism to verify that the borrower is trusted, such as those described above. - -If an unsuspecting contract with a non-reverting fallback function, or an EOA, would approve a `lender` implementing ERC3156, and not immediately use the approval, and if the `lender` would not verify the return value of `onFlashLoan`, then the unsuspecting contract or EOA could be drained of funds up to their allowance or balance limit. This would be executed by a `borrower` calling `flashLoan` on the victim. The flash loan would be executed and repaid, plus any fees, which would be accumulated by the `lender`. For this reason, it is important that the `lender` implements the specification in full and reverts if `onFlashLoan` doesn't return the keccak256 hash for "ERC3156FlashBorrower.onFlashLoan". - -### Flash minting external security considerations - -The typical quantum of tokens involved in flash mint transactions will give rise to new innovative attack vectors. - -#### Example 1 - interest rate attack -If there exists a lending protocol that offers stable interests rates, but it does not have floor/ceiling rate limits and it does not rebalance the fixed rate based on flash-induced liquidity changes, then it could be susceptible to the following scenario: - -FreeLoanAttack.sol -1. Flash mint 1 quintillion STAB -2. Deposit the 1 quintillion STAB + $1.5 million worth of ETH collateral -3. The quantum of your total deposit now pushes the stable interest rate down to 0.00001% stable interest rate -4. Borrow 1 million STAB on 0.00001% stable interest rate based on the 1.5M ETH collateral -5. Withdraw and burn the 1 quint STAB to close the original flash mint -6. You now have a 1 million STAB loan that is practically interest free for perpetuity ($0.10 / year in interest) - -The key takeaway being the obvious need to implement a flat floor/ceiling rate limit and to rebalance the rate based on short term liquidity changes. - -#### Example 2 - arithmetic overflow and underflow -If the flash mint provider does not place any limits on the amount of flash mintable tokens in a transaction, then anyone can flash mint 2^256-1 amount of tokens. - -The protocols on the receiving end of the flash mints will need to ensure their contracts can handle this, either by using a compiler that embeds overflow protection in the smart contract bytecode, or by setting explicit checks. - -### Flash minting internal security considerations - -The coupling of flash minting with business specific features in the same platform can easily lead to unintended consequences. - -#### Example - Treasury draining -Assume a smart contract that flash lends its native token. The same smart contract borrows from a third party when users burn the native token. This pattern would be used to aggregate in the smart contract the collateralized debt of several users into a single account in the third party. The flash mint could be used to cause the lender to borrow to its limit, and then pushing interest rates in the underlying lender, liquidate the flash lender: -1. Flash mint from `lender` a very large amount of FOO. -2. Redeem FOO for BAR, causing `lender` to borrow from `underwriter` all the way to its borrowing limit. -3. Trigger a debt rate increase in `underwriter`, making `lender` undercollateralized. -4. Liquidate the `lender` for profit. - -## 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-3156.md diff --git a/EIPS/eip-3198.md b/EIPS/eip-3198.md index d9980131fbd5e3..fdad71935dfae2 100644 --- a/EIPS/eip-3198.md +++ b/EIPS/eip-3198.md @@ -3,7 +3,7 @@ eip: 3198 title: BASEFEE opcode author: Abdelhamid Bakhta (@abdelhamidbakhta), Vitalik Buterin (@vbuterin) discussions-to: https://ethereum-magicians.org/t/eip-3198-basefeeopcode/5162 -status: Review +status: Final type: Standards Track category: Core created: 2021-01-13 @@ -59,4 +59,4 @@ Consumed gas: `2` 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3220.md b/EIPS/eip-3220.md index 8aef74d1759ea6..949413a3f24231 100644 --- a/EIPS/eip-3220.md +++ b/EIPS/eip-3220.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-10-21 @@ -45,10 +45,10 @@ Hence there is need for a more robust blockchain identifier that will overcome t | Name | Size(bytes) | Description | |---------------|-------------|-------------| | Truncated Block Hash | 16 | This is the block hash of the genesis block or the block hash of 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| 4 | 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 | Researve 0x00 as undefined chaintype. 0x01 as mainnet type. 0x1[0-A]: testnet, 0x2[0-A]: private development network| +|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 | 7 | Reserved for future use. Use 000000 for now. | +| 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. | @@ -58,7 +58,8 @@ We have considered various alternative specifications such as using a random uni ## Backwards Compatibility -Crosschainid can be backward compatible with EIP-155. The crosschain id contains a 4 byte segment to record the chainid based on EIP-155. +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 @@ -72,4 +73,4 @@ For blockchains that do not cryptographically sign crosschain id into the blocks ## 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-3224.md b/EIPS/eip-3224.md index 94b48a572b15f6..7d22ce6165ce0a 100644 --- a/EIPS/eip-3224.md +++ b/EIPS/eip-3224.md @@ -1,447 +1,7 @@ --- eip: 3224 -title: Described Data and Described Transactions -author: Richard Moore (@ricmoo), Nick Johnson (@arachnid) -discussions-to: https://github.com/ethereum/EIPs/issues/3225 -status: Draft -type: Standards Track category: ERC -created: 2021-01-23 -requires: 191 +status: Moved --- -## Simple Summary - -A technique for contract authors to enable wallets to provide -a human-readable description of what a given contract -interaction (via a transaction or signed message) will perform. - - -## Abstract - -Human-readable descriptions for machine executable operations, -described in higher level machine readable data, so that wallets -can provide meaningful feedback to the user describing the -action the user is about to perform. - - -## Motivation - -When using an Ethereum Wallet (e.g. MetaMask, Clef, Hardware -Wallets) users must accept and authorize signing messages or -sending transactions. - -Due to the complexity of Ethereum transactions, wallets are very -limitd in their ability to provide insight into the contents of -transactions user are approving; outside special-cased support -for common transactions such as ERC20 transfers, this often amounts -to asking the user to sign an opaque blob of binary data. - -This EIP presents a method for dapp developers to enable a more -comfortable user experience by providing wallets with a means -to generate a better description about what the contract claims -will happen. - -It does not address malicious contracts which wish to lie, it -only addresses honest contracts that want to make their user's -life better. We believe that this is a reasonable security model, -as transaction descriptions can be audited at the same time as -contract code, allowing auditors and code reviewers to check that -transaction descriptions are accurate as part of their review. - - -## Specification - -The **description string** and **described data** are generated -simultaneously by evaluating the contract -(i.e. the **describer**), passing the **describer inputs** to the -method: - -```solidity -function eipXXXDescribe(bytes describer_inputs) view returns (string description_string, bytes described_data); -``` - -The method must be executable in a static context, (i.e. any -side effects, such as logX, sstore, etc.), including through -indirect calls may be ignored. - -During evaluation, the `ADDRESS` (i.e. `to`), `CALLER` -(i.e. `from`), `VALUE`, and `GASPRICE` must be the same as the -values for the transaction being described, so that the -code generating the description can rely on them. For signing -**described messages**, `VALUE` should always be 0. - -When executing the bytecode, best efforts should be made to -ensure `BLOCKHASH`, `NUMBER`, `TIMESTAMP` and `DIFFICULTY` -match the `"latest"` block. The `COINBASE` should be the zero -address. - -The method may revert, in which case the signing must be aborted. - - -### New JSON-RPC Methods - -Clients which manage private keys should expose additional -methods for interacting with the related accounts. - -If an user interface is not present or expected for any other -account-based operations, the description strings should be -ignored and the described data used directly. - -These JSON-RPC methods will also be implemented in standard -Ethereum libraries, so the JSON-RPC description is meant more -of a canonical way to describe them. - - -### Signing Described Messages - -```solidity -eth_signDescribedMessage(address, describer, describerInput) -// Result: { -// description: "text/plain;Hello World", -// data: "0x...", // described data -// signature: "0x..." -// } -``` - -Compute the **description string** and **described data** by -evaluating the call to **describer**, with the -**describerInput** passed to the ABI encoded call to -`eipXXXDescription(bytes)`. The `VALUE` during execution must -be 0. - -If the wallet contains a user interface for accepting or -denying signing a message, it should present the description -string to the user. Optionally, a wallet may wish to -additionally provide a way to examine the described data. - -If accepted, the computed **described data** is signed -according to [EIP-191](./eip-191.md), with the *version -byte* of `0x00` and the *version specific data* of describer -address. - -That is: - -``` -0x19 0x00 DESCRIBER_ADDRESS 0xDESCRIBED_DATA -``` - -The returned result includes the **described data**, allowing -dapps that use parameters computed in the contract to be -available. - -### Sending Described Transactions - -```solidity -eth_sendDescribedTransaction(address, { - to: "0x...", - value: 1234, - nonce: 42, - gas: 42000, - gasPrice: 9000000000, - describerInput: "0x1234...", -}) -// Result: { -// description: "text/plain;Hello World", -// transaction: "0x...", // serialized signed transaction -// } -``` - -Compute the **description string** and **described data** by -evaluating the call to the **describer** `to`, with the -**describerInput** passed to the ABI encoded call to -`eipXXXDescription(bytes)`. - -If the wallet contains a user interface for accepting or -denying a transaction, it should present the description string -along with fee and value information. Optionally, a wallet may -wish to additionally provide a way to further examine the -transaction. - -If accepted, the transaction data is set to the computed -**described data**, the derived transaction is signed and sent, -and the **description string** and serialized signed -transaction is returned. - - -### Signing Described Transaction - -```solidity -eth_signDescribedTransaction(address, { - to: "0x...", - value: 1234, - nonce: 42, - gas: 42000, - gasPrice: 9000000000, - describerInput: "0x1234...", -}) -// Result: { -// description: "text/plain;Hello World", -// transaction: "0x...", // serialized signed transaction -// } -``` - -Compute the **description string** and **described data** by -evaluating the call to the **describer** `to`, with the -**describerInput** passed to the ABI encoded call to -`eipXXXDescription(bytes)`. - -If the wallet contains a user interface for accepting or -denying a transaction, it should present the description string -along with fee and value information. Optionally, a wallet may -wish to additionally provide a way to further examine the -transaction. - -If accepted, the transaction data is set to the computed -**described data**, the derived transaction is signed (and not -sent) and the **description string** and serialized signed -transaction is returned. - -### Description Strings - -A **description string** must begin with a mime-type followed -by a semi-colon (`;`). This EIP specifies only the `text/plain` -mime-type, but future EIPs may specify additional types to -enable more rich processing, such as `text/markdown` so that -addresses can be linkable within clients or to enable -multi-locale options, similar to multipart/form-data. - - -## Rationale - -### Meta Description - -There have been many attempts to solve this problem, many of -which attempt to examine the encoded transaction data or -message data directly. - -In many cases, the information that would be necessary for a -meaningful description is not present in the final encoded -transaction data or message data. - -Instead this EIP uses an indirect description of the data. - -For example, the `commit(bytes32)` method of ENS places a -commitement **hash** on-chain. The hash contains the -**blinded** name and address; since the name is blinded, the -encoded data (i.e. the hash) no longer contains the original -values and is insufficient to access the necessary values to -be included in a description. - -By instead describing the commitment indirectly (with the -original information intact: NAME, ADDRESS and SECRET) a -meaningful description can be computed (e.g. "commit to NAME for ADDRESS (with SECRET)") -and the matching data can be computed (i.e. `commit(hash(name, owner, secret))`). - -### Entangling the Contract Address - -To prevent data being signed from one contract being used -against another, the contract address is entanlged into -both the transaction (implicitly via the `to` field) and -in messages by the EIP-191 versions specific data. - -The use of the zero address is reserved. - -### Alternatives - -- NatSpec and company are a class of more complex languages that attempt to describe the encoded data directly. Because of the language complexity they often end up being quite large requiring entire runtime environments with ample processing power and memory, as well as additional sandboxing to reduce security concerns. One goal of this is to reduce the complexity to something that could execute on hardware wallets and other simple wallets. These also describe the data directly, which in many cases (such as blinded data), cannot adequately describe the data at all - -- Custom Languages; due to the complexity of Ethereum transactions, any language used would require a lot of expressiveness and re-inventing the wheel. The EVM already exists (it may not be ideal), but it is there and can handle everything necessary. - -- Format Strings (e.g. Trustless Signing UI Protocol; format strings can only operate on the class of regular languages, which in many cases is insufficient to describe an Ethereum transaction. This was an issue quite often during early attempts at solving this problem. - -- The signTypedData [EIP-712](./eip-712.md) has many parallels to what this EIP aims to solve - -- @TODO: More - - -## Backwards Compatibility - -All signatures for messages are generated using [EIP-191](./eip-191.md) -which had a previously compatible version byte of `0x00`, so -there should be no concerns with backwards compatibility. - - -## Test Cases - -All test cases operate against the published and verified contracts: - -- [Formatter](https://ropsten.etherscan.io/address/0x7a89c0521604008c93c97aa76950198bca73d933#code) -- [TestFormatter](https://ropsten.etherscan.io/address/0xab3045aa85cbcabb06ed3f3fe968fa5457727270#code) - -The private key used for signing messages and transactions is: - -``` -privateKey = "0x6283185307179586476925286766559005768394338798750211641949889184" -``` - - -### Messages - -**Example: login with signed message** - -- sends selector login() -- received data with selector doLogin(bytes32 timestamp) - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0xb34e97e800000000000000000000000000000000000000000000000000000000 - i.e. encode( - [ "bytes4" ], - [ SEL("login()") ] - ) - -Output: - Description: text/plain;Log into ethereum.org? - Data: 0x14629d78000000000000000000000000000000000000000000000000000000006010d607 - i.e. encodeWithSelector("doLogin(bytes32)", "0x000000000000000000000000000000000000000000000000000000006010d607" ] - -Signing: - Preimage: 0x1900ab3045aa85cbcabb06ed3f3fe968fa545772727014629d78000000000000000000000000000000000000000000000000000000006010d607 - Signature: 0x8b9def29343c85797a580c5cd3607c06e78a53351219f9ba706b9985c1a3c91e702bf678e07f5daf5ef48b3e3cc581202de233904b72cf2c4f7d714ce92075b21c -``` - -### Transactions - -All transaction test cases use the ropsten network (chainId: 3) -and for all unspecified properties use 0. - -**Example: ERC-20 transfer** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0xa9059cbb000000000000000000000000000000000000000000000000000000000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000002b992b75cbeb6000 - i.e. encode( - [ "bytes4", "address", "uint"], - [ SEL("transfer(address,uint256)"), "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18 ] - ) -Output: - Description: text/plain;Send 3.14159 TOKN to "ricmoose.eth" (0x8ba1f109551bD432803012645Ac136ddd64DBA72)? - Described Data: 0xa9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72 - i.e. encodeWithSelector("transfer(address,uint256)", "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18) - -Signing: - Signed Transaction: 0xf8a280808094ab3045aa85cbcabb06ed3f3fe968fa545772727080b844a9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba7229a0f33ea492d326ac32d9b7ae203c61bf7cf0ac576fb0cf8be8e4c63dc89c90de12a06c8efb28aaf3b70c032b3bd1edfc664578c49f040cf749bb19b000da56507fb2 -``` - -**Example: ERC-20 approve** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0x095ea7b3000000000000000000000000000000000000000000000000000000000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000002b992b75cbeb6000 - i.e. encode( - [ "bytes4", "address", "uint"], - [ SEL("approve(address,uint256)"), "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18 ] - ) - -Output: - Description: text/plain;Approve "ricmoose.eth" (0x8ba1f109551bD432803012645Ac136ddd64DBA72) to manage 3.14159 TOKN tokens? - Described Data: 0xa9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72 - i.e. encodeWithSelector("approve(address,uint256)", "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18) - -Signing: - Signed Transaction: 0xf8a280808094ab3045aa85cbcabb06ed3f3fe968fa545772727080b844a9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba7229a0f33ea492d326ac32d9b7ae203c61bf7cf0ac576fb0cf8be8e4c63dc89c90de12a06c8efb28aaf3b70c032b3bd1edfc664578c49f040cf749bb19b000da56507fb2 -``` - -**Example: ENS commit** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0x0f0e373f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000e31f43c1d823afaa67a8c5fbb8348176d225a79e65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b00000000000000000000000000000000000000000000000000000000000000087269636d6f6f7365000000000000000000000000000000000000000000000000 - i.e. encode( - [ "bytes4", "string", "address", "bytes32"], - [ SEL("commit(string,address,bytes32)"), "ricmoose", "0xE31f43C1d823AfAA67A8C5fbB8348176d225A79e", "0x65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b" ] - ) - -Output: - Description: text/plain;Commit to the ENS name "ricmoose.eth" for 0xE31f43C1d823AfAA67A8C5fbB8348176d225A79e? - Described Data: 0xf14fcbc8e4a4f2bb818545497be34c7ab30e6e87e0001df4ba82e7c8b3f224fbaf255b91 - i.e. encodeWithSelector("commit(bytes32)", makeCommitment("ricmoose", "0xE31f43C1d823AfAA67A8C5fbB8348176d225A79e", "0x65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b")) - -Signing: - Signed Transaction: 0xf88180808094ab3045aa85cbcabb06ed3f3fe968fa545772727080a4f14fcbc8e4a4f2bb818545497be34c7ab30e6e87e0001df4ba82e7c8b3f224fbaf255b912aa0a62b41d1ebda584fe84cf8a05f61b429fe4ec361e13c17f30a23281106b38a8da00bcdd896fe758d8f0cfac46445a48f76f5e9fe27790d67c51412cb98a12a0844 -``` - -**Example: WETH mint()** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0x1249c58b00000000000000000000000000000000000000000000000000000000 - i.e. encode( - [ "bytes4" ], - [ SEL("mint()") ] - ) - Value: 1.23 ether - -Output: - Description: text/plain;Mint 1.23 WETH (spending 1.23 ether)? - Described Data: 0x1249c58b - i.e. encodeWithSelector("mint()") - -Signing: - Signed Transaction: 0xf86980808094ab3045aa85cbcabb06ed3f3fe968fa5457727270881111d67bb1bb0000841249c58b29a012df802e1394a97caab23c15c3a8c931668df4b2d6d604ca23f3f6b836d0aafca0071a2aebef6a9848616b4d618912f2003fb4babde3dba451b5246f866281a654 -``` - -## Reference Implementation - -@TODO (consider adding it as one or more files in `../assets/eip-####/`) - -I will add examples in Solidity and JavaScript. - - -## Security Considerations - -### Escaping Text - -Wallets must be careful when displaying text provided by -contracts and proper efforts must be taken to sanitize -it, for example, be sure to consider: - -- HTML could be enbedded to attempt to trick web-based wallets into [executing code](https://en.wikipedia.org/wiki/Code_injection) using the script tag (possibly uploading any private keys to a server) -- In general, extreme care must be used when rendering HTML; consider the ENS names `not-ricmoo.eth` or ` ricmoo.eth`, which if rendered without care would appear as `ricmoo.eth`, which it is not -- Other marks which require escaping could be included, such as quotes (`"`), formatting (`\n` (new line), `\f` (form feed), `\t` (tab), any of many [non-standard whitespaces](https://en.wikipedia.org/wiki/Whitespace_character#Spaces_in_Unicode)), back-slassh (`\`) -- UTF-8 has had bugs in the past which could allow arbitrary code execution and [crashing renderers](https://osxdaily.com/2015/05/27/bug-crashes-messages-app-ios-workaround/); consider using the UTF-8 replacement character (or *something*) for code-points outside common planes or common sub-sets within planes -- [Homoglyphs attacks](https://en.wikipedia.org/wiki/IDN_homograph_attack) -- [Right-to-left](https://en.wikipedia.org/wiki/Right-to-left_mark) mark may affect rendering -- Many other things, deplnding on your environment - -### Distinguished Signed Data - -Applications implementing this EIP to sign message data should -ensure there are no collisions within the data which could -result in ambiguously signed data. - -@TODO: Expand on this; compare packed data to ABI encoded data? - -### Enumeration - -If an abort occurs during signing, the response from this call -should match the response from a declined signing request; -otherwise this could be used for enumeration attacks, etc. A -random interactive-scale delay should also be added, otherwise -a < 10ms response could be interpreted as an error. - -### Replayablility - -Transactions contain an explicit nonce, but signed messages do -not. - -For many purposes, such as signing in, a nonce could be -injected (using block.timestamp) into the data. The log in -service can verify this is a recent timestamp. The timestamp -may or may not be omitted from the description string in this -case, as it it largely useful internally only. - -In general, when signing messages a nonce often makes sense to -include to prevent the same signed data from being used in the -future. - - -## 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-3224.md diff --git a/EIPS/eip-3234.md b/EIPS/eip-3234.md index cc8d88a883a3f3..72fccc38651821 100644 --- a/EIPS/eip-3234.md +++ b/EIPS/eip-3234.md @@ -1,226 +1,7 @@ --- eip: 3234 -title: Batch Flash Loans -author: Alberto Cuesta Cañada (@albertocuestacanada), Fiona Kobayashi (@fifikobayashi), fubuloubu (@fubuloubu), Austin Williams (@onewayfunction) -discussions-to: https://ethereum-magicians.org/t/erc-3234-batch-flash-loans/5271 -status: Draft -type: Standards Track category: ERC -created: 2021-01-31 +status: Moved --- -## Simple Summary - -This ERC provides standard interfaces and processes for multiple-asset flash loans. - -## Motivation - -Flash loans of multiple assets, or batch flash loans, are a common offering of flash lenders, and have a strong use case in the simultaneous refinance of several positions between platforms. At the same time, batch flash loans are more complicated to use than single asset flash loans (ER3156). This divergence of use cases and user profiles calls for independent, but consistent, standards for single asset flash loans and batch flash loans. - - -## Specification - -A batch flash lending feature integrates two smart contracts using a callback pattern. These are called the LENDER and the RECEIVER in this EIP. - -### Lender Specification - -A `lender` MUST implement the IERC3234BatchFlashLender interface. -``` -pragma solidity ^0.7.0 || ^0.8.0; -import "./IERC3234BatchFlashBorrower.sol"; - - -interface IERC3234BatchFlashLender { - - /** - * @dev The amount of currency available to be lended. - * @param tokens The currency for each loan in the batch. - * @return The maximum amount that can be borrowed for each loan in the batch. - */ - function maxFlashLoan( - address[] calldata tokens - ) external view returns (uint256[]); - - /** - * @dev The fees to be charged for a given batch loan. - * @param tokens The loan currencies. - * @param amounts The amounts of tokens lent. - * @return The amount of each `token` to be charged for each loan, on top of the returned principal. - */ - function flashFee( - address[] calldata tokens, - uint256[] calldata amounts - ) external view returns (uint256[]); - - /** - * @dev Initiate a batch flash loan. - * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. - * @param tokens The loan currencies. - * @param amounts The amount of tokens lent. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - */ - function batchFlashLoan( - IERC3234BatchFlashBorrower receiver, - address[] calldata tokens, - uint256[] calldata amounts, - bytes[] calldata data - ) external returns (bool); -} -``` - -The `maxFlashLoan` function MUST return the maximum loan possible for each `token`. If a `token` is not currently supported `maxFlashLoan` MUST return 0, instead of reverting. - -The `flashFee` function MUST return the fees charged for each loan of `amount` `token`. If a token is not supported `flashFee` MUST revert. - -The `batchFlashLoan` function MUST include a callback to the `onBatchFlashLoan` function in a `IERC3234BatchFlashBorrower` contract. - -``` -function batchFlashLoan( - IERC3234BatchFlashBorrower receiver, - address[] calldata tokens, - uint256[] calldata amounts, - bytes calldata data -) external returns (bool) { - ... - require( - receiver.onBatchFlashLoan( - msg.sender, - tokens, - amounts, - fees, - data - ) == keccak256("ERC3234BatchFlashBorrower.onBatchFlashLoan"), - "IERC3234: Callback failed" - ); - ... -} -``` - -The `batchFlashLoan` function MUST transfer `amounts[i]` of each `tokens[i]` to `receiver` before the callback to the borrower. - -The `batchFlashLoan` function MUST include `msg.sender` as the `initiator` to `onBatchFlashLoan`. - -The `batchFlashLoan` function MUST NOT modify the `tokens`, `amounts` and `data` parameters received, and MUST pass them on to `onBatchFlashLoan`. - -The `lender` MUST verify that the `onBatchFlashLoan` callback returns the keccak256 hash of "ERC3234BatchFlashBorrower.onBatchFlashLoan". - -The `batchFlashLoan` function MUST include a `fees` argument to `onBatchFlashLoan` with the fee to pay for each individual `token` and `amount` lent, ensuring that `fees[i] == flashFee(tokens[i], amounts[i])`. - -After the callback, for each `token` in `tokens`, the `batchFlashLoan` function MUST take the `amounts[i] + fees[i]` of `tokens[i]` from the `receiver`, or revert if this is not successful. - -If successful, `batchFlashLoan` MUST return `true`. - -### Receiver Specification - -A `receiver` of flash loans MUST implement the IERC3234BatchFlashBorrower interface: - -``` -pragma solidity ^0.7.0 || ^0.8.0; - - -interface IERC3234BatchFlashBorrower { - - /** - * @dev Receive a flash loan. - * @param initiator The initiator of the loan. - * @param tokens The loan currency. - * @param amounts The amount of tokens lent. - * @param fees The additional amount of tokens to repay. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - * @return The keccak256 hash of "ERC3234BatchFlashBorrower.onBatchFlashLoan" - */ - function onBatchFlashLoan( - address initiator, - address[] calldata tokens, - uint256[] calldata amounts, - uint256[] calldata fees, - bytes calldata data - ) external returns (bytes32); -} -``` - -For the transaction to not revert, for each `token` in `tokens`, `receiver` MUST approve `amounts[i] + fees[i]` of `tokens[i]` to be taken by `msg.sender` before the end of `onBatchFlashLoan`. - -If successful, `onBatchFlashLoan` MUST return the keccak256 hash of "ERC3156BatchFlashBorrower.onBatchFlashLoan". - -## Rationale - -The interfaces described in this ERC have been chosen as to cover the known flash lending use cases, while allowing for safe and gas efficient implementations. - -`flashFee` reverts on unsupported tokens, because returning a numerical value would be incorrect. - -`batchFlashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the lender, and including both the use cases in which the tokens lended are held or minted by the lender. - -`receiver` is taken as a parameter to allow flexibility on the implementation of separate loan initiators and receivers. - -Existing flash lenders (Aave, dYdX and Uniswap) all provide flash loans of several token types from the same contract (LendingPool, SoloMargin and UniswapV2Pair). Providing a `token` parameter in both the `batchFlashLoan` and `onBatchFlashLoan` functions matches closely the observed functionality. - -A `bytes calldata data` parameter is included for the caller to pass arbitrary information to the `receiver`, without impacting the utility of the `batchFlashLoan` standard. - -`onBatchFlashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the `receiver`, and following the `onAction` naming pattern used as well in EIP-667. - -An `initiator` will often be required in the `onBatchFlashLoan` function, which the lender knows as `msg.sender`. An alternative implementation which would embed the `initiator` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -The `amounts` will be required in the `onBatchFlashLoan` function, which the lender took as a parameter. An alternative implementation which would embed the `amounts` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -The `fees` will often be calculated in the `batchFlashLoan` function, which the `receiver` must be aware of for repayment. Passing the `fees` as a parameter instead of appended to `data` is simple and effective. - -The `amount + fee` are pulled from the `receiver` to allow the `lender` to implement other features that depend on using `transferFrom`, without having to lock them for the duration of a flash loan. An alternative implementation where the repayment is transferred to the `lender` is also possible, but would need all other features in the lender to be also based in using `transfer` instead of `transferFrom`. Given the lower complexity and prevalence of a "pull" architecture over a "push" architecture, "pull" was chosen. - -## Security Considerations - -### Verification of callback arguments - -The arguments of `onBatchFlashLoan` are expected to reflect the conditions of the flash loan, but cannot be trusted unconditionally. They can be divided in two groups, that require different checks before they can be trusted to be genuine. - -0. No arguments can be assumed to be genuine without some kind of verification. `initiator`, `tokens` and `amounts` refer to a past transaction that might not have happened if the caller of `onBatchFlashLoan` decides to lie. `fees` might be false or calculated incorrectly. `data` might have been manipulated by the caller. -1. To trust that the value of `initiator`, `tokens`, `amounts` and `fees` are genuine a reasonable pattern is to verify that the `onBatchFlashLoan` caller is in a whitelist of verified flash lenders. Since often the caller of `batchFlashLoan` will also be receiving the `onBatchFlashLoan` callback this will be trivial. In all other cases flash lenders will need to be approved if the arguments in `onBatchFlashLoan` are to be trusted. -2. To trust that the value of `data` is genuine, in addition to the check in point 1, it is recommended that the `receiver` verifies that the `initiator` is in some list of trusted addresses. Trusting the `lender` and the `initiator` is enough to trust that the contents of `data` are genuine. - -### Flash lending security considerations - -#### Automatic approvals for untrusted borrowers -The safest approach is to implement an approval for `amount+fee` before the `batchFlashLoan` is executed. - -Including in `onBatchFlashLoan` the approval for the `lender` to take the `amount + fee` needs to be combined with a mechanism to verify that the borrower is trusted, such as those described above. - -If an unsuspecting contract with a non-reverting fallback function, or an EOA, would approve a `lender` implementing ERC3156, and not immediately use the approval, and if the `lender` would not verify the return value of `onBatchFlashLoan`, then the unsuspecting contract or EOA could be drained of funds up to their allowance or balance limit. This would be executed by a `borrower` calling `batchFlashLoan` on the victim. The flash loan would be executed and repaid, plus any fees, which would be accumulated by the `lender`. For this reason, it is important that the `lender` implements the specification in full and reverts if `onBatchFlashLoan` doesn't return the keccak256 hash for "ERC3156FlashBorrower.onBatchFlashLoan". - -### Flash minting external security considerations - -The typical quantum of tokens involved in flash mint transactions will give rise to new innovative attack vectors. - -#### Example 1 - interest rate attack -If there exists a lending protocol that offers stable interests rates, but it does not have floor/ceiling rate limits and it does not rebalance the fixed rate based on flash-induced liquidity changes, then it could be susceptible to the following scenario: - -FreeLoanAttack.sol -1. Flash mint 1 quintillion DAI -2. Deposit the 1 quintillion DAI + $1.5 million worth of ETH collateral -3. The quantum of your total deposit now pushes the stable interest rate down to 0.00001% stable interest rate -4. Borrow 1 million DAI on 0.00001% stable interest rate based on the 1.5M ETH collateral -5. Withdraw and burn the 1 quint DAI to close the original flash mint -6. You now have a 1 million DAI loan that is practically interest free for perpetuity ($0.10 / year in interest) - -The key takeaway being the obvious need to implement a flat floor/ceiling rate limit and to rebalance the rate based on short term liquidity changes. - -#### Example 2 - arithmetic overflow and underflow -If the flash mint provider does not place any limits on the amount of flash mintable tokens in a transaction, then anyone can flash mint 2^256-1 amount of tokens. - -The protocols on the receiving end of the flash mints will need to ensure their contracts can handle this. One obvious way is to leverage OpenZeppelin's SafeMath libraries as a catch-all safety net, however consideration should be given to when it is or isn't used given the gas tradeoffs. - -If you recall there was a series of incidents in 2018 where exchanges such as OKEx, Poloniex, HitBTC and Huobi had to shutdown deposits and withdrawls of ERC20 tokens due to integer overflows within the ERC20 token contracts. - - -### Flash minting internal security considerations - -The coupling of flash minting with business specific features in the same platform can easily lead to unintended consequences. - -#### Example - Treasury draining -In early implementations of the Yield Protocol flash loaned fyDai could be redeemed for Dai, which could be used to liquidate the Yield Protocol CDP vault in MakerDAO: -1. Flash mint a very large amount of fyDai. -2. Redeem for Dai as much fyDai as the Yield Protocol collateral would allow. -3. Trigger a stability rate increase with a call to `jug.drip` which would make the Yield Protocol uncollateralized. -4. Liquidate the Yield Protocol CDP vault in MakerDAO. - -## 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-3234.md diff --git a/EIPS/eip-3238.md b/EIPS/eip-3238.md index 4ed573cce5ec4e..3fa3a6c9bed155 100644 --- a/EIPS/eip-3238.md +++ b/EIPS/eip-3238.md @@ -5,7 +5,7 @@ author: Afri Schoedon (@q9f) discussions-to: https://github.com/ethereum/EIPs/issues/3239 type: Standards Track category: Core -status: Draft +status: Stagnant created: 2021-01-25 --- @@ -36,4 +36,4 @@ Alternatively, in order to maintain stability of the system, a it can be conside There are no known security issues with this proposal. ## 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-3267.md b/EIPS/eip-3267.md index fc489da16a4996..c44fe3e481a54a 100644 --- a/EIPS/eip-3267.md +++ b/EIPS/eip-3267.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2021-02-13 @@ -37,7 +37,7 @@ Paradoxically, it will directly benefit miners/validators, see the discussion. `MineFraction` = `TBD` (0..1) -[The contracts source](../assets/eip-3267/contracts/README.md) +[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. @@ -66,4 +66,4 @@ The security considerations are: See more in the discussion. ## 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-3298.md b/EIPS/eip-3298.md index fa32af840a2ee5..daa52e7df42625 100644 --- a/EIPS/eip-3298.md +++ b/EIPS/eip-3298.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2021-02-26 @@ -92,4 +92,4 @@ If refunds were to be removed, this would be the comparative table 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-3300.md b/EIPS/eip-3300.md index 8ca17c5ee7770d..d120916957c9f7 100644 --- a/EIPS/eip-3300.md +++ b/EIPS/eip-3300.md @@ -3,7 +3,7 @@ eip: 3300 title: Phase out refunds author: William Morriss (@wjmelements) discussions-to: https://ethereum-magicians.org/t/eip-3300-phase-out-refunds/5434 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2020-02-26 @@ -75,4 +75,4 @@ The effect of this will be increased gas price volatility: higher highs and lowe 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3322.md b/EIPS/eip-3322.md index 19d358f2402cc3..e865e06c84c03f 100644 --- a/EIPS/eip-3322.md +++ b/EIPS/eip-3322.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2020-03-04 @@ -65,4 +65,4 @@ Because the gas is added to the refund counter, no compatibility issues are anti DoS is already limited by the 50% refund limit. ## 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-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 index 6ce2475d317601..082ceaa1b78ace 100644 --- a/EIPS/eip-3332.md +++ b/EIPS/eip-3332.md @@ -94,4 +94,4 @@ The strategy described for preventing front-running by setting an upper bound on ## 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-3336.md b/EIPS/eip-3336.md index abc79a0725f35f..81015e9bf3d804 100644 --- a/EIPS/eip-3336.md +++ b/EIPS/eip-3336.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2021-03-06 @@ -68,4 +68,4 @@ TBD 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3337.md b/EIPS/eip-3337.md index 6a93ee2bd7281d..73ac30414505fa 100644 --- a/EIPS/eip-3337.md +++ b/EIPS/eip-3337.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2021-03-06 @@ -96,4 +96,4 @@ This EIP exclusively introduces new opcodes, and as a result should not impact a 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3338.md b/EIPS/eip-3338.md index 70e24b25198be3..0b61fe18b671d1 100644 --- a/EIPS/eip-3338.md +++ b/EIPS/eip-3338.md @@ -3,11 +3,11 @@ 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: Last Call +status: Withdrawn +withdrawal-reason: Withdrawn in favor of [EIP-2681](./eip-2681.md) type: Standards Track category: Core created: 2021-03-07 -review-period-end: 2021-03-25 --- ## Abstract @@ -52,4 +52,4 @@ None. ## 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-3368.md b/EIPS/eip-3368.md index bf5e49f4a2905e..6c186b22a8edd4 100644 --- a/EIPS/eip-3368.md +++ b/EIPS/eip-3368.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2021-03-12 @@ -38,7 +38,7 @@ elif 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" ; Recomendation to have in a fast track state, but NOT deployed to mainnet unless needed. +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. diff --git a/EIPS/eip-3372.md b/EIPS/eip-3372.md index 173bb494213748..9ac605a523ee7f 100644 --- a/EIPS/eip-3372.md +++ b/EIPS/eip-3372.md @@ -1,7 +1,7 @@ --- eip: 3372 title: 5 FNV primes for ethash -status: Draft +status: Stagnant type: Standards Track category: Core author: mineruniter969 (@mineruniter969), mineruniter969 @@ -120,4 +120,4 @@ There are no known security issues with this change. ## 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-3382.md b/EIPS/eip-3382.md index d32e00709b9d08..06788cb6911328 100644 --- a/EIPS/eip-3382.md +++ b/EIPS/eip-3382.md @@ -3,7 +3,8 @@ eip: 3382 title: Hardcoded Block Gas Limit author: Philippe Castonguay (@PhABC) discussions-to: https://ethereum-magicians.org/t/eip-3382-hardcoded-gas-limit -status: Review +status: Withdrawn +withdrawal-reason: The author prefers [EIP-3756](./eip-3756.md) type: Standards Track category: Core created: 2021-03-13 @@ -47,4 +48,4 @@ Rapid changes to the gas limit will likely be more difficult to execute, which c ## 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-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 index 8684051733bf06..bee317c77b1197 100644 --- a/EIPS/eip-3403.md +++ b/EIPS/eip-3403.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2021-03-16 @@ -131,4 +131,4 @@ Refunds are not visible to transaction execution, so this should not have any im 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](https://creativecommons.org/publicdomain/zero/1.0/). +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3416.md b/EIPS/eip-3416.md index 7c9ab1e1de41b7..d84650c14b5047 100644 --- a/EIPS/eip-3416.md +++ b/EIPS/eip-3416.md @@ -3,7 +3,7 @@ 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: Draft +status: Stagnant type: Standards Track category: Core created: 2021-03-18 @@ -101,4 +101,4 @@ 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-3436.md b/EIPS/eip-3436.md index bb43590ce8532f..b2476b0c7f9adf 100644 --- a/EIPS/eip-3436.md +++ b/EIPS/eip-3436.md @@ -3,9 +3,9 @@ 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: Draft +status: Stagnant type: Standards Track -category: Networking +category: Core created: 2021-03-25 requires: 225 --- @@ -19,7 +19,7 @@ Add a four step block rule to Clique that should reduce block production deadloc 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. +in-turn, and lowest hash. This would prevent deadlocks that have occurred in production systems. ## Motivation @@ -34,17 +34,17 @@ chain can halt with a shortest chain rule. ## Specification -When a Click validator is choosing between two different chain head blocks to build a nre proposed -block they should chose the blocks from the following priority list. +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 `header_number` is the integer +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, -`validator_index` is the number of the header, and `validator_count` is the count of the current +`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. @@ -113,4 +113,4 @@ this time. ## 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-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 index b6c13f50f93341..ca9c83ea69128e 100644 --- a/EIPS/eip-3450.md +++ b/EIPS/eip-3450.md @@ -1,190 +1,7 @@ --- eip: 3450 -title: Standardized Shamir Secret Sharing Scheme for BIP-39 Mnemonics -author: Daniel Streit (@danielstreit) -discussions-to: https://ethereum-magicians.org/t/erc-3450-standard-for-applying-shamirs-to-bip-39-mnemonics/5844 -status: Draft -type: Standards Track category: ERC -created: 2021-03-29 +status: Moved --- -## Simple Summary - -A standardized algorithm for applying Shamir's Secret Sharing Scheme to BIP-39 mnemonics. - -## Abstract - -A standardized approach to splitting a BIP-39 mnemonic into _N_ BIP-39 mnemonics, called shares, so that _T_ shares are required to recover the original mnemonic and no information about the original mnemonic, other than its size, is leaked with less than _T_ shares. - -## Motivation - -We'd like to make it easier for less-technical users to store keys securely. - -Currently, many users use BIP-39 mnemonics to store entropy values underlying their keys. These mnemonics are a single point of failure. If lost, the user may never regain access to the assets locked by the keys. If stolen, a malicious actor can steal the assets. - -Shamir's Secret Sharing Scheme addresses this concern directly. It creates "shares" of the secret, such that a subset can be used to recover the secret, but only if a minimum threshold of shares is reached. Without the minimum, no information about the original secret is leaked. - -One concern with Shamir's Secret Sharing Scheme is there is no canonical, standard implementation. This puts recovery at risk, as tooling may change over time. - -Here, we propose a standardized implementation of Shamir's Secret Sharing Scheme applied specifically to BIP-39 mnemonics, so users can easily create shares of their mnemonic, destroy the original, store the shares appropriately, and confidently recover the original mnemonic at a later date. - -## Specification - -### Shamir's Secret Sharing Scheme - -Shamir's Secret Sharing Scheme is a cryptographic method to split a secret into _N_ unique parts, where any _T_ of them are required to reconstruct the secret. - -First, a polynomial _f_ of degree _T_ − 1 is constructed. Then, each share is a point on the polynomial's curve: an integer _x_, and its corresponding _y_ point _f_(_x_). - -With any set of _T_ shares (or points), the initial polynomial can be recovered using polynomial interpolation. - -When constructing the initial polynomial, the secret is stored as the coefficient of x0 and the rest of the coefficients are randomly generated. - -### BIP-39 Mnemonics - -BIP-39 is a common standard for storing entropy as a list of words. It is easier to work with for human interactions than raw binary or hexadecimal representations of entropy. - -BIP-39 mnemonics encode two pieces of data: the original entropy and a checksum of that entropy. The checksum allows the mnemonic to be validated, ensuring that the user entered it correctly. - -#### Generating the Mnemonic - -The mnemonic must encode entropy in a multiple of 32 bits. With more entropy security is improved but the sentence length increases. We refer to the initial entropy length as ENT. The allowed size of ENT is 128-256 bits. - -First, an initial entropy of ENT bits is generated. A checksum is generated by taking the first `ENT / 32` bits of its SHA256 hash. This checksum is appended to the end of the initial entropy. Next, these concatenated bits are split into groups of 11 bits, each encoding a number from 0-2047, serving as an index into a word list. Finally, we convert these numbers into words and use the joined words as a mnemonic sentence. - -The following table describes the relation between the initial entropy length (ENT), the checksum length (CS), and the length of the generated mnemonic sentence (MS) in words. - -``` -CS = ENT / 32 -MS = (ENT + CS) / 11 - -| ENT | CS | ENT+CS | MS | -+-------+----+--------+------+ -| 128 | 4 | 132 | 12 | -| 160 | 5 | 165 | 15 | -| 192 | 6 | 198 | 18 | -| 224 | 7 | 231 | 21 | -| 256 | 8 | 264 | 24 | -``` - -#### Recovering the Entropy - -The initial entropy can be recovered by reversing the process above. The mnemonic is converted to bits, where each word is converted to 11 bits representing its index in the word list. The entropy portion is defined in the table above, based on the size of the mnemonic. - -#### Word List - -This specification only supports the BIP-39 English word list, but this may be expanded in the future. - -See [word list](../assets/eip-3450/wordlist.txt). - -### Applying Shamir's Scheme to BIP-39 Mnemonics - -To ensure that the shares are valid BIP-39 mnemonics, we: - -1. Convert the target BIP-39 mnemonic to its underlying entropy -2. Apply Shamir's Scheme to the entropy -3. Convert each resulting share's _y_ value to a BIP-39 mnemonic - -By converting to entropy before applying Shamir's Scheme, we omit the checksum from the initial secret, allowing us to calculate a new checksum for each share when converting the share _y_ values to mnemonics, ensuring that they are valid according to BIP-39. - -When applying Shamir's Scheme to the entropy, we apply it separately to each byte of the entropy and GF(256) is used as the underlying finite field. Bytes are interpreted as elements of GF(256) using polynomial representation with operations modulo the Rijndael irreducible polynomial _x_8 + _x_4 + _x_3 + _x_ + 1, following AES. - -### Share Format - -A share represents a point on the curve described by the underlying polynomial used to split the secret. It includes two pieces of data: - -- An ID: the _x_ value of the share -- A BIP-39 mnemonic: the _y_ value of the share represented by a mnemonic - -### Creating Shares - -Inputs: BIP-39 mnemonic, number of shares (_N_), threshold (_T_) - -Output: N Shares, each share including an ID, { _x_ | 0 < _x_ < 256 }, and a BIP-39 mnemonic of the same length as the input one - -1. Check the following conditions: - - 1 < T <= N < 256 - - The mnemonic is valid according to [BIP-39](#generating-the-mnemonic) -2. [Recover the underlying entropy of the mnemonic](#recovering-the-entropy) as a vector of bytes -3. Define values: - - Let _E_ be the byte-vector representation of the mnemonic's entropy - - Let _n_ be the length of _E_ - - Let _coeff1_, ... , _coeffT - 1_ be byte-vectors belonging to GF(256)_n_ generated randomly, independently with uniform distribution from a source suitable for generating cryptographic keys -4. Evaluate the polynomial for each share - - For each _x_ from 1 to _N_, evaluate the polynomial _f(x)_ = _E_ + _coeff1x1_ + ... + _coeffT - 1xT - 1_, where _x_ is the share ID and _f(x)_ is the share value (as a vector of bytes) -5. Using _f(x)_ as the underlying entropy, [generate a mnemonic](#generating-the-mnemonic) for each share -6. Return the ID and mnemonic for each share - -### Recovering the Mnemonic - -To recover the original mnemonic, we interpolate a polynomial _f_ from the given set of shares (or points on the polynomial) and evaluate _f(0)_. - -#### Polynomial Interpolation - -Given a set of _m_ points (_xi_, _yi_), 1 ≤ _i_ ≤ _m_, such that no two _xi_ values equal, there exists a polynomial that assumes the value _yi_ at each point _xi_. The polynomial of lowest degree that satisfies these conditions is uniquely determined and can be obtained using the Lagrange interpolation formula given below. - -Since Shamir's Secret Sharing Scheme is applied separately to each of the _n_ bytes of the shared mnemonic's entropy, we work with _yi_ as a vector of _n_ values, where _yi_[_k_] = _fk_(_xi_), 1 ≤ _k_ ≤ _n_, and _fk_ is the polynomial in the _k_-th instance of the scheme. - -#### Interpolate(_x_, {(_xi_, _yi_), 1 ≤ _i_ ≤ _m_}) - -Input: the desired index _x_, a set of index/value-vector pairs {(_xi_, _y__i_), 1 ≤ _i_ ≤ _m_} ⊆ GF(256) × GF(256)_n_ - -Output: the value-vector (_f_1(_x_), ... , _fn_(_x_)) - -![f_k(x) = \sum_{i=1}^m y_i[k] \prod_{\underset{j \neq i}{j=1}}^m \frac{x - x_j}{x_i - x_j}](../assets/eip-3450/lagrange.gif) - -#### Recover the Mnemonic - -Input: A set of _m_ Shares - -Output: The original mnemonic - -1. [Recover the underlying entropy of each share's mnemonic](#recovering-the-entropy) as a vector of bytes -2. Calculate _E_ = Interpolate(0, [(_x1_, _y1_),...,(_xm_, _ym_)]), where _x_ is the share ID and _y_ is the byte-vector of the share's mnemonic's entropy -3. Using _E_ as the underlying entropy, [generate a mnemonic](#generating-the-mnemonic) and return it - -## Rationale - -### Choice of Field - -The field GF(256) was chosen, because the field arithmetic is easy to implement in any programming language and many implementations are already available since it is used in the AES cipher. Although using GF(256) requires that we convert the mnemonic to its underlying entropy as a byte-vector, this is also easy to implement and many implementations of it exist in a variety of programming languages. - -GF(2048) was also considered. Using GF(2048), we could have applied Shamir's Scheme directly to the mnemonic, using the word indexes as the values. This would have allowed us to avoid converting the mnemonic to its underlying entropy. But, the resulting shares would not have been valid BIP-39 mnemonics - the checksum portion would not be a valid checksum of the entropy. And, working around this would add considerable complexity. - -Another option was GF(2_n_) where _n_ is the size of the entropy in bits. We'd still convert the mnemonic to entropy, but then apply Shamir's Scheme over the entire entropy rather than on a vector of values. The downside of this approach is we'd need a different field for each mnemonic strength along with an associated irreducible polynomial. Additionally, this would require working with very large numbers that can be cumbersome to work with in some languages. - -### Valid Share Mnemonics and Share IDs - -The shares produced by the specification include an ID, in addition to the BIP-39 mnemonic. - -Other options could have encoded the share ID into the mnemonic, simplifying storage - only the mnemonic would need to be stored. - -One possibility would be to store the ID instead of the checksum in the mnemonic. The downside of this approach is that the shares would not be _valid_ BIP-39 mnemonics because the "checksum" section of the mnemonic would not match the "entropy" section. Shares with valid BIP-39 mnemonics are useful because they are indistinguishable from any other. And users could store the ID in a variety of ways that obscure it. - -### Validation on Recovery - -We decided _not_ to include a validation mechanism on recovering the original mnemonic. This leaks less information to a potential attacker. There is no indication they've gotten the requisite number of shares until they've obtained _T_ + 1 shares. - -We could provide recovery validation by replacing one of the random coefficients with a checksum of the original mnemonic. Then, when recovering the original mnemonic and the polynomial, we could validate that the checksum coefficient is the valid checksum of recovered mnemonic. - -## Test Cases - -Coming soon. - -All implementations must be able to: - -- Split and recover each `mnemonic` with the given `numShares` and `threshold`. -- Recover the `mnemonic` from the given `knownShares`. - -## Security Considerations - -The shares produced by the specification include an ID in addition to the BIP-39 mnemonic. This raises two security concerns: - -Users **must** keep this ID in order to recover the original mnemonic. If the ID is lost, or separated from the share mnemonic, it may not be possible to recover the original. (Brute force recovery may or may not be possible depending on how much is known about the number of shares and threshold) - -The additional data may hint to an attacker of the existence of other keys and the scheme under which they are stored. Therefore, the ID should be stored in a way that obscures its use. - -## 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-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..12ca2f0bd2f738 --- /dev/null +++ b/EIPS/eip-3540.md @@ -0,0 +1,258 @@ +--- +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) +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 otherwised 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_height)+ +``` + +*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 | 2 bytes | 0x0001-0xFFFF | 16-bit unsigned big-endian integer denoting the length of the container section content | +| kind_data | 1 byte | 0x04 | 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_height | 2 bytes | 0x0000-0x03FF | maximum number of elements ever placed onto the operand stack 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 | + +See [EIP-4750](./eip-4750.md) for more information on the type section content. + +**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. +- `EXTDELEGATECALL` (`DELEGATECALL` replacement) 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 values or some kind of variable length field (e.g. LEB128). We have opted for fixed size, because it simplifies client implementations, and 16-bit seems enough, because of the currently exposed code size limit of 24576 bytes (see [EIP-170](./eip-170.md) and [EIP-3860](./eip-3860.md)). 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. + +## 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..78ed1ee17a83aa --- /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 the 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..23c2a4f3ab0f36 --- /dev/null +++ b/EIPS/eip-3670.md @@ -0,0 +1,136 @@ +--- +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: Review +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. + +## 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..40ebc7b8858fe4 --- /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 additionally limited by the max bytecode size 0x6000. Then any valid `jumpdests` section may not be more 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..42034250ae8dd4 --- /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 exists 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..5f8151e19ad1c9 --- /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 effected, 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 7ee67e529f41a0..2973e03a8d8bcb 100644 --- a/EIPS/eip-4.md +++ b/EIPS/eip-4.md @@ -5,7 +5,6 @@ author: Joseph Chow (@ethers) status: Final type: Meta created: 2015-11-17 -superseded-by: 1 --- # Abstract diff --git a/EIPS/eip-4200.md b/EIPS/eip-4200.md new file mode 100644 index 00000000000000..7c7a47caff97e2 --- /dev/null +++ b/EIPS/eip-4200.md @@ -0,0 +1,164 @@ +--- +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: Review +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 + +TBA + +## 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..df543d454f1667 --- /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 is 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 too old. 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 pronouncination of the EIP. When pronouncing the EIP number, it **MUST** be pronounced EIP "four fours". All other pronounciations 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..05e111d80e8ba5 --- /dev/null +++ b/EIPS/eip-4750.md @@ -0,0 +1,160 @@ +--- +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 comprised of 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_height`. *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_height` is further defined in [EIP-5450](./eip-5450.md). +3. The 0th code section MUST have 0 inputs and 0 outputs. + +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 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_height = type_section_contents[i * 4 + 2:i * 4 + 4]` - maximum operand stack height 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_height + type[target_section_index].inputs` (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 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. + +### 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` and `RJUMPI`) do not have this requirement and are validated once at deploy-time EOF instruction 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 + +TBA + +## 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..aafcbfd365d511 --- /dev/null +++ b/EIPS/eip-4760.md @@ -0,0 +1,63 @@ +--- +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 `SELFDESCRUCT` 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). \ No newline at end of file diff --git a/EIPS/eip-4762.md b/EIPS/eip-4762.md new file mode 100644 index 00000000000000..625f2b4105c7e0 --- /dev/null +++ b/EIPS/eip-4762.md @@ -0,0 +1,298 @@ +--- +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(address, 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(address, 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 changes 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..9ce1e4cf819876 --- /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: Review +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 f7c3c47dfbdc99..5c875111d0e9b0 100644 --- a/EIPS/eip-5.md +++ b/EIPS/eip-5.md @@ -6,7 +6,6 @@ status: Final type: Standards Track category: Core created: 2015-11-22 -superseded-by: 211 --- ### Abstract 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..d42d650dd1276d --- /dev/null +++ b/EIPS/eip-5003.md @@ -0,0 +1,88 @@ +--- +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: Stagnant +type: Standards Track +category: Core +created: 2022-03-26 +requires: 3074, 3607 +--- + +## 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..5633cbf4378d77 --- /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 distruptive? + +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 \ No newline at end of file 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..6b6ad04657c9dc --- /dev/null +++ b/EIPS/eip-5081.md @@ -0,0 +1,91 @@ +--- +eip: 5081 +title: Expirable Trainsaction +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` choose 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 +`transacton_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 presume 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..e546311640b6c8 --- /dev/null +++ b/EIPS/eip-5450.md @@ -0,0 +1,166 @@ +--- +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: Review +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 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`, `RETURNCONTRACT`, `REVERT`, `INVALID`. + +*note: `JUMPF` and `RETURNCONTRACT` 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. +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_height + types[target_section_index].inputs`, 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 for all instructions other than terminating instructions and unconditional jump. + 2. All targets of a conditional or unconditional jump. +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 (visited for the first time), record the instruction stack height bound as the value computed in 2.3. + 2. Otherwise instruction was 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: + +1. Compute the maximum stack height as the maximum of all recorded stack height upper bounds. +2. **Check** if the maximum stack height does not exceed the limit of 1023 (`0x3FF`). +3. **Check** if the maximum stack height matches the corresponding code section's `max_stack_height` within the type section. + +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 must 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. + +## 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 + +Needs discussion. + +## 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 325a70f9683ef0..f7016be98d9850 100644 --- a/EIPS/eip-55.md +++ b/EIPS/eip-55.md @@ -1,119 +1,7 @@ --- eip: 55 -title: Mixed-case checksum address encoding -author: Vitalik Buterin , Alex Van de Sande -discussions-to: https://github.com/ethereum/eips/issues/55 -type: Standards Track category: ERC -status: Final -created: 2016-01-14 +status: Moved --- -# Specification - -Code: - -``` python -import eth_utils - - -def checksum_encode(addr): # Takes a 20-byte binary address as input - hex_addr = addr.hex() - checksummed_buffer = "" - - # Treat the hex address as ascii/utf-8 for keccak256 hashing - hashed_address = eth_utils.keccak(text=hex_addr).hex() - - # Iterate over each character in the hex address - for nibble_index, character in enumerate(hex_addr): - - if character in "0123456789": - # We can't upper-case the decimal digits - checksummed_buffer += character - elif character in "abcdef": - # Check if the corresponding hex digit (nibble) in the hash is 8 or higher - hashed_address_nibble = int(hashed_address[nibble_index], 16) - if hashed_address_nibble > 7: - checksummed_buffer += character.upper() - else: - checksummed_buffer += character - else: - raise eth_utils.ValidationError( - f"Unrecognized hex character {character!r} at position {nibble_index}" - ) - - return "0x" + checksummed_buffer - - -def test(addr_str): - addr_bytes = eth_utils.to_bytes(hexstr=addr_str) - checksum_encoded = checksum_encode(addr_bytes) - assert checksum_encoded == addr_str, f"{checksum_encoded} != expected {addr_str}" - - -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 -``` +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..49df3983be2e30 --- /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. +- 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. The case of the third party iframe is dictated by the usage of the `allow` attribute and the Permissions API as defined in the rule above. + +## 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 `