diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b78b36 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +*.ac text eol=lf +*.am text eol=lf +*.sh text eol=lf +*.pl text eol=lf +*.py text eol=lf +*.go text eol=lf +*.c text eol=lf +*.cs text eol=lf +*.json text eol=lf diff --git a/.github/ISSUE_TEMPLATE/Story.md b/.github/ISSUE_TEMPLATE/Story.md new file mode 100644 index 0000000..7a7c989 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Story.md @@ -0,0 +1,17 @@ +--- +name: Story +about: Create a story + +--- + +# Overview + + + +- + +# Completion condition + + + +- diff --git a/.github/ISSUE_TEMPLATE/Task.md b/.github/ISSUE_TEMPLATE/Task.md new file mode 100644 index 0000000..e53247f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Task.md @@ -0,0 +1,23 @@ +--- +name: Task +about: Create a task + +--- + +# Overview + + + +- + +# Sub tasks + + + +- [ ] + +# Completion condition + + + +- \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..fa07710 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,44 @@ +## Linked Issue + + + +## Overview + + + +## How to use + + + +```bash +``` + +## Items reserved this time, or TODO + + + +## Check list + +** Person who issued ** +- [ ] checked script +- [ ] build successed +- [ ] Linked PullRequest and Issue + +** Reviewer ** +- [ ] (if necessary) Record the review results of related tickets. + +## Memo + + diff --git a/.github/workflows/check_pre-merge_develop.yml b/.github/workflows/check_pre-merge_develop.yml new file mode 100644 index 0000000..e7ab378 --- /dev/null +++ b/.github/workflows/check_pre-merge_develop.yml @@ -0,0 +1,93 @@ +name: develop pre-merge check + +on: + push: + branches: + - develop + - test_ci + paths-ignore: + - '.github/workflows/create_release-and-upload.yml' + - 'README.md' + pull_request: + branches: + - develop + - test_ci + +jobs: + build-and-test: + name: build & test + timeout-minutes: 20 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest, ubuntu-latest] + py-ver: [3.6, 3.7, 3.8, pypy3] + exclude: + - os: windows-latest + py-ver: pypy3 + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.py-ver }} + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: build + run: python setup.py build + - name: copy dll + if: runner.os == 'Windows' && (matrix.py-ver == '3.6' || matrix.py-ver == '3.7') + run: | + cp ./cmake_build/Release/*.dll ./cfd/ + echo "$GITHUB_WORKSPACE/cfd" >> $GITHUB_PATH + shell: bash + - name: test + run: python -m unittest discover -v tests + + pip-test: + name: pip test + timeout-minutes: 20 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest, ubuntu-latest] + py-ver: [3.6, 3.7, 3.8, pypy3] + exclude: + - os: windows-latest + py-ver: 3.6 + - os: windows-latest + py-ver: 3.7 + - os: windows-latest + py-ver: pypy3 + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.py-ver }} + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: install pip + run: python -m pip install -U pip + - name: install + run: pip install --user . + - name: dump info + run: pip show cfd + - name: call example + run: python ./tools/example.py + + doxygen-ubuntu: + name: doxygen-ubuntu + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: install_doxygen + run: sudo apt install doxygen graphviz + - name: doxygen_check + run: | + cd doc + doxygen Doxyfile_quiet_all diff --git a/.github/workflows/check_pre-merge_master.yml b/.github/workflows/check_pre-merge_master.yml new file mode 100644 index 0000000..6d5e320 --- /dev/null +++ b/.github/workflows/check_pre-merge_master.yml @@ -0,0 +1,88 @@ +name: master pre-merge check + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + build-and-test: + name: build & test + timeout-minutes: 20 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest, ubuntu-latest] + py-ver: [3.6, 3.7, 3.8, pypy3] + exclude: + - os: windows-latest + py-ver: pypy3 + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.py-ver }} + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: build + run: python setup.py build + - name: copy dll + if: runner.os == 'Windows' && (matrix.py-ver == '3.6' || matrix.py-ver == '3.7') + run: | + cp ./cmake_build/Release/*.dll ./cfd/ + echo "$GITHUB_WORKSPACE/cfd" >> $GITHUB_PATH + shell: bash + - name: test + run: python -m unittest discover -v tests + + pip-test: + name: pip test + timeout-minutes: 20 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest, ubuntu-latest] + py-ver: [3.6, 3.7, 3.8, pypy3] + exclude: + - os: windows-latest + py-ver: 3.6 + - os: windows-latest + py-ver: 3.7 + - os: windows-latest + py-ver: pypy3 + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.py-ver }} + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: install pip + run: python -m pip install -U pip + - name: install + run: pip install --user . + - name: dump info + run: pip show cfd + - name: call example + run: python ./tools/example.py + + doxygen-ubuntu: + name: doxygen-ubuntu + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: install_doxygen + run: sudo apt install doxygen graphviz + - name: doxygen_check + run: | + cd doc + doxygen Doxyfile_quiet_all diff --git a/.github/workflows/check_pre-merge_sprint.yml b/.github/workflows/check_pre-merge_sprint.yml new file mode 100644 index 0000000..a0bcb3c --- /dev/null +++ b/.github/workflows/check_pre-merge_sprint.yml @@ -0,0 +1,63 @@ +name: sprint pre-merge check + +on: + push: + branches: + - features/sprint* + paths-ignore: + - '.github/workflows/create_release-and-upload.yml' + - 'README.md' + pull_request: + branches: + - features/sprint* + +jobs: + build-and-test: + name: build & test + timeout-minutes: 20 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest, ubuntu-latest] + py-ver: [3.6, 3.7, 3.8, pypy3] + exclude: + - os: macos-latest + py-ver: 3.6 + - os: macos-latest + py-ver: 3.7 + - os: windows-latest + py-ver: 3.6 + - os: windows-latest + py-ver: pypy3 + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.py-ver }} + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: build + run: python setup.py build + - name: copy dll + if: runner.os == 'Windows' && matrix.py-ver == '3.7' + run: | + cp ./cmake_build/Release/*.dll ./cfd/ + echo "$GITHUB_WORKSPACE/cfd" >> $GITHUB_PATH + shell: bash + - name: test + run: python -m unittest discover -v tests + + doxygen-ubuntu: + name: doxygen-ubuntu + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: install_doxygen + run: sudo apt install doxygen graphviz + - name: doxygen_check + run: | + cd doc + doxygen Doxyfile_quiet_all diff --git a/.github/workflows/code_scanner.yml b/.github/workflows/code_scanner.yml new file mode 100644 index 0000000..2412605 --- /dev/null +++ b/.github/workflows/code_scanner.yml @@ -0,0 +1,106 @@ +name: code scan + +on: + push: + branches: + - master + - develop + - features/sprint* + - feature/code_scanning + pull_request: + branches: + - master + - develop + - features/sprint* + +jobs: + analyze-CodeQL: + name: CodeQL + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + # Override automatic language detection by changing the below list + # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] + language: ['python'] + # Learn more... + # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + # We must fetch at least the immediate parents so that if this is a pull request then we can checkout the head. + fetch-depth: 2 + + # If this run was triggered by a pull request event, then checkout the head of the pull request instead of the merge commit. + - run: git checkout HEAD^2 + if: ${{ github.event_name == 'pull_request' }} + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 + + # ℹ️ Command-line programs to run using the OS shell. + # https://git.io/JvXDl + + # ️ If the Autobuild fails above, remove it and uncomment the following three lines and modify them (or add more) to build your code if your project uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 + + OSSAR-Scan: + # OSSAR runs on windows-latest. + # ubuntu-latest and macos-latest support coming soon + runs-on: windows-latest + + steps: + # Checkout your code repository to scan + - name: Checkout repository + uses: actions/checkout@v2 + with: + # We must fetch at least the immediate parents so that if this is + # a pull request then we can checkout the head. + fetch-depth: 2 + + # If this run was triggered by a pull request event, then checkout + # the head of the pull request instead of the merge commit. + - run: git checkout HEAD^2 + if: ${{ github.event_name == 'pull_request' }} + + # Ensure a compatible version of dotnet is installed. + # The [Microsoft Security Code Analysis CLI](https://aka.ms/mscadocs) is built with dotnet v3.1.201. + # A version greater than or equal to v3.1.201 of dotnet must be installed on the agent in order to run this action. + # GitHub hosted runners already have a compatible version of dotnet installed and this step may be skipped. + # For self-hosted runners, ensure dotnet version 3.1.201 or later is installed by including this action: + # - name: Install .NET + # uses: actions/setup-dotnet@v1 + # with: + # dotnet-version: '3.1.x' + + # Run open source static analysis tools + - name: Run OSSAR + uses: github/ossar-action@v1 + id: ossar + + # Upload results to the Security tab + - name: Upload OSSAR results + uses: github/codeql-action/upload-sarif@v1 + with: + sarif_file: ${{ steps.ossar.outputs.sarifFile }} diff --git a/.github/workflows/create_release-and-upload.yml b/.github/workflows/create_release-and-upload.yml new file mode 100644 index 0000000..cacf7ec --- /dev/null +++ b/.github/workflows/create_release-and-upload.yml @@ -0,0 +1,162 @@ +name: create-release-upload + +on: + push: + tags: + - 'v*' + +jobs: + create_releases: + name: create-releases + runs-on: ubuntu-latest + outputs: + release_url: ${{ steps.output_url.outputs.upload_url }} + + steps: + - name: checkout + uses: actions/checkout@v2 + - name: Get the version + id: get_version + run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//} + shell: bash + - name: check package.json version + env: + version: ${{ steps.get_version.outputs.VERSION }} + run: python ./tools/version_checker.py ${version} + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: Release ${{ github.ref }} + body: | + Changes in this Release + - First Change + - Second Change + draft: false + prerelease: true + continue-on-error: true + - name: Get release + if: steps.create_release.outcome == 'failure' + id: get_release + uses: bruceadams/get-release@v1.2.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: output url + id: output_url + run: | + echo "::set-output name=upload_url::${{steps.get_release.outputs.upload_url}}${{steps.create_release.outputs.upload_url}}" + + upload-sdist: + name: upload-sdist + needs: create_releases + timeout-minutes: 20 + runs-on: ubuntu-latest + + steps: + - name: checkout + uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: 3.8 + - name: output url + id: get_url + run: echo "::set-output name=upload_url::${{ needs.create_releases.outputs.release_url }}" + - name: Get the version + id: get_version + run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//} + shell: bash + - name: dump version + env: + version: ${{ steps.get_version.outputs.VERSION }} + run: echo "version=${version}" + - name: create sdist + id: create_sdist + run: | + python setup.py sdist --formats=gztar,zip + cd dist + echo "::set-output name=sdist_tgz::$(ls *.tar.gz)" + echo "::set-output name=sdist_zip::$(ls *.zip)" + - name: Upload sdist for tgz + id: upload-sdist-tgz + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.get_url.outputs.upload_url }} + asset_path: ./dist/${{ steps.create_sdist.outputs.sdist_tgz }} + asset_name: ${{ steps.create_sdist.outputs.sdist_tgz }} + asset_content_type: application/zip + - name: Upload sdist for zip + id: upload-sdist-zip + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.get_url.outputs.upload_url }} + asset_path: ./dist/${{ steps.create_sdist.outputs.sdist_zip }} + asset_name: ${{ steps.create_sdist.outputs.sdist_zip }} + asset_content_type: application/zip + + upload-wheel: + name: upload-wheel + needs: create_releases + timeout-minutes: 20 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-10.15, windows-latest, ubuntu-18.04] + include: + - os: macos-10.15 + py-ver: 3.6 + pl-name: macosx_10_15_x86_64 + - os: ubuntu-18.04 + py-ver: 3.6 + pl-name: linux_x86_64 + - os: windows-latest + py-ver: 3.8 + pl-name: win_amd64 + + steps: + - name: checkout + uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.py-ver }} + - name: output url + id: get_url + run: echo "::set-output name=upload_url::${{ needs.create_releases.outputs.release_url }}" + - name: Get the version + id: get_version + run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\/v/} + shell: bash + - name: dump version + env: + version: ${{ steps.get_version.outputs.VERSION }} + run: echo "version=${version}" + shell: bash + - name: install pip & wheel + run: | + python -m pip install -U pip + pip install wheel + - name: create wheel + id: create_wheel + run: | + pip wheel . + echo "::set-output name=wheel::$(ls *.whl)" + shell: bash + - name: Upload sdist for tgz + id: upload-release-asset + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.get_url.outputs.upload_url }} + asset_path: ./${{ steps.create_wheel.outputs.wheel }} + asset_name: cfd-${{ steps.get_version.outputs.VERSION }}-py3-none-${{ matrix.pl-name }}.whl + asset_content_type: application/zip diff --git a/.gitignore b/.gitignore index b6e4761..ed2df2b 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,18 @@ dmypy.json # Pyre type checker .pyre/ + +*.lock + +external/* +!external/CMakeLists.txt +!external/googletest_CMakeLists.txt.in +!external/template_CMakeLists.txt.in + +cmake_build/ +.vscode/ + +/doc/html* +/doc/latex +/**/*_localdebug.bat +/*.whl diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..707aec4 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.13) + +set(PACKAGE_VERSION 1.0.0) + +#################### +# options +#################### +include(cmake/CfdCommonOption.cmake) +include(cmake/ConvertSrclistFunction.cmake) +include(cmake/CfdWallyOption.cmake) +include(cmake/CfdCommonSetting.cmake) + +# cfd option +option(CFD_SHARED "force shared build (ON or OFF. default:OFF)" OFF) +option(ENABLE_CAPI "enable c-api (ON or OFF. default:ON)" ON) +option(ENABLE_JSONAPI "enable json-api (ON or OFF. default:ON)" ON) + + +#################### +# subdirectories +#################### +project(cfd_all_test CXX) +if(NOT CFD_SINGLE_BUILD) +add_subdirectory(external) +endif() diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..037ecd0 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,12 @@ +include CMakeLists.txt LICENSE README.md template_CMakeLists.txt VERSION Pipfile +include *.py *.c *.cpp *.h *.config *.cmake +graft cfd +prune cfd/__pycache__ +graft tests +prune tests/__pycache__ +graft cmake +graft external +prune external/cfd +prune external/cfd-core +prune external/libwally-core +graft local_resource diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..0ca2a96 --- /dev/null +++ b/Pipfile @@ -0,0 +1,24 @@ +[dev-packages] +autopep8 = "*" +flake8 = "*" +coverage = "*" + +[packages] + +[scripts] +test = "python -m unittest discover -v tests" +test3 = "python3 -m unittest discover -v tests" +coverage = "coverage run --source cfd -m unittest discover -v tests" +report = "coverage report -m" +report_html = "coverage html" +report_xml = "coverage xml" +format = "autopep8 --aggressive --aggressive -ir setup.py cfd tests" +format_detail = "autopep8 --aggressive --aggressive -ivr setup.py cfd tests" +format_check = "autopep8 -d -r setup.py src" +lint = "flake8 --show-source setup.py cfd tests" +cleanup = "python ./tools/cleanup.py cmake_build" +build = "python ./setup.py build" +build3 = "python3 ./setup.py build" +doc = "cd doc && doxygen Doxyfile_quiet_all" +pip_install = "pip install" +pip_list = "pip list" diff --git a/README.md b/README.md index 0af24f9..f57525e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,266 @@ -# cfd-python -(WIP) +# Crypto Finance Development Kit for Python (CFD-PYTHON) + +## Dependencies + +- Python(CPython) (3.6 or higher) +- C/C++ Compiler +  - can compile c++11 +- CMake (3.14.3 or higher) + +### Windows + +download and install files. +- [Python](https://www.python.org/) +- [CMake](https://cmake.org/) (3.14.3 or higher) +- MSVC + - [Visual Studio](https://visualstudio.microsoft.com/downloads/) (Verified version is 2017 or higher) + - [Build Tools for Visual Studio](https://visualstudio.microsoft.com/downloads/) (2017 or higher) + - (Using only) [msvc redistribution package](https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads) + +### MacOS + +- [Homebrew](https://brew.sh/) + +```Shell +# xcode cli tools +xcode-select --install + +# install dependencies using Homebrew +brew install cmake python +``` + +### Linux(Ubuntu) + +```Shell +# install dependencies using APT package Manager +apt-get install -y build-essential cmake python3 python3-dev +(Ubuntu 20.04 or higher) apt-get install -y python-is-python3 +curl https://sh.rustup.rs -sSf | sh (select is 1) +``` + +cmake version 3.14.2 or lower, download from website and install cmake. +(https://cmake.org/download/) + +### pip install + +First update pip: +``` +python -m pip install -U --user pip + or +python3 -m pip install -U --user pip +``` + +Then install the required packages: +``` +pip install --user wheel pipenv +``` + +### setup pipenv + +use pipenv (for developer): +``` +pipenv install -d +``` + +--- + +## pip install / uninstall + +attention: [using python 3.7 or lower on windows](#using-python-37-or-lower-on-windows) + +### install from GitHub + +``` +pip install --user git+https://github.com/p2pderivatives/cfd-python@master +``` + +### install from source code + +Using unpack source code: +```Shell +pip install --user . +``` + +### install from wheel + +1. get releases asset. (ex. https://github.com/p2pderivatives/cfd-python/releases/download/v0.0.1/cfd-0.0.1-py3-none-win_amd64.whl ) +2. install pip + ``` + pip install --user cfd-0.0.1-py3-none-win_amd64.whl + ``` + +### uninstall + +``` +pip uninstall -y cfd +``` + +--- + +## Build native library on local + +### build + +use python: +``` +python setup.py build + or +(ubuntu 18.04) python3 setup.py build +``` + +use pipenv: +``` +pipenv run build + or +(ubuntu 18.04) pipenv run build3 +``` + +### cleanup + +``` +rm -rf cmake_build + or +pipenv run cleanup +``` + +## packaging + +### sdist file + +``` +python ./setup.py sdist +``` + +### wheel file + +``` +pip wheel . +``` + +--- + +## Test + +### Test + +use python: +``` +python -m unittest discover -v tests + or +(ubuntu 18.04) python3 -m unittest discover -v tests +``` + +use pipenv: +``` +pipenv run test + or +(ubuntu 18.04) pipenv run test3 +``` + +--- + +## Information for developers + +### using library + +- cfd + - cfd-core + - [libwally-core](https://github.com/cryptogarageinc/libwally-core/tree/cfd-develop) (forked from [ElementsProject/libwally-core](https://github.com/ElementsProject/libwally-core)) + - [univalue](https://github.com/jgarzik/univalue) (for JSON encoding and decoding) + +### formatter + +- autopep8 + use pipenv: + ``` + pipenv run format + ``` + +### linter + +- flake8 + use pipenv: + ``` + pipenv run lint + ``` + +### document tool + +- doxygen + +### support compilers + +- Visual Studio (2017 or higher) +- Clang (7.x or higher) +- GCC (5.x or higher) + +--- + +## Note + +### using python 3.7 or lower on windows + +When using Python 3.7 or lower on Windows, it is necessary to add the install destination to the environment variable PATH. (Must be persistent.) + +The path to add must specify where to install cfd, as in the following example: +``` +C:\Users\DummyUser\AppData\Local\Programs\Python\Python37\Lib\site-packages\cfd +``` + +### Git connection: + +Git repository connections default to HTTPS. +However, depending on the connection settings of GitHub, you may only be able to connect via SSH. +As a countermeasure, forcibly establish SSH connection by setting `CFD_CMAKE_GIT_SSH=1` in the environment variable. + +- Windows: (On the command line. Or set from the system setting screen.) +``` +set CFD_CMAKE_GIT_SSH=1 +``` + +- MacOS & Linux(Ubuntu): +``` +export CFD_CMAKE_GIT_SSH=1 +``` + +### Ignore git update for CMake External Project: + +Depending on your git environment, you may get the following error when checking out external: +``` + Performing update step for 'libwally-core-download' + Current branch cmake_build is up to date. + No stash entries found. + No stash entries found. + No stash entries found. + CMake Error at /workspace/cfd-core/build/external/libwally-core/download/libwally-core-download-prefix/tmp/libwally-core-download-gitupdate.cmake:133 (message): + + + Failed to unstash changes in: + '/workspace/cfd-core/external/libwally-core/'. + + You will have to resolve the conflicts manually +``` + +This phenomenon is due to the `git update` related command. +Please set an environment variable that skips update processing. + +- Windows: (On the command line. Or set from the system setting screen.) +``` +set CFD_CMAKE_GIT_SKIP_UPDATE=1 +``` + +- MacOS & Linux(Ubuntu): +``` +export CFD_CMAKE_GIT_SKIP_UPDATE=1 +``` + +### Precautions when creating a wheel file + +(May not be needed if using pip wheel) +If it does not work properly, discard the wheel on the python2 side and set PYTHONPATH: +``` +export PYTHONPATH=$PYTHONPATH:~/.local/lib/python3.6/site-packages/wheel +``` + +If you are using WSL, you also need to set the access permissions on the Windows side. Check out the following issues: +- https://github.com/pypa/packaging-problems/issues/258 diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..341cf11 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.2.0 \ No newline at end of file diff --git a/cfd/__init__.py b/cfd/__init__.py new file mode 100644 index 0000000..a3c6560 --- /dev/null +++ b/cfd/__init__.py @@ -0,0 +1,21 @@ +import os +import glob + +__version__ = '0.1.0' + +__all__ = [ + os.path.split(os.path.splitext(file)[0])[1] + for file in glob.glob(os.path.join( + os.path.dirname(__file__), '[a-zA-Z0-9]*.py')) +] +""" +'address', +'confidential_address', +'confidential_transaction', +'descriptor', +'hdwallet', +'key', +'script', +'transaction', +'util' +""" diff --git a/cfd/address.py b/cfd/address.py new file mode 100644 index 0000000..f73b07d --- /dev/null +++ b/cfd/address.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +## +# @file address.py +# @brief address function implements file. +# @note Copyright 2020 CryptoGarage +from .util import get_util, CfdError, JobHandle, to_hex_string +from .key import Network, Pubkey +from .script import HashType, Script + + +## +# @class Address +# @brief Address data. +class Address: + ## + # @var address + # address string + ## + # @var locking_script + # locking script (scriptPubkey) + ## + # @var pubkey + # pubkey for pubkey hash. + ## + # @var redeem_script + # redeem script for script hash. + ## + # @var p2sh_wrapped_script + # witness locking script for p2sh. + ## + # @var hash_type + # hash type. + ## + # @var network + # network. + ## + # @var witness_version + # witness version. + + ## + # @brief constructor. + # @param[in] address address + # @param[in] locking_script locking script + # @param[in] hash_type hash type + # @param[in] network network + # @param[in] pubkey public key + # @param[in] redeem_script redeem script + # @param[in] p2sh_wrapped_script witness locking script for p2sh + def __init__( + self, + address, + locking_script, + hash_type=HashType.P2SH, + network=Network.MAINNET, + pubkey='', + redeem_script='', + p2sh_wrapped_script=''): + self.address = address + self.locking_script = locking_script + self.pubkey = pubkey + self.redeem_script = redeem_script + self.p2sh_wrapped_script = p2sh_wrapped_script + self.hash_type = hash_type + self.network = network + self.witness_version = -1 + if p2sh_wrapped_script and len(p2sh_wrapped_script) > 2: + if int(locking_script[0:2], 16) < 16: + self.witness_version = int(p2sh_wrapped_script[0:2]) + elif len(locking_script) > 2: + if int(locking_script[0:2], 16) < 16: + self.witness_version = int(locking_script[0:2]) + + ## + # @brief get string. + # @return address. + def __str__(self): + return self.address + + +## +# @class AddressUtil +# @brief Address utility. +class AddressUtil: + ## + # @brief parse address string. + # @param[in] address address string + # @param[in] hash_type hash type + # @return address object. + @classmethod + def parse(cls, address, hash_type=HashType.P2WPKH): + util = get_util() + with util.create_handle() as handle: + network, _hash_type, witness_version,\ + locking_script, _ = util.call_func( + 'CfdGetAddressInfo', handle.get_handle(), str(address)) + _hash_type = HashType.get(_hash_type) + try: + if _hash_type == HashType.P2SH: + tmp_hash_type = HashType.get(hash_type) + if tmp_hash_type in { + HashType.P2SH_P2WPKH, HashType.P2SH_P2WSH}: + _hash_type = tmp_hash_type + except CfdError: + pass + return Address( + str(address), + locking_script, + hash_type=_hash_type, + network=Network.get(network)) + + ## + # @brief get p2pkh address. + # @param[in] pubkey public key + # @param[in] network network + # @return address object. + @classmethod + def p2pkh(cls, pubkey, network=Network.MAINNET): + return cls.from_pubkey_hash( + pubkey, HashType.P2PKH, network) + + ## + # @brief get p2wpkh address. + # @param[in] pubkey public key + # @param[in] network network + # @return address object. + @classmethod + def p2wpkh(cls, pubkey, network=Network.MAINNET): + return cls.from_pubkey_hash( + pubkey, HashType.P2WPKH, network) + + ## + # @brief get p2sh-p2wpkh address. + # @param[in] pubkey public key + # @param[in] network network + # @return address object. + @classmethod + def p2sh_p2wpkh(cls, pubkey, network=Network.MAINNET): + return cls.from_pubkey_hash( + pubkey, HashType.P2SH_P2WPKH, network) + + ## + # @brief get p2sh address. + # @param[in] redeem_script redeem script + # @param[in] network network + # @return address object. + @classmethod + def p2sh(cls, redeem_script, network=Network.MAINNET): + return cls.from_script_hash( + redeem_script, HashType.P2SH, network) + + ## + # @brief get p2wsh address. + # @param[in] redeem_script redeem script + # @param[in] network network + # @return address object. + @classmethod + def p2wsh(cls, redeem_script, network=Network.MAINNET): + return cls.from_script_hash( + redeem_script, HashType.P2WSH, network) + + ## + # @brief get p2sh-p2wsh address. + # @param[in] redeem_script redeem script + # @param[in] network network + # @return address object. + @classmethod + def p2sh_p2wsh(cls, redeem_script, network=Network.MAINNET): + return cls.from_script_hash( + redeem_script, HashType.P2SH_P2WSH, network) + + ## + # @brief get pubkey hash address. + # @param[in] pubkey public key + # @param[in] hash_type hash type + # @param[in] network network + # @return address object. + @classmethod + def from_pubkey_hash( + cls, + pubkey, + hash_type, + network=Network.MAINNET): + _pubkey = str(pubkey) + _hash_type = HashType.get(hash_type) + _network = Network.get(network) + util = get_util() + with util.create_handle() as handle: + addr, locking_script, segwit_locking_script = util.call_func( + 'CfdCreateAddress', + handle.get_handle(), _hash_type.value, _pubkey, + '', _network.value) + return Address( + addr, + locking_script, + hash_type=_hash_type, + network=_network, + pubkey=Pubkey(_pubkey), + p2sh_wrapped_script=segwit_locking_script) + + ## + # @brief get script hash address. + # @param[in] redeem_script redeem script + # @param[in] hash_type hash type + # @param[in] network network + # @return address object. + @classmethod + def from_script_hash( + cls, + redeem_script, + hash_type, + network=Network.MAINNET): + _script = str(redeem_script) + _hash_type = HashType.get(hash_type) + _network = Network.get(network) + util = get_util() + with util.create_handle() as handle: + addr, locking_script, segwit_locking_script = util.call_func( + 'CfdCreateAddress', + handle.get_handle(), _hash_type.value, '', + _script, _network.value) + return Address( + addr, + locking_script, + hash_type=_hash_type, + network=_network, + redeem_script=Script(_script), + p2sh_wrapped_script=segwit_locking_script) + + ## + # @brief get multisig address. + # @param[in] require_num require signature num + # @param[in] pubkey_list pubkey list + # @param[in] hash_type hash type + # @param[in] network network + # @return address object. + @classmethod + def multisig( + cls, + require_num, + pubkey_list, + hash_type, + network=Network.MAINNET): + if isinstance(require_num, int) is False: + raise CfdError( + error_code=1, message='Error: Invalid require_num type.') + if (isinstance(pubkey_list, list) is False) or ( + len(pubkey_list) == 0): + raise CfdError( + error_code=1, message='Error: Invalid pubkey_list.') + _hash_type = HashType.get(hash_type) + _network = Network.get(network) + util = get_util() + with util.create_handle() as handle: + word_handle = util.call_func( + 'CfdInitializeMultisigScript', handle.get_handle(), + _network.value, _hash_type.value) + with JobHandle( + handle, + word_handle, + 'CfdFreeMultisigScriptHandle') as addr_handle: + for pubkey in pubkey_list: + util.call_func( + 'CfdAddMultisigScriptData', + handle.get_handle(), addr_handle.get_handle(), + to_hex_string(pubkey)) + + addr, redeem_script, witness_script = util.call_func( + 'CfdFinalizeMultisigScript', + handle.get_handle(), addr_handle.get_handle(), + require_num) + if _hash_type == HashType.P2SH: + witness_script = redeem_script + redeem_script = '' + + addr_obj = AddressUtil.parse(addr) + return Address( + addr, + addr_obj.locking_script, + hash_type=_hash_type, + network=_network, + redeem_script=Script(witness_script), + p2sh_wrapped_script=redeem_script) + + ## + # @brief get address from locking script. + # @param[in] locking_script locking script + # @param[in] network network + # @return address object. + @classmethod + def from_locking_script( + cls, + locking_script, + network=Network.MAINNET): + _script = str(locking_script) + _network = Network.get(network) + util = get_util() + with util.create_handle() as handle: + addr = util.call_func( + 'CfdGetAddressFromLockingScript', + handle.get_handle(), _script, _network.value) + return cls.parse(addr) + + ## + # @brief get multisig pubkey addresses. + # @param[in] redeem_script multisig script + # @param[in] hash_type hash type + # @param[in] network network + # @return address object list. + @classmethod + def get_multisig_address_list( + cls, + redeem_script, + hash_type, + network=Network.MAINNET): + _script = str(redeem_script) + _hash_type = HashType.get(hash_type) + _network = Network.get(network) + util = get_util() + addr_list = [] + with util.create_handle() as handle: + word_handle, max_index = util.call_func( + 'CfdGetAddressesFromMultisig', handle.get_handle(), + _script, _network.value, _hash_type.value) + with JobHandle( + handle, + word_handle, + 'CfdFreeAddressesMultisigHandle') as addr_handle: + for i in range(max_index): + addr, pubkey = util.call_func( + 'CfdGetAddressFromMultisigKey', + handle.get_handle(), addr_handle.get_handle(), i) + _addr = cls.parse(addr) + _addr.pubkey = pubkey + addr_list.append(_addr) + return addr_list + + +## +# All import target. +__all__ = ['Address', 'AddressUtil'] diff --git a/cfd/confidential_address.py b/cfd/confidential_address.py new file mode 100644 index 0000000..9b2e167 --- /dev/null +++ b/cfd/confidential_address.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +## +# @file confidential_address.py +# @brief elements confidential address function implements file. +# @note Copyright 2020 CryptoGarage +from .util import get_util, to_hex_string + + +## +# @class ConfidentialAddress +# @brief Elements confidential address class. +class ConfidentialAddress: + ## + # @var confidential_address + # confidential address string + ## + # @var address + # address + ## + # @var confidential_key + # confidential key + + ## + # @brief parse confidential address. + # @param[in] confidential_address confidential address + # @return ConfidentialAddress object + @classmethod + def parse(cls, confidential_address): + util = get_util() + with util.create_handle() as handle: + _addr, _key, _ = util.call_func( + 'CfdParseConfidentialAddress', handle.get_handle(), + confidential_address) + return ConfidentialAddress(_addr, _key) + + ## + # @brief constructor. + # @param[in] address address address + # @param[in] confidential_key confidential key + def __init__(self, address, confidential_key): + self.address = address + self.confidential_key = confidential_key + util = get_util() + with util.create_handle() as handle: + self.confidential_address = util.call_func( + 'CfdCreateConfidentialAddress', handle.get_handle(), + str(address), to_hex_string(confidential_key)) + + ## + # @brief get string. + # @return confidential address. + def __str__(self): + return self.confidential_address + + +## +# All import target. +__all__ = ['ConfidentialAddress'] diff --git a/cfd/confidential_transaction.py b/cfd/confidential_transaction.py new file mode 100644 index 0000000..8471f61 --- /dev/null +++ b/cfd/confidential_transaction.py @@ -0,0 +1,1498 @@ +# -*- coding: utf-8 -*- +## +# @file confidential_transaction.py +# @brief elements confidential transaction function implements file. +# @note Copyright 2020 CryptoGarage +from .util import ReverseByteData, CfdError, JobHandle,\ + CfdErrorCode, to_hex_string, get_util, ByteData +from .key import Network, SigHashType, Privkey +from .script import HashType +from .transaction import UtxoData, OutPoint, Txid, TxIn, TxOut, _FundTxOpt,\ + _TransactionBase +from enum import Enum +import copy +import ctypes + + +## +# @class BlindFactor +# @brief blind factor (blinder) class. +class BlindFactor(ReverseByteData): + ## + # @brief constructor. + # @param[in] data blind factor + def __init__(self, data): + super().__init__(data) + if len(self.hex) != 64: + raise CfdError( + error_code=1, message='Error: Invalid blind factor.') + + +## +# @class ConfidentialNonce +# @brief elements nonce class. +class ConfidentialNonce: + ## + # @var hex + # hex + + ## + # @brief constructor. + # @param[in] data confidential key or nonce commitment + def __init__(self, data=''): + self.hex = to_hex_string(data) + if len(self.hex) not in {0, 66}: + raise CfdError( + error_code=1, message='Error: Invalid nonce.') + + ## + # @brief get string. + # @return hex. + def __str__(self): + return self.hex + + +## +# @class ConfidentialAsset +# @brief elements asset class. +class ConfidentialAsset: + ## + # @var hex + # hex + + ## + # @brief constructor. + # @param[in] data asset or asset commitment + def __init__(self, data): + self.hex = to_hex_string(data) + if len(self.hex) == 64: + self.hex = str(ReverseByteData(data)) + if len(self.hex) not in {0, 64, 66}: + raise CfdError( + error_code=1, message='Error: Invalid asset.') + + ## + # @brief get string. + # @return hex. + def __str__(self): + return self.hex + + ## + # @brief get blind state. + # @retval True blinded. + # @retval False unblind. + def has_blind(self): + if (len(self.hex) == 66) and (self.hex[0] == '0') and ( + self.hex[1].lower() in {'a', 'b'}): + return True + return False + + ## + # @brief get commitment. (can use unblind only) + # @param[in] asset_blind_factor asset blind factor + # @return asset commitment + def get_commitment(self, asset_blind_factor): + if self.has_blind(): + raise CfdError( + error_code=1, message='Error: Blind asset.') + util = get_util() + with util.create_handle() as handle: + commitment = util.call_func( + 'CfdGetAssetCommitment', handle.get_handle(), + self.hex, to_hex_string(asset_blind_factor)) + return ConfidentialAsset(commitment) + + +## +# @class ConfidentialValue +# @brief elements value class. +class ConfidentialValue: + ## + # @var hex + # hex + ## + # @var amount + # amount + + ## + # @brief create instance. + # @param[in] value value + # @param[in] amount amount + # @return ConfidentialValue + @classmethod + def create(cls, value, amount): + _value_hex = to_hex_string(value) + if isinstance(value, ConfidentialValue): + return value + elif len(_value_hex) != 0: + return ConfidentialValue(_value_hex) + else: + return ConfidentialValue(amount) + + ## + # @brief get hex string from amount. + # @param[in] amount amount + # @return hex string + def _byte_from_amount(cls, amount): + util = get_util() + with util.create_handle() as handle: + value_hex = util.call_func( + 'CfdGetConfidentialValueHex', handle.get_handle(), + amount, False) + return value_hex + + ## + # @brief constructor. + # @param[in] data value or value commitment or amount + def __init__(self, data): + if isinstance(data, int): + self.amount = data + self.hex = self._byte_from_amount(self.amount) + elif isinstance(data, float) or isinstance(data, complex): + raise CfdError( + error_code=1, message='Error: Invalid amount format.') + else: + self.hex = to_hex_string(data) + self.amount = 0 + if len(self.hex) not in {0, 18, 66}: + raise CfdError( + error_code=1, message='Error: Invalid value.') + + ## + # @brief get string. + # @return hex or amount. + def __str__(self): + return str(self.amount) if self.amount != 0 else self.hex + + ## + # @brief get blind state. + # @retval True blinded. + # @retval False unblind. + def has_blind(self): + return (len(self.hex) == 66) + + ## + # @brief get commitment. (can use unblind only) + # @param[in] asset_commitment asset commitment + # @param[in] blind_factor amount blind factor + # @return amount commitment + def get_commitment(self, asset_commitment, blind_factor): + if self.has_blind(): + raise CfdError( + error_code=1, message='Error: Blind value.') + if isinstance(asset_commitment, ConfidentialAsset) and ( + asset_commitment.has_blind() is False): + raise CfdError( + error_code=1, message='Error: Unblind asset.') + util = get_util() + with util.create_handle() as handle: + commitment = util.call_func( + 'CfdGetValueCommitment', handle.get_handle(), + self.amount, to_hex_string(asset_commitment), + to_hex_string(blind_factor)) + return ConfidentialValue(commitment) + + +## +# @class ElementsUtxoData +# @brief elements utxo class. +class ElementsUtxoData(UtxoData): + ## + # @var outpoint + # outpoint (for UtxoData class) + ## + # @var amount + # amount (for UtxoData class) + ## + # @var value + # value + ## + # @var asset + # asset + ## + # @var is_issuance + # is issuance + ## + # @var is_blind_issuance + # is blinded issuance + ## + # @var is_pegin + # is pegin + ## + # @var pegin_btc_tx_size + # pegin btc transaction size + ## + # @var fedpeg_script + # fedpeg script + ## + # @var asset_blinder + # asset blind factor + ## + # @var amount_blinder + # amount blind factor + + ## + # @brief constructor. + # @param[in] outpoint outpoint + # @param[in] txid txid + # @param[in] vout vout + # @param[in] amount amount + # @param[in] descriptor descriptor + # @param[in] scriptsig_template scriptsig template + # @param[in] value value + # @param[in] asset asset + # @param[in] is_issuance issuance flag + # @param[in] is_blind_issuance blinded issuance flag + # @param[in] is_pegin pegin flag + # @param[in] pegin_btc_tx_size pegin btc tx size + # @param[in] fedpeg_script fedpeg script + # @param[in] asset_blinder asset blind factor + # @param[in] amount_blinder amount blind factor + def __init__( + self, outpoint=None, txid='', vout=0, + amount=0, descriptor='', scriptsig_template='', + value='', asset='', is_issuance=False, is_blind_issuance=False, + is_pegin=False, pegin_btc_tx_size=0, fedpeg_script='', + asset_blinder='', amount_blinder=''): + super().__init__( + outpoint=outpoint, txid=txid, vout=vout, + amount=amount, descriptor=descriptor, + scriptsig_template=scriptsig_template) + self.value = ConfidentialValue.create(value, amount) + self.asset = asset + self.is_issuance = is_issuance + self.is_blind_issuance = is_blind_issuance + self.is_pegin = is_pegin + self.pegin_btc_tx_size = pegin_btc_tx_size + self.fedpeg_script = fedpeg_script + self.asset_blinder = asset_blinder + self.amount_blinder = amount_blinder + if self.amount == 0: + self.amount = self.value.amount + + ## + # @brief equal method. + # @param[in] other other object. + # @return true or false. + def __eq__(self, other): + if not isinstance(other, ElementsUtxoData): + return NotImplemented + return self.outpoint == other.outpoint + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __lt__(self, other): + if not isinstance(other, ElementsUtxoData): + return NotImplemented + return (self.outpoint) < (other.outpoint) + + ## + # @brief equal method. + # @param[in] other other object. + # @return true or false. + def __ne__(self, other): + return not self.__eq__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __le__(self, other): + return self.__lt__(other) or self.__eq__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __gt__(self, other): + return not self.__le__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __ge__(self, other): + return not self.__lt__(other) + + +## +# @class UnblindData +# @brief unblind data class. +class UnblindData: + ## + # @var asset + # asset + ## + # @var value + # value + ## + # @var asset_blinder + # asset blind factor + ## + # @var amount_blinder + # amount blind factor + + ## + # @brief constructor. + # @param[in] asset asset + # @param[in] amount amount + # @param[in] asset_blinder asset blind factor + # @param[in] amount_blinder amount blind factor + def __init__(self, asset, amount, asset_blinder, amount_blinder): + self.asset = asset + self.value = ConfidentialValue(amount) + self.asset_blinder = BlindFactor(asset_blinder) + self.amount_blinder = BlindFactor(amount_blinder) + + ## + # @brief get string. + # @return hex + def __str__(self): + return '{},{}'.format(self.asset, self.value) + + +## +# @class Issuance +# @brief Issuance data class. +class Issuance: + ## + # @var entropy + # entropy + ## + # @var nonce + # nonce + ## + # @var asset_value + # asset value + ## + # @var token_value + # token value + + ## + # @brief constructor. + def __init__(self, entropy='', nonce='', asset_value=0, token_value=0): + self.entropy = entropy + self.nonce = nonce + self.asset_value = ConfidentialValue(asset_value) + self.token_value = ConfidentialValue(token_value) + + ## + # @brief get string. + # @return hex + def __str__(self): + return '{},{},{}'.format( + self.entropy, self.asset_value, self.token_value) + + +## +# @class IssuanceKeyPair +# @brief Issuance blinding key pair class. +class IssuanceKeyPair: + ## + # @var asset_key + # asset blinding key + ## + # @var token_key + # token blinding key + + ## + # @brief constructor. + # @param[in] asset_key asset blinding key + # @param[in] token_key token blinding key + def __init__(self, asset_key='', token_key=''): + self.asset_key = asset_key + self.token_key = token_key + + ## + # @brief get string. + # @return hex + def __str__(self): + return 'IssuanceKeyPair' + + +## +# @class ConfidentialTxIn +# @brief elements transaction input class. +class ConfidentialTxIn(TxIn): + ## + # @var pegin_witness_stack + # pegin witness stack + ## + # @var issuance + # issuance + + ## + # @brief constructor. + # @param[in] outpoint outpoint + # @param[in] txid txid + # @param[in] vout vout + # @param[in] sequence sequence + def __init__(self, outpoint=None, txid='', vout=0, + sequence=TxIn.SEQUENCE_DISABLE): + super().__init__(outpoint, txid, vout, sequence) + self.pegin_witness_stack = [] + self.issuance = Issuance() + + +## +# @class ConfidentialTxOut +# @brief elements transaction output class. +class ConfidentialTxOut(TxOut): + ## + # @var value + # value + ## + # @var asset + # asset + ## + # @var nonce + # nonce + ## + # @var surjectionproof + # surjection proof + ## + # @var rangeproof + # range proof + + ## + # @brief get destroy amount txout. + # @param[in] amount amount + # @param[in] asset asset + # @param[in] nonce nonce + # @return ConfidentialTxOut + @classmethod + def for_destroy_amount(cls, amount, asset, nonce=''): + return ConfidentialTxOut(amount, asset=asset, nonce=nonce, + locking_script='6a') + + ## + # @brief get fee txout. + # @param[in] amount amount + # @param[in] asset asset + # @return ConfidentialTxOut + @classmethod + def for_fee(cls, amount, asset): + return ConfidentialTxOut(amount, asset=asset) + + ## + # @brief constructor. + # @param[in] amount amount + # @param[in] address address + # @param[in] locking_script locking script + # @param[in] value value + # @param[in] asset asset + # @param[in] nonce nonce + def __init__( + self, amount=0, address='', locking_script='', + value='', asset='', nonce=''): + super().__init__( + amount=amount, address=address, locking_script=locking_script) + self.value = ConfidentialValue.create(value, amount) + self.asset = ConfidentialAsset(asset) + self.nonce = ConfidentialNonce(nonce) + self.surjectionproof = [] + self.rangeproof = [] + + +## +# @class TargetAmountData +# @brief target amount data for fund transaction. +class TargetAmountData: + ## + # @var amount + # amount + ## + # @var asset + # asset + ## + # @var reserved_address + # reserved address + + ## + # @brief constructor. + # @param[in] amount amount + # @param[in] asset asset + # @param[in] reserved_address reserved address + def __init__(self, amount, asset, reserved_address=''): + self.amount = amount + self.asset = asset + self.reserved_address = reserved_address + + +## +# @class ConfidentialTransaction +# @brief elements transaction. +class ConfidentialTransaction(_TransactionBase): + ## + # @var hex + # transaction hex string + ## + # @var txin_list + # transaction input list + ## + # @var txout_list + # transaction output list + ## + # @var txid + # txid + ## + # @var wtxid + # wtxid + ## + # @var wit_hash + # wit_hash + ## + # @var size + # transaction size + ## + # @var vsize + # transaction vsize + ## + # @var weight + # transaction size weight + ## + # @var version + # version + ## + # @var locktime + # locktime + + ## + # bitcoin network value. + NETWORK = Network.LIQUID_V1.value + ## + # blind minimumBits on default. + DEFAULT_BLIND_MINIMUM_BITS = 52 + ## + # transaction's free function name. + FREE_FUNC_NAME = 'CfdFreeTransactionHandle' + + ## + # @brief parse transaction to json. + # @param[in] hex transaction hex + # @param[in] network network + # @param[in] full_dump full_dump flag + # @return json string + @classmethod + def parse_to_json(cls, hex, network=Network.LIQUID_V1, + full_dump=False): + _network = Network.get(network) + mainchain_str = 'mainnet' + network_str = 'liquidv1' + if _network != Network.LIQUID_V1: + mainchain_str = 'regtest' + network_str = 'regtest' + full_dump_str = 'true' if full_dump else 'false' + cmd = '{{"hex":"{}","network":"{}","{}":"{}","fullDump":{}}}' + request_json = cmd.format( + hex, network_str, 'mainchainNetwork', mainchain_str, + full_dump_str) + util = get_util() + with util.create_handle() as handle: + return util.call_func( + 'CfdRequestExecuteJson', handle.get_handle(), + 'ElementsDecodeRawTransaction', request_json) + + ## + # @brief get blinding key for elemens default. + # @param[in] master_blinding_key master blinding key + # @param[in] locking_script locking script + # @return blinding key + @classmethod + def get_default_blinding_key(cls, master_blinding_key, locking_script): + _key = to_hex_string(master_blinding_key) + _script = to_hex_string(locking_script) + util = get_util() + with util.create_handle() as handle: + return util.call_func( + 'CfdGetDefaultBlindingKey', handle.get_handle(), + _key, _script) + + ## + # @brief get issuance blinding key for elemens default. + # @param[in] master_blinding_key master blinding key + # @param[in] txid txid + # @param[in] vout vout + # @return blinding key + @classmethod + def get_issuance_blinding_key(cls, master_blinding_key, + txid, vout): + _key = to_hex_string(master_blinding_key) + _txid = to_hex_string(txid) + util = get_util() + with util.create_handle() as handle: + return util.call_func( + 'CfdGetIssuanceBlindingKey', handle.get_handle(), + _key, _txid, vout) + + ## + # @brief create transaction. + # @param[in] version version + # @param[in] locktime locktime + # @param[in] txins txin list + # @param[in] txouts txout list + # @param[in] enable_cache enable tx cache + # @return transaction object + @classmethod + def create(cls, version, locktime, txins=[], txouts=[], enable_cache=True): + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTransaction', handle.get_handle(), + cls.NETWORK, version, locktime, '') + with JobHandle( + handle, _tx_handle, cls.FREE_FUNC_NAME) as tx_handle: + for txin in txins: + sec = TxIn.get_sequence_number(locktime, txin.sequence) + util.call_func( + 'CfdAddTransactionInput', handle.get_handle(), + tx_handle.get_handle(), str(txin.outpoint.txid), + txin.outpoint.vout, sec) + for txout in txouts: + util.call_func( + 'CfdAddConfidentialTxOutput', handle.get_handle(), + tx_handle.get_handle(), txout.amount, + str(txout.address), + str(txout.locking_script), + str(txout.asset), str(txout.nonce)) + hex = util.call_func( + 'CfdFinalizeTransaction', handle.get_handle(), + tx_handle.get_handle()) + return ConfidentialTransaction(hex, enable_cache) + + ## + # @brief get transaction from hex. + # @param[in] hex tx hex + # @param[in] enable_cache enable tx cache + # @return transaction object + @classmethod + def from_hex(cls, hex, enable_cache=True): + return ConfidentialTransaction(hex, enable_cache) + + ## + # @brief constructor. + # @param[in] hex tx hex + # @param[in] enable_cache enable tx cache + def __init__(self, hex, enable_cache=True): + super().__init__(hex, self.NETWORK, enable_cache) + self.txin_list = [] + self.txout_list = [] + self._update_tx_all() + + ## + # @brief get transaction input. + # @param[in] handle cfd handle + # @param[in] tx_handle tx handle + # @param[in] index index + # @param[in] outpoint outpoint + # @retval [0] txin + # @retval [1] index + def _get_txin(self, handle, tx_handle, index=0, outpoint=None): + util = get_util() + + if isinstance(outpoint, OutPoint): + index = util.call_func( + 'CfdGetTxInIndexByHandle', handle.get_handle(), + tx_handle.get_handle(), str(outpoint.txid), + outpoint.vout) + + txid, vout, seq, script = util.call_func( + 'CfdGetTxInByHandle', handle.get_handle(), + tx_handle.get_handle(), index) + txin = ConfidentialTxIn(txid=txid, vout=vout, sequence=seq) + txin.script_sig = script + + txin.witness_stack = [] + _count = util.call_func( + 'CfdGetTxInWitnessCountByHandle', handle.get_handle(), + tx_handle.get_handle(), 0, index) + for i in range(_count): + data = util.call_func( + 'CfdGetTxInWitnessByHandle', handle.get_handle(), + tx_handle.get_handle(), 0, index, i) + txin.witness_stack.append(data) + + entropy, nonce, asset_amount, asset_value, token_amount,\ + toke_value, _, _ = util.call_func( + 'CfdGetTxInIssuanceInfoByHandle', + handle.get_handle(), tx_handle.get_handle(), index) + txin.issuance.entropy = entropy + txin.issuance.nonce = nonce + txin.issuance.asset_value = ConfidentialValue.create( + asset_value, asset_amount) + txin.issuance.token_value = ConfidentialValue.create( + toke_value, token_amount) + + txin.pegin_witness_stack = [] + _count = util.call_func( + 'CfdGetTxInWitnessCountByHandle', handle.get_handle(), + tx_handle.get_handle(), 1, index) + for i in range(_count): + data = util.call_func( + 'CfdGetTxInWitnessByHandle', handle.get_handle(), + tx_handle.get_handle(), 1, index, i) + txin.pegin_witness_stack.append(data) + return txin, index + + ## + # @brief update transaction information. + # @return void + def _update_info(self): + if self.enable_cache is False: + return + util = get_util() + with util.create_handle() as handle: + ret = util.call_func( + 'CfdGetConfidentialTxInfo', handle.get_handle(), self.hex) + # for doxygen + self.txid = Txid(ret[0]) + self.wtxid = Txid(ret[1]) + self.wit_hash = ret[2] + self.size = ret[3] + self.vsize = ret[4] + self.weight = ret[5] + self.version = ret[6] + self.locktime = ret[7] + + ## + # @brief update transaction input. + # @param[in] outpoint outpoint + # @return void + def _update_txin(self, outpoint): + if self.enable_cache is False: + return + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTxDataHandle', handle.get_handle(), + self.NETWORK, self.hex) + with JobHandle(handle, _tx_handle, + self.FREE_FUNC_NAME) as tx_handle: + self.txid, self.wtxid, self.wit_hash, self.size, self.vsize,\ + self.weight, self.version, self.locktime = util.call_func( + 'CfdGetConfidentialTxInfoByHandle', + handle.get_handle(), tx_handle.get_handle()) + self.txid = Txid(self.txid) + self.wtxid = Txid(self.wtxid) + # update txin + txin, index = self._get_txin( + handle, tx_handle, outpoint=outpoint) + self.txin_list[index] = txin + + ## + # @brief get transaction all data. + # @retval [0] txin list + # @retval [1] txout list + def get_tx_all(self): + def get_txin_list(handle, tx_handle): + txin_list = [] + _count = util.call_func( + 'CfdGetTxInCountByHandle', handle.get_handle(), + tx_handle.get_handle()) + for i in range(_count): + txin, _ = self._get_txin(handle, tx_handle, i) + txin_list.append(txin) + return txin_list + + def get_txout_list(handle, tx_handle): + txout_list = [] + _count = util.call_func( + 'CfdGetTxOutCountByHandle', handle.get_handle(), + tx_handle.get_handle()) + for i in range(_count): + # CfdGetConfidentialTxOutByHandle + asset, amount, value_commitment, nonce,\ + script = util.call_func( + 'CfdGetConfidentialTxOutSimpleByHandle', + handle.get_handle(), tx_handle.get_handle(), i) + txout = ConfidentialTxOut( + amount=amount, locking_script=script, + asset=asset, value=value_commitment, nonce=nonce) + txout_list.append(txout) + return txout_list + + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTxDataHandle', handle.get_handle(), + self.NETWORK, self.hex) + with JobHandle( + handle, _tx_handle, + self.FREE_FUNC_NAME) as tx_handle: + self.txid, self.wtxid, self.wit_hash, self.size, self.vsize,\ + self.weight, self.version, self.locktime = util.call_func( + 'CfdGetConfidentialTxInfoByHandle', + handle.get_handle(), tx_handle.get_handle()) + self.txid = Txid(self.txid) + self.wtxid = Txid(self.wtxid) + self.txin_list = get_txin_list(handle, tx_handle) + self.txout_list = get_txout_list(handle, tx_handle) + return self.txin_list, self.txout_list + + ## + # @brief add transaction input. + # @param[in] outpoint outpoint + # @param[in] sequence sequence + # @param[in] txid txid + # @param[in] vout vout + # @return void + def add_txin(self, outpoint=None, sequence=-1, + txid='', vout=0): + sec = TxIn.get_sequence_number(self.locktime, sequence) + txin = ConfidentialTxIn( + outpoint=outpoint, sequence=sec, txid=txid, vout=vout) + self.add([txin], []) + + ## + # @brief add transaction output. + # @param[in] amount amount + # @param[in] address address + # @param[in] locking_script locking script + # @param[in] value value + # @param[in] asset asset + # @param[in] nonce nonce + # @return void + def add_txout( + self, amount=0, address='', locking_script='', + value='', asset='', nonce=''): + txout = ConfidentialTxOut( + amount, address, locking_script, value, asset, nonce) + self.add([], [txout]) + + ## + # @brief add transaction fee output. + # @param[in] amount amount + # @param[in] asset asset + # @return void + def add_fee_txout(self, amount, asset): + self.add_txout(amount, asset=asset) + + ## + # @brief add transaction destroy amount output. + # @param[in] amount amount + # @param[in] asset asset + # @param[in] nonce nonce + # @return void + def add_destroy_amount_txout(self, amount, asset, nonce=''): + self.add_txout(amount, locking_script='6a', asset=asset, nonce=nonce) + + ## + # @brief add transaction. + # @param[in] txins txin list + # @param[in] txouts txout list + # @return void + def add(self, txins, txouts): + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTransaction', handle.get_handle(), + self.NETWORK, 0, 0, self.hex) + with JobHandle( + handle, _tx_handle, self.FREE_FUNC_NAME) as tx_handle: + for txin in txins: + sec = TxIn.get_sequence_number( + self.locktime, txin.sequence) + util.call_func( + 'CfdAddTransactionInput', handle.get_handle(), + tx_handle.get_handle(), str(txin.outpoint.txid), + txin.outpoint.vout, sec) + for txout in txouts: + util.call_func( + 'CfdAddConfidentialTxOutput', + handle.get_handle(), + tx_handle.get_handle(), txout.amount, + str(txout.address), + str(txout.locking_script), + str(txout.asset), str(txout.nonce)) + self.hex = util.call_func( + 'CfdFinalizeTransaction', handle.get_handle(), + tx_handle.get_handle()) + self.txid, self.wtxid, self.wit_hash, self.size, self.vsize,\ + self.weight, self.version, self.locktime = util.call_func( + 'CfdGetConfidentialTxInfoByHandle', + handle.get_handle(), tx_handle.get_handle()) + self.txid = Txid(self.txid) + self.wtxid = Txid(self.wtxid) + self.txin_list += copy.deepcopy(txins) + self.txout_list += copy.deepcopy(txouts) + + ## + # @brief update transaction output amount. + # @param[in] index index + # @param[in] amount amount + # @return void + def update_txout_amount(self, index, amount): + util = get_util() + with util.create_handle() as handle: + self.hex = util.call_func( + 'CfdUpdateTxOutAmount', handle.get_handle(), + self.NETWORK, self.hex, index, amount) + self._update_info() + self.txout_list[index].amount = amount + + ## + # @brief update transaction output fee amount. + # @param[in] amount amount + # @return void + def update_txout_fee_amount(self, amount): + index = self.get_txout_index() + self.update_txout_amount(index, amount) + + ## + # @brief blind transaction output. + # @param[in] utxo_list utxo list + # @param[in] confidential_address_list confidential address list + # @param[in] direct_confidential_key_map direct confidential key map + # @param[in] minimum_range_value minimum range value + # @param[in] exponent exponent + # @param[in] minimum_bits minimum bits + # @return void + def blind_txout(self, utxo_list, confidential_address_list=[], + direct_confidential_key_map={}, + minimum_range_value=1, exponent=0, minimum_bits=-1): + self.blind(utxo_list=utxo_list, + confidential_address_list=confidential_address_list, + direct_confidential_key_map=direct_confidential_key_map, + minimum_range_value=minimum_range_value, + exponent=exponent, minimum_bits=minimum_bits) + + ## + # @brief blind transaction output. + # @param[in] utxo_list utxo list + # @param[in] issuance_key_map issuance key map + # @param[in] confidential_address_list confidential address list + # @param[in] direct_confidential_key_map direct confidential key map + # @param[in] minimum_range_value minimum range value + # @param[in] exponent exponent + # @param[in] minimum_bits minimum bits + # @return void + def blind(self, utxo_list, + issuance_key_map={}, + confidential_address_list=[], + direct_confidential_key_map={}, + minimum_range_value=1, exponent=0, minimum_bits=-1): + if minimum_bits == -1: + minimum_bits = self.DEFAULT_BLIND_MINIMUM_BITS + + def set_opt(handle, tx_handle, key, i_val=0): + util.call_func( + 'CfdSetBlindTxOption', handle.get_handle(), + tx_handle.get_handle(), key.value, i_val) + + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeBlindTx', handle.get_handle()) + with JobHandle( + handle, _tx_handle, 'CfdFreeBlindHandle') as tx_handle: + issuance_count = 0 + for txin in utxo_list: + asset_key, token_key = '', '' + if str(txin.outpoint) in issuance_key_map: + item = issuance_key_map[str(txin.outpoint)] + asset_key, token_key = item.asset_key, item.token_key + issuance_count += 1 + util.call_func( + 'CfdAddBlindTxInData', handle.get_handle(), + tx_handle.get_handle(), + to_hex_string(txin.outpoint.txid), + txin.outpoint.vout, to_hex_string(txin.asset), + to_hex_string(txin.asset_blinder), + to_hex_string(txin.amount_blinder), + txin.amount, asset_key, token_key) + if issuance_count != len(issuance_key_map): + raise CfdError( + error_code=1, + message='Error: Issuance Txid is not found.') + for addr in confidential_address_list: + util.call_func( + 'CfdAddBlindTxOutByAddress', handle.get_handle(), + tx_handle.get_handle(), str(addr)) + for key_index in direct_confidential_key_map.keys(): + key = direct_confidential_key_map[key_index] + util.call_func( + 'CfdAddBlindTxOutData', handle.get_handle(), + tx_handle.get_handle(), int(key_index), + to_hex_string(key)) + set_opt(handle, tx_handle, + _BlindOpt.MINIMUM_RANGE_VALUE, minimum_range_value) + set_opt(handle, tx_handle, _BlindOpt.EXPONENT, exponent) + set_opt(handle, tx_handle, + _BlindOpt.MINIMUM_BITS, minimum_bits) + self.hex = util.call_func( + 'CfdFinalizeBlindTx', handle.get_handle(), + tx_handle.get_handle(), self.hex) + self._update_tx_all() + + ## + # @brief unblind transaction output. + # @param[in] index txout index + # @param[in] blinding_key blinding key + # @return UnblindData + def unblind_txout(self, index, blinding_key): + util = get_util() + with util.create_handle() as handle: + asset, asset_amount, asset_blinder,\ + amount_blinder = util.call_func( + 'CfdUnblindTxOut', handle.get_handle(), + self.hex, index, to_hex_string(blinding_key)) + return UnblindData( + asset, asset_amount, asset_blinder, amount_blinder) + + ## + # @brief unblind transaction issuance. + # @param[in] index txout index + # @param[in] asset_key asset blinding key + # @param[in] token_key token blinding key + # @retval [0] asset unblind data + # @retval [1] token unblind data + def unblind_issuance(self, index, asset_key, token_key=''): + util = get_util() + with util.create_handle() as handle: + asset, asset_amount, asset_blinder, amount_blinder, token,\ + token_amount, token_blinder,\ + token_amount_blinder = util.call_func( + 'CfdUnblindIssuance', handle.get_handle(), + self.hex, index, to_hex_string(asset_key), + to_hex_string(token_key)) + asset_data = UnblindData( + asset, asset_amount, asset_blinder, amount_blinder) + token_data = UnblindData( + token, token_amount, token_blinder, token_amount_blinder) + return asset_data, token_data + + ## + # @brief set reissue asset. + # @param[in] utxo utxo data + # @param[in] amount amount + # @param[in] address address + # @param[in] entropy entropy + # @return reissue asset + def set_raw_reissue_asset(self, utxo, amount, address, entropy): + _amount = amount + if isinstance(amount, ConfidentialValue): + _amount = amount.amount + util = get_util() + with util.create_handle() as handle: + _asset, self.hex = util.call_func( + 'CfdSetRawReissueAsset', handle.get_handle(), + self.hex, to_hex_string(utxo.outpoint.txid), + utxo.outpoint.vout, _amount, + to_hex_string(utxo.asset_blinder), + to_hex_string(entropy), str(address), '') + return ConfidentialAsset(_asset) + + ## + # @brief get signature hash. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] value value + # @param[in] pubkey pubkey + # @param[in] redeem_script redeem script + # @param[in] sighashtype sighash type + # @return sighash + def get_sighash(self, outpoint, hash_type, value, pubkey='', + redeem_script='', sighashtype=SigHashType.ALL): + _hash_type = HashType.get(hash_type) + _pubkey = to_hex_string(pubkey) + _script = to_hex_string(redeem_script) + _sighashtype = SigHashType.get(sighashtype) + _value = value + if isinstance(value, ConfidentialValue) is False: + _value = ConfidentialValue(value) + util = get_util() + with util.create_handle() as handle: + sighash = util.call_func( + 'CfdCreateConfidentialSighash', handle.get_handle(), + self.hex, str(outpoint.txid), outpoint.vout, + _hash_type.value, _pubkey, _script, + _value.amount, _value.hex, _sighashtype.get_type(), + _sighashtype.anyone_can_pay()) + return ByteData(sighash) + + ## + # @brief add sign with private key. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] privkey privkey + # @param[in] value value + # @param[in] sighashtype sighash type + # @param[in] grind_r grind-R flag + # @return void + def sign_with_privkey( + self, outpoint, hash_type, privkey, value, + sighashtype=SigHashType.ALL, grind_r=True): + _hash_type = HashType.get(hash_type) + if isinstance(privkey, Privkey): + _privkey = privkey + elif isinstance(privkey, str) and (len(privkey) != 64): + _privkey = Privkey(wif=privkey) + else: + _privkey = Privkey(hex=privkey) + _pubkey = _privkey.pubkey + _sighashtype = SigHashType.get(sighashtype) + _value = value + if isinstance(value, ConfidentialValue) is False: + _value = ConfidentialValue(value) + util = get_util() + with util.create_handle() as handle: + self.hex = util.call_func( + 'CfdAddConfidentialTxSignWithPrivkeySimple', + handle.get_handle(), self.hex, str(outpoint.txid), + outpoint.vout, _hash_type.value, str(_pubkey), + str(_privkey), _value.amount, _value.hex, + _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), grind_r) + self._update_txin(outpoint) + + ## + # @brief verify sign. + # @param[in] outpoint outpoint + # @param[in] address address + # @param[in] hash_type hash type + # @param[in] value value + # @return void + def verify_sign(self, outpoint, address, hash_type, value): + _hash_type = HashType.get(hash_type) + _value = value + if isinstance(value, ConfidentialValue) is False: + _value = ConfidentialValue(value) + util = get_util() + with util.create_handle() as handle: + util.call_func( + 'CfdVerifyTxSign', handle.get_handle(), + self.NETWORK, self.hex, str(outpoint.txid), + outpoint.vout, str(address), _hash_type.value, + '', _value.amount, _value.hex) + + ## + # @brief verify signature. + # @param[in] outpoint outpoint + # @param[in] signature signature + # @param[in] hash_type hash type + # @param[in] pubkey pubkey + # @param[in] value value + # @param[in] redeem_script redeem script + # @param[in] sighashtype sighash type + # @retval True signature valid. + # @retval False signature invalid. + def verify_signature( + self, outpoint, signature, hash_type, pubkey, value, + redeem_script='', sighashtype=SigHashType.ALL): + _signature = to_hex_string(signature) + _pubkey = to_hex_string(pubkey) + _script = to_hex_string(redeem_script) + _hash_type = HashType.get(hash_type) + _sighashtype = SigHashType.get(sighashtype) + _value = value + if isinstance(value, ConfidentialValue) is False: + _value = ConfidentialValue(value) + try: + util = get_util() + with util.create_handle() as handle: + util.call_func( + 'CfdVerifySignature', handle.get_handle(), + self.NETWORK, self.hex, _signature, _hash_type.value, + _pubkey, _script, str(outpoint.txid), + outpoint.vout, _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), _value.amount, _value.hex) + return True + except CfdError as err: + if err.error_code == CfdErrorCode.SIGN_VERIFICATION.value: + return False + else: + raise err + + ## + # @brief select coins. + # @param[in] utxo_list utxo list + # @param[in] tx_fee_amount txout fee amount + # @param[in] target_list collect target list + # @param[in] fee_asset fee asset + # @param[in] effective_fee_rate effective fee rate + # @param[in] long_term_fee_rate long term fee rate + # @param[in] dust_fee_rate dust fee rate + # @param[in] knapsack_min_change minimum change threshold for knapsack + # @param[in] exponent exponent + # @param[in] minimum_bits minimum bits + # @retval [0] select utxo list. + # @retval [1] utxo fee. + # @retval [2] total tx fee. + @classmethod + def select_coins( + cls, utxo_list, tx_fee_amount, target_list, fee_asset, + effective_fee_rate=0.11, long_term_fee_rate=0.11, + dust_fee_rate=3.0, knapsack_min_change=-1, + exponent=0, minimum_bits=52): + if (isinstance(utxo_list, list) is False) or ( + len(utxo_list) == 0): + raise CfdError(error_code=1, message='Error: Invalid utxo_list.') + util = get_util() + + def set_opt(handle, tx_handle, key, i_val=0, f_val=0, b_val=False): + util.call_func( + 'CfdSetOptionCoinSelection', handle.get_handle(), + tx_handle.get_handle(), key.value, + int(i_val), float(f_val), b_val) + + with util.create_handle() as handle: + work_handle = util.call_func( + 'CfdInitializeCoinSelection', handle.get_handle(), + len(utxo_list), len(target_list), str(fee_asset), + int(tx_fee_amount), float(effective_fee_rate), + float(long_term_fee_rate), float(dust_fee_rate), + int(knapsack_min_change)) + with JobHandle(handle, work_handle, + 'CfdFreeCoinSelectionHandle') as tx_handle: + for index, utxo in enumerate(utxo_list): + util.call_func( + 'CfdAddCoinSelectionUtxoTemplate', + handle.get_handle(), tx_handle.get_handle(), index, + str(utxo.outpoint.txid), utxo.outpoint.vout, + utxo.amount, + str(utxo.asset), + str(utxo.descriptor), + to_hex_string(utxo.scriptsig_template)) + + total_collect_amount = 0 + for index, target in enumerate(target_list): + util.call_func( + 'CfdAddCoinSelectionAmount', + handle.get_handle(), tx_handle.get_handle(), index, + target.amount, str(target.asset)) + total_collect_amount += target.amount + + set_opt(handle, tx_handle, _CoinSelectionOpt.EXPONENT, + i_val=exponent) + set_opt(handle, tx_handle, _CoinSelectionOpt.MINIMUM_BITS, + i_val=minimum_bits) + + _utxo_fee = util.call_func( + 'CfdFinalizeCoinSelection', + handle.get_handle(), tx_handle.get_handle()) + + selected_utxo_list = [] + total_amount_map = {} + if (total_collect_amount > 0) or (_utxo_fee > 0): + for i in range(len(utxo_list)): + _utxo_index = util.call_func( + 'CfdGetSelectedCoinIndex', + handle.get_handle(), tx_handle.get_handle(), i) + if _utxo_index < 0: + break + elif _utxo_index < len(utxo_list): + selected_utxo_list.append(utxo_list[_utxo_index]) + + for index, target in enumerate(target_list): + total_amount = util.call_func( + 'CfdGetSelectedCoinAssetAmount', + handle.get_handle(), tx_handle.get_handle(), index) + total_amount_map[target.asset] = total_amount + return selected_utxo_list, _utxo_fee, total_amount_map + + ## + # @brief estimate fee. + # @param[in] utxo_list txin utxo list + # @param[in] fee_asset fee asset + # @param[in] fee_rate fee rate + # @param[in] is_blind blind flag + # @param[in] exponent exponent + # @param[in] minimum_bits minimum bits + # @retval [0] total tx fee. (txout fee + utxo fee) + # @retval [1] txout fee. + # @retval [2] utxo fee. + def estimate_fee(self, utxo_list, fee_asset, fee_rate=0.11, + is_blind=True, exponent=0, minimum_bits=52): + _fee_asset = ConfidentialAsset(fee_asset) + if (isinstance(utxo_list, list) is False) or ( + len(utxo_list) == 0): + raise CfdError( + error_code=1, message='Error: Invalid utxo_list.') + util = get_util() + + def set_opt(handle, tx_handle, key, i_val=0, f_val=0, b_val=False): + util.call_func( + 'CfdSetOptionEstimateFee', handle.get_handle(), + tx_handle.get_handle(), key.value, + int(i_val), float(f_val), b_val) + + with util.create_handle() as handle: + work_handle = ctypes.c_void_p() + util.call_func( + 'CfdInitializeEstimateFee', handle.get_handle(), + ctypes.byref(work_handle), True) + with JobHandle(handle, work_handle.value, + 'CfdFreeEstimateFeeHandle') as tx_handle: + for utxo in utxo_list: + util.call_func( + 'CfdAddTxInTemplateForEstimateFee', + handle.get_handle(), tx_handle.get_handle(), + str(utxo.outpoint.txid), utxo.outpoint.vout, + str(utxo.descriptor), str(utxo.asset), + utxo.is_issuance, utxo.is_blind_issuance, + utxo.is_pegin, utxo.pegin_btc_tx_size, + to_hex_string(utxo.fedpeg_script), + to_hex_string(utxo.scriptsig_template)) + + set_opt(handle, tx_handle, _FeeOpt.EXPONENT, i_val=exponent) + set_opt(handle, tx_handle, _FeeOpt.MINIMUM_BITS, + i_val=minimum_bits) + + _txout_fee = ctypes.c_int64() + _utxo_fee = ctypes.c_int64() + util.call_func( + 'CfdFinalizeEstimateFee', + handle.get_handle(), tx_handle.get_handle(), + self.hex, str(_fee_asset), ctypes.byref(_txout_fee), + ctypes.byref(_utxo_fee), is_blind, fee_rate) + txout_fee, utxo_fee = _txout_fee.value, _utxo_fee.value + return (txout_fee + utxo_fee), txout_fee, utxo_fee + + ## + # @brief fund transaction. + # @param[in] txin_utxo_list txin list + # @param[in] utxo_list utxo list + # @param[in] target_list collect target list + # @param[in] fee_asset fee asset + # @param[in] effective_fee_rate effective fee rate + # @param[in] long_term_fee_rate long term fee rate + # @param[in] dust_fee_rate dust fee rate + # @param[in] knapsack_min_change minimum change threshold for knapsack + # @param[in] is_blind blind flag + # @param[in] exponent exponent + # @param[in] minimum_bits minimum bits + # @retval [0] total tx fee. + # @retval [1] used reserved address. (None or reserved_address) + def fund_raw_transaction( + self, txin_utxo_list, utxo_list, target_list, + fee_asset, effective_fee_rate=0.11, + long_term_fee_rate=-1.0, dust_fee_rate=-1.0, + knapsack_min_change=-1, is_blind=True, + exponent=0, minimum_bits=52): + util = get_util() + + def set_opt(handle, tx_handle, key, i_val=0, f_val=0, b_val=False): + util.call_func( + 'CfdSetOptionFundRawTx', handle.get_handle(), + tx_handle.get_handle(), key.value, + int(i_val), float(f_val), b_val) + + with util.create_handle() as handle: + work_handle = util.call_func( + 'CfdInitializeFundRawTx', handle.get_handle(), + self.NETWORK, len(target_list), str(fee_asset)) + with JobHandle(handle, work_handle, + 'CfdFreeFundRawTxHandle') as tx_handle: + for utxo in txin_utxo_list: + util.call_func( + 'CfdAddTxInTemplateForFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + str(utxo.outpoint.txid), utxo.outpoint.vout, + utxo.amount, str(utxo.descriptor), + str(utxo.asset), + utxo.is_issuance, utxo.is_blind_issuance, + utxo.is_pegin, utxo.pegin_btc_tx_size, + to_hex_string(utxo.fedpeg_script), + to_hex_string(utxo.scriptsig_template)) + for utxo in utxo_list: + util.call_func( + 'CfdAddUtxoTemplateForFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + str(utxo.outpoint.txid), utxo.outpoint.vout, + utxo.amount, str(utxo.descriptor), str(utxo.asset), + to_hex_string(utxo.scriptsig_template)) + + for index, target in enumerate(target_list): + util.call_func( + 'CfdAddTargetAmountForFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + index, target.amount, str(target.asset), + str(target.reserved_address)) + + set_opt(handle, tx_handle, _FundTxOpt.DUST_FEE_RATE, + f_val=dust_fee_rate) + set_opt(handle, tx_handle, _FundTxOpt.LONG_TERM_FEE_RATE, + f_val=long_term_fee_rate) + set_opt(handle, tx_handle, _FundTxOpt.KNAPSACK_MIN_CHANGE, + i_val=knapsack_min_change) + set_opt(handle, tx_handle, _FundTxOpt.USE_BLIND, + b_val=is_blind) + set_opt(handle, tx_handle, _FundTxOpt.EXPONENT, + i_val=exponent) + set_opt(handle, tx_handle, _FundTxOpt.MINIMUM_BITS, + i_val=minimum_bits) + + _tx_fee, _append_txout_count, _new_hex = util.call_func( + 'CfdFinalizeFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + self.hex, effective_fee_rate) + + _used_addr_list = [] + for i in range(_append_txout_count): + _used_addr = util.call_func( + 'CfdGetAppendTxOutFundRawTx', + handle.get_handle(), tx_handle.get_handle(), i) + _used_addr_list.append(_used_addr) + + self.hex = _new_hex + self._update_tx_all() + return _tx_fee, _used_addr_list + + +## +# @class _BlindOpt +# @brief Blind option class. +class _BlindOpt(Enum): + ## + # blind minimum range value (for elements) + MINIMUM_RANGE_VALUE = 1 + ## + # blind exponent (for elements) + EXPONENT = 2 + ## + # blind minimum bits (for elements) + MINIMUM_BITS = 3 + + +## +# @class _CoinSelectionOpt +# @brief CoinSelection option class. +class _CoinSelectionOpt(Enum): + ## + # blind exponent (for elements) + EXPONENT = 1 + ## + # blind minimum bits (for elements) + MINIMUM_BITS = 2 + + +## +# @class _FeeOpt +# @brief EstimateFee option class. +class _FeeOpt(Enum): + ## + # blind exponent (for elements) + EXPONENT = 1 + ## + # blind minimum bits (for elements) + MINIMUM_BITS = 2 + + +## +# All import target. +__all__ = [ + 'BlindFactor', + 'ConfidentialNonce', + 'ConfidentialAsset', + 'ConfidentialValue', + 'ElementsUtxoData', + 'Issuance', + 'IssuanceKeyPair', + 'UnblindData', + 'TargetAmountData', + 'ConfidentialTxIn', + 'ConfidentialTxOut', + 'ConfidentialTransaction' +] diff --git a/cfd/descriptor.py b/cfd/descriptor.py new file mode 100644 index 0000000..a846611 --- /dev/null +++ b/cfd/descriptor.py @@ -0,0 +1,438 @@ +# -*- coding: utf-8 -*- +## +# @file descriptor.py +# @brief hdwallet function implements file. +# @note Copyright 2020 CryptoGarage +from .util import get_util, JobHandle, CfdError +from .address import AddressUtil +from .key import Network +from .script import HashType +from enum import Enum + + +## +# @class DescriptorScriptType +# @brief Descriptor script type +class DescriptorScriptType(Enum): + ## + # null + NULL = 0 + ## + # p2sh + SH = 1 + ## + # p2wsh + WSH = 2 + ## + # p2pk + PK = 3 + ## + # p2pkh + PKH = 4 + ## + # p2wpkh + WPKH = 5 + ## + # combo + COMBO = 6 + ## + # multi + MULTI = 7 + ## + # sorted multi + SORTED_MULTI = 8 + ## + # address + ADDR = 9 + ## + # raw + RAW = 10 + + ## + # @brief get string. + # @return name. + def as_str(self): + return self.name.lower().replace('_', '') + + ## + # @brief get object. + # @param[in] desc_type descriptor type + # @return object. + @classmethod + def get(cls, desc_type): + if (isinstance(desc_type, DescriptorScriptType)): + return desc_type + elif (isinstance(desc_type, int)): + _num = int(desc_type) + for type_data in DescriptorScriptType: + if _num == type_data.value: + return type_data + else: + _type = str(desc_type).lower() + for type_data in DescriptorScriptType: + if _type == type_data.name.lower(): + return type_data + raise CfdError( + error_code=1, + message='Error: Invalid type.') + + +## +# @class DescriptorKeyType +# @brief Descriptor key type +class DescriptorKeyType(Enum): + ## + # null + NULL = 0 + ## + # public key + PUBLIC = 1 + ## + # bip32 (ext pubkey) + BIP32 = 2 + ## + # bip32 (ext privkey) + BIP32_PRIV = 3 + + ## + # @brief get string. + # @return name. + def as_str(self): + if self == DescriptorKeyType.PUBLIC: + return 'pubkey' + elif self == DescriptorKeyType.BIP32: + return 'extPubkey' + elif self == DescriptorKeyType.BIP32_PRIV: + return 'extPrivkey' + return self.name + + ## + # @brief get object. + # @param[in] desc_type descriptor type + # @return object. + @classmethod + def get(cls, desc_type): + if (isinstance(desc_type, DescriptorKeyType)): + return desc_type + elif (isinstance(desc_type, int)): + _num = int(desc_type) + for type_data in DescriptorKeyType: + if _num == type_data.value: + return type_data + else: + _type = str(desc_type).lower() + for type_data in DescriptorKeyType: + if _type == type_data.name.lower(): + return type_data + if _type == 'pubkey': + return DescriptorKeyType.PUBLIC + elif _type == 'extpubkey': + return DescriptorKeyType.BIP32 + elif _type == 'extprivkey': + return DescriptorKeyType.BIP32_PRIV + raise CfdError( + error_code=1, + message='Error: Invalid type.') + + +## +# @class DescriptorKeyData +# @brief Descriptor key data +class DescriptorKeyData: + ## + # @var key_type + # key type + ## + # @var pubkey + # pubkey + ## + # @var ext_pubkey + # ext pubkey + ## + # @var ext_privkey + # ext privkey + + ## + # @brief constructor. + # @param[in] key_type key type + # @param[in] pubkey pubkey + # @param[in] ext_pubkey ext pubkey + # @param[in] ext_privkey ext privkey + def __init__( + self, + key_type=DescriptorKeyType.NULL, + pubkey='', + ext_pubkey='', + ext_privkey=''): + self.key_type = DescriptorKeyType.get(key_type) + self.pubkey = pubkey + self.ext_pubkey = ext_pubkey + self.ext_privkey = ext_privkey + + ## + # @brief get string. + # @return descriptor. + def __str__(self): + if self.key_type == DescriptorKeyType.PUBLIC: + return str(self.pubkey) + elif self.key_type == DescriptorKeyType.BIP32: + return str(self.ext_pubkey) + elif self.key_type == DescriptorKeyType.BIP32_PRIV: + return str(self.ext_privkey) + return '' + + +## +# @class DescriptorScriptData +# @brief Descriptor script data +class DescriptorScriptData: + ## + # @var script_type + # script type + ## + # @var depth + # depth + ## + # @var hash_type + # hash type + ## + # @var address + # address + ## + # @var redeem_script + # redeem script + ## + # @var key_data + # key data + ## + # @var key_list + # key list + ## + # @var multisig_require_num + # multisig require num + + ## + # @brief constructor. + # @param[in] script_type script type + # @param[in] depth depth + # @param[in] hash_type hash type + # @param[in] address address + # @param[in] redeem_script redeem script + # @param[in] key_data key data + # @param[in] key_list key list + # @param[in] multisig_require_num multisig require num + def __init__( + self, script_type, depth, hash_type, address, + redeem_script='', + key_data=None, + key_list=[], + multisig_require_num=0): + self.script_type = script_type + self.depth = depth + self.hash_type = hash_type + self.address = address + self.redeem_script = redeem_script + self.key_data = key_data + self.key_list = key_list + self.multisig_require_num = multisig_require_num + + +## +# @class Descriptor +# @brief Descriptor data +class Descriptor: + ## + # @var path + # bip32 path + ## + # @var descriptor + # descriptor string + ## + # @var network + # network + ## + # @var script_list + # script list + ## + # @var data + # reference data + + ## + # @brief constructor. + # @param[in] descriptor descriptor + # @param[in] network network + # @param[in] path bip32 path + def __init__(self, descriptor, network=Network.MAINNET, path=''): + self.network = Network.get(network) + self.path = str(path) + self.descriptor = self._verify(str(descriptor)) + self.script_list = self._parse() + self.data = self._analyze() + + ## + # @brief verify descriptor. + # @param[in] descriptor descriptor + # @return append checksum descriptor + def _verify(self, descriptor): + util = get_util() + with util.create_handle() as handle: + return util.call_func( + 'CfdGetDescriptorChecksum', handle.get_handle(), + self.network.value, descriptor) + + ## + # @brief parse descriptor. + # @return script list + def _parse(self): + util = get_util() + with util.create_handle() as handle: + word_handle, max_index = util.call_func( + 'CfdParseDescriptor', handle.get_handle(), + self.descriptor, self.network.value, self.path) + with JobHandle( + handle, + word_handle, + 'CfdFreeDescriptorHandle') as desc_handle: + + def get_key(index): + return util.call_func( + 'CfdGetDescriptorMultisigKey', + handle.get_handle(), desc_handle.get_handle(), + index) + + script_list = [] + for i in range(max_index + 1): + max_index, depth, script_type, locking_script,\ + address, hash_type, redeem_script, key_type,\ + pubkey, ext_pubkey, ext_privkey, is_multisig,\ + max_key_num, req_sig_num = util.call_func( + 'CfdGetDescriptorData', + handle.get_handle(), desc_handle.get_handle(), i) + _script_type = DescriptorScriptType.get(script_type) + _hash_type = HashType.P2SH + if _script_type != DescriptorScriptType.RAW: + _hash_type = HashType.get(hash_type) + data = DescriptorScriptData( + _script_type, depth, _hash_type, address) + if _script_type in { + DescriptorScriptType.COMBO, + DescriptorScriptType.PK, + DescriptorScriptType.PKH, + DescriptorScriptType.WPKH}: + data.key_data = DescriptorKeyData( + key_type, pubkey, ext_pubkey, ext_privkey) + data.address = AddressUtil.parse(address, hash_type) + elif _script_type in { + DescriptorScriptType.SH, + DescriptorScriptType.WSH, + DescriptorScriptType.MULTI, + DescriptorScriptType.SORTED_MULTI}: + data.address = AddressUtil.parse(address, hash_type) + if is_multisig is False: + data.redeem_script = redeem_script + else: + key_list = [] + for i in range(max_key_num): + key_info = DescriptorKeyData(*get_key(i)) + key_list.append(key_info) + data.key_list = key_list + data.multisig_require_num = req_sig_num + elif _script_type == DescriptorScriptType.RAW: + pass + elif _script_type == DescriptorScriptType.ADDR: + data.address = AddressUtil.parse(address, hash_type) + + script_list.append(data) + if _script_type == DescriptorScriptType.COMBO: + # TODO: combo data is top only. + break + return script_list + + ## + # @brief analyze descriptor. + # @return reference data + def _analyze(self): + if (self.script_list[0].hash_type in { + HashType.P2WSH, HashType.P2SH}) and ( + len(self.script_list) > 1) and ( + self.script_list[1].hash_type == HashType.P2PKH): + data = DescriptorScriptData( + self.script_list[0].script_type, + self.script_list[0].depth, + self.script_list[0].hash_type, + self.script_list[0].address, + self.script_list[0].redeem_script, + self.script_list[1].key_data) + return data + + if (self.script_list[0].hash_type == HashType.P2SH_P2WSH) and ( + len(self.script_list) > 2) and ( + self.script_list[2].hash_type == HashType.P2PKH): + data = DescriptorScriptData( + self.script_list[0].script_type, + self.script_list[0].depth, + self.script_list[0].hash_type, + self.script_list[0].address, + self.script_list[1].redeem_script, + self.script_list[2].key_data) + return data + if len(self.script_list) == 1: + return self.script_list[0] + + if self.script_list[0].hash_type == HashType.P2SH_P2WSH: + if self.script_list[1].multisig_require_num > 0: + multisig_require_num = self.script_list[1].multisig_require_num + data = DescriptorScriptData( + self.script_list[0].script_type, + self.script_list[0].depth, + self.script_list[0].hash_type, + self.script_list[0].address, + self.script_list[1].redeem_script, + key_list=self.script_list[1].key_list, + multisig_require_num=multisig_require_num) + return data + else: + data = DescriptorScriptData( + self.script_list[0].script_type, + self.script_list[0].depth, + self.script_list[0].hash_type, + self.script_list[0].address, + self.script_list[1].redeem_script) + return data + elif self.script_list[0].hash_type == HashType.P2SH_P2WPKH: + data = DescriptorScriptData( + self.script_list[0].script_type, + self.script_list[0].depth, + self.script_list[0].hash_type, + self.script_list[0].address, + key_data=self.script_list[1].key_data) + return data + return self.script_list[0] + + ## + # @brief get string. + # @return descriptor. + def __str__(self): + return self.descriptor + + +## +# @brief parse descriptor. +# @param[in] descriptor descriptor +# @param[in] network network +# @param[in] path bip32 path +# @retval Descriptor descriptor object +def parse_descriptor(descriptor, network=Network.MAINNET, path=''): + return Descriptor(descriptor, network=network, path=path) + + +## +# All import target. +__all__ = [ + 'parse_descriptor', + 'Descriptor', + 'DescriptorScriptType', + 'DescriptorKeyType', + 'DescriptorScriptData', + 'DescriptorKeyData' +] diff --git a/cfd/hdwallet.py b/cfd/hdwallet.py new file mode 100644 index 0000000..c97d3f5 --- /dev/null +++ b/cfd/hdwallet.py @@ -0,0 +1,635 @@ +# -*- coding: utf-8 -*- +## +# @file hdwallet.py +# @brief hdwallet function implements file. +# @note Copyright 2020 CryptoGarage +from .util import get_util, JobHandle, to_hex_string, CfdError +from .key import Network, Privkey, Pubkey +from enum import Enum +import unicodedata + + +## +# xpriv mainnet version +XPRIV_MAINNET_VERSION = '0488ade4' +## +# xpriv testnet version +XPRIV_TESTNET_VERSION = '04358394' +## +# xpub mainnet version +XPUB_MAINNET_VERSION = '0488b21e' +## +# xpub testnet version +XPUB_TESTNET_VERSION = '043587cf' + + +## +# @class ExtKeyType +# @brief ExtKey type. +class ExtKeyType(Enum): + ## + # Ext privkey + EXT_PRIVKEY = 0 + ## + # Ext pubkey + EXT_PUBKEY = 1 + + ## + # @brief get string. + # @return name. + def __str__(self): + return self.name.lower().replace('_', '') + + ## + # @brief get string. + # @return name. + def as_str(self): + return self.name.lower().replace('_', '') + + ## + # @brief get object. + # @param[in] key_type key type + # @return object. + @classmethod + def get(cls, key_type): + if (isinstance(key_type, ExtKeyType)): + return key_type + elif (isinstance(key_type, int)): + _num = int(key_type) + for _type in ExtKeyType: + if _num == _type.value: + return _type + else: + _key_type = str(key_type).lower() + for _type in ExtKeyType: + if _key_type == _type.name.lower(): + return _type + if _key_type == 'extprivkey': + return ExtKeyType.EXT_PRIVKEY + elif _key_type == 'extpubkey': + return ExtKeyType.EXT_PUBKEY + raise CfdError( + error_code=1, + message='Error: Invalid extkey type.') + + +## +# @class Extkey +# @brief ExtKey base class. +class Extkey(object): + ## + # @var extkey_type + # extkey type + ## + # @var util + # cfd util + ## + # @var version + # version + ## + # @var fingerprint + # fingerprint + ## + # @var chain_code + # chain code + ## + # @var depth + # depth + ## + # @var child_number + # child number + ## + # @var extkey + # extkey + ## + # @var network + # network + + ## + # @brief constructor. + # @param[in] extkey_type extkey type + def __init__(self, extkey_type): + self.extkey_type = extkey_type + self.util = get_util() + self.version = '' + self.fingerprint = '' + self.chain_code = '' + self.depth = 0 + self.child_number = 0 + self.extkey = '' + self.network = Network.TESTNET + + ## + # @brief get extkey information. + # @param[in] extkey extkey + # @return void + def _get_information(self, extkey): + with self.util.create_handle() as handle: + result = self.util.call_func( + 'CfdGetExtkeyInformation', handle.get_handle(), extkey) + self.version, self.fingerprint, self.chain_code, self.depth, \ + self.child_number = result + self.extkey = extkey + if self.extkey_type == ExtKeyType.EXT_PRIVKEY: + main, test, name = XPRIV_MAINNET_VERSION,\ + XPRIV_TESTNET_VERSION, 'privkey' + else: + main, test, name = XPUB_MAINNET_VERSION,\ + XPUB_TESTNET_VERSION, 'pubkey' + if self.version == main: + self.network = Network.MAINNET + elif self.version == test: + self.network = Network.TESTNET + else: + raise CfdError( + error_code=1, + message='Error: Invalid ext {}.'.format(name)) + + ## + # @brief get extkey information. + # @param[in] path bip32 path + # @param[in] number bip32 number + # @param[in] number_list bip32 number list + # @retval [0] bip32 path + # @retval [1] bip32 number list + @classmethod + def _convert_path(cls, path='', number=0, number_list=[]): + if path != '': + return path, [] + if isinstance(number_list, list) and ( + len(number_list) > 0) and (isinstance(number_list[0], int)): + for num in number_list: + if (num < 0) or (num > 0xffffffff): + raise CfdError( + error_code=1, + message='Error: Invalid number_list item range.') + return '', number_list + if (not isinstance(number, int)) or ( + number < 0) or (number > 0xffffffff): + raise CfdError( + error_code=1, + message='Error: Invalid number range.') + return '', [number] + + ## + # @brief get extkey path data. + # @param[in] bip32_path bip32 path + # @param[in] key_type key type + # @return path data + def _get_path_data(self, bip32_path, key_type): + with self.util.create_handle() as handle: + return self.util.call_func( + 'CfdGetParentExtkeyPathData', handle.get_handle(), + self.extkey, bip32_path, key_type.value) + + ## + # @brief create extkey. + # @param[in] key_type key type + # @param[in] network network + # @param[in] fingerprint fingerprint + # @param[in] key key + # @param[in] chain_code chain_code + # @param[in] depth depth + # @param[in] number number + # @param[in] parent_key parent key + # @return Extkey string + @classmethod + def _create( + cls, key_type, network, fingerprint, key, chain_code, + depth, number, parent_key=''): + _network = Network.get_mainchain(network) + _fingerprint = '' + _path, _num_list = cls._convert_path(number=number) + _number = _num_list[0] if len(_num_list) > 0 else number + if parent_key == '': + _fingerprint = fingerprint + _network = Network.get_mainchain(network) + util = get_util() + with util.create_handle() as handle: + _extkey = util.call_func( + 'CfdCreateExtkey', handle.get_handle(), + _network.value, key_type.value, parent_key, + _fingerprint, key, chain_code, depth, _number) + return _extkey + + +## +# @class ExtPrivkey +# @brief ExtPrivkey class. +class ExtPrivkey(Extkey): + ## + # @var privkey + # privkey + + ## + # @brief create extkey from seed. + # @param[in] seed seed + # @param[in] network network + # @return ExtPrivkey + @classmethod + def from_seed(cls, seed, network=Network.MAINNET): + _seed = to_hex_string(seed) + _network = Network.get_mainchain(network) + util = get_util() + with util.create_handle() as handle: + _extkey = util.call_func( + 'CfdCreateExtkeyFromSeed', handle.get_handle(), + _seed, _network.value, ExtKeyType.EXT_PRIVKEY.value) + return ExtPrivkey(_extkey) + + ## + # @brief create extkey. + # @param[in] network network + # @param[in] fingerprint fingerprint + # @param[in] key key + # @param[in] chain_code chain_code + # @param[in] depth depth + # @param[in] number number + # @param[in] parent_key parent key + # @return ExtPrivkey + @classmethod + def create( + cls, network, fingerprint, key, chain_code, + depth, number, parent_key=''): + _extkey = cls._create( + ExtKeyType.EXT_PRIVKEY, network, fingerprint, key, + chain_code, depth, number, parent_key) + return ExtPrivkey(_extkey) + + ## + # @brief constructor. + # @param[in] extkey extkey + def __init__(self, extkey): + super().__init__(ExtKeyType.EXT_PRIVKEY) + self._get_information(extkey) + with self.util.create_handle() as handle: + _hex, wif = self.util.call_func( + 'CfdGetPrivkeyFromExtkey', handle.get_handle(), + self.extkey, self.network.value) + self.privkey = Privkey(wif=wif) + + ## + # @brief get string. + # @return extkey. + def __str__(self): + return self.extkey + + ## + # @brief derive key. + # @param[in] path bip32 path + # @param[in] number bip32 number + # @param[in] number_list bip32 number list + # @return ExtPrivkey + def derive(self, path='', number=0, number_list=[]): + _path, _list = self._convert_path(path, number, number_list) + with self.util.create_handle() as handle: + if _path == '': + _extkey = self.extkey + for child in _list: + hardened = True if child >= 0x80000000 else False + _extkey = self.util.call_func( + 'CfdCreateExtkeyFromParent', + handle.get_handle(), _extkey, child, hardened, + self.network.value, + ExtKeyType.EXT_PRIVKEY.value) + else: + _extkey = self.util.call_func( + 'CfdCreateExtkeyFromParentPath', handle.get_handle(), + self.extkey, _path, self.network.value, + ExtKeyType.EXT_PRIVKEY.value) + return ExtPrivkey(_extkey) + + ## + # @brief derive pubkey. + # @param[in] path bip32 path + # @param[in] number bip32 number + # @param[in] number_list bip32 number list + # @return ExtPubkey + def derive_pubkey(self, path='', number=0, number_list=[]): + return self.derive( + path=path, + number=number, + number_list=number_list).get_extpubkey() + + ## + # @brief get ext pubkey. + # @return ExtPubkey + def get_extpubkey(self): + with self.util.create_handle() as handle: + ext_pubkey = self.util.call_func( + 'CfdCreateExtPubkey', handle.get_handle(), + self.extkey, self.network.value) + return ExtPubkey(ext_pubkey) + + ## + # @brief get extkey path data. + # @param[in] bip32_path bip32 path + # @param[in] key_type key type + # @return path data + def get_path_data(self, bip32_path, key_type=ExtKeyType.EXT_PRIVKEY): + path_data, child_key = self._get_path_data( + bip32_path, key_type) + _key_type = ExtKeyType.get(key_type) + if _key_type == ExtKeyType.EXT_PUBKEY: + return path_data, ExtPubkey(child_key) + else: + return path_data, ExtPrivkey(child_key) + + +## +# @class ExtPubkey +# @brief ExtPubkey class. +class ExtPubkey(Extkey): + ## + # @var pubkey + # pubkey + + ## + # @brief create extkey. + # @param[in] network network + # @param[in] fingerprint fingerprint + # @param[in] key key + # @param[in] chain_code chain_code + # @param[in] depth depth + # @param[in] number number + # @param[in] parent_key parent key + # @return ExtPubkey + @classmethod + def create( + cls, network, fingerprint, key, chain_code, + depth, number, parent_key=''): + _extkey = cls._create( + ExtKeyType.EXT_PUBKEY, network, fingerprint, key, + chain_code, depth, number, parent_key) + return ExtPubkey(_extkey) + + ## + # @brief constructor. + # @param[in] extkey extkey + def __init__(self, extkey): + super().__init__(ExtKeyType.EXT_PUBKEY) + self._get_information(extkey) + with self.util.create_handle() as handle: + hex = self.util.call_func( + 'CfdGetPubkeyFromExtkey', handle.get_handle(), + self.extkey, self.network.value) + self.pubkey = Pubkey(hex) + + ## + # @brief get string. + # @return extkey. + def __str__(self): + return self.extkey + + ## + # @brief derive key. + # @param[in] path bip32 path + # @param[in] number bip32 number + # @param[in] number_list bip32 number list + # @return ExtPubkey + def derive(self, path='', number=0, number_list=[]): + _path, _list = self._convert_path(path, number, number_list) + with self.util.create_handle() as handle: + if len(_path) == 0: + _extkey = self.extkey + for child in _list: + hardened = True if child >= 0x80000000 else False + _extkey = self.util.call_func( + 'CfdCreateExtkeyFromParent', + handle.get_handle(), + _extkey, child, hardened, + self.network.value, + ExtKeyType.EXT_PUBKEY.value) + else: + _extkey = self.util.call_func( + 'CfdCreateExtkeyFromParentPath', handle.get_handle(), + self.extkey, _path, self.network.value, + ExtKeyType.EXT_PUBKEY.value) + return ExtPubkey(_extkey) + + ## + # @brief get extkey path data. + # @param[in] bip32_path bip32 path + # @return path data + def get_path_data(self, bip32_path): + path_data, child_key = self._get_path_data( + bip32_path, ExtKeyType.EXT_PUBKEY) + return path_data, ExtPubkey(child_key) + + +## +# @class MnemonicLanguage +# @brief Mnemonic language class. +class MnemonicLanguage(Enum): + ## + # English + EN = 'en' + ## + # Spanish + ES = 'es' + ## + # French + FR = 'fr' + ## + # Italic + IT = 'it' + ## + # Japanese + JP = 'jp' + ## + # Simplified Chinese + ZH_CN = 'zhs' + ## + # Traditional Chinese + ZH_TW = 'zht' + + ## + # @brief get object. + # @param[in] language language + # @return object. + @classmethod + def get(cls, language): + if (isinstance(language, MnemonicLanguage)): + return language + else: + _type = str(language).lower() + for lang_data in MnemonicLanguage: + if _type == lang_data.value: + return lang_data + _type = str(language).upper() + for lang_data in MnemonicLanguage: + if _type == lang_data.name: + return lang_data + if _type == 'ZHCN': + return MnemonicLanguage.ZH_CN + if _type == 'ZHTW': + return MnemonicLanguage.ZH_TW + raise CfdError( + error_code=1, + message='Error: Invalid lang.') + + +## +# @class HDWallet +# @brief HDWallet class. +class HDWallet: + ## + # @var seed + # seed + ## + # @var network + # network + ## + # @var ext_privkey + # ext privkey + + @classmethod + ## + # @brief get mnemonic word list. + # @param[in] language language + # @return word_list mnemonic word list + def get_mnemonic_word_list(cls, language): + util = get_util() + _lang = MnemonicLanguage.get(language).value + word_list = [] + with util.create_handle() as handle: + word_handle, max_index = util.call_func( + 'CfdInitializeMnemonicWordList', handle.get_handle(), _lang) + with JobHandle( + handle, + word_handle, + 'CfdFreeMnemonicWordList') as mnemonic_handle: + for i in range(max_index): + word = util.call_func( + 'CfdGetMnemonicWord', + handle.get_handle(), mnemonic_handle.get_handle(), i) + word_list.append(word) + return word_list + + ## + # @brief get mnemonic. + # @param[in] entropy entropy + # @param[in] language language + # @return mnemonic + @classmethod + def get_mnemonic(cls, entropy, language): + _entropy = to_hex_string(entropy) + _lang = MnemonicLanguage.get(language).value + util = get_util() + with util.create_handle() as handle: + mnemonic = util.call_func( + 'CfdConvertEntropyToMnemonic', + handle.get_handle(), _entropy, _lang) + return mnemonic + + ## + # @brief get entropy. + # @param[in] mnemonic mnemonic + # @param[in] language language + # @param[in] strict_check strict check + # @return entropy + @classmethod + def get_entropy(cls, mnemonic, language, strict_check=True): + _mnemonic = cls._convert_mnemonic(mnemonic) + _lang = MnemonicLanguage.get(language).value + _mnemonic = unicodedata.normalize('NFKD', _mnemonic) + util = get_util() + with util.create_handle() as handle: + _, entropy = util.call_func( + 'CfdConvertMnemonicToSeed', handle.get_handle(), + _mnemonic, '', strict_check, _lang, False) + return entropy + + ## + # @brief create extkey from seed. + # @param[in] seed seed + # @param[in] network network + # @return HDWallet + @classmethod + def from_seed(cls, seed, network=Network.MAINNET): + return HDWallet(seed=seed, network=network) + + ## + # @brief create extkey from mnemonic. + # @param[in] mnemonic mnemonic + # @param[in] language language + # @param[in] passphrase passphrase + # @param[in] network network + # @param[in] strict_check strict check + # @return HDWallet + @classmethod + def from_mnemonic( + cls, mnemonic, language='en', passphrase='', + network=Network.MAINNET, strict_check=True): + return HDWallet( + mnemonic=mnemonic, language=language, + passphrase=passphrase, network=network, strict_check=strict_check) + + ## + # @brief constructor. + # @param[in] seed seed + # @param[in] mnemonic mnemonic + # @param[in] language language + # @param[in] passphrase passphrase + # @param[in] network network + # @param[in] strict_check strict check + def __init__( + self, seed='', mnemonic='', language='en', passphrase='', + network=Network.MAINNET, strict_check=True): + self.seed = to_hex_string(seed) + self.network = Network.get_mainchain(network) + _mnemonic = self._convert_mnemonic(mnemonic) + _lang = MnemonicLanguage.get(language).value + _mnemonic = unicodedata.normalize('NFKD', _mnemonic) + _passphrase = unicodedata.normalize('NFKD', passphrase) + if _mnemonic != '': + util = get_util() + with util.create_handle() as handle: + self.seed, _ = util.call_func( + 'CfdConvertMnemonicToSeed', + handle.get_handle(), _mnemonic, _passphrase, + strict_check, _lang, False) + self.ext_privkey = ExtPrivkey.from_seed(self.seed, self.network) + + ## + # @brief get privkey. + # @param[in] path bip32 path + # @param[in] number bip32 number + # @param[in] number_list bip32 number list + # @return ExtPrivkey + def get_privkey(self, path='', number=0, number_list=[]): + return self.ext_privkey.derive(path, number, number_list) + + ## + # @brief get pubkey. + # @param[in] path bip32 path + # @param[in] number bip32 number + # @param[in] number_list bip32 number list + # @return ExtPubkey + def get_pubkey(self, path='', number=0, number_list=[]): + return self.ext_privkey.derive_pubkey(path, number, number_list) + + ## + # @brief convert mnemonic. + # @param[in] mnemonic mnemonic + # @return mnemonic + @classmethod + def _convert_mnemonic(cls, mnemonic): + _words = ' '.join(mnemonic) if isinstance(mnemonic, list) else mnemonic + return _words.replace(' ', ' ') if isinstance(_words, str) else _words + + +## +# All import target. +__all__ = [ + 'ExtKeyType', + 'Extkey', + 'ExtPrivkey', + 'ExtPubkey', + 'MnemonicLanguage', + 'HDWallet', + 'XPRIV_MAINNET_VERSION', + 'XPRIV_TESTNET_VERSION', + 'XPUB_MAINNET_VERSION', + 'XPUB_TESTNET_VERSION' +] diff --git a/cfd/key.py b/cfd/key.py new file mode 100644 index 0000000..a64cbf7 --- /dev/null +++ b/cfd/key.py @@ -0,0 +1,910 @@ +# -*- coding: utf-8 -*- +## +# @file key.py +# @brief key function implements file. +# @note Copyright 2020 CryptoGarage +from .util import get_util, CfdError, to_hex_string, CfdErrorCode, JobHandle +import hashlib +from enum import Enum + + +## +# @class Network +# @brief Network Type +class Network(Enum): + ## + # Network: Bitcoin Mainnet + MAINNET = 0 + ## + # Network: Bitcoin Testnet + TESTNET = 1 + ## + # Network: Bitcoin Regtest + REGTEST = 2 + ## + # Network: Liquid LiquidV1 + LIQUID_V1 = 10 + ## + # Network: Liquid ElementsRegtest + ELEMENTS_REGTEST = 11 + ## + # Network: Liquid custom chain + CUSTOM_CHAIN = 12 + + ## + # @brief get string. + # @return name. + def __str__(self): + return self.name.lower().replace('_', '') + + ## + # @brief get string. + # @return name. + def as_str(self): + return self.name.lower().replace('_', '') + + ## + # @brief get object. + # @param[in] network network + # @return object. + @classmethod + def get(cls, network): + if (isinstance(network, Network)): + return network + elif (isinstance(network, int)): + _num = int(network) + for net in Network: + if _num == net.value: + return net + else: + _network = str(network).lower() + for net in Network: + if _network == net.name.lower(): + return net + if _network == 'liquidv1': + return Network.LIQUID_V1 + elif _network in {'elementsregtest', 'liquidregtest'}: + return Network.ELEMENTS_REGTEST + raise CfdError( + error_code=1, + message='Error: Invalid network type.') + + ## + # @brief get mainchain object. + # @param[in] network network + # @return object. + @classmethod + def get_mainchain(cls, network): + _network = cls.get(network) + if _network == Network.LIQUID_V1: + _network = Network.MAINNET + elif _network in {Network.ELEMENTS_REGTEST, Network.CUSTOM_CHAIN}: + _network = Network.TESTNET + return _network + + +## +# @class SigHashType +# @brief Signature hash type +class SigHashType(Enum): + ## + # SigHashType: all + ALL = 1 + ## + # SigHashType: none + NONE = 2 + ## + # SigHashType: single + SINGLE = 3 + ## + # SigHashType: all+anyoneCanPay + ALL_PLUS_ANYONE_CAN_PAY = 0x81 + ## + # SigHashType: none+anyoneCanPay + NONE_PLUS_ANYONE_CAN_PAY = 0x82 + ## + # SigHashType: single+anyoneCanPay + SINGLE_PLUS_ANYONE_CAN_PAY = 0x83 + + ## + # @brief get string. + # @return name. + def __str__(self): + return self.name.lower().replace('_', '') + + ## + # @brief get string. + # @return name. + def as_str(self): + return self.name.lower().replace('_', '') + + ## + # @brief get type value. + # @return value. + def get_type(self): + return self.value & 0x0f + + ## + # @brief get anyone can pay flag. + # @retval True anyone can pay is true. + # @retval False anyone can pay is false. + def anyone_can_pay(self): + return self.value >= 0x80 + + ## + # @brief get type object. + # @return object. + def get_type_object(self): + return self.get(self.get_type()) + + ## + # @brief get object. + # @param[in] sighashtype sighash type + # @param[in] anyone_can_pay anyone can pay flag + # @return object. + @classmethod + def get(cls, sighashtype, anyone_can_pay=False): + if (isinstance(sighashtype, SigHashType)): + if anyone_can_pay is True: + return cls.get(sighashtype.value | 0x80) + else: + return sighashtype + elif (isinstance(sighashtype, int)): + _num = int(sighashtype) + if anyone_can_pay is True: + _num |= 0x80 + for hash_type in SigHashType: + if _num == hash_type.value: + return hash_type + else: + _hash_type = str(sighashtype).lower() + if (anyone_can_pay is True) and ( + _hash_type.find('_plus_anyone_can_pay') == -1): + _hash_type += '_plus_anyone_can_pay' + for hash_type in SigHashType: + if _hash_type == hash_type.name.lower(): + return hash_type + raise CfdError( + error_code=1, + message='Error: Invalid sighash type.') + + +## +# @class Privkey +# @brief privkey class. +class Privkey: + ## + # @var hex + # privkey hex + ## + # @var wif + # wallet import format + ## + # @var network + # network type. + ## + # @var is_compressed + # pubkey compressed flag + ## + # @var wif_first + # wif set flag. + ## + # @var pubkey + # pubkey + + ## + # @brief generate key pair. + # @param[in] is_compressed pubkey compressed + # @param[in] network network type + # @return private key + @classmethod + def generate(cls, is_compressed=True, network=Network.MAINNET): + _network = Network.get_mainchain(network) + util = get_util() + with util.create_handle() as handle: + _, _, wif = util.call_func( + 'CfdCreateKeyPair', handle.get_handle(), + is_compressed, _network.value) + return Privkey(wif=wif) + + ## + # @brief create privkey from hex string. + # @param[in] hex hex string + # @param[in] network network type + # @param[in] is_compressed pubkey compressed + # @return private key + @classmethod + def from_hex(cls, hex, network=Network.MAINNET, is_compressed=True): + return Privkey(hex=hex, network=network, + is_compressed=is_compressed) + + ## + # @brief create privkey from hex string. + # @param[in] wif wallet import format + # @return private key + @classmethod + def from_wif(cls, wif): + return Privkey(wif=wif) + + ## + # @brief constructor. + # @param[in] wif wif + # @param[in] hex hex + # @param[in] network network + # @param[in] is_compressed pubkey compressed + def __init__( + self, + wif='', + hex='', + network=Network.MAINNET, + is_compressed=True): + self.hex = to_hex_string(hex) + self.wif = wif + self.network = Network.get_mainchain(network) + self.is_compressed = is_compressed + util = get_util() + with util.create_handle() as handle: + if len(wif) == 0: + self.wif_first = False + self.wif = util.call_func( + 'CfdGetPrivkeyWif', handle.get_handle(), + self.hex, self.network.value, is_compressed) + else: + self.wif_first = True + self.hex, self.network, \ + self.is_compressed = util.call_func( + 'CfdParsePrivkeyWif', handle.get_handle(), + self.wif) + self.network = Network.get_mainchain(self.network) + self.pubkey = util.call_func( + 'CfdGetPubkeyFromPrivkey', handle.get_handle(), + self.hex, '', self.is_compressed) + + ## + # @brief get string. + # @return pubkey hex. + def __str__(self): + return self.wif if (self.wif_first) else self.hex + + ## + # @brief add tweak. + # @param[in] tweak tweak bytes. (32 byte) + # @return tweaked private key + def add_tweak(self, tweak): + _tweak = to_hex_string(tweak) + util = get_util() + with util.create_handle() as handle: + _key = util.call_func( + 'CfdPrivkeyTweakAdd', handle.get_handle(), + self.hex, _tweak) + return Privkey( + hex=_key, network=self.network, + is_compressed=self.is_compressed) + + ## + # @brief mul tweak. + # @param[in] tweak tweak bytes. (32 byte) + # @return tweaked private key + def mul_tweak(self, tweak): + _tweak = to_hex_string(tweak) + util = get_util() + with util.create_handle() as handle: + _key = util.call_func( + 'CfdPrivkeyTweakMul', handle.get_handle(), + self.hex, _tweak) + return Privkey( + hex=_key, network=self.network, + is_compressed=self.is_compressed) + + ## + # @brief negate. + # @return negated private key + def negate(self): + util = get_util() + with util.create_handle() as handle: + _key = util.call_func( + 'CfdNegatePrivkey', handle.get_handle(), self.hex) + return Privkey( + hex=_key, network=self.network, + is_compressed=self.is_compressed) + + ## + # @brief calculate ec-signature. + # @param[in] sighash sighash + # @param[in] grind_r grind-r flag + # @return signature + def calculate_ec_signature(self, sighash, grind_r=True): + _sighash = to_hex_string(sighash) + util = get_util() + with util.create_handle() as handle: + signature = util.call_func( + 'CfdCalculateEcSignature', handle.get_handle(), + _sighash, self.hex, '', self.network.value, grind_r) + sign = SignParameter(signature) + sign.use_der_encode = True + return sign + + +## +# @class Pubkey +# @brief pubkey class. +class Pubkey: + ## + # @var _hex + # pubkey hex + + ## + # @brief combine pubkey. + # @param[in] pubkey_list pubkey list + # @return combined pubkey + @classmethod + def combine(cls, pubkey_list): + if (isinstance(pubkey_list, list) is False) or ( + len(pubkey_list) <= 1): + raise CfdError( + error_code=1, + message='Error: Invalid pubkey list.') + util = get_util() + with util.create_handle() as handle: + word_handle = util.call_func( + 'CfdInitializeCombinePubkey', handle.get_handle()) + with JobHandle(handle, word_handle, + 'CfdFreeCombinePubkeyHandle') as key_handle: + for pubkey in pubkey_list: + util.call_func( + 'CfdAddCombinePubkey', + handle.get_handle(), key_handle.get_handle(), + to_hex_string(pubkey)) + + _key = util.call_func( + 'CfdFinalizeCombinePubkey', + handle.get_handle(), key_handle.get_handle()) + return Pubkey(_key) + + ## + # @brief constructor. + # @param[in] pubkey pubkey + def __init__(self, pubkey): + self._hex = to_hex_string(pubkey) + # validate + util = get_util() + with util.create_handle() as handle: + util.call_func( + 'CfdCompressPubkey', handle.get_handle(), self._hex) + + ## + # @brief get string. + # @return pubkey hex. + def __str__(self): + return self._hex + + ## + # @brief compress pubkey. + # @return compressed pubkey. + def compress(self): + util = get_util() + with util.create_handle() as handle: + _pubkey = util.call_func( + 'CfdCompressPubkey', handle.get_handle(), self._hex) + return Pubkey(_pubkey) + + ## + # @brief uncompress pubkey. + # @return uncompressed pubkey. + def uncompress(self): + util = get_util() + with util.create_handle() as handle: + _pubkey = util.call_func( + 'CfdUncompressPubkey', handle.get_handle(), self._hex) + return Pubkey(_pubkey) + + ## + # @brief add tweak. + # @param[in] tweak tweak bytes. (32 byte) + # @return tweaked public key + def add_tweak(self, tweak): + _tweak = to_hex_string(tweak) + util = get_util() + with util.create_handle() as handle: + _pubkey = util.call_func( + 'CfdPubkeyTweakAdd', handle.get_handle(), + self._hex, _tweak) + return Pubkey(_pubkey) + + ## + # @brief mul tweak. + # @param[in] tweak tweak bytes. (32 byte) + # @return tweaked public key + def mul_tweak(self, tweak): + _tweak = to_hex_string(tweak) + util = get_util() + with util.create_handle() as handle: + _pubkey = util.call_func( + 'CfdPubkeyTweakMul', handle.get_handle(), + self._hex, _tweak) + return Pubkey(_pubkey) + + ## + # @brief negate. + # @return negated public key + def negate(self): + util = get_util() + with util.create_handle() as handle: + _pubkey = util.call_func( + 'CfdNegatePubkey', handle.get_handle(), self._hex) + return Pubkey(_pubkey) + + ## + # @brief verify ec-signature. + # @param[in] sighash sighash + # @param[in] signature signature + # @retval True Verify success. + # @retval False Verify fail. + def verify_ec_signature(self, sighash, signature): + try: + util = get_util() + with util.create_handle() as handle: + util.call_func( + 'CfdVerifyEcSignature', handle.get_handle(), + sighash, self._hex, signature) + return True + except CfdError as err: + if err.error_code == CfdErrorCode.SIGN_VERIFICATION.value: + return False + else: + raise err + + +## +# @class SignParameter +# @brief sign parameter container. +class SignParameter: + ## + # @var hex + # hex data + ## + # @var related_pubkey + # related pubkey for multisig + ## + # @var sighashtype + # sighash type + ## + # @var use_der_encode + # use der encode. + + ## + # @brief encode signature to der. + # @param[in] signature signature + # @param[in] sighashtype sighash type + # @return der encoded signature + @classmethod + def encode_by_der(cls, signature, sighashtype=SigHashType.ALL): + _signature = to_hex_string(signature) + _sighashtype = SigHashType.get(sighashtype) + util = get_util() + with util.create_handle() as handle: + der_signature = util.call_func( + 'CfdEncodeSignatureByDer', handle.get_handle(), + _signature, _sighashtype.get_type(), + _sighashtype.anyone_can_pay()) + return SignParameter(der_signature, '', _sighashtype) + + ## + # @brief decode signature from der. + # @param[in] signature signature + # @return der decoded signature + @classmethod + def decode_from_der(cls, signature): + der_signature = to_hex_string(signature) + util = get_util() + with util.create_handle() as handle: + _signature, sighashtype, anyone_can_pay = util.call_func( + 'CfdDecodeSignatureFromDer', handle.get_handle(), + der_signature) + _sighashtype = SigHashType.get(sighashtype, anyone_can_pay) + return SignParameter(_signature, '', _sighashtype) + + ## + # @brief normalize signature. + # @param[in] signature signature + # @return normalized signature + @classmethod + def normalize(cls, signature): + _signature = to_hex_string(signature) + _sighashtype = SigHashType.ALL + if isinstance(signature, SignParameter): + _sighashtype = signature.sighashtype + util = get_util() + with util.create_handle() as handle: + normalize_sig = util.call_func( + 'CfdNormalizeSignature', handle.get_handle(), _signature) + return SignParameter(normalize_sig, '', _sighashtype) + + ## + # @brief constructor. + # @param[in] data sign data + # @param[in] related_pubkey related_pubkey + # @param[in] sighashtype sighash type + # @param[in] use_der_encode use der encode + def __init__(self, data, related_pubkey='', + sighashtype=SigHashType.ALL, use_der_encode=False): + self.hex = to_hex_string(data) + self.related_pubkey = related_pubkey + self.sighashtype = SigHashType.get(sighashtype) + self.use_der_encode = use_der_encode + + ## + # @brief get string. + # @return sing data hex. + def __str__(self): + return self.hex + + ## + # @brief set der encode flag. + # @return void + def set_der_encode(self): + self.use_der_encode = True + + +## +# @class EcdsaAdaptor +# @brief Ecdsa adaptor. +class EcdsaAdaptor: + ## + # @brief sign. + # @param[in] message message (byte or string) + # @param[in] secret_key secret key + # @param[in] adaptor adaptor bytes + # @param[in] is_message_hashed message is hashed byte. + # @retval result[0] adaptor signature + # @retval result[1] adaptor proof + @classmethod + def sign(cls, message, secret_key, adaptor, + is_message_hashed=True): + msg = message + if (not is_message_hashed) and isinstance(message, str): + m = hashlib.sha256() + m.update(message.encode('utf-8')) + msg = m.hexdigest() + _msg = to_hex_string(msg) + _sk = to_hex_string(secret_key) + _adaptor = to_hex_string(adaptor) + util = get_util() + with util.create_handle() as handle: + signature, proof = util.call_func( + 'CfdSignEcdsaAdaptor', handle.get_handle(), + _msg, _sk, _adaptor) + return signature, proof + + ## + # @brief adapt. + # @param[in] adaptor_signature adaptor signature + # @param[in] adaptor_secret adaptor secret key + # @return adapted signature + @classmethod + def adapt(cls, adaptor_signature, adaptor_secret): + _sig = to_hex_string(adaptor_signature) + _sk = to_hex_string(adaptor_secret) + util = get_util() + with util.create_handle() as handle: + signature = util.call_func( + 'CfdAdaptEcdsaAdaptor', handle.get_handle(), _sig, _sk) + return signature + + ## + # @brief extract secret. + # @param[in] adaptor_signature adaptor signature + # @param[in] signature signature + # @param[in] adaptor adaptor bytes + # @return adaptor secret key + @classmethod + def extract_secret(cls, adaptor_signature, signature, adaptor): + _adaptor_signature = to_hex_string(adaptor_signature) + _signature = to_hex_string(signature) + _adaptor = to_hex_string(adaptor) + util = get_util() + with util.create_handle() as handle: + adaptor_secret = util.call_func( + 'CfdExtractEcdsaAdaptorSecret', handle.get_handle(), + _adaptor_signature, _signature, _adaptor) + return Privkey(hex=adaptor_secret) + + ## + # @brief verify. + # @param[in] adaptor_signature adaptor signature + # @param[in] proof adaptor proof + # @param[in] adaptor adaptor bytes + # @param[in] message message (byte or string) + # @param[in] pubkey public key + # @param[in] is_message_hashed message is hashed byte. + # @retval True Verify success. + # @retval False Verify fail. + @classmethod + def verify(cls, adaptor_signature, proof, adaptor, message, pubkey, + is_message_hashed=True): + msg = message + if (not is_message_hashed) and isinstance(message, str): + m = hashlib.sha256() + m.update(message.encode('utf-8')) + msg = m.hexdigest() + _msg = to_hex_string(msg) + _adaptor_signature = to_hex_string(adaptor_signature) + _proof = to_hex_string(proof) + _adaptor = to_hex_string(adaptor) + _pk = to_hex_string(pubkey) + util = get_util() + with util.create_handle() as handle: + try: + util.call_func( + 'CfdVerifyEcdsaAdaptor', handle.get_handle(), + _adaptor_signature, _proof, _adaptor, _msg, _pk) + return True + except CfdError as err: + if err.error_code == CfdErrorCode.SIGN_VERIFICATION.value: + return False + else: + raise err + + +## +# @class SchnorrPubkey +# @brief Schnorr public key. +class SchnorrPubkey: + ## + # @var hex + # hex data + + ## + # @brief create SchnorrPubkey from privkey. + # @param[in] privkey private key + # @retval [0] SchnorrPubkey + # @retval [1] parity flag + @classmethod + def from_privkey(cls, privkey): + if isinstance(privkey, Privkey): + _privkey = privkey.hex + elif isinstance(privkey, str) and (len(privkey) != 64): + _sk = Privkey(wif=privkey) + _privkey = _sk.hex + else: + _privkey = to_hex_string(privkey) + util = get_util() + with util.create_handle() as handle: + pubkey, parity = util.call_func( + 'CfdGetSchnorrPubkeyFromPrivkey', handle.get_handle(), + _privkey) + return SchnorrPubkey(pubkey), parity + + ## + # @brief create SchnorrPubkey from pubkey. + # @param[in] pubkey public key + # @retval [0] SchnorrPubkey + # @retval [1] parity flag + @classmethod + def from_pubkey(cls, pubkey): + _pubkey = to_hex_string(pubkey) + util = get_util() + with util.create_handle() as handle: + schnorr_pubkey, parity = util.call_func( + 'CfdGetSchnorrPubkeyFromPubkey', handle.get_handle(), + _pubkey) + return SchnorrPubkey(schnorr_pubkey), parity + + ## + # @brief add tweak from privkey. + # @param[in] privkey private key + # @param[in] tweak tweak data + # @retval [0] tweaked SchnorrPubkey + # @retval [1] tweaked parity flag + # @retval [2] tweaked Privkey + @classmethod + def add_tweak_from_privkey(cls, privkey, tweak): + if isinstance(privkey, Privkey): + _privkey = privkey.hex + elif isinstance(privkey, str) and (len(privkey) != 64): + _sk = Privkey(wif=privkey) + _privkey = _sk.hex + else: + _privkey = to_hex_string(privkey) + _tweak = to_hex_string(tweak) + util = get_util() + with util.create_handle() as handle: + pubkey, parity, tweaked_privkey = util.call_func( + 'CfdSchnorrKeyPairTweakAdd', handle.get_handle(), + _privkey, _tweak) + return SchnorrPubkey(pubkey), parity, Privkey.from_hex( + tweaked_privkey) + + ## + # @brief constructor. + # @param[in] data pubkey data + def __init__(self, data): + self.hex = to_hex_string(data) + if len(self.hex) != 64: + raise CfdError( + error_code=1, message='Error: Invalid schnorr pubkey.') + + ## + # @brief get string. + # @return pubkey hex. + def __str__(self): + return self.hex + + ## + # @brief add tweak. + # @param[in] tweak tweak data + # @retval [0] tweaked SchnorrPubkey + # @retval [1] tweaked parity flag + def add_tweak(self, tweak): + _tweak = to_hex_string(tweak) + util = get_util() + with util.create_handle() as handle: + schnorr_pubkey, parity = util.call_func( + 'CfdSchnorrPubkeyTweakAdd', handle.get_handle(), + self.hex, _tweak) + return SchnorrPubkey(schnorr_pubkey), parity + + ## + # @brief check tweakAdd from base pubkey. + # @param[in] tweaked_parity tweaked parity flag. + # @param[in] base_pubkey base pubkey + # @param[in] tweak tweak data + # @retval True tweaked pubkey from base pubkey. + # @retval False other. + def is_tweaked(self, tweaked_parity, base_pubkey, tweak): + _base_pubkey = to_hex_string(base_pubkey) + _tweak = to_hex_string(tweak) + try: + util = get_util() + with util.create_handle() as handle: + util.call_func( + 'CfdCheckTweakAddFromSchnorrPubkey', handle.get_handle(), + self.hex, tweaked_parity, _base_pubkey, _tweak) + return True + except CfdError as err: + if err.error_code == CfdErrorCode.SIGN_VERIFICATION.value: + return False + else: + raise err + + +## +# @class SchnorrSignature +# @brief Schnorr signature. +class SchnorrSignature: + ## + # @var signature + # signature data + ## + # @var nonce + # nonce data + ## + # @var key + # key data + + ## + # @brief constructor. + # @param[in] signature signature + def __init__(self, signature): + self.signature = to_hex_string(signature) + util = get_util() + with util.create_handle() as handle: + self.nonce, self.key = util.call_func( + 'CfdSplitSchnorrSignature', handle.get_handle(), + self.signature) + self.nonce = SchnorrPubkey(self.nonce) + self.key = Privkey(hex=self.key) + + ## + # @brief get string. + # @return signature hex. + def __str__(self): + return self.signature + + +## +# @class SchnorrUtil +# @brief Schnorr utility. +class SchnorrUtil: + ## + # @brief sign. + # @param[in] message message (byte or string) + # @param[in] secret_key secret key + # @param[in] aux_rand random bytes + # @param[in] nonce nonce bytes + # @param[in] is_message_hashed message is hashed byte. + # @return signature + @classmethod + def sign(cls, message, secret_key, aux_rand='', nonce='', + is_message_hashed=True): + msg = message + if (not is_message_hashed) and isinstance(message, str): + m = hashlib.sha256() + m.update(message.encode('utf-8')) + msg = m.hexdigest() + _msg = to_hex_string(msg) + _sk = to_hex_string(secret_key) + _rand = to_hex_string(aux_rand) + _nonce = to_hex_string(nonce) + util = get_util() + with util.create_handle() as handle: + if _nonce != '': + signature = util.call_func( + 'CfdSignSchnorrWithNonce', handle.get_handle(), + _msg, _sk, _nonce) + else: + signature = util.call_func( + 'CfdSignSchnorr', handle.get_handle(), _msg, _sk, _rand) + return SchnorrSignature(signature) + + ## + # @brief compute sigpoint. + # @param[in] message message (byte or string) + # @param[in] nonce nonce bytes + # @param[in] pubkey public key + # @param[in] is_message_hashed message is hashed byte. + # @return signature + @classmethod + def compute_sig_point(cls, message, nonce, pubkey, + is_message_hashed=True): + msg = message + if (not is_message_hashed) and isinstance(message, str): + m = hashlib.sha256() + m.update(message.encode('utf-8')) + msg = m.hexdigest() + _msg = to_hex_string(msg) + _nonce = to_hex_string(nonce) + _pubkey = to_hex_string(pubkey) + util = get_util() + with util.create_handle() as handle: + sig_point = util.call_func( + 'CfdComputeSchnorrSigPoint', handle.get_handle(), + _msg, _nonce, _pubkey) + return Pubkey(sig_point) + + ## + # @brief verify. + # @param[in] signature signature + # @param[in] message message (byte or string) + # @param[in] pubkey public key + # @param[in] is_message_hashed message is hashed byte. + # @retval True Verify success. + # @retval False Verify fail. + @classmethod + def verify(cls, signature, message, pubkey, + is_message_hashed=True): + msg = message + if (not is_message_hashed) and isinstance(message, str): + m = hashlib.sha256() + m.update(message.encode('utf-8')) + msg = m.hexdigest() + _msg = to_hex_string(msg) + _signature = to_hex_string(signature) + _pk = to_hex_string(pubkey) + util = get_util() + with util.create_handle() as handle: + try: + util.call_func( + 'CfdVerifySchnorr', handle.get_handle(), + _signature, _msg, _pk) + return True + except CfdError as err: + if err.error_code == CfdErrorCode.SIGN_VERIFICATION.value: + return False + else: + raise err + + +## +# All import target. +__all__ = [ + 'Network', + 'SigHashType', + 'Privkey', + 'Pubkey', + 'SignParameter', + 'EcdsaAdaptor', + 'SchnorrPubkey', + 'SchnorrSignature', + 'SchnorrUtil' +] diff --git a/cfd/script.py b/cfd/script.py new file mode 100644 index 0000000..43c0fbf --- /dev/null +++ b/cfd/script.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +## +# @file script.py +# @brief bitcoin script function implements file. +# @note Copyright 2020 CryptoGarage +from .util import CfdError, to_hex_string, get_util, JobHandle +from .key import SignParameter, SigHashType +from enum import Enum + + +## +# @class HashType +# @brief Hash Type +class HashType(Enum): + ## + # HashType: p2sh + P2SH = 1 + ## + # HashType: p2pkh + P2PKH = 2 + ## + # HashType: p2wsh + P2WSH = 3 + ## + # HashType: p2wpkh + P2WPKH = 4 + ## + # HashType: p2sh-p2wsh + P2SH_P2WSH = 5 + ## + # HashType: p2sh-p2wpkh + P2SH_P2WPKH = 6 + + ## + # @brief get string. + # @return name. + def __str__(self): + return self.name.lower().replace('_', '-') + + ## + # @brief get string. + # @return name. + def as_str(self): + return self.name.lower().replace('_', '-') + + ## + # @brief get object. + # @param[in] hashtype hashtype + # @return object + @classmethod + def get(cls, hashtype): + if (isinstance(hashtype, HashType)): + return hashtype + elif (isinstance(hashtype, int)): + _num = int(hashtype) + for hash_type in HashType: + if _num == hash_type.value: + return hash_type + else: + _hash_type = str(hashtype).lower() + for hash_type in HashType: + if _hash_type == hash_type.name.lower(): + return hash_type + if _hash_type == 'p2sh-p2wsh': + return HashType.P2SH_P2WSH + elif _hash_type == 'p2sh-p2wpkh': + return HashType.P2SH_P2WPKH + raise CfdError( + error_code=1, + message='Error: Invalid hash type: {}'.format(hashtype)) + + +## +# @class Script +# @brief Script +class Script: + ## + # @var hex + # script hex + ## + # @var asm + # asm + + ## + # @brief get script from asm. + # @param[in] script_items asm strings (list or string) + # @return script object + @classmethod + def from_asm(cls, script_items): + _asm = script_items + if isinstance(script_items, list): + _asm = ' '.join(script_items) + if len(_asm) == 0: + raise CfdError( + error_code=1, + message='Error: empty script items.') + util = get_util() + with util.create_handle() as handle: + _hex = util.call_func( + 'CfdConvertScriptAsmToHex', handle.get_handle(), _asm) + return Script(_hex) + + ## + # @brief create multisig scriptsig. + # @param[in] redeem_script multisig script + # @param[in] sign_parameter_list signature list + # @return script object + @classmethod + def create_multisig_scriptsig(cls, redeem_script, sign_parameter_list): + _script = to_hex_string(redeem_script) + util = get_util() + with util.create_handle() as handle: + word_handle = util.call_func( + 'CfdInitializeMultisigScriptSig', handle.get_handle()) + with JobHandle( + handle, + word_handle, + 'CfdFreeMultisigScriptSigHandle') as script_handle: + for param in sign_parameter_list: + if isinstance(param, SignParameter) is False: + raise CfdError( + error_code=1, + message='Error: Invalid sign_parameter_list item.') + if (len(param.hex) <= 130) and param.use_der_encode: + _sighashtype = SigHashType.get(param.sighashtype) + util.call_func( + 'CfdAddMultisigScriptSigDataToDer', + handle.get_handle(), script_handle.get_handle(), + param.hex, _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), + param.related_pubkey) + else: + util.call_func( + 'CfdAddMultisigScriptSigData', + handle.get_handle(), script_handle.get_handle(), + param.hex, param.related_pubkey) + scriptsig = util.call_func( + 'CfdFinalizeMultisigScriptSig', + handle.get_handle(), script_handle.get_handle(), + _script) + return Script(scriptsig) + + ## + # @brief constructor. + # @param[in] script script + def __init__(self, script): + self.hex = to_hex_string(script) + self.asm = Script._parse(self.hex) + + ## + # @brief get string. + # @return script hex. + def __str__(self): + return self.hex + + ## + # @brief create multisig scriptsig. + # @param[in] script script + # @return script asm + @classmethod + def _parse(cls, script): + util = get_util() + script_list = [] + with util.create_handle() as handle: + word_handle, max_index = util.call_func( + 'CfdParseScript', handle.get_handle(), script) + with JobHandle( + handle, + word_handle, + 'CfdFreeScriptItemHandle') as script_handle: + for i in range(max_index): + item = util.call_func( + 'CfdGetScriptItem', + handle.get_handle(), script_handle.get_handle(), i) + script_list.append(item) + return ' '.join(script_list) + + +## +# All import target. +__all__ = [ + 'Script', + 'HashType' +] diff --git a/cfd/transaction.py b/cfd/transaction.py new file mode 100644 index 0000000..761061f --- /dev/null +++ b/cfd/transaction.py @@ -0,0 +1,1175 @@ +# -*- coding: utf-8 -*- +## +# @file transaction.py +# @brief transaction function implements file. +# @note Copyright 2020 CryptoGarage +from .util import get_util, JobHandle, CfdError, to_hex_string,\ + CfdErrorCode, ReverseByteData, ByteData +from .address import Address, AddressUtil +from .key import Network, SigHashType, SignParameter, Privkey +from .script import HashType +from enum import Enum +import ctypes +import copy + + +## +# @class Txid +# @brief Txid class. +class Txid(ReverseByteData): + ## + # @brief constructor. + # @param[in] txid txid + def __init__(self, txid): + super().__init__(txid) + if len(self.hex) != 64: + raise CfdError( + error_code=1, message='Error: Invalid txid.') + + +## +# @class OutPoint +# @brief OutPoint class. +class OutPoint: + ## + # @var txid + # txid + ## + # @var vout + # vout + + ## + # @brief constructor. + # @param[in] txid txid + # @param[in] vout vout + def __init__(self, txid, vout): + self.txid = Txid(txid) + self.vout = vout + if isinstance(vout, int) is False: + raise CfdError( + error_code=1, + message='Error: Invalid vout type.') + + ## + # @brief get string. + # @return txid. + def __str__(self): + return '{},{}'.format(str(self.txid), self.vout) + + ## + # @brief equal method. + # @param[in] other other object. + # @return true or false. + def __eq__(self, other): + if not isinstance(other, OutPoint): + return NotImplemented + return (self.txid.hex == other.txid.hex) and ( + self.vout == other.vout) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __lt__(self, other): + if not isinstance(other, OutPoint): + return NotImplemented + return (self.txid.hex, self.vout) < (other.txid.hex, other.vout) + + ## + # @brief equal method. + # @param[in] other other object. + # @return true or false. + def __ne__(self, other): + return not self.__eq__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __le__(self, other): + return self.__lt__(other) or self.__eq__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __gt__(self, other): + return not self.__le__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __ge__(self, other): + return not self.__lt__(other) + + +## +# @class UtxoData +# @brief UtxoData class. +class UtxoData: + ## + # @var outpoint + # outpoint + ## + # @var amount + # amount + ## + # @var descriptor + # descriptor + ## + # @var scriptsig_template + # scriptsig template + + ## + # @brief constructor. + # @param[in] outpoint outpoint + # @param[in] txid txid + # @param[in] vout vout + # @param[in] amount amount + # @param[in] descriptor descriptor + # @param[in] scriptsig_template scriptsig template + def __init__( + self, outpoint=None, txid='', vout=0, + amount=0, descriptor='', scriptsig_template=''): + if isinstance(outpoint, OutPoint): + self.outpoint = outpoint + else: + self.outpoint = OutPoint(txid, vout) + self.amount = amount + self.descriptor = descriptor + self.scriptsig_template = scriptsig_template + + ## + # @brief get string. + # @return hex. + def __str__(self): + return str(self.outpoint) + + ## + # @brief equal method. + # @param[in] other other object. + # @return true or false. + def __eq__(self, other): + if not isinstance(other, UtxoData): + return NotImplemented + return self.outpoint == other.outpoint + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __lt__(self, other): + if not isinstance(other, UtxoData): + return NotImplemented + return (self.outpoint) < (other.outpoint) + + ## + # @brief equal method. + # @param[in] other other object. + # @return true or false. + def __ne__(self, other): + return not self.__eq__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __le__(self, other): + return self.__lt__(other) or self.__eq__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __gt__(self, other): + return not self.__le__(other) + + ## + # @brief diff method. + # @param[in] other other object. + # @return true or false. + def __ge__(self, other): + return not self.__lt__(other) + + +## +# @class TxIn +# @brief Transacton input. +class TxIn: + ## + # @var outpoint + # outpoint + ## + # @var sequence + # sequence + ## + # @var script_sig + # script sig + ## + # @var witness_stack + # witness stack + + ## + # sequence disable. + SEQUENCE_DISABLE = 0xffffffff + ## + # sequence final. + SEQUENCE_FINAL = 0xfffffffe + + ## + # @brief get sequence number. + # @param[in] locktime locktime + # @param[in] sequence sequence + # @return sequence number. + @classmethod + def get_sequence_number(cls, locktime=0, sequence=SEQUENCE_DISABLE): + if sequence not in [-1, TxIn.SEQUENCE_DISABLE]: + return sequence + elif locktime == 0: + return TxIn.SEQUENCE_DISABLE + else: + return TxIn.SEQUENCE_FINAL + + ## + # @brief constructor. + # @param[in] outpoint outpoint + # @param[in] txid txid + # @param[in] vout vout + # @param[in] sequence sequence + def __init__(self, outpoint=None, txid='', vout=0, + sequence=SEQUENCE_DISABLE): + if isinstance(outpoint, OutPoint): + self.outpoint = outpoint + else: + self.outpoint = OutPoint(txid=txid, vout=vout) + self.sequence = sequence + self.script_sig = '' + self.witness_stack = [] + + ## + # @brief get string. + # @return hex. + def __str__(self): + return str(self.outpoint) + + +## +# @class TxOut +# @brief Transacton output. +class TxOut: + ## + # @var amount + # amount + ## + # @var address + # address + ## + # @var locking_script + # locking script + + ## + # @brief constructor. + # @param[in] amount amount + # @param[in] address address + # @param[in] locking_script locking script + def __init__(self, amount, address='', locking_script=''): + self.amount = amount + if address != '': + self.address = address + self.locking_script = '' + else: + self.locking_script = locking_script + self.address = '' + + ## + # @brief constructor. + # @param[in] network network + # @return address. + def get_address(self, network=Network.MAINNET): + if isinstance(self.address, Address): + return self.address + if self.address != '': + return AddressUtil.parse(self.address) + return AddressUtil.from_locking_script(self.locking_script, network) + + ## + # @brief get string. + # @return address or script. + def __str__(self): + if (self.address != ''): + return str(self.address) + else: + return str(self.locking_script) + + +## +# @class _TransactionBase +# @brief Transacton base. +class _TransactionBase: + ## + # @var hex + # transaction hex string + ## + # @var network + # transaction network type + ## + # @var enable_cache + # use transaction cache + + ## + # @brief constructor. + # @param[in] hex transaction hex + # @param[in] network network + # @param[in] enable_cache enable_cache + def __init__(self, hex, network, enable_cache=True): + self.hex = to_hex_string(hex) + self.enable_cache = enable_cache + self.network = network + + ## + # @brief get string. + # @return tx hex. + def __str__(self): + return self.hex + + ## + # @brief update transaction cache all. + # @return void + def _update_tx_all(self): + if self.enable_cache: + self.get_tx_all() + + ## + # @brief get transaction input. + # @param[in] handle cfd handle + # @param[in] tx_handle tx handle + # @param[in] index index + # @param[in] outpoint outpoint + # @retval [0] txin + # @retval [1] index + def _get_txin(self, handle, tx_handle, index=0, outpoint=None): + util = get_util() + + if isinstance(outpoint, OutPoint): + index = util.call_func( + 'CfdGetTxInIndexByHandle', handle.get_handle(), + tx_handle.get_handle(), str(outpoint.txid), + outpoint.vout) + + txid, vout, seq, script = util.call_func( + 'CfdGetTxInByHandle', handle.get_handle(), + tx_handle.get_handle(), index) + txin = TxIn(txid=txid, vout=vout, sequence=seq) + txin.script_sig = script + + txin.witness_stack = [] + _count = util.call_func( + 'CfdGetTxInWitnessCountByHandle', handle.get_handle(), + tx_handle.get_handle(), 0, index) + for i in range(_count): + data = util.call_func( + 'CfdGetTxInWitnessByHandle', handle.get_handle(), + tx_handle.get_handle(), 0, index, i) + txin.witness_stack.append(data) + return txin, index + + ## + # @brief get transaction input index. + # @param[in] outpoint outpoint + # @param[in] txid txid + # @param[in] vout vout + # @return index + def get_txin_index(self, outpoint=None, txid='', vout=0): + txin = TxIn(outpoint=outpoint, txid=txid, vout=vout) + util = get_util() + with util.create_handle() as handle: + index = util.call_func( + 'CfdGetTxInIndex', handle.get_handle(), + self.network, self.hex, str(txin.outpoint.txid), + txin.outpoint.vout) + return index + + ## + # @brief get transaction output index. + # @param[in] address address + # @param[in] locking_script locking_script + # @return index + def get_txout_index(self, address='', locking_script=''): + # get first target only. + _script = to_hex_string(locking_script) + util = get_util() + with util.create_handle() as handle: + index = util.call_func( + 'CfdGetTxOutIndex', handle.get_handle(), + self.network, self.hex, str(address), _script) + return index + + ## + # @brief add pubkey hash sign. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] pubkey pubkey + # @param[in] signature signature + # @param[in] sighashtype sighash type + # @return void + def add_pubkey_hash_sign( + self, outpoint, hash_type, pubkey, signature, + sighashtype=SigHashType.ALL): + _hash_type = HashType.get(hash_type) + _pubkey = to_hex_string(pubkey) + _signature = to_hex_string(signature) + _sighashtype = SigHashType.get(sighashtype) + if isinstance(signature, SignParameter) and ( + _sighashtype == SigHashType.ALL): + _sighashtype = SigHashType.get(signature.sighashtype) + use_der_encode = (len(_signature) <= 130) is True + util = get_util() + with util.create_handle() as handle: + self.hex = util.call_func( + 'CfdAddPubkeyHashSign', handle.get_handle(), + self.network, self.hex, str(outpoint.txid), + outpoint.vout, _hash_type.value, _pubkey, + _signature, use_der_encode, _sighashtype.get_type(), + _sighashtype.anyone_can_pay()) + self._update_txin(outpoint) + + ## + # @brief add multisig sign. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] redeem_script redeem script + # @param[in] signature_list signature list + # @return void + def add_multisig_sign( + self, outpoint, hash_type, redeem_script, + signature_list): + if (isinstance(signature_list, list) is False) or ( + len(signature_list) == 0): + raise CfdError( + error_code=1, message='Error: Invalid signature_list.') + _hash_type = HashType.get(hash_type) + _script = to_hex_string(redeem_script) + util = get_util() + with util.create_handle() as handle: + word_handle = util.call_func( + 'CfdInitializeMultisigSign', handle.get_handle()) + with JobHandle(handle, word_handle, + 'CfdFreeMultisigSignHandle') as tx_handle: + for sig in signature_list: + _sig = to_hex_string(sig) + _sighashtype = SigHashType.ALL + _related_pubkey = '' + use_der = (len(_sig) in [128, 130]) + if isinstance(sig, SignParameter): + _sighashtype = SigHashType.get(sig.sighashtype) + _related_pubkey = to_hex_string(sig.related_pubkey) + use_der = sig.use_der_encode + elif use_der: + raise CfdError( + error_code=1, message='Error: Invalid signature.') + + if use_der: + util.call_func( + 'CfdAddMultisigSignDataToDer', + handle.get_handle(), tx_handle.get_handle(), + _sig, _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), _related_pubkey) + else: + util.call_func( + 'CfdAddMultisigSignData', + handle.get_handle(), tx_handle.get_handle(), + _sig, _related_pubkey) + + self.hex = util.call_func( + 'CfdFinalizeMultisigSign', + handle.get_handle(), tx_handle.get_handle(), + self.network, self.hex, str(outpoint.txid), + outpoint.vout, _hash_type.value, _script) + self._update_txin(outpoint) + + ## + # @brief add script hash sign. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] redeem_script redeem script + # @param[in] signature_list signature list + # @return void + def add_script_hash_sign( + self, outpoint, hash_type, redeem_script, + signature_list): + if (isinstance(signature_list, list) is False) or ( + len(signature_list) == 0): + raise CfdError( + error_code=1, message='Error: Invalid signature_list.') + _hash_type = HashType.get(hash_type) + _script = to_hex_string(redeem_script) + util = get_util() + with util.create_handle() as handle: + clear_stack = True + for sig in signature_list: + _sig = sig + if not isinstance(sig, str): + _sig = to_hex_string(sig) + _sighashtype = SigHashType.ALL + use_der_encode = False + if isinstance(sig, SignParameter): + _sighashtype = SigHashType.get(sig.sighashtype) + use_der_encode = sig.use_der_encode + + self.hex = util.call_func( + 'CfdAddTxSign', handle.get_handle(), + self.network, self.hex, str(outpoint.txid), + outpoint.vout, _hash_type.value, _sig, + use_der_encode, _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), clear_stack) + clear_stack = False + + self.hex = util.call_func( + 'CfdAddScriptHashSign', + handle.get_handle(), self.network, self.hex, + str(outpoint.txid), outpoint.vout, _hash_type.value, + _script, False) + self._update_txin(outpoint) + + ## + # @brief add sign. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] sign_data sign data + # @param[in] clear_stack clear stack + # @param[in] use_der_encode use der encode + # @param[in] sighashtype sighash type + # @return void + def add_sign( + self, outpoint, hash_type, sign_data, + clear_stack=False, use_der_encode=False, + sighashtype=SigHashType.ALL): + _hash_type = HashType.get(hash_type) + _sign_data = sign_data + if not isinstance(sign_data, str): + _sign_data = to_hex_string(sign_data) + _sighashtype = SigHashType.get(sighashtype) + util = get_util() + with util.create_handle() as handle: + self.hex = util.call_func( + 'CfdAddTxSign', handle.get_handle(), + self.network, self.hex, str(outpoint.txid), + outpoint.vout, _hash_type.value, _sign_data, + use_der_encode, _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), clear_stack) + self._update_txin(outpoint) + + +## +# @class Transaction +# @brief Bitcoin Transacton. +class Transaction(_TransactionBase): + ## + # @var hex + # transaction hex string + ## + # @var txin_list + # transaction input list + ## + # @var txout_list + # transaction output list + ## + # @var txid + # txid + ## + # @var wtxid + # wtxid + ## + # @var size + # transaction size + ## + # @var vsize + # transaction vsize + ## + # @var weight + # transaction size weight + ## + # @var version + # version + ## + # @var locktime + # locktime + + ## + # bitcoin network value. + NETWORK = Network.MAINNET.value + ## + # transaction's free function name. + FREE_FUNC_NAME = 'CfdFreeTransactionHandle' + + ## + # @brief parse transaction to json. + # @param[in] hex transaction hex + # @param[in] network network + # @return json string + @classmethod + def parse_to_json(cls, hex, network=Network.MAINNET): + _network = Network.get(network) + network_str = 'mainnet' + if _network == Network.TESTNET: + network_str = 'testnet' + elif _network == Network.REGTEST: + network_str = 'regtest' + request_json = '{{"hex":"{}","network":"{}"}}'.format(hex, network_str) + util = get_util() + with util.create_handle() as handle: + return util.call_func( + 'CfdRequestExecuteJson', handle.get_handle(), + 'DecodeRawTransaction', request_json) + + ## + # @brief create transaction. + # @param[in] version version + # @param[in] locktime locktime + # @param[in] txins txin list + # @param[in] txouts txout list + # @param[in] enable_cache enable tx cache + # @return transaction object + @classmethod + def create(cls, version, locktime, txins, txouts, enable_cache=True): + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTransaction', handle.get_handle(), + cls.NETWORK, version, locktime, '') + with JobHandle( + handle, _tx_handle, cls.FREE_FUNC_NAME) as tx_handle: + for txin in txins: + sec = TxIn.get_sequence_number(locktime, txin.sequence) + util.call_func( + 'CfdAddTransactionInput', handle.get_handle(), + tx_handle.get_handle(), str(txin.outpoint.txid), + txin.outpoint.vout, sec) + for txout in txouts: + util.call_func( + 'CfdAddTransactionOutput', handle.get_handle(), + tx_handle.get_handle(), txout.amount, + str(txout.address), + str(txout.locking_script), '') + hex = util.call_func( + 'CfdFinalizeTransaction', handle.get_handle(), + tx_handle.get_handle()) + return Transaction(hex, enable_cache) + + ## + # @brief get transaction from hex. + # @param[in] hex tx hex + # @param[in] enable_cache enable tx cache + # @return transaction object + @classmethod + def from_hex(cls, hex, enable_cache=True): + return Transaction(hex, enable_cache) + + ## + # @brief constructor. + # @param[in] hex tx hex + # @param[in] enable_cache enable tx cache + def __init__(self, hex, enable_cache=True): + super().__init__(hex, self.NETWORK, enable_cache) + self.txin_list = [] + self.txout_list = [] + self._update_tx_all() + + ## + # @brief update transaction information. + # @return void + def _update_info(self): + if self.enable_cache is False: + return + util = get_util() + with util.create_handle() as handle: + ret = util.call_func( + 'CfdGetTxInfo', handle.get_handle(), + self.NETWORK, self.hex) + # for doxygen + self.txid = Txid(ret[0]) + self.wtxid = Txid(ret[1]) + self.size = ret[2] + self.vsize = ret[3] + self.weight = ret[4] + self.version = ret[5] + self.locktime = ret[6] + + ## + # @brief update transaction input. + # @param[in] outpoint outpoint + # @return void + def _update_txin(self, outpoint): + if self.enable_cache is False: + return + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTxDataHandle', handle.get_handle(), + self.NETWORK, self.hex) + with JobHandle(handle, _tx_handle, + self.FREE_FUNC_NAME) as tx_handle: + self.txid, self.wtxid, self.size, self.vsize, self.weight,\ + self.version, self.locktime = util.call_func( + 'CfdGetTxInfoByHandle', handle.get_handle(), + tx_handle.get_handle()) + self.txid = Txid(self.txid) + self.wtxid = Txid(self.wtxid) + # update txin + txin, index = self._get_txin( + handle, tx_handle, outpoint=outpoint) + self.txin_list[index] = txin + + ## + # @brief get transaction all data. + # @retval [0] txin list + # @retval [1] txout list + def get_tx_all(self): + def get_txin_list(handle, tx_handle): + txin_list = [] + _count = util.call_func( + 'CfdGetTxInCountByHandle', handle.get_handle(), + tx_handle.get_handle()) + for i in range(_count): + txin, _ = self._get_txin(handle, tx_handle, i) + txin_list.append(txin) + return txin_list + + def get_txout_list(handle, tx_handle): + txout_list = [] + _count = util.call_func( + 'CfdGetTxOutCountByHandle', handle.get_handle(), + tx_handle.get_handle()) + for i in range(_count): + amount, script, _ = util.call_func( + 'CfdGetTxOutByHandle', handle.get_handle(), + tx_handle.get_handle(), i) + txout = TxOut(amount=amount, locking_script=script) + txout_list.append(txout) + return txout_list + + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTxDataHandle', handle.get_handle(), + self.NETWORK, self.hex) + with JobHandle(handle, _tx_handle, + self.FREE_FUNC_NAME) as tx_handle: + self.txid, self.wtxid, self.size, self.vsize, self.weight,\ + self.version, self.locktime = util.call_func( + 'CfdGetTxInfoByHandle', handle.get_handle(), + tx_handle.get_handle()) + self.txid = Txid(self.txid) + self.wtxid = Txid(self.wtxid) + self.txin_list = get_txin_list(handle, tx_handle) + self.txout_list = get_txout_list(handle, tx_handle) + return self.txin_list, self.txout_list + + ## + # @brief add transaction input. + # @param[in] outpoint outpoint + # @param[in] sequence sequence + # @param[in] txid txid + # @param[in] vout vout + # @return void + def add_txin(self, outpoint=None, sequence=-1, + txid='', vout=0): + sec = TxIn.get_sequence_number(self.locktime, sequence) + txin = TxIn( + outpoint=outpoint, sequence=sec, txid=txid, vout=vout) + self.add([txin], []) + + ## + # @brief add transaction output. + # @param[in] amount amount + # @param[in] address address + # @param[in] locking_script locking script + # @return void + def add_txout(self, amount, address='', locking_script=''): + txout = TxOut(amount, address, locking_script) + self.add([], [txout]) + + ## + # @brief add transaction. + # @param[in] txins txin list + # @param[in] txouts txout list + # @return void + def add(self, txins, txouts): + util = get_util() + with util.create_handle() as handle: + _tx_handle = util.call_func( + 'CfdInitializeTransaction', handle.get_handle(), + self.NETWORK, 0, 0, self.hex) + with JobHandle( + handle, _tx_handle, self.FREE_FUNC_NAME) as tx_handle: + for txin in txins: + sec = TxIn.get_sequence_number( + self.locktime, txin.sequence) + util.call_func( + 'CfdAddTransactionInput', handle.get_handle(), + tx_handle.get_handle(), str(txin.outpoint.txid), + txin.outpoint.vout, sec) + for txout in txouts: + util.call_func( + 'CfdAddTransactionOutput', handle.get_handle(), + tx_handle.get_handle(), txout.amount, + str(txout.address), + str(txout.locking_script), '') + self.hex = util.call_func( + 'CfdFinalizeTransaction', handle.get_handle(), + tx_handle.get_handle()) + self.txid, self.wtxid, self.size, self.vsize, self.weight,\ + self.version, self.locktime = util.call_func( + 'CfdGetTxInfoByHandle', handle.get_handle(), + tx_handle.get_handle()) + self.txid = Txid(self.txid) + self.wtxid = Txid(self.wtxid) + self.txin_list += copy.deepcopy(txins) + self.txout_list += copy.deepcopy(txouts) + + ## + # @brief update transaction output amount. + # @param[in] index index + # @param[in] amount amount + # @return void + def update_txout_amount(self, index, amount): + util = get_util() + with util.create_handle() as handle: + self.hex = util.call_func( + 'CfdUpdateTxOutAmount', handle.get_handle(), + self.NETWORK, self.hex, index, amount) + self._update_info() + self.txout_list[index].amount = amount + + ## + # @brief get signature hash. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] amount amount + # @param[in] pubkey pubkey + # @param[in] redeem_script redeem script + # @param[in] sighashtype sighash type + # @return sighash + def get_sighash( + self, + outpoint, + hash_type, + amount=0, + pubkey='', + redeem_script='', + sighashtype=SigHashType.ALL): + _hash_type = HashType.get(hash_type) + _pubkey = to_hex_string(pubkey) + _script = to_hex_string(redeem_script) + _sighashtype = SigHashType.get(sighashtype) + util = get_util() + with util.create_handle() as handle: + sighash = util.call_func( + 'CfdCreateSighash', handle.get_handle(), + self.NETWORK, self.hex, str(outpoint.txid), + outpoint.vout, _hash_type.value, _pubkey, + _script, amount, _sighashtype.get_type(), + _sighashtype.anyone_can_pay()) + return ByteData(sighash) + + ## + # @brief add sign with private key. + # @param[in] outpoint outpoint + # @param[in] hash_type hash type + # @param[in] privkey privkey + # @param[in] amount amount + # @param[in] sighashtype sighash type + # @param[in] grind_r grind-R flag + # @return void + def sign_with_privkey( + self, + outpoint, + hash_type, + privkey, + amount=0, + sighashtype=SigHashType.ALL, + grind_r=True): + _hash_type = HashType.get(hash_type) + if isinstance(privkey, Privkey): + _privkey = privkey + elif isinstance(privkey, str) and (len(privkey) != 64): + _privkey = Privkey(wif=privkey) + else: + _privkey = Privkey(hex=privkey) + _pubkey = _privkey.pubkey + _sighashtype = SigHashType.get(sighashtype) + util = get_util() + with util.create_handle() as handle: + self.hex = util.call_func( + 'CfdAddSignWithPrivkeySimple', handle.get_handle(), + self.NETWORK, self.hex, str(outpoint.txid), + outpoint.vout, _hash_type.value, str(_pubkey), + str(_privkey), amount, _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), grind_r) + self._update_txin(outpoint) + + ## + # @brief verify sign. + # @param[in] outpoint outpoint + # @param[in] address address + # @param[in] hash_type hash type + # @param[in] amount amount + # @return void + def verify_sign(self, outpoint, address, hash_type, amount): + _hash_type = HashType.get(hash_type) + util = get_util() + with util.create_handle() as handle: + util.call_func( + 'CfdVerifyTxSign', handle.get_handle(), + self.NETWORK, self.hex, str(outpoint.txid), + outpoint.vout, str(address), _hash_type.value, + '', amount, '') + + ## + # @brief verify signature. + # @param[in] outpoint outpoint + # @param[in] signature signature + # @param[in] hash_type hash type + # @param[in] pubkey pubkey + # @param[in] amount amount + # @param[in] redeem_script redeem script + # @param[in] sighashtype sighash type + # @retval True signature valid. + # @retval False signature invalid. + def verify_signature( + self, outpoint, signature, hash_type, pubkey, amount=0, + redeem_script='', sighashtype=SigHashType.ALL): + _signature = to_hex_string(signature) + _pubkey = to_hex_string(pubkey) + _script = to_hex_string(redeem_script) + _hash_type = HashType.get(hash_type) + _sighashtype = SigHashType.get(sighashtype) + try: + util = get_util() + with util.create_handle() as handle: + util.call_func( + 'CfdVerifySignature', handle.get_handle(), + self.NETWORK, self.hex, _signature, _hash_type.value, + _pubkey, _script, str(outpoint.txid), + outpoint.vout, _sighashtype.get_type(), + _sighashtype.anyone_can_pay(), amount, '') + return True + except CfdError as err: + if err.error_code == CfdErrorCode.SIGN_VERIFICATION.value: + return False + else: + raise err + + ## + # @brief select coins. + # @param[in] utxo_list utxo list + # @param[in] tx_fee_amount txout fee amount + # @param[in] target_amount collect target amount + # @param[in] effective_fee_rate effective fee rate + # @param[in] long_term_fee_rate long term fee rate + # @param[in] dust_fee_rate dust fee rate + # @param[in] knapsack_min_change minimum change threshold for knapsack + # @retval [0] select utxo list. + # @retval [1] utxo fee. + # @retval [2] total tx fee. + @classmethod + def select_coins( + cls, utxo_list, tx_fee_amount, target_amount, + effective_fee_rate=20.0, long_term_fee_rate=20.0, + dust_fee_rate=3.0, knapsack_min_change=-1): + if (isinstance(utxo_list, list) is False) or ( + len(utxo_list) == 0): + raise CfdError( + error_code=1, message='Error: Invalid utxo_list.') + util = get_util() + with util.create_handle() as handle: + word_handle = util.call_func( + 'CfdInitializeCoinSelection', handle.get_handle(), + len(utxo_list), 1, '', tx_fee_amount, effective_fee_rate, + long_term_fee_rate, dust_fee_rate, knapsack_min_change) + with JobHandle(handle, word_handle, + 'CfdFreeCoinSelectionHandle') as tx_handle: + for index, utxo in enumerate(utxo_list): + util.call_func( + 'CfdAddCoinSelectionUtxoTemplate', + handle.get_handle(), tx_handle.get_handle(), index, + str(utxo.outpoint.txid), utxo.outpoint.vout, + utxo.amount, '', str(utxo.descriptor), + to_hex_string(utxo.scriptsig_template)) + util.call_func( + 'CfdAddCoinSelectionAmount', + handle.get_handle(), tx_handle.get_handle(), 0, + target_amount, '') + + _utxo_fee = util.call_func( + 'CfdFinalizeCoinSelection', + handle.get_handle(), tx_handle.get_handle()) + + selected_utxo_list = [] + total_amount = 0 + if (target_amount != 0) or (tx_fee_amount != 0): + for i in range(len(utxo_list)): + _utxo_index = util.call_func( + 'CfdGetSelectedCoinIndex', + handle.get_handle(), tx_handle.get_handle(), i) + if _utxo_index < 0: + break + elif _utxo_index < len(utxo_list): + selected_utxo_list.append(utxo_list[_utxo_index]) + total_amount = util.call_func( + 'CfdGetSelectedCoinAssetAmount', + handle.get_handle(), tx_handle.get_handle(), 0) + return selected_utxo_list, _utxo_fee, total_amount + + ## + # @brief estimate fee. + # @param[in] utxo_list txin utxo list + # @param[in] fee_rate fee rate + # @retval [0] total tx fee. (txout fee + utxo fee) + # @retval [1] txout fee. + # @retval [2] utxo fee. + def estimate_fee(self, utxo_list, fee_rate=20.0): + if (isinstance(utxo_list, list) is False) or ( + len(utxo_list) == 0): + raise CfdError( + error_code=1, message='Error: Invalid utxo_list.') + util = get_util() + with util.create_handle() as handle: + work_handle = ctypes.c_void_p() + util.call_func( + 'CfdInitializeEstimateFee', handle.get_handle(), + ctypes.byref(work_handle), False) + with JobHandle(handle, work_handle.value, + 'CfdFreeEstimateFeeHandle') as tx_handle: + for utxo in utxo_list: + util.call_func( + 'CfdAddTxInTemplateForEstimateFee', + handle.get_handle(), tx_handle.get_handle(), + str(utxo.outpoint.txid), utxo.outpoint.vout, + str(utxo.descriptor), '', False, False, False, + 0, '', to_hex_string(utxo.scriptsig_template)) + + _txout_fee = ctypes.c_int64() + _utxo_fee = ctypes.c_int64() + util.call_func( + 'CfdFinalizeEstimateFee', + handle.get_handle(), tx_handle.get_handle(), + self.hex, '', ctypes.byref(_txout_fee), + ctypes.byref(_utxo_fee), False, float(fee_rate)) + txout_fee, utxo_fee = _txout_fee.value, _utxo_fee.value + return (txout_fee + utxo_fee), txout_fee, utxo_fee + + ## + # @brief fund transaction. + # @param[in] txin_utxo_list txin list + # @param[in] utxo_list utxo list + # @param[in] reserved_address sending reserved address + # @param[in] target_amount collect target amount + # @param[in] effective_fee_rate effective fee rate + # @param[in] long_term_fee_rate long term fee rate + # @param[in] dust_fee_rate dust fee rate + # @param[in] knapsack_min_change minimum change threshold for knapsack + # @retval [0] total tx fee. + # @retval [1] used reserved address. (None or reserved_address) + def fund_raw_transaction( + self, txin_utxo_list, utxo_list, reserved_address, + target_amount=0, effective_fee_rate=20.0, + long_term_fee_rate=20.0, dust_fee_rate=-1.0, + knapsack_min_change=-1): + util = get_util() + + def set_opt(handle, tx_handle, key, i_val=0, f_val=0, b_val=False): + util.call_func( + 'CfdSetOptionFundRawTx', handle.get_handle(), + tx_handle.get_handle(), int(key.value), + int(i_val), float(f_val), b_val) + + with util.create_handle() as handle: + word_handle = util.call_func( + 'CfdInitializeFundRawTx', handle.get_handle(), + self.NETWORK, 1, '') + with JobHandle(handle, word_handle, + 'CfdFreeFundRawTxHandle') as tx_handle: + for utxo in txin_utxo_list: + util.call_func( + 'CfdAddTxInTemplateForFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + str(utxo.outpoint.txid), utxo.outpoint.vout, + utxo.amount, str(utxo.descriptor), + '', False, False, False, 0, '', + to_hex_string(utxo.scriptsig_template)) + for utxo in utxo_list: + util.call_func( + 'CfdAddUtxoTemplateForFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + str(utxo.outpoint.txid), utxo.outpoint.vout, + utxo.amount, str(utxo.descriptor), '', + to_hex_string(utxo.scriptsig_template)) + + util.call_func( + 'CfdAddTargetAmountForFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + 0, target_amount, '', str(reserved_address)) + + set_opt(handle, tx_handle, _FundTxOpt.DUST_FEE_RATE, + f_val=dust_fee_rate) + set_opt(handle, tx_handle, _FundTxOpt.LONG_TERM_FEE_RATE, + f_val=long_term_fee_rate) + set_opt(handle, tx_handle, _FundTxOpt.KNAPSACK_MIN_CHANGE, + i_val=knapsack_min_change) + + _tx_fee, _append_txout_count, _new_hex = util.call_func( + 'CfdFinalizeFundRawTx', + handle.get_handle(), tx_handle.get_handle(), + self.hex, effective_fee_rate) + + _used_addr = '' + if _append_txout_count > 0: + _used_addr = util.call_func( + 'CfdGetAppendTxOutFundRawTx', + handle.get_handle(), tx_handle.get_handle(), 0) + used_addr = None + if _used_addr == reserved_address: + used_addr = reserved_address + + self.hex = _new_hex + self._update_tx_all() + return _tx_fee, used_addr + + +## +# @class _FundTxOpt +# @brief FundTransaction option class. +class _FundTxOpt(Enum): + ## + # use blind (for elements) + USE_BLIND = 1 + ## + # dust fee rate + DUST_FEE_RATE = 2 + ## + # long term fee rate + LONG_TERM_FEE_RATE = 3 + ## + # minimum change threshold for knapsack + KNAPSACK_MIN_CHANGE = 4 + ## + # blind exponent (for elements) + EXPONENT = 5 + ## + # blind minimum bits (for elements) + MINIMUM_BITS = 6 + + +## +# All import target. +__all__ = [ + 'Txid', + 'OutPoint', + 'UtxoData', + 'TxIn', + 'TxOut', + '_TransactionBase', + 'Transaction' +] diff --git a/cfd/util.py b/cfd/util.py new file mode 100644 index 0000000..d096d7f --- /dev/null +++ b/cfd/util.py @@ -0,0 +1,903 @@ +# -*- coding: utf-8 -*- +## +# @file util.py +# @brief cfd utility file. +# @note Copyright 2020 CryptoGarage +from ctypes import c_int, c_void_p, c_char_p, c_int32, c_int64,\ + c_uint32, c_uint64, c_bool, c_double, c_ubyte, \ + CDLL, byref, POINTER, ArgumentError +from os.path import isfile, abspath +from enum import Enum +import platform +import os +import re + +################ +# Public class # +################ + + +## +# @class CfdErrorCode +# @brief Cfd error code. +class CfdErrorCode(Enum): + ## + # CfdErrorCode: success + SUCCESS = 0 + ## + # CfdErrorCode: unknown error. + UNKNOWN = -1 + ## + # CfdErrorCode: internal error. + INTERNAL = -2 + ## + # CfdErrorCode: memory full error. + MEMORY_FULL = -3 + ## + # CfdErrorCode: illegal argument error. + ILLEGAL_ARGUMENT = 1 + ## + # CfdErrorCode: illegal state error. + ILLEGAL_STATE = 2 + ## + # CfdErrorCode: out of range error. + OUT_OF_RANGE = 3 + ## + # CfdErrorCode: invalid setting. + INVALID_SETTING = 4 + ## + # CfdErrorCode: connection error. + CONNECTION_ERROR = 5 + ## + # CfdErrorCode: disk access error. + DISK_ACCESS_ERROR = 6 + ## + # CfdErrorCode: sign verification. + SIGN_VERIFICATION = 7 + + +## +# @class CfdError +# @brief cfd custom error class. +class CfdError(Exception): + ## + # @var error_code + # error code + ## + # @var message + # error message + + ## + # @brief constructor. + # @param[in] error_code error code + # @param[in] message error message + def __init__(self, error_code=CfdErrorCode.UNKNOWN.value, message=''): + self.error_code = error_code + self.message = message + + ## + # @brief get error information. + # @return error information. + def __str__(self): + return 'code={}, msg={}'.format(self.error_code, self.message) + + +## +# @class ByteData +# @brief cfd byte data class. +class ByteData: + ## + # @var hex + # hex string + + ## + # @brief constructor. + # @param[in] data byte data + def __init__(self, data): + if isinstance(data, bytes) or isinstance(data, bytearray): + self.hex = data.hex() + elif isinstance(data, list): + self.hex = ''.join("%02x" % b for b in data) + else: + self.hex = str(data).lower() + bytes.fromhex(self.hex) # check hex + + ## + # @brief get string. + # @return hex. + def __str__(self): + return self.hex + + ## + # @brief get bytes data. + # @return bytes data. + def as_bytes(self): + return bytes.fromhex(self.hex) + + ## + # @brief get array data. + # @return array data. + def as_array(self): + _hex_list = re.split('(..)', self.hex)[1::2] + return [int('0x' + s, 16) for s in _hex_list] + + ## + # @brief get serialized data. + # @return serialize hex. + def serialize(self): + util = get_util() + with util.create_handle() as handle: + _serialized = util.call_func( + 'CfdSerializeByteData', handle.get_handle(), self.hex) + return ByteData(_serialized) + + +## +# @class ReverseByteData +# @brief reversible byte data class. +class ReverseByteData: + ## + # @var hex + # hex string + + ## + # @brief constructor. + # @param[in] data byte data + def __init__(self, data): + if isinstance(data, bytes) or isinstance(data, bytearray): + _data = data.hex() + _list = re.split('(..)', _data)[1::2] + new_list = _list[::-1] + self.hex = ''.join(new_list) + elif isinstance(data, list): + new_list = data[::-1] + self.hex = ''.join("%02x" % b for b in new_list) + else: + self.hex = str(data).lower() + if self.hex != '': + try: + bytes.fromhex(self.hex) + except ValueError: + raise CfdError( + error_code=1, + message='Error: Invalid hex value.') + + ## + # @brief get string. + # @return hex. + def __str__(self): + return self.hex + + ## + # @brief get bytes data. + # @return bytes data. + def as_bytes(self): + _hex_list = re.split('(..)', self.hex)[1::2] + _hex_list = _hex_list[::-1] + return bytes.fromhex(''.join(_hex_list)) + + ## + # @brief get array data. + # @return array data. + def as_array(self): + _hex_list = re.split('(..)', self.hex)[1::2] + _hex_list = _hex_list[::-1] + return [int('0x' + s, 16) for s in _hex_list] + + +## +# @brief get hex string. +# @param[in] value data +# @return hex string. +def to_hex_string(value): + if isinstance(value, bytes): + return value.hex() + elif isinstance(value, bytearray): + return value.hex() + elif isinstance(value, list): + return "".join("%02x" % b for b in value) + elif str(type(value)) == "": + return value.hex + else: + _hex = str(value) + if _hex != '': + try: + bytes.fromhex(_hex) + except ValueError: + raise CfdError( + error_code=1, + message='Error: Invalid hex value.') + return _hex + + +################## +# Internal class # +################## + + +## +# @class CVoidPP +# @brief void double pointer class. +class CVoidPP(object): + pass + + +## +# @class CCharPP +# @brief char double pointer class. +class CCharPP(object): + pass + + +## +# @class CBoolP +# @brief bool pointer class. +class CBoolP(object): + pass + + +## +# @class CIntP +# @brief int pointer class. +class CIntP(object): + pass + + +## +# @class CUint32P +# @brief uint32 pointer class. +class CUint32P(object): + pass + + +## +# @class CInt32P +# @brief int32 pointer class. +class CInt32P(object): + pass + + +## +# @class CUint64P +# @brief uint64 pointer class. +class CUint64P(object): + pass + + +## +# @class CInt64P +# @brief int64 pointer class. +class CInt64P(object): + pass + + +## +# @brief void double pointer. +c_void_p_p = CVoidPP() +## +# @brief char double pointer. +c_char_p_p = CCharPP() +## +# @brief bool pointer. +c_bool_p = CBoolP() +## +# @brief int pointer. +c_int_p = CIntP() +## +# @brief uint32 pointer. +c_uint32_p = CUint32P() +## +# @brief int32 pointer. +c_int32_p = CInt32P() +## +# @brief uint64 pointer. +c_uint64_p = CUint64P() +## +# @brief int64 pointer. +c_int64_p = CInt64P() + + +## +# @class CfdHandle +# @brief cfd handle class. +class CfdHandle: + ## + # @var _handle + # handle pointer + + ## + # @brief constructor. + # @param[in] handle handle + def __init__(self, handle): + self._handle = handle + + ## + # @brief get handle. + # @retval _handle handle. + def get_handle(self): + return self._handle + + ## + # @brief enter method. + # @retval self object. + def __enter__(self): + return self + + ## + # @brief exit method. + # @param[in] type type + # @param[in] value value + # @param[in] traceback traceback + # @return void + def __exit__(self, type, value, traceback): + get_util().free_handle(self._handle) + + +## +# @class JobHandle +# @brief cfd job handle class. +class JobHandle: + ## + # @var _handle + # cfd handle. + ## + # @var _job_handle + # job handle. + ## + # @var _close_func + # close function name. + + ## + # @brief constructor. + # @param[in] handle handle + # @param[in] job_handle job handle + # @param[in] close_function_name close func name. + def __init__(self, handle, job_handle, close_function_name): + self._handle = handle + self._job_handle = job_handle + self._close_func = close_function_name + + ## + # @brief get job handle. + # @retval _job_handle handle. + def get_handle(self): + return self._job_handle + + ## + # @brief enter method. + # @retval self object. + def __enter__(self): + return self + + ## + # @brief exit method. + # @param[in] type type + # @param[in] value value + # @param[in] traceback traceback + # @return void + def __exit__(self, type, value, traceback): + get_util().call_func( + self._close_func, + self._handle.get_handle(), + self._job_handle) + + +## +# @class CfdUtil +# @brief cfd utility class. +class CfdUtil: + ## + # @var _instance + # singleton instance. + + ## + # function map list + _FUNC_LIST = [ + ("CfdCreateAddress", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_int, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdInitializeMultisigScript", c_int, [c_void_p, c_int, c_int, c_void_p_p]), # noqa: E501 + ("CfdAddMultisigScriptData", c_int, [c_void_p, c_void_p, c_char_p]), # noqa: E501 + ("CfdFinalizeMultisigScript", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdFreeMultisigScriptHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdParseDescriptor", c_int, [c_void_p, c_char_p, c_int, c_char_p, c_void_p_p, c_uint32_p]), # noqa: E501 + ("CfdGetDescriptorData", c_int, [c_void_p, c_void_p, c_uint32, c_uint32_p, c_uint32_p, c_int_p, c_char_p_p, c_char_p_p, c_int_p, c_char_p_p, c_int_p, c_char_p_p, c_char_p_p, c_char_p_p, c_bool_p, c_uint32_p, c_uint32_p]), # noqa: E501 + ("CfdGetDescriptorMultisigKey", c_int, [c_void_p, c_void_p, c_uint32, c_int_p, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdFreeDescriptorHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdGetDescriptorChecksum", c_int, [c_void_p, c_int, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdGetAddressesFromMultisig", c_int, [c_void_p, c_char_p, c_int, c_int, c_void_p_p, c_uint32_p]), # noqa: E501 + ("CfdGetAddressFromMultisigKey", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdFreeAddressesMultisigHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdGetAddressFromLockingScript", c_int, [c_void_p, c_char_p, c_int, c_char_p_p]), # noqa: E501 + ("CfdGetAddressInfo", c_int, [c_void_p, c_char_p, c_int_p, c_int_p, c_int_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdInitializeCoinSelection", c_int, [c_void_p, c_uint32, c_uint32, c_char_p, c_int64, c_double, c_double, c_double, c_int64, c_void_p_p]), # noqa: E501 + ("CfdAddCoinSelectionUtxo", c_int, [c_void_p, c_void_p, c_int32, c_char_p, c_uint32, c_int64, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddCoinSelectionUtxoTemplate", c_int, [c_void_p, c_void_p, c_int32, c_char_p, c_uint32, c_int64, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddCoinSelectionAmount", c_int, [c_void_p, c_void_p, c_uint32, c_int64, c_char_p]), # noqa: E501 + ("CfdSetOptionCoinSelection", c_int, [c_void_p, c_void_p, c_int, c_int64, c_double, c_bool]), # noqa: E501 + ("CfdFinalizeCoinSelection", c_int, [c_void_p, c_void_p, c_int64_p]), # noqa: E501 + ("CfdGetSelectedCoinIndex", c_int, [c_void_p, c_void_p, c_uint32, c_int32_p]), # noqa: E501 + ("CfdGetSelectedCoinAssetAmount", c_int, [c_void_p, c_void_p, c_uint32, c_int64_p]), # noqa: E501 + ("CfdFreeCoinSelectionHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdInitializeEstimateFee", c_int, [c_void_p, c_void_p_p, c_bool]), # noqa: E501 + ("CfdAddTxInForEstimateFee", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_char_p, c_char_p, c_bool, c_bool, c_bool, c_uint32, c_char_p]), # noqa: E501 + ("CfdAddTxInTemplateForEstimateFee", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_char_p, c_char_p, c_bool, c_bool, c_bool, c_uint32, c_char_p, c_char_p]), # noqa: E501 + ("CfdSetOptionEstimateFee", c_int, [c_void_p, c_void_p, c_int, c_int64, c_double, c_bool]), # noqa: E501 + ("CfdFinalizeEstimateFee", c_int, [c_void_p, c_void_p, c_char_p, c_char_p, c_int64_p, c_int64_p, c_bool, c_double]), # noqa: E501 + ("CfdFreeEstimateFeeHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdGetSupportedFunction", c_int, [c_uint64_p]), # noqa: E501 + ("CfdInitialize", c_int, []), # noqa: E501 + ("CfdFinalize", c_int, [c_bool]), # noqa: E501 + ("CfdCreateHandle", c_int, [c_void_p_p]), # noqa: E501 + ("CfdCreateSimpleHandle", c_int, [c_void_p_p]), # noqa: E501 + ("CfdCloneHandle", c_int, [c_void_p, c_void_p_p]), # noqa: E501 + ("CfdCopyErrorState", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdFreeHandle", c_int, [c_void_p]), # noqa: E501 + ("CfdFreeBuffer", c_int, [c_void_p]), # noqa: E501 + ("CfdFreeStringBuffer", c_int, [c_char_p]), # noqa: E501 + ("CfdGetLastErrorCode", c_int, [c_void_p]), # noqa: E501 + ("CfdGetLastErrorMessage", c_int, [c_void_p, c_char_p_p]), # noqa: E501 + ("CfdRequestExecuteJson", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdSerializeByteData", c_int, [c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdCreateConfidentialAddress", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdParseConfidentialAddress", c_int, [c_void_p, c_char_p, c_char_p_p, c_char_p_p, c_int_p]), # noqa: E501 + ("CfdInitializeConfidentialTx", c_int, [c_void_p, c_uint32, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdAddConfidentialTxIn", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdAddConfidentialTxOut", c_int, [c_void_p, c_char_p, c_char_p, c_int64, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdUpdateConfidentialTxOut", c_int, [c_void_p, c_char_p, c_uint32, c_char_p, c_int64, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdGetConfidentialTxInfo", c_int, [c_void_p, c_char_p, c_char_p_p, c_char_p_p, c_char_p_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p]), # noqa: E501 + ("CfdGetConfidentialTxIn", c_int, [c_void_p, c_char_p, c_uint32, c_char_p_p, c_uint32_p, c_uint32_p, c_char_p_p]), # noqa: E501 + ("CfdGetConfidentialTxInWitness", c_int, [c_void_p, c_char_p, c_uint32, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdGetConfidentialTxInPeginWitness", c_int, [c_void_p, c_char_p, c_uint32, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdGetTxInIssuanceInfo", c_int, [c_void_p, c_char_p, c_uint32, c_char_p_p, c_char_p_p, c_int64_p, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetConfidentialTxOut", c_int, [c_void_p, c_char_p, c_uint32, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetConfidentialTxInCount", c_int, [c_void_p, c_char_p, c_uint32_p]), # noqa: E501 + ("CfdGetConfidentialTxInWitnessCount", c_int, [c_void_p, c_char_p, c_uint32, c_uint32_p]), # noqa: E501 + ("CfdGetConfidentialTxInPeginWitnessCount", c_int, [c_void_p, c_char_p, c_uint32, c_uint32_p]), # noqa: E501 + ("CfdGetConfidentialTxOutCount", c_int, [c_void_p, c_char_p, c_uint32_p]), # noqa: E501 + ("CfdGetConfidentialTxInIndex", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_uint32_p]), # noqa: E501 + ("CfdGetConfidentialTxOutIndex", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_uint32_p]), # noqa: E501 + ("CfdGetConfidentialTxInfoByHandle", c_int, [c_void_p, c_void_p, c_char_p_p, c_char_p_p, c_char_p_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p]), # noqa: E501 + ("CfdGetTxInIssuanceInfoByHandle", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p, c_char_p_p, c_int64_p, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetConfidentialTxOutSimpleByHandle", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetConfidentialTxOutByHandle", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdSetRawReissueAsset", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_int64, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetIssuanceBlindingKey", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdGetDefaultBlindingKey", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdInitializeBlindTx", c_int, [c_void_p, c_void_p_p]), # noqa: E501 + ("CfdSetBlindTxOption", c_int, [c_void_p, c_void_p, c_int, c_int64]), # noqa: E501 + ("CfdAddBlindTxInData", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_char_p, c_char_p, c_char_p, c_int64, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddBlindTxOutData", c_int, [c_void_p, c_void_p, c_uint32, c_char_p]), # noqa: E501 + ("CfdAddBlindTxOutByAddress", c_int, [c_void_p, c_void_p, c_char_p]), # noqa: E501 + ("CfdFinalizeBlindTx", c_int, [c_void_p, c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdFreeBlindHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdAddConfidentialTxSign", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_bool, c_char_p, c_bool, c_char_p_p]), # noqa: E501 + ("CfdAddConfidentialTxDerSign", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_bool, c_char_p, c_int, c_bool, c_bool, c_char_p_p]), # noqa: E501 + ("CfdFinalizeElementsMultisigSign", c_int, [c_void_p, c_void_p, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_char_p, c_bool, c_char_p_p]), # noqa: E501 + ("CfdAddConfidentialTxSignWithPrivkeySimple", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_char_p, c_int64, c_char_p, c_int, c_bool, c_bool, c_char_p_p]), # noqa: E501 + ("CfdCreateConfidentialSighash", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_char_p, c_int64, c_char_p, c_int, c_bool, c_char_p_p]), # noqa: E501 + ("CfdUnblindTxOut", c_int, [c_void_p, c_char_p, c_uint32, c_char_p, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdUnblindIssuance", c_int, [c_void_p, c_char_p, c_uint32, c_char_p, c_char_p, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p, c_char_p_p, c_int64_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdVerifyConfidentialTxSignature", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_uint32, c_int, c_bool, c_int64, c_char_p, c_int]), # noqa: E501 + ("CfdVerifyConfidentialTxSign", c_int, [c_void_p, c_char_p, c_char_p, c_uint32, c_char_p, c_int, c_char_p, c_int64, c_char_p]), # noqa: E501 + ("CfdGetConfidentialValueHex", c_int, [c_void_p, c_int64, c_bool, c_char_p_p]), # noqa: E501 + ("CfdGetAssetCommitment", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdGetValueCommitment", c_int, [c_void_p, c_int64, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdAddConfidentialTxOutput", c_int, [c_void_p, c_void_p, c_int64, c_char_p, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdCalculateEcSignature", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_int, c_bool, c_char_p_p]), # noqa: E501 + ("CfdVerifyEcSignature", c_int, [c_void_p, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdSignEcdsaAdaptor", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdAdaptEcdsaAdaptor", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdExtractEcdsaAdaptorSecret", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdVerifyEcdsaAdaptor", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdGetSchnorrPubkeyFromPrivkey", c_int, [c_void_p, c_char_p, c_char_p_p, c_bool_p]), # noqa: E501 + ("CfdGetSchnorrPubkeyFromPubkey", c_int, [c_void_p, c_char_p, c_char_p_p, c_bool_p]), # noqa: E501 + ("CfdSchnorrPubkeyTweakAdd", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p, c_bool_p]), # noqa: E501 + ("CfdSchnorrKeyPairTweakAdd", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p, c_bool_p, c_char_p_p]), # noqa: E501 + ("CfdCheckTweakAddFromSchnorrPubkey", c_int, [c_void_p, c_char_p, c_bool, c_char_p, c_char_p]), # noqa: E501 + ("CfdSignSchnorr", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdSignSchnorrWithNonce", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdComputeSchnorrSigPoint", c_int, [c_void_p, c_char_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdVerifySchnorr", c_int, [c_void_p, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdSplitSchnorrSignature", c_int, [c_void_p, c_char_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdEncodeSignatureByDer", c_int, [c_void_p, c_char_p, c_int, c_bool, c_char_p_p]), # noqa: E501 + ("CfdDecodeSignatureFromDer", c_int, [c_void_p, c_char_p, c_char_p_p, c_int_p, c_bool_p]), # noqa: E501 + ("CfdNormalizeSignature", c_int, [c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdCreateKeyPair", c_int, [c_void_p, c_bool, c_int, c_char_p_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetPrivkeyFromWif", c_int, [c_void_p, c_char_p, c_int, c_char_p_p]), # noqa: E501 + ("CfdGetPrivkeyWif", c_int, [c_void_p, c_char_p, c_int, c_bool, c_char_p_p]), # noqa: E501 + ("CfdParsePrivkeyWif", c_int, [c_void_p, c_char_p, c_char_p_p, c_int_p, c_bool_p]), # noqa: E501 + ("CfdGetPubkeyFromPrivkey", c_int, [c_void_p, c_char_p, c_char_p, c_bool, c_char_p_p]), # noqa: E501 + ("CfdCompressPubkey", c_int, [c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdUncompressPubkey", c_int, [c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdInitializeCombinePubkey", c_int, [c_void_p, c_void_p_p]), # noqa: E501 + ("CfdAddCombinePubkey", c_int, [c_void_p, c_void_p, c_char_p]), # noqa: E501 + ("CfdFinalizeCombinePubkey", c_int, [c_void_p, c_void_p, c_char_p_p]), # noqa: E501 + ("CfdFreeCombinePubkeyHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdPubkeyTweakAdd", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdPubkeyTweakMul", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdNegatePubkey", c_int, [c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdPrivkeyTweakAdd", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdPrivkeyTweakMul", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdNegatePrivkey", c_int, [c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdCreateExtkeyFromSeed", c_int, [c_void_p, c_char_p, c_int, c_int, c_char_p_p]), # noqa: E501 + ("CfdCreateExtkey", c_int, [c_void_p, c_int, c_int, c_char_p, c_char_p, c_char_p, c_char_p, c_ubyte, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdCreateExtkeyFromParent", c_int, [c_void_p, c_char_p, c_uint32, c_bool, c_int, c_int, c_char_p_p]), # noqa: E501 + ("CfdCreateExtkeyFromParentPath", c_int, [c_void_p, c_char_p, c_char_p, c_int, c_int, c_char_p_p]), # noqa: E501 + ("CfdCreateExtPubkey", c_int, [c_void_p, c_char_p, c_int, c_char_p_p]), # noqa: E501 + ("CfdGetPrivkeyFromExtkey", c_int, [c_void_p, c_char_p, c_int, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetPubkeyFromExtkey", c_int, [c_void_p, c_char_p, c_int, c_char_p_p]), # noqa: E501 + ("CfdGetParentExtkeyPathData", c_int, [c_void_p, c_char_p, c_char_p, c_int, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetExtkeyInformation", c_int, [c_void_p, c_char_p, c_char_p_p, c_char_p_p, c_char_p_p, c_uint32_p, c_uint32_p]), # noqa: E501 + ("CfdInitializeMnemonicWordList", c_int, [c_void_p, c_char_p, c_void_p_p, c_uint32_p]), # noqa: E501 + ("CfdGetMnemonicWord", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdFreeMnemonicWordList", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdConvertMnemonicToSeed", c_int, [c_void_p, c_char_p, c_char_p, c_bool, c_char_p, c_bool, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdConvertEntropyToMnemonic", c_int, [c_void_p, c_char_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdInitializeTxSerializeForLedger", c_int, [c_void_p, c_void_p_p]), # noqa: E501 + ("CfdAddTxOutMetaDataForLedger", c_int, [c_void_p, c_void_p, c_uint32, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdFinalizeTxSerializeForLedger", c_int, [c_void_p, c_void_p, c_int, c_char_p, c_bool, c_bool, c_char_p_p]), # noqa: E501 + ("CfdFinalizeTxSerializeHashForLedger", c_int, [c_void_p, c_void_p, c_int, c_char_p, c_bool, c_bool, c_bool, c_char_p_p]), # noqa: E501 + ("CfdFreeTxSerializeForLedger", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdParseScript", c_int, [c_void_p, c_char_p, c_void_p_p, c_uint32_p]), # noqa: E501 + ("CfdGetScriptItem", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdFreeScriptItemHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdConvertScriptAsmToHex", c_int, [c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdInitializeMultisigScriptSig", c_int, [c_void_p, c_void_p_p]), # noqa: E501 + ("CfdAddMultisigScriptSigData", c_int, [c_void_p, c_void_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddMultisigScriptSigDataToDer", c_int, [c_void_p, c_void_p, c_char_p, c_int, c_bool, c_char_p]), # noqa: E501 + ("CfdFinalizeMultisigScriptSig", c_int, [c_void_p, c_void_p, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdFreeMultisigScriptSigHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdInitializeTransaction", c_int, [c_void_p, c_int, c_uint32, c_uint32, c_char_p, c_void_p_p]), # noqa: E501 + ("CfdAddTransactionInput", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_uint32]), # noqa: E501 + ("CfdAddTransactionOutput", c_int, [c_void_p, c_void_p, c_int64, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdFinalizeTransaction", c_int, [c_void_p, c_void_p, c_char_p_p]), # noqa: E501 + ("CfdFreeTransactionHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdUpdateTxOutAmount", c_int, [c_void_p, c_int, c_char_p, c_uint32, c_int64, c_char_p_p]), # noqa: E501 + ("CfdAddTxSign", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_bool, c_int, c_bool, c_bool, c_char_p_p]), # noqa: E501 + ("CfdAddPubkeyHashSign", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_char_p, c_bool, c_int, c_bool, c_char_p_p]), # noqa: E501 + ("CfdAddScriptHashSign", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_bool, c_char_p_p]), # noqa: E501 + ("CfdAddSignWithPrivkeySimple", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_char_p, c_int64, c_int, c_bool, c_bool, c_char_p_p]), # noqa: E501 + ("CfdInitializeMultisigSign", c_int, [c_void_p, c_void_p_p]), # noqa: E501 + ("CfdAddMultisigSignData", c_int, [c_void_p, c_void_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddMultisigSignDataToDer", c_int, [c_void_p, c_void_p, c_char_p, c_int, c_bool, c_char_p]), # noqa: E501 + ("CfdFinalizeMultisigSign", c_int, [c_void_p, c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_char_p_p]), # noqa: E501 + ("CfdFreeMultisigSignHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdVerifySignature", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_int, c_char_p, c_char_p, c_char_p, c_uint32, c_int, c_bool, c_int64, c_char_p]), # noqa: E501 + ("CfdVerifyTxSign", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_char_p, c_int, c_char_p, c_int64, c_char_p]), # noqa: E501 + ("CfdCreateSighash", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_int, c_char_p, c_char_p, c_int64, c_int, c_bool, c_char_p_p]), # noqa: E501 + ("CfdGetTxInfo", c_int, [c_void_p, c_int, c_char_p, c_char_p_p, c_char_p_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p]), # noqa: E501 + ("CfdGetTxIn", c_int, [c_void_p, c_int, c_char_p, c_uint32, c_char_p_p, c_uint32_p, c_uint32_p, c_char_p_p]), # noqa: E501 + ("CfdGetTxInWitness", c_int, [c_void_p, c_int, c_char_p, c_uint32, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdGetTxOut", c_int, [c_void_p, c_int, c_char_p, c_uint32, c_int64_p, c_char_p_p]), # noqa: E501 + ("CfdGetTxInCount", c_int, [c_void_p, c_int, c_char_p, c_uint32_p]), # noqa: E501 + ("CfdGetTxInWitnessCount", c_int, [c_void_p, c_int, c_char_p, c_uint32, c_uint32_p]), # noqa: E501 + ("CfdGetTxOutCount", c_int, [c_void_p, c_int, c_char_p, c_uint32_p]), # noqa: E501 + ("CfdGetTxInIndex", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_uint32, c_uint32_p]), # noqa: E501 + ("CfdGetTxOutIndex", c_int, [c_void_p, c_int, c_char_p, c_char_p, c_char_p, c_uint32_p]), # noqa: E501 + ("CfdInitializeTxDataHandle", c_int, [c_void_p, c_int, c_char_p, c_void_p_p]), # noqa: E501 + ("CfdFreeTxDataHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ("CfdGetModifiedTxByHandle", c_int, [c_void_p, c_void_p, c_char_p_p]), # noqa: E501 + ("CfdGetTxInfoByHandle", c_int, [c_void_p, c_void_p, c_char_p_p, c_char_p_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p, c_uint32_p]), # noqa: E501 + ("CfdGetTxInByHandle", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p, c_uint32_p, c_uint32_p, c_char_p_p]), # noqa: E501 + ("CfdGetTxInWitnessByHandle", c_int, [c_void_p, c_void_p, c_int, c_uint32, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdGetTxOutByHandle", c_int, [c_void_p, c_void_p, c_uint32, c_int64_p, c_char_p_p, c_char_p_p]), # noqa: E501 + ("CfdGetTxInCountByHandle", c_int, [c_void_p, c_void_p, c_uint32_p]), # noqa: E501 + ("CfdGetTxInWitnessCountByHandle", c_int, [c_void_p, c_void_p, c_int, c_uint32, c_uint32_p]), # noqa: E501 + ("CfdGetTxOutCountByHandle", c_int, [c_void_p, c_void_p, c_uint32_p]), # noqa: E501 + ("CfdGetTxInIndexByHandle", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_uint32_p]), # noqa: E501 + ("CfdGetTxOutIndexByHandle", c_int, [c_void_p, c_void_p, c_char_p, c_char_p, c_uint32_p]), # noqa: E501 + ("CfdInitializeFundRawTx", c_int, [c_void_p, c_int, c_uint32, c_char_p, c_void_p_p]), # noqa: E501 + ("CfdAddTxInForFundRawTx", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_int64, c_char_p, c_char_p, c_bool, c_bool, c_bool, c_uint32, c_char_p]), # noqa: E501 + ("CfdAddTxInTemplateForFundRawTx", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_int64, c_char_p, c_char_p, c_bool, c_bool, c_bool, c_uint32, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddUtxoForFundRawTx", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_int64, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddUtxoTemplateForFundRawTx", c_int, [c_void_p, c_void_p, c_char_p, c_uint32, c_int64, c_char_p, c_char_p, c_char_p]), # noqa: E501 + ("CfdAddTargetAmountForFundRawTx", c_int, [c_void_p, c_void_p, c_uint32, c_int64, c_char_p, c_char_p]), # noqa: E501 + ("CfdSetOptionFundRawTx", c_int, [c_void_p, c_void_p, c_int, c_int64, c_double, c_bool]), # noqa: E501 + ("CfdFinalizeFundRawTx", c_int, [c_void_p, c_void_p, c_char_p, c_double, c_int64_p, c_uint32_p, c_char_p_p]), # noqa: E501 + ("CfdGetAppendTxOutFundRawTx", c_int, [c_void_p, c_void_p, c_uint32, c_char_p_p]), # noqa: E501 + ("CfdFreeFundRawTxHandle", c_int, [c_void_p, c_void_p]), # noqa: E501 + ] + + ## + # @brief get instance. + # @return utility instance. + @classmethod + def get_instance(cls): + if not hasattr(cls, "_instance"): + cls._instance = cls() + return cls._instance + + ## + # @var free_str_func + # free native string buffer function. + ## + # @var _cfd + # cfd dll object. + ## + # @var _func_map + # cfd function map. + + ## + # @brief constructor. + # @return utility instance. + def __init__(self): + self._func_map = {} + + lib_path = self._collect_lib_path() + try: + """ + TODO: python 3.7 or lower for windows is used dll + on the current dir only or under. + """ + self._cfd = CDLL(lib_path) + except OSError as e: + print('OSError: dll path = ' + lib_path) + raise e + except FileNotFoundError as e: + print('FileNotFoundError: dll path = ' + lib_path) + raise e + + free_func = self._cfd.CfdFreeStringBuffer + free_func.restype, free_func.argtypes = c_int, [c_char_p] + self.free_str_func = free_func + self._load_functions() + + ## + # @brief collect library path. + # @return cfd library path. + def _collect_lib_path(self): + has_win = platform.system() == 'Windows' + has_mac = platform.system() == 'Darwin' + abs_path = os.path.dirname(os.path.abspath(__file__)) + '/' + + so_ext = 'dylib' if has_mac else 'dll' if has_win else 'so' + so_prefix = '' if has_win else 'lib' + lib_name = '{}cfd.{}'.format(so_prefix, so_ext) + lib_path = lib_name + root_dir = './' + is_find = isfile(root_dir + lib_path) + + if not is_find: + for depth in [0, 1, 2]: + root_dir = abs_path + '../' * depth + if isfile(root_dir + lib_path): + is_find = True + break + + if not is_find: + lib_path = os.path.join('cmake_build', 'Release', lib_path) + for depth in [0, 1, 2]: + root_dir = abs_path + '../' * depth + if isfile(root_dir + lib_path): + is_find = True + break + + if not is_find: + lib_path = lib_name + if has_win: + paths = os.getenv('PATH').split(';') + for path in paths: + try: + fs = os.listdir(path) + for f in fs: + if f == 'lib' and isfile( + os.path.join(path, 'lib', lib_name)): + root_dir = os.path.join(path, 'lib') + '/' + except WindowsError: + pass + else: + paths = ['/usr/local/lib/', '/usr/local/lib64/'] + for path in paths: + if isfile(path + lib_name): + root_dir = path + + if has_mac: + root_dir = abspath(root_dir) + '/' + elif has_win: + root_dir = root_dir.replace('/', '\\') + return root_dir + lib_path + + ## + # @brief load cfd functions. + # @return void + def _load_functions(self): + def bind_fn(name, res, args): + try: + fn = getattr(self._cfd, name) + if args: + fn.restype, fn.argtypes = res, args + else: + fn.restype = res + except Exception as err: + print('Exception: ' + str(err)) + print('name: ' + name) + print('response: ' + res) + print('parameters: ' + args) + raise err + # print('bind: {}, {}, {}'.format(name, res, args)) + return fn + + def in_string_fn_wrapper(fn, pos, *args): + if isinstance(args[pos], str): + new_args = [a for a in args] + new_args[pos] = new_args[pos].encode('utf-8') + return fn(*new_args) + return fn(*args) + + def string_fn_wrapper(fn, *args): + try: + # Return output string parameters directly without leaking + p = c_char_p() + new_args = [a for a in args] + [byref(p)] + ret = fn(*new_args) + ret_str = None if p.value is None else p.value.decode('utf-8') + self.free_str_func(p) + if isinstance(ret, tuple): + return [ret_str, ((ret[0],) + (ret_str,) + ret[1:])][True] + else: + return [ret_str, (ret, ret_str)][True] + except ArgumentError as err: + print('Exception: ' + str(err)) + print('name: ' + str(fn)) + print('new_args: {}'.format(new_args)) + raise err + + def value_fn_wrapper(p, fn, *args): + new_args = [a for a in args] + [byref(p)] + ret = fn(*new_args) + if isinstance(ret, tuple): + return [p.value, ((ret[0],) + (p.value,) + ret[1:])][True] + else: + return [p.value, (ret, p.value)][True] + + def make_str_fn(f): + return lambda *args: string_fn_wrapper(f, *args) + + def make_void_fn(fn): + return lambda *args: value_fn_wrapper(c_void_p(), fn, *args) + + def make_bool_fn(fn): + return lambda *args: value_fn_wrapper(c_bool(), fn, *args) + + def make_int_fn(fn): + return lambda *args: value_fn_wrapper(c_int(), fn, *args) + + def make_uint32_fn(fn): + return lambda *args: value_fn_wrapper(c_uint32(), fn, *args) + + def make_int32_fn(fn): + return lambda *args: value_fn_wrapper(c_int32(), fn, *args) + + def make_uint64_fn(fn): + return lambda *args: value_fn_wrapper(c_uint64(), fn, *args) + + def make_int64_fn(fn): + return lambda *args: value_fn_wrapper(c_int64(), fn, *args) + + def make_input_str_fn(fn, pos): + return lambda *args: in_string_fn_wrapper(fn, pos, *args) + + for func_info in CfdUtil._FUNC_LIST: + name, restype, argtypes = func_info + + in_str_pos = [i for (i, t) in enumerate(argtypes) if t == c_char_p] + str_pos = [i for (i, t) in enumerate(argtypes) if t == c_char_p_p] + void_pos = [i for (i, t) in enumerate(argtypes) if t == c_void_p_p] + bool_pos = [i for (i, t) in enumerate(argtypes) if t == c_bool_p] + int_pos = [i for (i, t) in enumerate(argtypes) if t == c_int_p] + int32_pos = [i for (i, t) in enumerate(argtypes) if t == c_int32_p] + uint32_pos = [i for (i, t) in enumerate( + argtypes) if t == c_uint32_p] + int64_pos = [i for (i, t) in enumerate(argtypes) if t == c_int64_p] + uint64_pos = [i for (i, t) in enumerate( + argtypes) if t == c_uint64_p] + for i in range(len(argtypes)): + if isinstance(argtypes[i], CCharPP): + argtypes[i] = POINTER(c_char_p) + elif isinstance(argtypes[i], CVoidPP): + argtypes[i] = POINTER(c_void_p) + elif isinstance(argtypes[i], CBoolP): + argtypes[i] = POINTER(c_bool) + elif isinstance(argtypes[i], CIntP): + argtypes[i] = POINTER(c_int) + elif isinstance(argtypes[i], CInt32P): + argtypes[i] = POINTER(c_int32) + elif isinstance(argtypes[i], CUint32P): + argtypes[i] = POINTER(c_uint32) + elif isinstance(argtypes[i], CInt64P): + argtypes[i] = POINTER(c_int64) + elif isinstance(argtypes[i], CUint64P): + argtypes[i] = POINTER(c_uint64) + + fn = bind_fn(name, restype, argtypes) + + i = len(argtypes) - 1 + while i >= 0: + if len(str_pos) > 0 and i in str_pos: + fn = make_str_fn(fn) + elif len(void_pos) > 0 and i in void_pos: + fn = make_void_fn(fn) + elif len(bool_pos) > 0 and i in bool_pos: + fn = make_bool_fn(fn) + elif len(int_pos) > 0 and i in int_pos: + fn = make_int_fn(fn) + elif len(int32_pos) > 0 and i in int32_pos: + fn = make_int32_fn(fn) + elif len(uint32_pos) > 0 and i in uint32_pos: + fn = make_uint32_fn(fn) + elif len(int64_pos) > 0 and i in int64_pos: + fn = make_int64_fn(fn) + elif len(uint64_pos) > 0 and i in uint64_pos: + fn = make_uint64_fn(fn) + i -= 1 + + if len(in_str_pos) > 0 and fn: + for pos in in_str_pos: + fn = make_input_str_fn(fn, pos) + self._func_map[name] = fn + + ## + # @brief call cfd function. + # @param[in] name function name. + # @param[in] *args function arguments. + # @return response data. + # @throw CfdError occurred error. + def call_func(self, name, *args): + # print('call: {}{}'.format(name, args)) + ret = self._func_map[name](*args) + err_code = ret + if isinstance(ret, tuple): + err_code = ret[0] + if err_code != 0: + message = 'Error: ' + name + if len(args) > 0 and \ + args[0] != 'CfdCreateSimpleHandle' and \ + args[0] != 'CfdFreeHandle' and \ + args[0] != 'CfdFreeBuffer': + temp_ret, err_msg = self._func_map['CfdGetLastErrorMessage']( + args[0]) + if temp_ret == 0: + message = err_msg + raise CfdError(error_code=err_code, message=message) + if isinstance(ret, tuple) is False: + return + elif len(ret) == 1: + return ret[0] + elif len(ret) == 2: + return ret[1] + else: + return ret[1:] + + ## + # @brief create cfd handle. + # @return cfd handle + # @throw CfdError occurred error. + def create_handle(self): + ret, handle = self._func_map['CfdCreateSimpleHandle']() + if ret != 0: + raise CfdError( + error_code=ret, + message='Error: CfdCreateSimpleHandle') + return CfdHandle(handle) + + ## + # @brief free cfd handle. + # @param[in] handle cfd handle + # @return result + def free_handle(self, handle): + return self._func_map['CfdFreeHandle'](handle) + + +## +# @brief get utility object. +# @return utility object. +def get_util(): + return CfdUtil.get_instance() + + +## +# All import target. +__all__ = [ + 'CfdError', + 'ByteData', + 'ReverseByteData' +] diff --git a/cmake/CfdCommonOption.cmake b/cmake/CfdCommonOption.cmake new file mode 100644 index 0000000..73a61ce --- /dev/null +++ b/cmake/CfdCommonOption.cmake @@ -0,0 +1,90 @@ +if(CMAKE_JS_INC) +option(ENABLE_SHARED "enable shared library (ON or OFF. default:ON)" ON) +else() +option(ENABLE_SHARED "enable shared library (ON or OFF. default:OFF)" OFF) +endif() +option(ENABLE_ELEMENTS "enable elements code (ON or OFF. default:ON)" ON) +option(ENABLE_TESTS "enable code tests (ON or OFF. default:ON)" ON) +option(ENABLE_EMSCRIPTEN "enable EMSCRIPTEN (ON or OFF. default:OFF)" OFF) + +# use "cmake -DCMAKE_BUILD_TYPE=Debug" or "cmake-js -D" +# option(ENABLE_DEBUG "enable debugging (ON or OFF. default:OFF)" OFF) + +if(NOT WIN32) +#option(TARGET_RPATH "target rpath list (separator is ';') (default:)" "") +set(TARGET_RPATH "" CACHE STRING "target rpath list (separator is ';') (default:)") +option(ENABLE_COVERAGE "enable code coverage (ON or OFF. default:OFF)" OFF) +option(ENABLE_RPATH "enable rpath (ON or OFF. default:ON)" ON) +else() +set(TARGET_RPATH "") +set(ENABLE_COVERAGE FALSE) +set(ENABLE_RPATH off) +endif() + +if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") +set(ENABLE_DEBUG TRUE) +set(RPATH_TARGET "Debug") +set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$:DEBUGBUILD>) +if(ENABLE_COVERAGE AND ${ENABLE_COVERAGE}) +set(STACK_PROTECTOR_OPT "") +else() +set(STACK_PROTECTOR_OPT $,/GS,-fstack-check -fstack-protector>) +endif() +else() +set(ENABLE_DEBUG FALSE) +set(RPATH_TARGET "Release") +set(STACK_PROTECTOR_OPT "") +endif() # CMAKE_BUILD_TYPE + +if(NOT WIN32) +if(ENABLE_RPATH) +set(CMAKE_SKIP_BUILD_RPATH FALSE) +if(APPLE) +set(CMAKE_MACOSX_RPATH 1) +else() +set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) +endif() +set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) +set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + +if(TARGET_RPATH) +if(APPLE) +string(REPLACE "\$\$ORIGIN" "." TEMP_RPATH1 "${TARGET_RPATH}") +string(REPLACE "\$ORIGIN" "." TEMP_RPATH2 "${TEMP_RPATH1}") +string(REPLACE "\$\${ORIGIN}" "." TEMP_RPATH3 "${TEMP_RPATH2}") +string(REPLACE "\${ORIGIN}" "." MODIFIED_RPATH "${TEMP_RPATH3}") +set(CMAKE_INSTALL_RPATH "${MODIFIED_RPATH};./;./build/${RPATH_TARGET};@rpath") +else() +string(REPLACE "\$\${ORIGIN}" "$$ORIGIN" TEMP_RPATH1 "${TARGET_RPATH}") +string(REPLACE "\${ORIGIN}" "$ORIGIN" MODIFIED_RPATH "${TEMP_RPATH1}") +set(CMAKE_INSTALL_RPATH "${MODIFIED_RPATH};$ORIGIN/;./;./build/${RPATH_TARGET};@rpath") +endif() +else(TARGET_RPATH) +if(APPLE) +set(CMAKE_INSTALL_RPATH "./;./build/${RPATH_TARGET};@rpath") +else() +set(CMAKE_INSTALL_RPATH "$ORIGIN/;./;./build/${RPATH_TARGET};@rpath") +endif() +endif(TARGET_RPATH) +# message(STATUS "CMAKE_INSTALL_RPATH is => ${CMAKE_INSTALL_RPATH}") +else() +set(CMAKE_SKIP_BUILD_RPATH TRUE) +endif() +endif() + +if(NOT ENABLE_ELEMENTS) +set(ELEMENTS_COMP_OPT "") +set(CFD_ELEMENTS_USE CFD_DISABLE_ELEMENTS) +else() +set(ELEMENTS_COMP_OPT BUILD_ELEMENTS) +set(CFD_ELEMENTS_USE "") +endif() + +if(NOT ENABLE_EMSCRIPTEN) +set(USE_EMSCRIPTEN FALSE) +set(EMSCRIPTEN_OPT "") +else() +set(USE_EMSCRIPTEN TRUE) +set(EMSCRIPTEN_OPT "") +#set(EMSCRIPTEN_OPT "-fwasm-exceptions") +endif() diff --git a/cmake/CfdCommonSetting.cmake b/cmake/CfdCommonSetting.cmake new file mode 100644 index 0000000..d1d6852 --- /dev/null +++ b/cmake/CfdCommonSetting.cmake @@ -0,0 +1,11 @@ +set(BINARY_SUBDIR_NAME $,Debug,Release>) +if(NOT CFD_ROOT_BINARY_DIR) +set(CFD_ROOT_BINARY_DIR ${CMAKE_BINARY_DIR}) +set(CFD_OBJ_BINARY_DIR ${CMAKE_BINARY_DIR}/${BINARY_SUBDIR_NAME}) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CFD_OBJ_BINARY_DIR}) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CFD_OBJ_BINARY_DIR}) # for linux +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CFD_OBJ_BINARY_DIR}) +endif() +# for libwally +set(WALLY_OBJ_BINARY_DIR ${CFD_ROOT_BINARY_DIR}/${BINARY_SUBDIR_NAME}) +set(WALLY_ROOT_BINARY_DIR ${CFD_ROOT_BINARY_DIR}) diff --git a/cmake/CfdCoverage.cmake b/cmake/CfdCoverage.cmake new file mode 100644 index 0000000..7be37f6 --- /dev/null +++ b/cmake/CfdCoverage.cmake @@ -0,0 +1,11 @@ +if(ENABLE_DEBUG AND ENABLE_COVERAGE AND ${ENABLE_DEBUG} AND ${ENABLE_COVERAGE}) +set(COLLECT_COVERAGE ON) +set(PROFILE_ARCS_OPT -fprofile-arcs) +set(TEST_COVERAGE_OPT -ftest-coverage) +set(GCOV_LIBRARY gcov) +set(COVERAGE 1) +else() +set(PROFILE_ARCS_OPT "") +set(TEST_COVERAGE_OPT "") +set(GCOV_LIBRARY "") +endif() diff --git a/cmake/CfdWallyOption.cmake b/cmake/CfdWallyOption.cmake new file mode 100644 index 0000000..63df95d --- /dev/null +++ b/cmake/CfdWallyOption.cmake @@ -0,0 +1,9 @@ +# libwally options +option(ENABLE_SWIG_PYTHON "enable the SWIG python interface (ON or OFF. default:OFF)" OFF) +option(ENABLE_SWIG_JAVA "enable the SWIG java (JNI) interface (ON or OFF. default:OFF)" OFF) +if(CMAKE_JS_INC) +option(ENABLE_JS_WRAPPER "enable the Javascript interface wrappers (ON or OFF. default:ON)" ON) +else() +set(ENABLE_JS_WRAPPER OFF) +endif() +set(GENERATE_WALLY ON) diff --git a/cmake/ConvertSrclistFunction.cmake b/cmake/ConvertSrclistFunction.cmake new file mode 100644 index 0000000..ce78191 --- /dev/null +++ b/cmake/ConvertSrclistFunction.cmake @@ -0,0 +1,10 @@ +function(transform_makefile_srclist INPUT_FILE OUTPUT_FILE) + file(READ ${INPUT_FILE} MAKEFILE_INC_TEXT) + + string(REGEX REPLACE "\\\\\n" "@@@@LF@@@@" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + string(REGEX REPLACE "([a-zA-Z_][a-zA-Z0-9_]*)[\t ]*=[\t ]*([^\n]*)" "SET(\\1 \\2)" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + string(REPLACE "@@@@LF@@@@" "\n" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + string(REGEX REPLACE "\\$\\(([a-zA-Z_][a-zA-Z0-9_]*)\\)" "\${\\1}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + string(REGEX REPLACE "@([a-zA-Z_][a-zA-Z0-9_]*)@" "\${\\1}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) + file(WRITE ${OUTPUT_FILE} ${MAKEFILE_INC_TEXT}) +endfunction() diff --git a/cmake/Cpp11Setting.cmake b/cmake/Cpp11Setting.cmake new file mode 100644 index 0000000..c6beeab --- /dev/null +++ b/cmake/Cpp11Setting.cmake @@ -0,0 +1,18 @@ +if(${ENABLE_DEBUG}) +if(MSVC) +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /Od /Zi") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Od /Zi") +else() +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -ggdb") +endif() +endif() + +if(${USE_EMSCRIPTEN}) +# feature: -fwasm-exceptions +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s DISABLE_EXCEPTION_CATCHING=0") +endif() + +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/cmake/EnableCcache.cmake b/cmake/EnableCcache.cmake new file mode 100644 index 0000000..77e9f11 --- /dev/null +++ b/cmake/EnableCcache.cmake @@ -0,0 +1,19 @@ +option(CCACHE_ENABLE + "If the command ccache is avilable, use it for compile. (default: on)" ON) + +find_program(CCACHE_EXE ccache) +if(CCACHE_EXE) + if(CCACHE_ENABLE) + message(STATUS "Enable ccache") + if(CMAKE_C_COMPILER_LAUNCHER) + set(CMAKE_C_COMPILER_LAUNCHER "${CMAKE_C_COMPILER_LAUNCHER}" "${CCACHE_EXE}") + else() + set(CMAKE_C_COMPILER_LAUNCHER "${CCACHE_EXE}") + endif() + if(CMAKE_CXX_COMPILER_LAUNCHER) + set(CMAKE_CXX_COMPILER_LAUNCHER "${CMAKE_CXX_COMPILER_LAUNCHER}" "${CCACHE_EXE}") + else() + set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_EXE}") + endif() + endif() +endif() diff --git a/doc/Doxyfile b/doc/Doxyfile new file mode 100644 index 0000000..f6b5fed --- /dev/null +++ b/doc/Doxyfile @@ -0,0 +1,2536 @@ +# Doxyfile 1.8.15 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the configuration +# file that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# https://www.gnu.org/software/libiconv/ for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "cfd-python" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = 0.0.1 + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all generated output in the proper direction. +# Possible values are: None, LTR, RTL and Context. +# The default value is: None. + +OUTPUT_TEXT_DIRECTION = None + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines (in the resulting output). You can put ^^ in the value part of an +# alias to insert a newline as if a physical newline was in the original file. +# When you need a literal { or } or , in the value part of an alias you have to +# escape them by means of a backslash (\), this can lead to conflicts with the +# commands \{ and \} for these it is advised to use the version @{ and @} or use +# a double escape (\\{ and \\}) + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice +# sources only. Doxygen will then generate output that is more tailored for that +# language. For instance, namespaces will be presented as modules, types will be +# separated into more groups, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_SLICE = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, +# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: +# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser +# tries to guess whether the code is fixed or free formatted code, this is the +# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is +# Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See https://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 0. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 0 + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO, these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. If +# EXTRACT_ALL is set to YES then this flag will automatically be disabled. +# The default value is: NO. + +WARN_NO_PARAMDOC = YES + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = ../cfd + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: https://www.gnu.org/software/libiconv/) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, +# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, +# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, *.qsf and *.ice. + +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.idl \ + *.ddl \ + *.odl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.cs \ + *.d \ + *.php \ + *.php4 \ + *.php5 \ + *.phtml \ + *.inc \ + *.m \ + *.markdown \ + *.md \ + *.mm \ + *.dox \ + *.py \ + *.pyw \ + *.f90 \ + *.f95 \ + *.f03 \ + *.f08 \ + *.f \ + *.for \ + *.tcl \ + *.vhd \ + *.vhdl \ + *.ucf \ + *.qsf + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = */univalue/* + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# entity all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see https://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# https://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = NO + +# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML +# documentation will contain a main index with vertical navigation menus that +# are dynamically created via Javascript. If disabled, the navigation index will +# consists of multiple levels of tabs that are statically embedded in every HTML +# page. Disable this option to support browsers that do not have Javascript, +# like the Qt help browser. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_MENUS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: https://developer.apple.com/xcode/), introduced with OSX +# 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy +# genXcode/_index.html for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# http://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANSPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# https://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from https://www.mathjax.org before deployment. +# The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /