pax_global_header00006660000000000000000000000064147413026450014520gustar00rootroot0000000000000052 comment=a950702558502dcf4c9cfca656f3bd82725badb2 eth-hash-0.7.1/000077500000000000000000000000001474130264500132265ustar00rootroot00000000000000eth-hash-0.7.1/.circleci/000077500000000000000000000000001474130264500150615ustar00rootroot00000000000000eth-hash-0.7.1/.circleci/config.yml000066400000000000000000000235061474130264500170570ustar00rootroot00000000000000version: 2.1 # heavily inspired by https://raw.githubusercontent.com/pinax/pinax-wiki/6bd2a99ab6f702e300d708532a6d1d9aa638b9f8/.circleci/config.yml common: &common working_directory: ~/repo steps: - checkout - run: name: merge pull request base command: ./.circleci/merge_pr.sh - run: name: merge pull request base (2nd try) command: ./.circleci/merge_pr.sh when: on_fail - run: name: merge pull request base (3rd try) command: ./.circleci/merge_pr.sh when: on_fail - restore_cache: keys: - cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} - run: name: install dependencies command: | python -m pip install --upgrade pip python -m pip install tox - run: name: run tox command: python -m tox run -r - save_cache: paths: - .hypothesis - .tox - ~/.cache/pip - ~/.local key: cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} orbs: win: circleci/windows@5.0.0 windows-wheel-steps: windows-wheel-setup: &windows-wheel-setup executor: name: win/default shell: bash.exe working_directory: C:\Users\circleci\project\eth-hash environment: TOXENV: windows-wheel restore-cache-step: &restore-cache-step restore_cache: keys: - cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} install-pyenv-step: &install-pyenv-step run: name: install pyenv command: | pip install pyenv-win --target $HOME/.pyenv echo 'export PYENV="$HOME/.pyenv/pyenv-win/"' >> $BASH_ENV echo 'export PYENV_ROOT="$HOME/.pyenv/pyenv-win/"' >> $BASH_ENV echo 'export PYENV_USERPROFILE="$HOME/.pyenv/pyenv-win/"' >> $BASH_ENV echo 'export PATH="$PATH:$HOME/.pyenv/pyenv-win/bin"' >> $BASH_ENV echo 'export PATH="$PATH:$HOME/.pyenv/pyenv-win/shims"' >> $BASH_ENV source $BASH_ENV pyenv update install-latest-python-step: &install-latest-python-step run: name: install latest python version and tox command: | LATEST_VERSION=$(pyenv install --list | grep -E "${MINOR_VERSION}\.[0-9]+$" | tail -1) echo "installing python version $LATEST_VERSION" pyenv install $LATEST_VERSION pyenv global $LATEST_VERSION python3 -m pip install --upgrade pip python3 -m pip install tox run-tox-step: &run-tox-step run: name: run tox command: | echo 'running tox with' $(python3 --version) python3 -m tox run -r save-cache-step: &save-cache-step save_cache: paths: - .tox key: cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} docs: &docs working_directory: ~/repo steps: - checkout - restore_cache: keys: - cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} - run: name: install dependencies command: | python -m pip install --upgrade pip python -m pip install tox - run: name: install latexpdf dependencies command: | sudo apt-get update sudo apt-get install latexmk tex-gyre texlive-fonts-extra texlive-xetex xindy - run: name: run tox command: python -m tox run -r - store_artifacts: path: /home/circleci/repo/docs/_build - save_cache: paths: - .tox - ~/.cache/pip - ~/.local key: cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} resource_class: xlarge jobs: docs: <<: *docs docker: - image: cimg/python:3.10 environment: TOXENV: docs py38-core: <<: *common docker: - image: cimg/python:3.8 environment: TOXENV: py38-core py39-core: <<: *common docker: - image: cimg/python:3.9 environment: TOXENV: py39-core py310-core: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: py310-core py311-core: <<: *common docker: - image: cimg/python:3.11 environment: TOXENV: py311-core py312-core: <<: *common docker: - image: cimg/python:3.12 environment: TOXENV: py312-core py313-core: <<: *common docker: - image: cimg/python:3.13 environment: TOXENV: py313-core py38-lint: <<: *common docker: - image: cimg/python:3.8 environment: TOXENV: py38-lint py39-lint: <<: *common docker: - image: cimg/python:3.9 environment: TOXENV: py39-lint py310-lint: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: py310-lint py311-lint: <<: *common docker: - image: cimg/python:3.11 environment: TOXENV: py311-lint py312-lint: <<: *common docker: - image: cimg/python:3.12 environment: TOXENV: py312-lint py313-lint: <<: *common docker: - image: cimg/python:3.13 environment: TOXENV: py313-lint py38-wheel: <<: *common docker: - image: cimg/python:3.8 environment: TOXENV: py38-wheel py39-wheel: <<: *common docker: - image: cimg/python:3.9 environment: TOXENV: py39-wheel py310-wheel: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: py310-wheel py311-wheel: <<: *common docker: - image: cimg/python:3.11 environment: TOXENV: py311-wheel py312-wheel: <<: *common docker: - image: cimg/python:3.12 environment: TOXENV: py312-wheel py313-wheel: <<: *common docker: - image: cimg/python:3.13 environment: TOXENV: py313-wheel py311-windows-wheel: <<: *windows-wheel-setup steps: - checkout - <<: *restore-cache-step - <<: *install-pyenv-step - run: name: set minor version command: echo "export MINOR_VERSION='3.11'" >> $BASH_ENV - <<: *install-latest-python-step - <<: *run-tox-step - <<: *save-cache-step py312-windows-wheel: <<: *windows-wheel-setup steps: - checkout - <<: *restore-cache-step - <<: *install-pyenv-step - run: name: set minor version command: echo "export MINOR_VERSION='3.12'" >> $BASH_ENV - <<: *install-latest-python-step - <<: *run-tox-step - <<: *save-cache-step py313-windows-wheel: <<: *windows-wheel-setup steps: - checkout - <<: *restore-cache-step - <<: *install-pyenv-step - run: name: set minor version command: echo "export MINOR_VERSION='3.13'" >> $BASH_ENV - <<: *install-latest-python-step - <<: *run-tox-step - <<: *save-cache-step py38-backend-pysha3: <<: *common docker: - image: cimg/python:3.8 environment: TOXENV: py38-backend-pysha3 py39-backend-pysha3: <<: *common docker: - image: cimg/python:3.9 environment: TOXENV: py39-backend-pysha3 py310-backend-pysha3: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: py310-backend-pysha3 py311-backend-pysha3: <<: *common docker: - image: cimg/python:3.11 environment: TOXENV: py311-backend-pysha3 py312-backend-pysha3: <<: *common docker: - image: cimg/python:3.12 environment: TOXENV: py312-backend-pysha3 py313-backend-pysha3: <<: *common docker: - image: cimg/python:3.13 environment: TOXENV: py313-backend-pysha3 py38-backend-pycryptodome: <<: *common docker: - image: cimg/python:3.8 environment: TOXENV: py38-backend-pycryptodome py39-backend-pycryptodome: <<: *common docker: - image: cimg/python:3.9 environment: TOXENV: py39-backend-pycryptodome py310-backend-pycryptodome: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: py310-backend-pycryptodome py311-backend-pycryptodome: <<: *common docker: - image: cimg/python:3.11 environment: TOXENV: py311-backend-pycryptodome py312-backend-pycryptodome: <<: *common docker: - image: cimg/python:3.12 environment: TOXENV: py312-backend-pycryptodome py313-backend-pycryptodome: <<: *common docker: - image: cimg/python:3.13 environment: TOXENV: py313-backend-pycryptodome define: &all_jobs - docs - py38-core - py39-core - py310-core - py311-core - py312-core - py313-core - py38-lint - py39-lint - py310-lint - py311-lint - py312-lint - py313-lint - py38-wheel - py39-wheel - py310-wheel - py311-wheel - py312-wheel - py313-wheel - py311-windows-wheel - py312-windows-wheel - py313-windows-wheel - py38-backend-pysha3 - py39-backend-pysha3 - py310-backend-pysha3 - py311-backend-pysha3 - py312-backend-pysha3 - py313-backend-pysha3 - py38-backend-pycryptodome - py39-backend-pycryptodome - py310-backend-pycryptodome - py311-backend-pycryptodome - py312-backend-pycryptodome - py313-backend-pycryptodome workflows: version: 2 test: jobs: *all_jobs nightly: triggers: - schedule: # Weekdays 12:00p UTC cron: "0 12 * * 1,2,3,4,5" filters: branches: only: - main jobs: *all_jobs eth-hash-0.7.1/.circleci/merge_pr.sh000077500000000000000000000011271474130264500172210ustar00rootroot00000000000000#!/usr/bin/env bash if [[ -n "${CIRCLE_PR_NUMBER}" ]]; then PR_INFO_URL=https://api.github.com/repos/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME/pulls/$CIRCLE_PR_NUMBER PR_BASE_BRANCH=$(curl -L "$PR_INFO_URL" | python -c 'import json, sys; obj = json.load(sys.stdin); sys.stdout.write(obj["base"]["ref"])') git fetch origin +"$PR_BASE_BRANCH":circleci/pr-base # We need these config values or git complains when creating the # merge commit git config --global user.name "Circle CI" git config --global user.email "circleci@example.com" git merge --no-edit circleci/pr-base fi eth-hash-0.7.1/.git-blame-ignore-revs000066400000000000000000000000511474130264500173220ustar00rootroot000000000000008283caecd1d046e087ad10ecccc8242fa1d9c711 eth-hash-0.7.1/.github/000077500000000000000000000000001474130264500145665ustar00rootroot00000000000000eth-hash-0.7.1/.github/ISSUE_TEMPLATE/000077500000000000000000000000001474130264500167515ustar00rootroot00000000000000eth-hash-0.7.1/.github/ISSUE_TEMPLATE/bug_report.yml000066400000000000000000000035461474130264500216540ustar00rootroot00000000000000name: Bug Report description: File a bug report labels: ["bug"] body: - type: markdown attributes: value: "## What was wrong" - type: textarea id: what-happened attributes: label: What happened? description: Also tell us what you expected to happen validations: required: true - type: textarea id: code-that-caused attributes: label: Code that produced the error description: Formats to Python, no backticks needed render: python validations: required: false - type: textarea id: error-output attributes: label: Full error output description: Formats to shell, no backticks needed render: shell validations: required: false - type: markdown attributes: value: "## Potential Solutions" - type: textarea id: how-to-fix attributes: label: Fill this section in if you know how this could or should be fixed description: Include any relevant examples or reference material validations: required: false - type: input id: lib-version attributes: label: eth-hash Version description: Which version of eth-hash are you using? placeholder: x.x.x validations: required: false - type: input id: py-version attributes: label: Python Version description: Which version of Python are you using? placeholder: x.x.x validations: required: false - type: input id: os attributes: label: Operating System description: Which operating system are you using? placeholder: osx/linux/win validations: required: false - type: textarea id: pip-freeze attributes: label: Output from `pip freeze` description: Run `python -m pip freeze` and paste the output below render: shell validations: required: false eth-hash-0.7.1/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000003261474130264500207420ustar00rootroot00000000000000blank_issues_enabled: true contact_links: - name: Questions about using eth-hash? url: https://discord.gg/GHryRvPB84 about: You can ask and answer usage questions on the Ethereum Python Community Discord eth-hash-0.7.1/.github/ISSUE_TEMPLATE/feature_request.yml000066400000000000000000000004601474130264500226770ustar00rootroot00000000000000name: Feature Request description: Request a new feature labels: ["feature_request"] body: - type: textarea id: feature-description attributes: label: What feature should we add? description: Include any relevant examples or reference material validations: required: true eth-hash-0.7.1/.github/pull_request_template.md000066400000000000000000000005741474130264500215350ustar00rootroot00000000000000### What was wrong? Related to Issue # Closes # ### How was it fixed? ### Todo: - [ ] Clean up commit history - [ ] Add or update documentation related to these changes - [ ] Add entry to the [release notes](https://github.com/ethereum/eth-hash/blob/main/newsfragments/README.md) #### Cute Animal Picture ![Put a link to a cute animal picture inside the parenthesis-->](<>) eth-hash-0.7.1/.gitignore000066400000000000000000000025231474130264500152200ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build .build eggs .eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 pip-wheel-metadata venv* .venv* # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Complexity output/*.html output/*/index.html # Sphinx docs/_build docs/modules.rst docs/*.internal.rst docs/*.utils.rst docs/*._utils.* # Blockchain chains # Hypothesis Property base testing .hypothesis # tox/pytest cache .cache .pytest_cache # pycache __pycache__/ # Test output logs logs # VIM temp files *.sw[op] # mypy .mypy_cache # macOS .DS_Store # pyenv .python-version # vs-code .vscode # jupyter notebook files *.ipynb # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm # For a more precise, explicit template, see: # https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 ## General .idea/* .idea_modules/* ## File-based project format: *.iws ## IntelliJ out/ ## Plugin-specific files: ### JIRA plugin atlassian-ide-plugin.xml ### Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties # END JetBrains section eth-hash-0.7.1/.pre-commit-config.yaml000066400000000000000000000035121474130264500175100ustar00rootroot00000000000000exclude: '.project-template|docs/conf.py' repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-yaml - id: check-toml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/asottile/pyupgrade rev: v3.15.0 hooks: - id: pyupgrade args: [--py38-plus] - repo: https://github.com/psf/black rev: 23.9.1 hooks: - id: black - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 additional_dependencies: - flake8-bugbear==23.9.16 exclude: setup.py - repo: https://github.com/PyCQA/autoflake rev: v2.2.1 hooks: - id: autoflake - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/pycqa/pydocstyle rev: 6.3.0 hooks: - id: pydocstyle additional_dependencies: - tomli # required until >= python311 - repo: https://github.com/executablebooks/mdformat rev: 0.7.17 hooks: - id: mdformat additional_dependencies: - mdformat-gfm - repo: local hooks: - id: mypy-local name: run mypy with all dev dependencies present entry: python -m mypy -p eth_hash language: system always_run: true pass_filenames: false - repo: https://github.com/PrincetonUniversity/blocklint rev: v0.2.5 hooks: - id: blocklint exclude: 'docs/Makefile|docs/release_notes.rst|tox.ini' - repo: local hooks: - id: check-rst-files name: Check for .rst files in the top-level directory entry: sh -c 'ls *.rst 1>/dev/null 2>&1 && { echo "found .rst file in top-level folder"; exit 1; } || exit 0' language: system always_run: true pass_filenames: false eth-hash-0.7.1/.project-template/000077500000000000000000000000001474130264500165635ustar00rootroot00000000000000eth-hash-0.7.1/.project-template/fill_template_vars.py000066400000000000000000000044151474130264500230150ustar00rootroot00000000000000#!/usr/bin/env python3 import os import sys import re from pathlib import Path def _find_files(project_root): path_exclude_pattern = r"\.git($|\/)|venv|_build" file_exclude_pattern = r"fill_template_vars\.py|\.swp$" filepaths = [] for dir_path, _dir_names, file_names in os.walk(project_root): if not re.search(path_exclude_pattern, dir_path): for file in file_names: if not re.search(file_exclude_pattern, file): filepaths.append(str(Path(dir_path, file))) return filepaths def _replace(pattern, replacement, project_root): print(f"Replacing values: {pattern}") for file in _find_files(project_root): try: with open(file) as f: content = f.read() content = re.sub(pattern, replacement, content) with open(file, "w") as f: f.write(content) except UnicodeDecodeError: pass def main(): project_root = Path(os.path.realpath(sys.argv[0])).parent.parent module_name = input("What is your python module name? ") pypi_input = input(f"What is your pypi package name? (default: {module_name}) ") pypi_name = pypi_input or module_name repo_input = input(f"What is your github project name? (default: {pypi_name}) ") repo_name = repo_input or pypi_name rtd_input = input( f"What is your readthedocs.org project name? (default: {pypi_name}) " ) rtd_name = rtd_input or pypi_name project_input = input( f"What is your project name (ex: at the top of the README)? (default: {repo_name}) " ) project_name = project_input or repo_name short_description = input("What is a one-liner describing the project? ") _replace("", module_name, project_root) _replace("", pypi_name, project_root) _replace("", repo_name, project_root) _replace("", rtd_name, project_root) _replace("", project_name, project_root) _replace("", short_description, project_root) os.makedirs(project_root / module_name, exist_ok=True) Path(project_root / module_name / "__init__.py").touch() Path(project_root / module_name / "py.typed").touch() if __name__ == "__main__": main() eth-hash-0.7.1/.project-template/refill_template_vars.py000066400000000000000000000015771474130264500233520ustar00rootroot00000000000000#!/usr/bin/env python3 import os import sys from pathlib import Path import subprocess def main(): template_dir = Path(os.path.dirname(sys.argv[0])) template_vars_file = template_dir / "template_vars.txt" fill_template_vars_script = template_dir / "fill_template_vars.py" with open(template_vars_file, "r") as input_file: content_lines = input_file.readlines() process = subprocess.Popen( [sys.executable, str(fill_template_vars_script)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) for line in content_lines: process.stdin.write(line) process.stdin.flush() stdout, stderr = process.communicate() if process.returncode != 0: print(f"Error occurred: {stderr}") sys.exit(1) print(stdout) if __name__ == "__main__": main() eth-hash-0.7.1/.project-template/template_vars.txt000066400000000000000000000001731474130264500221730ustar00rootroot00000000000000eth_hash eth-hash eth-hash eth-hash eth-hash The Ethereum hashing function, keccak256, sometimes (erroneously) called sha3 eth-hash-0.7.1/.readthedocs.yaml000066400000000000000000000005171474130264500164600ustar00rootroot00000000000000version: 2 build: os: ubuntu-22.04 tools: python: "3.10" sphinx: configuration: docs/conf.py fail_on_warning: true python: install: - method: pip path: . extra_requirements: - docs - pycryptodome - pysha3 # Build all formats for RTD Downloads - htmlzip, pdf, epub formats: all eth-hash-0.7.1/LICENSE000066400000000000000000000021071474130264500142330ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2018-2025 The Ethereum Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. eth-hash-0.7.1/MANIFEST.in000066400000000000000000000003201474130264500147570ustar00rootroot00000000000000include LICENSE include README.md recursive-include scripts * recursive-include tests * global-include *.pyi graft tests recursive-exclude * __pycache__ recursive-exclude * *.py[co] prune .tox prune venv* eth-hash-0.7.1/Makefile000066400000000000000000000067071474130264500147000ustar00rootroot00000000000000CURRENT_SIGN_SETTING := $(shell git config commit.gpgSign) .PHONY: clean-pyc clean-build docs help: @echo "clean-build - remove build artifacts" @echo "clean-pyc - remove Python file artifacts" @echo "clean - run clean-build and clean-pyc" @echo "dist - build package and cat contents of the dist directory" @echo "lint - fix linting issues with pre-commit" @echo "test - run tests quickly with the default Python" @echo "docs - generate docs and open in browser (linux-docs for version on linux)" @echo "autobuild-docs - live update docs when changes are saved" @echo "package-test - build package and install it in a venv for manual testing" @echo "notes - consume towncrier newsfragments and update release notes in docs - requires bump to be set" @echo "release - package and upload a release (does not run notes target) - requires bump to be set" clean-build: rm -fr build/ rm -fr dist/ rm -fr *.egg-info clean-pyc: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + find . -name '__pycache__' -exec rm -rf {} + clean: clean-build clean-pyc dist: clean python -m build ls -l dist lint: @pre-commit run --all-files --show-diff-on-failure || ( \ echo "\n\n\n * pre-commit should have fixed the errors above. Running again to make sure everything is good..." \ && pre-commit run --all-files --show-diff-on-failure \ ) test: python -m pytest tests # docs commands docs: check-docs open docs/_build/html/index.html linux-docs: check-docs xdg-open docs/_build/html/index.html autobuild-docs: sphinx-autobuild --open-browser docs docs/_build/html # docs helpers validate-newsfragments: python ./newsfragments/validate_files.py towncrier build --draft --version preview check-docs: build-docs validate-newsfragments build-docs: sphinx-apidoc -o docs/ . setup.py "*conftest*" $(MAKE) -C docs clean $(MAKE) -C docs html $(MAKE) -C docs doctest check-docs-ci: build-docs build-docs-ci validate-newsfragments build-docs-ci: $(MAKE) -C docs latexpdf $(MAKE) -C docs epub # release commands package-test: clean python -m build python scripts/release/test_package.py notes: check-bump # Let UPCOMING_VERSION be the version that is used for the current bump $(eval UPCOMING_VERSION=$(shell bump-my-version bump --dry-run $(bump) -v | awk -F"'" '/New version will be / {print $$2}')) # Now generate the release notes to have them included in the release commit towncrier build --yes --version $(UPCOMING_VERSION) # Before we bump the version, make sure that the towncrier-generated docs will build make build-docs git commit -m "Compile release notes for v$(UPCOMING_VERSION)" release: check-bump check-git clean # verify that notes command ran correctly ./newsfragments/validate_files.py is-empty CURRENT_SIGN_SETTING=$(git config commit.gpgSign) git config commit.gpgSign true bump-my-version bump $(bump) python -m build git config commit.gpgSign "$(CURRENT_SIGN_SETTING)" git push upstream && git push upstream --tags twine upload dist/* # release helpers check-bump: ifndef bump $(error bump must be set, typically: major, minor, patch, or devnum) endif check-git: # require that upstream is configured for ethereum/eth-hash @if ! git remote -v | grep "upstream[[:space:]]git@github.com:ethereum/eth-hash.git (push)\|upstream[[:space:]]https://github.com/ethereum/eth-hash (push)"; then \ echo "Error: You must have a remote named 'upstream' that points to 'eth-hash'"; \ exit 1; \ fi eth-hash-0.7.1/README.md000066400000000000000000000033111474130264500145030ustar00rootroot00000000000000# eth-hash [![Join the conversation on Discord](https://img.shields.io/discord/809793915578089484?color=blue&label=chat&logo=discord&logoColor=white)](https://discord.gg/GHryRvPB84) [![Build Status](https://circleci.com/gh/ethereum/eth-hash.svg?style=shield)](https://circleci.com/gh/ethereum/eth-hash) [![PyPI version](https://badge.fury.io/py/eth-hash.svg)](https://badge.fury.io/py/eth-hash) [![Python versions](https://img.shields.io/pypi/pyversions/eth-hash.svg)](https://pypi.python.org/pypi/eth-hash) [![Docs build](https://readthedocs.org/projects/eth-hash/badge/?version=latest)](https://eth-hash.readthedocs.io/en/latest/?badge=latest) The Ethereum hashing function, keccak256, sometimes (erroneously) called sha3 Note: the similarly named [pyethash](https://github.com/ethereum/ethash) has a completely different use: it generates proofs of work. This is a low-level library, intended to be used internally by other Ethereum tools. If you're looking for a convenient hashing tool, check out [`eth_utils.keccak()`](https://eth-utils.readthedocs.io/en/stable/utilities.html#keccak-bytes-int-bool-text-str-hexstr-str-bytes) which will be a little friendlier, and provide access to other helpful utilities. Read the [documentation](https://eth-hash.readthedocs.io/). [View the change log](https://eth-hash.readthedocs.io/en/latest/release_notes.html). ## Installation ```sh python -m pip install "eth-hash[pycryptodome]" ``` ```py >>> from eth_hash.auto import keccak >>> keccak(b'') b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" ``` See the [docs](http://eth-hash.readthedocs.io/en/latest/quickstart.html#quickstart) for more about choosing and installing backends. eth-hash-0.7.1/docs/000077500000000000000000000000001474130264500141565ustar00rootroot00000000000000eth-hash-0.7.1/docs/Makefile000066400000000000000000000151621474130264500156230ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/eth_hash.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/eth_hash.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/eth_hash" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/eth_hash" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." eth-hash-0.7.1/docs/code_of_conduct.rst000066400000000000000000000062771474130264500200410ustar00rootroot00000000000000Code of Conduct --------------- Our Pledge ~~~~~~~~~~ In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards ~~~~~~~~~~~~~ Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting Our Responsibilities ~~~~~~~~~~~~~~~~~~~~ Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope ~~~~~ This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement ~~~~~~~~~~~ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at snakecharmers@ethereum.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution ~~~~~~~~~~~ This Code of Conduct is adapted from the `Contributor Covenant `_, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html eth-hash-0.7.1/docs/conf.py000066400000000000000000000221501474130264500154550ustar00rootroot00000000000000# eth-hash documentation build configuration file, created by # sphinx-quickstart on Thu Oct 16 20:43:24 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) import os DIR = os.path.dirname("__file__") with open(os.path.join(DIR, "../setup.py"), "r") as f: for line in f: if "version=" in line: setup_version = line.split('"')[1] break # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx", "sphinx_rtd_theme", "sphinx.ext.autosectionlabel", ] suppress_warnings = ["autosectionlabel.*"] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "eth-hash" copyright = "2018-2023, The Ethereum Foundation" __version__ = setup_version # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(__version__.split(".")[:2]) # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [ "_build", "modules.rst", ] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "eth_hashdoc" # -- Options for LaTeX output --------------------------------------------- latex_engine = "xelatex" latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( "index", "eth_hash.tex", "eth-hash Documentation", "The Ethereum Foundation", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( "index", "eth_hash", "eth-hash Documentation", ["The Ethereum Foundation"], 1, ) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "eth-hash", "eth-hash Documentation", "The Ethereum Foundation", "eth-hash", "The Ethereum hashing function, keccak256, sometimes (erroneously) called sha3", "Miscellaneous", ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # -- Intersphinx configuration ------------------------------------------------ intersphinx_mapping = { "python": ("https://docs.python.org/3.10", None), } # -- Doctest configuration ---------------------------------------- import doctest doctest_default_flags = ( 0 | doctest.DONT_ACCEPT_TRUE_FOR_1 | doctest.ELLIPSIS | doctest.IGNORE_EXCEPTION_DETAIL | doctest.NORMALIZE_WHITESPACE ) eth-hash-0.7.1/docs/contributing.rst000066400000000000000000000116771474130264500174330ustar00rootroot00000000000000Contributing ------------ Thank you for your interest in contributing! We welcome all contributions no matter their size. Please read along to learn how to get started. If you get stuck, feel free to ask for help in `Ethereum Python Discord server `_. Setting the stage ~~~~~~~~~~~~~~~~~ To get started, fork the repository to your own github account, then clone it to your development machine: .. code:: sh git clone git@github.com:your-github-username/eth-hash.git Next, install the development dependencies. We recommend using a virtual environment, such as `virtualenv `_. .. code:: sh cd eth-hash virtualenv -p python venv . venv/bin/activate python -m pip install -e ".[dev]" pre-commit install Running the tests ~~~~~~~~~~~~~~~~~ A great way to explore the code base is to run the tests. We can run all tests with: .. code:: sh pytest tests Code Style ~~~~~~~~~~ We use `pre-commit `_ to enforce a consistent code style across the library. This tool runs automatically with every commit, but you can also run it manually with: .. code:: sh make lint If you need to make a commit that skips the ``pre-commit`` checks, you can do so with ``git commit --no-verify``. This library uses type hints, which are enforced by the ``mypy`` tool (part of the ``pre-commit`` checks). All new code is required to land with type hints, with the exception of code within the ``tests`` directory. Documentation ~~~~~~~~~~~~~ Good documentation will lead to quicker adoption and happier users. Please check out our guide on `how to create documentation for the Python Ethereum ecosystem `_. Pull Requests ~~~~~~~~~~~~~ It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission. GitHub's documentation for working on pull requests is `available here `_. Once you've made a pull request, take a look at the Circle CI build status in the GitHub interface and make sure all tests are passing. In general pull requests that do not pass the CI build yet won't get reviewed unless explicitly requested. If the pull request introduces changes that should be reflected in the release notes, please add a `newsfragment` file as explained `here `_. If possible, the change to the release notes file should be included in the commit that introduces the feature or bugfix. Releasing ~~~~~~~~~ Releases are typically done from the ``main`` branch, except when releasing a beta (in which case the beta is released from ``main``, and the previous stable branch is released from said branch). Final test before each release ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before releasing a new version, build and test the package that will be released: .. code:: sh git checkout main && git pull make package-test This will build the package and install it in a temporary virtual environment. Follow the instructions to activate the venv and test whatever you think is important. You can also preview the release notes: .. code:: sh towncrier --draft Build the release notes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before bumping the version number, build the release notes. You must include the part of the version to bump (see below), which changes how the version number will show in the release notes. .. code:: sh make notes bump=$$VERSION_PART_TO_BUMP$$ If there are any errors, be sure to re-run make notes until it works. Push the release to github & pypi ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After confirming that the release package looks okay, release a new version: .. code:: sh make release bump=$$VERSION_PART_TO_BUMP$$ This command will: - Bump the version number as specified in ``.pyproject.toml`` and ``setup.py``. - Create a git commit and tag for the new version. - Build the package. - Push the commit and tag to github. - Push the new package files to pypi. Which version part to bump ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``$$VERSION_PART_TO_BUMP$$`` must be one of: ``major``, ``minor``, ``patch``, ``stage``, or ``devnum``. The version format for this repo is ``{major}.{minor}.{patch}`` for stable, and ``{major}.{minor}.{patch}-{stage}.{devnum}`` for unstable (``stage`` can be alpha or beta). If you are in a beta version, ``make release bump=stage`` will switch to a stable. To issue an unstable version when the current version is stable, specify the new version explicitly, like ``make release bump="--new-version 4.0.0-alpha.1"`` You can see what the result of bumping any particular version part would be with ``bump-my-version show-bump`` eth-hash-0.7.1/docs/eth_hash.backends.rst000066400000000000000000000012741474130264500202500ustar00rootroot00000000000000eth\_hash.backends package ========================== Submodules ---------- eth\_hash.backends.auto module ------------------------------ .. automodule:: eth_hash.backends.auto :members: :undoc-members: :show-inheritance: eth\_hash.backends.pycryptodome module -------------------------------------- .. automodule:: eth_hash.backends.pycryptodome :members: :undoc-members: :show-inheritance: eth\_hash.backends.pysha3 module -------------------------------- .. automodule:: eth_hash.backends.pysha3 :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: eth_hash.backends :members: :undoc-members: :show-inheritance: eth-hash-0.7.1/docs/eth_hash.rst000066400000000000000000000004621474130264500164750ustar00rootroot00000000000000eth\_hash package ================= eth\_hash\.auto module ---------------------- .. automodule:: eth_hash.auto :members: :undoc-members: :show-inheritance: eth\_hash\.main module ---------------------- .. automodule:: eth_hash.main :members: :undoc-members: :show-inheritance: eth-hash-0.7.1/docs/index.rst000066400000000000000000000007321474130264500160210ustar00rootroot00000000000000eth-hash ============================== The Ethereum hashing function, keccak256, sometimes (erroneously) called sha3 Installation ------------ .. code-block:: bash python -m pip install eth-hash .. toctree:: :maxdepth: 2 quickstart eth_hash.backends eth_hash release_notes .. toctree:: :maxdepth: 1 :caption: Community contributing code_of_conduct Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` eth-hash-0.7.1/docs/quickstart.rst000066400000000000000000000044341474130264500171070ustar00rootroot00000000000000Quickstart ============ Choose a hashing backend --------------------------- If you're not sure, choose "pycryptodome" because it supports pypy3. You can find a full list of each currently supported backend in :mod:`eth_hash.backends`. Install ---------- Put the backend you would like to use in brackets during install, like: .. code-block:: shell python -m pip install "eth-hash[pycryptodome]" Compute a Keccak256 Hash ----------------------------- .. doctest:: >>> from eth_hash.auto import keccak >>> keccak(b'') b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" You may also compute hashes incrementally .. doctest:: >>> from eth_hash.auto import keccak >>> preimage = keccak.new(b'part-a') >>> preimage.update(b'part-b') >>> preimage.digest() b'6\x91l\xdd50\xd6[\x7f\xf9B\xff\xc9SW\x98\xc3\xaal\xd9\xde\xdd6I\xb7\x91\x9e\xf4`pl\x08' The preimage object returned may be copied as well. .. doctest:: >>> from eth_hash.auto import keccak >>> preimage = keccak.new(b'part-a') >>> preimage_copy = preimage.copy() >>> preimage.update(b'part-b') >>> preimage.digest() b'6\x91l\xdd50\xd6[\x7f\xf9B\xff\xc9SW\x98\xc3\xaal\xd9\xde\xdd6I\xb7\x91\x9e\xf4`pl\x08' >>> preimage_copy.update(b'part-c') >>> preimage_copy.digest() b'\xffcy45\xea\xdd\xdf\x8e(\x1c\xfcF\xf3\xd4\xa1S\x0f\xdf\xd8\x01!\xb2(\xe1\xc7\xc6\xa3\x08\xc3\n\x0b' Select one of many installed backends --------------------------------------- If you have several backends installed, you may want to explicitly specify which one to load. You can specify in an environment variable, or at runtime. Specify backend by environment variable ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code-block:: shell $ ETH_HASH_BACKEND="pysha3" python >>> from eth_hash.auto import keccak # This runs with the pysha3 backend >>> keccak(b'') b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" Specify backend at runtime ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code-block:: python >>> from eth_hash.backends import pysha3 >>> from eth_hash import Keccak256 >>> keccak = Keccak256(pysha3) >>> keccak(b'') b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" eth-hash-0.7.1/docs/release_notes.rst000066400000000000000000000122531474130264500175430ustar00rootroot00000000000000Release Notes ============= .. towncrier release notes start eth-hash v0.7.1 (2025-01-13) ---------------------------- Internal Changes - for eth-hash Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Merge template, updating CI runs and what is included in package files (`#59 `__) - Run ``mypy`` linting locally via a ``pre-commit`` hook (`#60 `__) - Merge template updates, notably adding support for ``py313`` and moving docs from the ``README`` to ReadTheDocs (`#61 `__) eth-hash v0.7.0 (2024-03-01) ---------------------------- Internal Changes - for eth-hash Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Merge template updates, notably adding py312 support and testing docs build for all formats (`#57 `__) eth-hash v0.6.0 (2024-01-10) ---------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Drop python 3.7 support (`#53 `__) Internal Changes - for eth-hash Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Merge project template updates, notably use ``pre-commit`` for linting and change the name of ``master`` branch to ``main`` (`#53 `__) - Correct booleans in ``pyproject.toml`` and add test for presence of ``eth_hash.__version__`` attribute (`#55 `__) eth-hash v0.5.2 (2023-06-07) ---------------------------- Internal Changes - for eth-hash Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - remove unused docs deps, bump version of remaining (`#48 `__) - merge updates from the python project template (`#51 `__) eth-hash v0.5.1 (2022-11-09) ---------------------------- Features ~~~~~~~~ - Add support for Python 3.11 (`#45 `__) eth-hash v0.5.0 (2022-07-20) ---------------------------- Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Prefer pysha3 backend by default (`#42 `__) eth-hash v0.4.0 (2022-07-06) ---------------------------- Features ~~~~~~~~ - Add support for Python 3.8, 3.9, 3.10 (`#40 `__) Deprecations and Removals ~~~~~~~~~~~~~~~~~~~~~~~~~ - Drop support for Python 3.5 and 3.6 (`#39 `__) Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - `#40 `__, `#41 `__ eth-hash v0.3.3 (2022-06-30) ---------------------------- Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Keccak backend was initialized every time it was called. Now it's initialized only the first time it's called. (`#36 `__) Internal Changes - for eth-hash Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Prune ``venv`` files from the release via MANIFEST.in (`#38 `__) eth-hash v0.3.2 (2021-09-03) ---------------------------- Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - Drop eth-utils requirement, to fix dependency cycle (`#33 `__) eth-hash v0.3.1 (2021-01-21) ---------------------------- Bugfixes ~~~~~~~~ - Bugfix to export type annotations (`#28 `__) eth-hash v0.3.0 (2021-01-20) ---------------------------- Features ~~~~~~~~ - Export type annotations, for use in importing projects (`#29 `__) Internal Changes - for eth-hash Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Import 3 years worth of template updates (`#29 `__) v0.2.0 -------------- Released September 5, 2018 - set `pycryptodome` version to `>=3.6.6,<4` to fix a recently discovered vulnerability v0.1.4 -------------- Released May 28, 2018 - Ensure the auto backend is pickleable (#19) v0.1.3 -------------- Released May 14, 2018 - The pycryptodome backend now allows ``update()``, then ``digest()``, then ``update()``. v0.1.2 -------------- Released Apr 2, 2018 - You can now import eth-hash without a backend, it won't fail until trying to generate a hash v0.1.1 -------------- Released Mar 15, 2018 - upgrade pycryptodome to v3.5.1+ - performance improvements with preimage - Better docs and tests v0.1.0 -------------- Released Feb 28, 2018 - Add support for :class:`bytearray` input to keccak - Add support for incrementally building hash results v0.1.0-alpha.3 -------------- Released Feb 7, 2018 - Add pycryptodome backend support - Add pysha3 backend support - Can specify backend in environment variable ``ETH_HASH_BACKEND`` - New :ref:`Quickstart` docs v0.1.0-alpha.2 -------------- Released Feb 6, 2018 - Bugfix pypy3 reference in pypi v0.1.0-alpha.1 -------------- - Launched repository, claimed names for pip, RTD, github, etc eth-hash-0.7.1/eth_hash/000077500000000000000000000000001474130264500150115ustar00rootroot00000000000000eth-hash-0.7.1/eth_hash/__init__.py000066400000000000000000000002101474130264500171130ustar00rootroot00000000000000from importlib.metadata import ( version as __version, ) from .main import ( Keccak256, ) __version__ = __version("eth-hash") eth-hash-0.7.1/eth_hash/abc.py000066400000000000000000000011651474130264500161130ustar00rootroot00000000000000from abc import ( ABC, abstractmethod, ) from typing import ( Union, ) class PreImageAPI(ABC): @abstractmethod def __init__(self, value: bytes) -> None: ... @abstractmethod def update(self, value: bytes) -> None: ... @abstractmethod def digest(self) -> bytes: ... @abstractmethod def copy(self) -> "PreImageAPI": ... class BackendAPI(ABC): @abstractmethod def keccak256(self, in_data: Union[bytearray, bytes]) -> bytes: ... @abstractmethod def preimage(self, in_data: Union[bytearray, bytes]) -> PreImageAPI: ... eth-hash-0.7.1/eth_hash/auto.py000066400000000000000000000002101474130264500163240ustar00rootroot00000000000000from eth_hash.backends.auto import ( AutoBackend, ) from eth_hash.main import ( Keccak256, ) keccak = Keccak256(AutoBackend()) eth-hash-0.7.1/eth_hash/backends/000077500000000000000000000000001474130264500165635ustar00rootroot00000000000000eth-hash-0.7.1/eth_hash/backends/__init__.py000066400000000000000000000005401474130264500206730ustar00rootroot00000000000000""" A collection of optional backends that implement hashing. You must manually select and install the backend you want. If the backend is not installed, then trying to import the module for that backend will cause an :class:`ImportError`. See :ref:`Choose a hashing backend` for more. """ SUPPORTED_BACKENDS = [ "pycryptodome", "pysha3", ] eth-hash-0.7.1/eth_hash/backends/auto.py000066400000000000000000000014151474130264500201060ustar00rootroot00000000000000from typing import ( Union, ) from eth_hash.abc import ( BackendAPI, PreImageAPI, ) from eth_hash.utils import ( auto_choose_backend, ) class AutoBackend(BackendAPI): def _initialize(self) -> None: backend = auto_choose_backend() # Use setattr to circumvent mypy's confusion, see: # https://github.com/python/mypy/issues/2427 setattr(self, "keccak256", backend.keccak256) # noqa: B010 setattr(self, "preimage", backend.preimage) # noqa: B010 def keccak256(self, in_data: Union[bytearray, bytes]) -> bytes: self._initialize() return self.keccak256(in_data) def preimage(self, in_data: Union[bytearray, bytes]) -> PreImageAPI: self._initialize() return self.preimage(in_data) eth-hash-0.7.1/eth_hash/backends/pycryptodome.py000066400000000000000000000023401474130264500216720ustar00rootroot00000000000000from typing import ( Union, cast, ) from Crypto.Hash import ( keccak, ) from eth_hash.abc import ( BackendAPI, PreImageAPI, ) class CryptodomePreimage(PreImageAPI): def __init__(self, prehash: bytes) -> None: self._hash = keccak.new(data=prehash, digest_bits=256, update_after_digest=True) # pycryptodome doesn't expose a `copy` mechanism for it's hash objects # so we keep a record of all of the parts for when/if we need to copy # them. self._parts = [prehash] def update(self, prehash: bytes) -> None: self._hash.update(prehash) self._parts.append(prehash) def digest(self) -> bytes: return cast(bytes, self._hash.digest()) def copy(self) -> "CryptodomePreimage": return CryptodomePreimage(b"".join(self._parts)) class CryptodomeBackend(BackendAPI): def keccak256(self, prehash: Union[bytearray, bytes]) -> bytes: hasher = keccak.new(data=prehash, digest_bits=256) return cast(bytes, hasher.digest()) def preimage(self, prehash: Union[bytearray, bytes]) -> PreImageAPI: return CryptodomePreimage(prehash) backend = CryptodomeBackend() keccak256 = backend.keccak256 preimage = backend.preimage eth-hash-0.7.1/eth_hash/backends/pysha3.py000066400000000000000000000017001474130264500203420ustar00rootroot00000000000000from typing import ( Union, ) from sha3 import ( keccak_256 as _keccak_256, ) from eth_hash.abc import ( BackendAPI, PreImageAPI, ) class Pysha3Preimage(PreImageAPI): def __init__(self, prehash: bytes) -> None: self._hash = _keccak_256(prehash) def update(self, prehash: bytes) -> None: return self._hash.update(prehash) # type: ignore def digest(self) -> bytes: return self._hash.digest() # type: ignore def copy(self) -> "Pysha3Preimage": dup = Pysha3Preimage(b"") dup._hash = self._hash.copy() return dup class PySha3Backend(BackendAPI): def keccak256(self, prehash: Union[bytearray, bytes]) -> bytes: return _keccak_256(prehash).digest() # type: ignore def preimage(self, prehash: Union[bytearray, bytes]) -> PreImageAPI: return Pysha3Preimage(prehash) backend = PySha3Backend() keccak256 = backend.keccak256 preimage = backend.preimage eth-hash-0.7.1/eth_hash/main.py000066400000000000000000000037601474130264500163150ustar00rootroot00000000000000from typing import ( Union, ) from .abc import ( BackendAPI, PreImageAPI, ) class Keccak256: def __init__(self, backend: BackendAPI) -> None: self._backend = backend self.hasher = self._hasher_first_run self.preimage = self._preimage_first_run def _hasher_first_run(self, in_data: Union[bytearray, bytes]) -> bytes: """ Validate, on first-run, that the hasher backend is valid. After first run, replace this with the new hasher method. This is a bit of a hacky way to minimize overhead on hash calls after this first one. """ # Execute directly before saving method, # to let any side-effects settle (see AutoBackend) result = self._backend.keccak256(in_data) new_hasher = self._backend.keccak256 assert ( new_hasher(b"") == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501 ) self.hasher = new_hasher return result def _preimage_first_run(self, in_data: Union[bytearray, bytes]) -> PreImageAPI: # Execute directly before saving method, # to let any side-effects settle (see AutoBackend) result = self._backend.preimage(in_data) self.preimage = self._backend.preimage return result def __call__(self, preimage: Union[bytearray, bytes]) -> bytes: if not isinstance(preimage, (bytearray, bytes)): raise TypeError( "Can only compute the hash of `bytes` or `bytearray` values, " f"not {repr(preimage)}" ) return self.hasher(preimage) def new(self, preimage: Union[bytearray, bytes]) -> PreImageAPI: if not isinstance(preimage, (bytearray, bytes)): raise TypeError( "Can only compute the hash of `bytes` or `bytearray` values, " f"not {repr(preimage)}" ) return self.preimage(preimage) eth-hash-0.7.1/eth_hash/py.typed000066400000000000000000000000001474130264500164760ustar00rootroot00000000000000eth-hash-0.7.1/eth_hash/utils.py000066400000000000000000000041721474130264500165270ustar00rootroot00000000000000import importlib import logging import os from eth_hash.abc import ( BackendAPI, ) from eth_hash.backends import ( SUPPORTED_BACKENDS, ) def auto_choose_backend() -> BackendAPI: env_backend = get_backend_in_environment() if env_backend: return load_environment_backend(env_backend) else: return choose_available_backend() def get_backend_in_environment() -> str: return os.environ.get("ETH_HASH_BACKEND", "") def load_backend(backend_name: str) -> BackendAPI: import_path = f"eth_hash.backends.{backend_name}" module = importlib.import_module(import_path) try: backend = module.backend except AttributeError as e: raise ValueError( f"Import of {import_path} failed, because {module} does not have " "'backend' attribute" ) from e if isinstance(backend, BackendAPI): return backend else: raise ValueError( f"Import of {import_path} failed, because {backend} is an invalid back end" ) def load_environment_backend(env_backend: str) -> BackendAPI: if env_backend in SUPPORTED_BACKENDS: try: return load_backend(env_backend) except ImportError as e: raise ImportError( f"The backend specified in ETH_HASH_BACKEND, '{env_backend}', is not " f"installed. Install with `python -m pip install " f'"eth-hash[{env_backend}]"`.' ) from e else: raise ValueError( f"The backend specified in ETH_HASH_BACKEND, '{env_backend}', is not " f"supported. Choose one of: {SUPPORTED_BACKENDS}" ) def choose_available_backend() -> BackendAPI: for backend in SUPPORTED_BACKENDS: try: return load_backend(backend) except ImportError: logging.getLogger("eth_hash").debug( f"Failed to import {backend}", exc_info=True ) raise ImportError( f"None of these hashing backends are installed: {SUPPORTED_BACKENDS}.\n" f'Install with `python -m pip install "eth-hash[{SUPPORTED_BACKENDS[0]}]"`.' ) eth-hash-0.7.1/newsfragments/000077500000000000000000000000001474130264500161115ustar00rootroot00000000000000eth-hash-0.7.1/newsfragments/README.md000066400000000000000000000020221474130264500173640ustar00rootroot00000000000000This directory collects "newsfragments": short files that each contain a snippet of ReST-formatted text that will be added to the next release notes. This should be a description of aspects of the change (if any) that are relevant to users. (This contrasts with the commit message and PR description, which are a description of the change as relevant to people working on the code itself.) Each file should be named like `..rst`, where `` is an issue number, and `` is one of: - `breaking` - `bugfix` - `deprecation` - `docs` - `feature` - `internal` - `misc` - `performance` - `removal` So for example: `123.feature.rst`, `456.bugfix.rst` If the PR fixes an issue, use that number here. If there is no issue, then open up the PR first and use the PR number for the newsfragment. Note that the `towncrier` tool will automatically reflow your text, so don't try to do any fancy formatting. Run `towncrier build --draft` to get a preview of what the release notes entry will look like in the final release notes. eth-hash-0.7.1/newsfragments/validate_files.py000077500000000000000000000021621474130264500214420ustar00rootroot00000000000000#!/usr/bin/env python3 # Towncrier silently ignores files that do not match the expected ending. # We use this script to ensure we catch these as errors in CI. import pathlib import sys ALLOWED_EXTENSIONS = { ".breaking.rst", ".bugfix.rst", ".deprecation.rst", ".docs.rst", ".feature.rst", ".internal.rst", ".misc.rst", ".performance.rst", ".removal.rst", } ALLOWED_FILES = { "validate_files.py", "README.md", } THIS_DIR = pathlib.Path(__file__).parent num_args = len(sys.argv) - 1 assert num_args in {0, 1} if num_args == 1: assert sys.argv[1] in ("is-empty",) for fragment_file in THIS_DIR.iterdir(): if fragment_file.name in ALLOWED_FILES: continue elif num_args == 0: full_extension = "".join(fragment_file.suffixes) if full_extension not in ALLOWED_EXTENSIONS: raise Exception(f"Unexpected file: {fragment_file}") elif sys.argv[1] == "is-empty": raise Exception(f"Unexpected file: {fragment_file}") else: raise RuntimeError( f"Strange: arguments {sys.argv} were validated, but not found" ) eth-hash-0.7.1/pyproject.toml000066400000000000000000000104041474130264500161410ustar00rootroot00000000000000[tool.autoflake] exclude = "__init__.py" remove_all_unused_imports = true [tool.isort] combine_as_imports = true extra_standard_library = "pytest" force_grid_wrap = 1 force_sort_within_sections = true force_to_top = "pytest" honor_noqa = true known_first_party = "eth_hash" known_third_party = "hypothesis,Crypto,sha3" multi_line_output = 3 profile = "black" use_parentheses = true [tool.mypy] check_untyped_defs = true disallow_any_generics = true disallow_incomplete_defs = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = true disallow_untyped_defs = true ignore_missing_imports = true strict_equality = true strict_optional = true warn_redundant_casts = true warn_return_any = true warn_unused_configs = true warn_unused_ignores = true [tool.pydocstyle] # All error codes found here: # http://www.pydocstyle.org/en/3.0.0/error_codes.html # # Ignored: # D1 - Missing docstring error codes # # Selected: # D2 - Whitespace error codes # D3 - Quote error codes # D4 - Content related error codes select = "D2,D3,D4" # Extra ignores: # D200 - One-line docstring should fit on one line with quotes # D203 - 1 blank line required before class docstring # D204 - 1 blank line required after class docstring # D205 - 1 blank line required between summary line and description # D212 - Multi-line docstring summary should start at the first line # D302 - Use u""" for Unicode docstrings # D400 - First line should end with a period # D401 - First line should be in imperative mood # D412 - No blank lines allowed between a section header and its content # D415 - First line should end with a period, question mark, or exclamation point add-ignore = "D200,D203,D204,D205,D212,D302,D400,D401,D412,D415" # Explanation: # D400 - Enabling this error code seems to make it a requirement that the first # sentence in a docstring is not split across two lines. It also makes it a # requirement that no docstring can have a multi-sentence description without a # summary line. Neither one of those requirements seem appropriate. [tool.pytest.ini_options] addopts = "-v --showlocals --durations 10" log_date_format = "%m-%d %H:%M:%S" log_format = "%(levelname)8s %(asctime)s %(filename)20s %(message)s" xfail_strict = true [tool.towncrier] # Read https://github.com/ethereum/eth-hash/blob/main/newsfragments/README.md for instructions directory = "newsfragments" filename = "docs/release_notes.rst" issue_format = "`#{issue} `__" package = "eth_hash" title_format = "eth-hash v{version} ({project_date})" underlines = ["-", "~", "^"] [[tool.towncrier.type]] directory = "breaking" name = "Breaking Changes" showcontent = true [[tool.towncrier.type]] directory = "bugfix" name = "Bugfixes" showcontent = true [[tool.towncrier.type]] directory = "deprecation" name = "Deprecations" showcontent = true [[tool.towncrier.type]] directory = "docs" name = "Improved Documentation" showcontent = true [[tool.towncrier.type]] directory = "feature" name = "Features" showcontent = true [[tool.towncrier.type]] directory = "internal" name = "Internal Changes - for eth-hash Contributors" showcontent = true [[tool.towncrier.type]] directory = "misc" name = "Miscellaneous Changes" showcontent = false [[tool.towncrier.type]] directory = "performance" name = "Performance Improvements" showcontent = true [[tool.towncrier.type]] directory = "removal" name = "Removals" showcontent = true [tool.bumpversion] current_version = "0.7.1" parse = """ (?P\\d+) \\.(?P\\d+) \\.(?P\\d+) (- (?P[^.]*) \\.(?P\\d+) )? """ serialize = [ "{major}.{minor}.{patch}-{stage}.{devnum}", "{major}.{minor}.{patch}", ] search = "{current_version}" replace = "{new_version}" regex = false ignore_missing_version = false tag = true sign_tags = true tag_name = "v{new_version}" tag_message = "Bump version: {current_version} → {new_version}" allow_dirty = false commit = true message = "Bump version: {current_version} → {new_version}" [tool.bumpversion.parts.stage] optional_value = "stable" first_value = "stable" values = [ "alpha", "beta", "stable", ] [tool.bumpversion.part.devnum] [[tool.bumpversion.files]] filename = "setup.py" search = "version=\"{current_version}\"" replace = "version=\"{new_version}\"" eth-hash-0.7.1/scripts/000077500000000000000000000000001474130264500147155ustar00rootroot00000000000000eth-hash-0.7.1/scripts/release/000077500000000000000000000000001474130264500163355ustar00rootroot00000000000000eth-hash-0.7.1/scripts/release/test_package.py000066400000000000000000000025071474130264500213450ustar00rootroot00000000000000from pathlib import ( Path, ) import subprocess from tempfile import ( TemporaryDirectory, ) import venv def create_venv(parent_path: Path) -> Path: venv_path = parent_path / "package-smoke-test" venv.create(venv_path, with_pip=True) subprocess.run( [venv_path / "bin" / "pip", "install", "-U", "pip", "setuptools"], check=True ) return venv_path def find_wheel(project_path: Path) -> Path: wheels = list(project_path.glob("dist/*.whl")) if len(wheels) != 1: raise Exception( f"Expected one wheel. Instead found: {wheels} " f"in project {project_path.absolute()}" ) return wheels[0] def install_wheel(venv_path: Path, wheel_path: Path) -> None: subprocess.run( [venv_path / "bin" / "pip", "install", f"{wheel_path}"], check=True, ) def test_install_local_wheel() -> None: with TemporaryDirectory() as tmpdir: venv_path = create_venv(Path(tmpdir)) wheel_path = find_wheel(Path(".")) install_wheel(venv_path, wheel_path) print("Installed", wheel_path.absolute(), "to", venv_path) print(f"Activate with `source {venv_path}/bin/activate`") input("Press enter when the test has completed. The directory will be deleted.") if __name__ == "__main__": test_install_local_wheel() eth-hash-0.7.1/setup.py000066400000000000000000000044001474130264500147360ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import ( find_packages, setup, ) extras_require = { "dev": [ "build>=0.9.0", "bump_my_version>=0.19.0", "ipython", "mypy==1.10.0", "pre-commit>=3.4.0", "tox>=4.0.0", "twine", "wheel", ], "docs": [ "sphinx>=6.0.0", "sphinx-autobuild>=2021.3.14", "sphinx_rtd_theme>=1.0.0", "towncrier>=24,<25", ], "test": [ "pytest>=7.0.0", "pytest-xdist>=2.4.0", ], # optional backends: "pycryptodome": [ "pycryptodome>=3.6.6,<4", ], "pysha3": [ "pysha3>=1.0.0,<2.0.0;python_version<'3.9'", "safe-pysha3>=1.0.0;python_version>='3.9'", ], } extras_require["dev"] = ( extras_require["dev"] + extras_require["docs"] + extras_require["test"] ) with open("./README.md") as readme: long_description = readme.read() setup( name="eth-hash", # *IMPORTANT*: Don't manually change the version here. Use `make bump`, as described in readme version="0.7.1", description="""eth-hash: The Ethereum hashing function, keccak256, sometimes (erroneously) called sha3""", long_description=long_description, long_description_content_type="text/markdown", author="The Ethereum Foundation", author_email="snakecharmers@ethereum.org", url="https://github.com/ethereum/eth-hash", include_package_data=True, install_requires=[], python_requires=">=3.8, <4", extras_require=extras_require, py_modules=["eth_hash"], license="MIT", zip_safe=False, keywords="ethereum", packages=find_packages(exclude=["scripts", "scripts.*", "tests", "tests.*"]), package_data={"eth_hash": ["py.typed"]}, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", ], ) eth-hash-0.7.1/tests/000077500000000000000000000000001474130264500143705ustar00rootroot00000000000000eth-hash-0.7.1/tests/backends/000077500000000000000000000000001474130264500161425ustar00rootroot00000000000000eth-hash-0.7.1/tests/backends/pycryptodome/000077500000000000000000000000001474130264500207005ustar00rootroot00000000000000eth-hash-0.7.1/tests/backends/pycryptodome/conftest.py000066400000000000000000000012441474130264500231000ustar00rootroot00000000000000import pytest @pytest.fixture(params=["auto", "explicit", "env"]) def keccak(monkeypatch, request, keccak_auto): if request.param == "auto": return keccak_auto elif request.param == "explicit": from eth_hash import ( Keccak256, ) from eth_hash.backends import ( pycryptodome, ) return Keccak256(pycryptodome) elif request.param == "env": monkeypatch.setenv("ETH_HASH_BACKEND", "pycryptodome") from eth_hash.auto import ( keccak, ) return keccak else: raise AssertionError(f"Unrecognized approach to import keccak: {request.param}") eth-hash-0.7.1/tests/backends/pycryptodome/test_results.py000077700000000000000000000000001474130264500273322../test_results.pyustar00rootroot00000000000000eth-hash-0.7.1/tests/backends/pysha3/000077500000000000000000000000001474130264500173515ustar00rootroot00000000000000eth-hash-0.7.1/tests/backends/pysha3/conftest.py000066400000000000000000000012221474130264500215450ustar00rootroot00000000000000import pytest @pytest.fixture(params=["auto", "explicit", "env"]) def keccak(monkeypatch, request, keccak_auto): if request.param == "auto": return keccak_auto elif request.param == "explicit": from eth_hash import ( Keccak256, ) from eth_hash.backends import ( pysha3, ) return Keccak256(pysha3) elif request.param == "env": monkeypatch.setenv("ETH_HASH_BACKEND", "pysha3") from eth_hash.auto import ( keccak, ) return keccak else: raise AssertionError(f"Unrecognized approach to import keccak: {request.param}") eth-hash-0.7.1/tests/backends/pysha3/test_results.py000077700000000000000000000000001474130264500260032../test_results.pyustar00rootroot00000000000000eth-hash-0.7.1/tests/backends/test_results.py000066400000000000000000000074301474130264500212600ustar00rootroot00000000000000import pytest import pickle # Note that this file is symlink'd in all backend folders, so a change here is # automatically shared across backend tests. If you want to add a backend-specific # test, add it to a new file. @pytest.fixture def keccak_auto(): from eth_hash.auto import ( keccak, ) return keccak @pytest.mark.parametrize( "prehash, expected_result", ( ( b"", b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p", # noqa: E501 ), ( bytearray(b""), b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p", # noqa: E501 ), ), ) def test_keccak_256(keccak, prehash, expected_result): assert keccak(prehash) == expected_result @pytest.mark.parametrize( "parts, expected_result", ( ( [b""], b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p", # noqa: E501 ), ( [bytearray(b"")], b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p", # noqa: E501 ), ( [b"", b"", b""], b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p", # noqa: E501 ), ( [bytearray(b""), bytearray(b""), bytearray(b"")], b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p", # noqa: E501 ), ( [b"arst", b"tsra"], b"\xb1\xf3T\xb2\x8f\xf2\x84R\xd6\xb9\xd6\x1fA\x06\x1b\xbe\x82\xbe\xb1\xfc\x98\xf33d\xa8\x05\x8d\x1a]\x16M\x05", # noqa: E501 ), ( [bytearray(b"arst"), bytearray(b"tsra")], b"\xb1\xf3T\xb2\x8f\xf2\x84R\xd6\xb9\xd6\x1fA\x06\x1b\xbe\x82\xbe\xb1\xfc\x98\xf33d\xa8\x05\x8d\x1a]\x16M\x05", # noqa: E501 ), ( [bytearray(b"arst"), b"tsra"], b"\xb1\xf3T\xb2\x8f\xf2\x84R\xd6\xb9\xd6\x1fA\x06\x1b\xbe\x82\xbe\xb1\xfc\x98\xf33d\xa8\x05\x8d\x1a]\x16M\x05", # noqa: E501 ), ( [b"arst", bytearray(b"tsra")], b"\xb1\xf3T\xb2\x8f\xf2\x84R\xd6\xb9\xd6\x1fA\x06\x1b\xbe\x82\xbe\xb1\xfc\x98\xf33d\xa8\x05\x8d\x1a]\x16M\x05", # noqa: E501 ), ), ) def test_keccak_256_preimage(keccak, parts, expected_result): preimage = keccak.new(parts[0]) for part in parts[1:]: preimage.update(part) assert preimage.digest() == expected_result def test_copy_keccak_256_preimage(keccak): preimage_origin = keccak.new(b"") preimage_copy = preimage_origin.copy() preimage_origin.update(b"arsttsra") assert ( preimage_origin.digest() == b"\xb1\xf3T\xb2\x8f\xf2\x84R\xd6\xb9\xd6\x1fA\x06\x1b\xbe\x82\xbe\xb1\xfc\x98\xf33d\xa8\x05\x8d\x1a]\x16M\x05" # noqa: E501 ) assert ( preimage_copy.digest() == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501 ) def test_update_digest_update(keccak): preimage = keccak.new(b"") preimage.update(b"arst") assert ( preimage.digest() == b"\xc30[\xc9\xde\x12D\xe4\x80P\x96,\xedP\xb7Y4\xc3p\x06\xe9\x9e\x8bzb!>\x94\\=\xfc\xd7" # noqa: E501 ) preimage.update(b"tsra") assert ( preimage.digest() == b"\xb1\xf3T\xb2\x8f\xf2\x84R\xd6\xb9\xd6\x1fA\x06\x1b\xbe\x82\xbe\xb1\xfc\x98\xf33d\xa8\x05\x8d\x1a]\x16M\x05" # noqa: E501 ) def test_auto_pickleable(keccak_auto): serialized = pickle.dumps(keccak_auto) deserialized = pickle.loads(serialized) assert deserialized(b"arst") == keccak_auto(b"arst") eth-hash-0.7.1/tests/core/000077500000000000000000000000001474130264500153205ustar00rootroot00000000000000eth-hash-0.7.1/tests/core/test_import_and_version.py000066400000000000000000000037561474130264500226450ustar00rootroot00000000000000import pytest import sys from unittest import ( mock, ) def clean_module(name): """Clean a module import so all variables in it will be created again""" try: del sys.modules[name] except KeyError: pass return def test_import_auto(): clean_module("eth_hash.auto") from eth_hash.auto import keccak # noqa: F401 def test_import_auto_empty_crash(monkeypatch): clean_module("eth_hash.auto") from eth_hash.auto import ( keccak, ) with mock.patch.dict("sys.modules", {"sha3": None, "Crypto.Hash": None}): with pytest.raises( ImportError, match="None of these hashing backends are installed" ): keccak(b"eh") def test_import_and_version(): clean_module("eth_hash") import eth_hash assert isinstance(eth_hash.__version__, str) @pytest.mark.parametrize( "backend", [ "pycryptodome", "pysha3", ], ) def test_load_by_env(monkeypatch, backend): clean_module("eth_hash.auto") from eth_hash.auto import ( keccak, ) monkeypatch.setenv("ETH_HASH_BACKEND", backend) with mock.patch.dict("sys.modules", {"sha3": None, "Crypto.Hash": None}): with pytest.raises(ImportError) as excinfo: keccak(b"triggered") expected_msg = ( f"The backend specified in ETH_HASH_BACKEND, '{backend}', is not installed. " f'Install with `python -m pip install "eth-hash[{backend}]"`.' ) assert expected_msg in str(excinfo.value) def test_load_unavailable_backend_by_env(monkeypatch): clean_module("eth_hash.auto") from eth_hash.auto import ( keccak, ) backend = "this-backend-will-never-exist" monkeypatch.setenv("ETH_HASH_BACKEND", backend) with pytest.raises(ValueError) as excinfo: keccak(b"triggered") expected_msg = ( f"The backend specified in ETH_HASH_BACKEND, '{backend}', is not supported. " "Choose one of" ) assert expected_msg in str(excinfo.value) eth-hash-0.7.1/tox.ini000066400000000000000000000034701474130264500145450ustar00rootroot00000000000000[tox] envlist= py{38,39,310,311,312,313}-core py{38,39,310,311,312,313}-lint py{38,39,310,311,312,313}-wheel windows-wheel py{38,39,310,311,312,313}-backend-pycryptodome py{38,39,310,311,312,313}-backend-pysha3 docs [flake8] exclude=venv*,.tox,docs,build extend-ignore=E203 max-line-length=88 per-file-ignores=__init__.py:F401 [blocklint] max_issue_threshold=1 [testenv] usedevelop=True commands= core: pytest {posargs:tests/core} docs: make check-docs-ci pycryptodome: pytest {posargs:tests/backends/pycryptodome} pysha3: pytest {posargs:tests/backends/pysha3} basepython= docs: python windows-wheel: python py38: python3.8 py39: python3.9 py310: python3.10 py311: python3.11 py312: python3.12 py313: python3.13 extras= test docs docs: pycryptodome docs: pysha3 pycryptodome pysha3 allowlist_externals=make,pre-commit [testenv:py{38,39,310,311,312,313}-lint] deps=pre-commit extras=dev commands= pre-commit install pre-commit run --all-files --show-diff-on-failure [testenv:py{38,39,310,311,312,313}-wheel] deps= wheel build[virtualenv] allowlist_externals= /bin/rm /bin/bash commands= python -m pip install --upgrade pip /bin/rm -rf build dist python -m build /bin/bash -c 'python -m pip install --upgrade "$(ls dist/eth_hash-*-py3-none-any.whl)" --progress-bar off' python -c "import eth_hash" skip_install=true [testenv:windows-wheel] deps= wheel build[virtualenv] allowlist_externals= bash.exe commands= python --version python -m pip install --upgrade pip bash.exe -c "rm -rf build dist" python -m build bash.exe -c 'python -m pip install --upgrade "$(ls dist/eth_hash-*-py3-none-any.whl)" --progress-bar off' python -c "import eth_hash" skip_install=true