├── .github └── workflows │ └── workflow.yml ├── .gitignore ├── .travis.yml ├── CHANGELOG ├── CONTRIBUTING.md ├── Changelog.md ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── README.md ├── README_SOLC.md ├── README_bcos3.md ├── attrdict ├── __init__.py ├── default.py ├── dictionary.py ├── mapping.py ├── merge.py └── mixins.py ├── bcos3sdk ├── __init__.py ├── bcos3callbackfuture.py ├── bcos3client.py ├── bcos3datadef.py ├── bcos3sdk_wrap.py ├── bcos3sdkconfig.py ├── consensus_precompile.py ├── precompile_def.py ├── sol │ ├── BfsPrecompiled.sol │ ├── Cast.sol │ ├── ConsensusPrecompiled.sol │ ├── ContractAuthPrecompiled.sol │ ├── Crypto.sol │ ├── EntryWrapper.sol │ ├── SystemConfigPrecompiled.sol │ ├── Table.sol │ └── abi │ │ ├── BfsPrecompiled.abi │ │ ├── Cast.abi │ │ ├── ConsensusPrecompiled.abi │ │ ├── Crypto.abi │ │ ├── EntryWrapper.abi │ │ ├── KVTable.abi │ │ ├── SystemConfigPrecompiled.abi │ │ ├── Table.abi │ │ └── TableManager.abi └── transaction_status.py ├── bcos3sdklib ├── bcos3_sdk_config_sample.ini └── download_c_libs.py ├── bcos_solc.py ├── bin └── accounts │ ├── gm_account.json │ ├── pemtest.pem │ └── pyaccount.keystore ├── ci ├── ci_check.sh ├── ci_local.sh └── code_security_audit.sh ├── client ├── __init__.py ├── bcosclient.py ├── bcoserror.py ├── bcoskeypair.py ├── bcostransactions.py ├── channel_push_dispatcher.py ├── channelhandler.py ├── channelpack.py ├── clientlogger.py ├── codegen_template.py ├── common │ ├── __init__.py │ ├── common.py │ ├── compiler.py │ ├── transaction_common.py │ ├── transaction_exception.py │ └── transaction_status_code.py ├── contractnote.py ├── datatype_parser.py ├── event_callback.py ├── filedownloader.py ├── format_param_by_abi.py ├── gm_account.py ├── local_lib_helper.py ├── precompile │ ├── cns │ │ ├── __init__.py │ │ └── cns_service.py │ ├── common.py │ ├── config │ │ └── config_precompile.py │ ├── consensus │ │ └── consensus_precompile.py │ ├── crud │ │ ├── condition.py │ │ └── crud_service.py │ └── permission │ │ └── permission_service.py ├── signer_impl.py ├── signtransaction.py ├── ssl_sock_wrap.py ├── stattool.py ├── tassl_sock_wrap_impl.py └── transactions.py ├── client_config.py.template ├── clog.ini ├── codegen.py ├── console.py ├── console2.py ├── console3.py ├── console_utils ├── __init__.py ├── cmd_account.py ├── cmd_bcos3_rpc.py ├── cmd_bcos3_transaction.py ├── cmd_encode.py ├── cmd_transaction.py ├── command_parser.py ├── console_common.py ├── precompile.py └── rpc_console.py ├── contracts ├── ArrayDemo.sol ├── HelloEvent.sol ├── HelloWorld.sol ├── HelloWorld6.sol ├── HelloWorldTest.sol ├── HelloWorldex.sol ├── KVTableTest.sol ├── KVTableTest20.sol ├── LiteNote.sol ├── LiteNote6.sol ├── NeedInit.sol ├── NoteGroup.sol ├── NoteItem.sol ├── Ok.sol ├── ParallelContract.sol ├── ParallelOk.sol ├── SimpleInfo.sol ├── Table.sol ├── Table20.sol ├── TableTest.sol ├── TestStruct.sol ├── hello_world.abi ├── hello_world.wasm └── precompile │ ├── CNS.sol │ ├── CRUD.sol │ ├── Consensus.sol │ ├── Permission.sol │ ├── SystemConfig.sol │ └── TableFactory.sol ├── cython_tassl_wrap ├── .gitignore ├── LICENSE ├── README.md ├── build_all.sh ├── channelpack.py ├── clean.sh ├── cpp_common │ ├── client_tools.cpp │ ├── client_tools.h │ ├── native_tassl_sock_wrap.cpp │ ├── native_tassl_sock_wrap.h │ └── native_tassl_sock_wrap_api_def.h ├── cpp_linux │ ├── Makefile │ ├── fetch_tassl_obj.sh │ ├── runtime_libs_linux │ │ ├── cython_tassl_sock_wrap.cpython-38-x86_64-linux-gnu.so │ │ ├── libcrypto.so │ │ ├── libnative_tassl_sock_wrap.so │ │ ├── libssl.so │ │ └── libtassl_sock_wrap.so │ ├── tassl_sock_wrap.cpp │ ├── tassl_sock_wrap.h │ ├── test_native.cpp │ └── test_tassl_sock.cpp ├── cpp_win │ ├── Makefile │ ├── runfast.sh │ ├── runtime_libs_mingw64 │ │ ├── cython_tassl_sock_wrap-cpython-38.dll │ │ ├── libgcc_s_seh-1.dll │ │ ├── libpython3.8.dll │ │ ├── libstdc++-6.dll │ │ ├── libtassl_sock_wrap.dll │ │ ├── libwinpthread-1.dll │ │ └── native_tassl_sock_wrap.dll │ ├── tassl_sock_wrap.h │ ├── test_native.cpp │ ├── test_simple.cpp │ └── test_tassl_sock.cpp ├── cython_tassl_sock_wrap.pxd ├── cython_tassl_sock_wrap.pyx ├── deploy_tool.py ├── doc │ └── total.jpg ├── exec_setup.sh ├── native_tassl_sock_wrap.py ├── run_tassl.sh ├── setup_tassl_sock_wrap.py ├── tassl_ssock_wrap_factory.py ├── test │ ├── litenote │ │ ├── litenote.c │ │ ├── litenote.cpp │ │ ├── litenote.h │ │ ├── litenote.pyx │ │ ├── run_me.sh │ │ ├── setup.py │ │ └── testlitenote.py │ ├── simplessl │ │ ├── Makefile │ │ ├── test.h │ │ └── test_tassl.c │ └── wrap_sample │ │ ├── Makefile │ │ ├── buildext.sh │ │ ├── clib.cpp │ │ ├── clib.h │ │ ├── lib.py │ │ ├── libtest.cpp │ │ ├── py_ssock_wrap.cpp │ │ ├── py_ssock_wrap.pxd │ │ ├── py_ssock_wrap.pyx │ │ ├── pyssocktest.py │ │ ├── run_ssock.sh │ │ ├── setup.py │ │ ├── ssock_wrap.cpp │ │ ├── ssock_wrap.exp │ │ ├── ssock_wrap.h │ │ ├── testlib.py │ │ ├── testssock.py │ │ ├── wrap_test.c │ │ └── wrap_test.cpp ├── test_native_tassl_sock_wrap.py └── test_tassl_sock_wrap.py ├── demo ├── demo_bcos3_amop.py ├── demo_bcos3_event.py ├── demo_event_callback.py ├── demo_get2.py ├── demo_get3.py ├── demo_perf.py ├── demo_transaction2.py └── demo_transaction3.py ├── eth_abi ├── LICENSE ├── README.md ├── __init__.py ├── abi.py ├── base.py ├── codec.py ├── constants.py ├── decoding.py ├── encoding.py ├── exceptions.py ├── grammar.py ├── packed.py ├── py.typed ├── registry.py ├── tools │ ├── __init__.py │ └── _strategies.py └── utils │ ├── __init__.py │ ├── numeric.py │ ├── padding.py │ └── string.py ├── eth_account ├── LICENSE ├── README.md ├── __init__.py ├── _utils │ ├── __init__.py │ ├── keyfile.py │ ├── structured_data │ │ ├── __init__.py │ │ ├── hashing.py │ │ ├── signing.py │ │ └── validation.py │ └── validation.py ├── account.py ├── datastructures.py ├── messages.py └── signers │ ├── __init__.py │ ├── base.py │ └── local.py ├── eth_hash ├── LICENSE ├── README.md ├── __init__.py ├── auto.py ├── backends │ ├── __init__.py │ ├── auto.py │ ├── pycryptodome.py │ └── pysha3.py ├── main.py ├── preimage.py └── utils.py ├── eth_keys ├── LICENSE ├── README.md ├── __init__.py ├── backends │ ├── __init__.py │ ├── base.py │ ├── coincurve.py │ └── native │ │ ├── __init__.py │ │ ├── ecdsa.py │ │ ├── jacobian.py │ │ └── main.py ├── constants.py ├── datatypes.py ├── exceptions.py ├── main.py ├── py.typed ├── utils │ ├── __init__.py │ ├── address.py │ ├── der.py │ ├── module_loading.py │ ├── numeric.py │ └── padding.py └── validation.py ├── eth_rlp ├── HashableRLP.py └── __init__.py ├── eth_typing ├── LICENSE ├── README.md ├── __init__.py ├── abi.py ├── bls.py ├── encoding.py ├── enums.py ├── ethpm.py ├── evm.py └── py.typed ├── eth_utils ├── LICENSE ├── README.md ├── __init__.py ├── __main__.py ├── abi.py ├── address.py ├── applicators.py ├── conversions.py ├── crypto.py ├── currency.py ├── curried │ └── __init__.py ├── debug.py ├── decorators.py ├── encoding.py ├── exceptions.py ├── functional.py ├── hexadecimal.py ├── humanize.py ├── logging.py ├── module_loading.py ├── numeric.py ├── py.typed ├── toolz.py ├── types.py ├── typing │ ├── __init__.py │ └── misc.py └── units.py ├── event_callback.py ├── gmssl ├── README.md ├── __init__.py ├── func.py ├── libsm3 │ ├── LICENSE │ ├── README.md │ ├── __init__.py │ ├── libsm3.py │ ├── sm3.c │ ├── sm3.h │ └── sm3.py ├── sm2.py ├── sm2_helper.py ├── sm2_integer.py ├── sm2_parameter.py ├── sm3.py ├── sm3_implement.py └── sm4.py ├── hexbytes ├── __init__.py ├── main.py └── py.typed ├── images ├── FISCO_BCOS_Logo.svg └── qr_code1.png ├── init_env.sh ├── linux_python_setup.md ├── parsimonious ├── __init__.py ├── exceptions.py ├── expressions.py ├── grammar.py ├── nodes.py ├── tests │ ├── __init__.py │ ├── benchmarks.py │ ├── test_benchmarks.py │ ├── test_expressions.py │ ├── test_grammar.py │ └── test_nodes.py └── utils.py ├── py_vesion_checker.py ├── pytest.ini ├── release_note.txt ├── requirements-ref.txt ├── requirements.txt ├── rlp ├── LICENSE ├── README.md ├── __init__.py ├── atomic.py ├── codec.py ├── exceptions.py ├── lazy.py ├── sedes │ ├── __init__.py │ ├── big_endian_int.py │ ├── binary.py │ ├── boolean.py │ ├── lists.py │ ├── raw.py │ ├── serializable.py │ └── text.py └── utils.py ├── sample ├── AddrTableWorker.abi ├── AddrTableWorker.sol ├── contract.ini ├── error.json ├── posttxbyhash.txt ├── receipt.json └── tx_simpleinfo_set.json ├── setup.py ├── solcjs ├── tests ├── __init__.py ├── test_eventcallback.py ├── test_helloworld.py ├── test_info.py ├── test_simpleinfo.py ├── test_sm2.py ├── test_sm3.py ├── test_sm4.py ├── testaccounts.py ├── testamop.py ├── testbcos3client.py ├── testbcos3event.py ├── testbcos3sdk.py ├── testbcos3tx.py ├── testchannelpack.py ├── testclient.py ├── testcodec.py ├── testconfig.py ├── testconsensus.py ├── testcrypto.py ├── testdatatypeparser.py ├── testdeploy.py ├── testfunctiondata.py ├── testgmaccount.py ├── testhello.py ├── testhelloworldparser.py ├── testjscall.py ├── testjstx.py ├── testrawtranscation.py ├── testrawtx_gm.py ├── testrpc.py ├── testsigner.py ├── testssl.py ├── teststruct.py └── teststructclient.py ├── tools └── download_solc.sh ├── tox.ini └── utils ├── __init__.py ├── abi.py ├── blocks.py ├── caching.py ├── contracts.py ├── datastructures.py ├── datatypes.py ├── decorators.py ├── encoding.py ├── events.py ├── exceptions.py ├── formatters.py ├── function_identifiers.py ├── http.py ├── normalizers.py ├── request.py ├── rpc.py ├── rpc_abi.py ├── threads.py ├── transactions.py └── validation.py /.github/workflows/workflow.yml: -------------------------------------------------------------------------------- 1 | name: Python SDK GitHub Actions 2 | on: 3 | push: 4 | pull_request: 5 | paths-ignore: 6 | - "docs/**" 7 | - "Changelog.md" 8 | - "README.md" 9 | release: 10 | types: [published, created, edited] 11 | jobs: 12 | build: 13 | name: build 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [ubuntu-18.04, macos-latest] 18 | steps: 19 | - uses: actions/checkout@v2 20 | with: 21 | fetch-depth: 5 22 | - name: install macOS dependencies 23 | if: runner.os == 'macOS' 24 | run: brew install openssl@1.1 curl 25 | - name: install Ubuntu dependencies 26 | if: runner.os == 'Linux' 27 | run: sudo apt install -y git curl openssl 28 | - name: install python 29 | run: ./init_env.sh -p 30 | - name: install solc 31 | run: ./init_env.sh -i 32 | - name: run integration for Linux 33 | if: runner.os == 'Linux' 34 | run: eval "$(cat ~/.bashrc | tail -n +10)" && echo ${PATH} && pyenv activate python-sdk && python --version && pip install --upgrade pip && pip install -r requirements.txt && bash -x ci/ci_check.sh 35 | - name: run integration for macos 36 | if: runner.os == 'macOS' 37 | run: eval "$(cat ~/.bashrc | tail -n +10)" && echo ${PATH} && pyenv activate python-sdk && python --version && pip install --upgrade pip && pip install -r requirements.txt && bash -x ci/ci_check.sh 38 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | git: 3 | depth: 5 4 | matrix: 5 | include: 6 | - name: "Scan code with cobra" 7 | python: 3.6 8 | dist: xenial 9 | before_cache: 10 | cache: 11 | before_install: 12 | script: | 13 | bash ci/code_security_audit.sh 14 | - name: "Python 3.7.1 on Xenial Linux" 15 | python: 3.7 # this works for Linux but is ignored on macOS or Windows 16 | dist: xenial # required for Python >= 3.7 17 | - name: "Python 3.6 on Xenial Linux" 18 | python: 3.6 19 | dist: xenial 20 | - name: "Python 3.5 on Xenial Linux" 21 | python: 3.5 22 | dist: xenial 23 | addons: 24 | apt: 25 | packages: 26 | - openssl 27 | - curl 28 | - npm 29 | homebrew: 30 | packages: 31 | - openssl 32 | - curl 33 | - npm 34 | install: 35 | - python --version 36 | - pip install -r requirements.txt 37 | - bash init_env.sh -i 38 | script: | 39 | bash -x ci/ci_check.sh 40 | 41 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | See `docs/releases.rst`. 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | To start development you should begin by cloning the repo. 4 | 5 | ```bash 6 | $ git clone [repo_url] 7 | ``` 8 | -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | (2022-09) 2 | 3 | **新版本:** 支持FISCO BCOS 3.x 4 | 5 | 6 | (2021-09) 7 | 8 | **新特性** 9 | - 支持liquid合约 10 | - 支持结构体参数和结果解析 11 | - 采用native c库连接国密tls 12 | 13 | 14 | (2021-08) 15 | 16 | **新特性** 17 | - 支持liquid合约 18 | - 支持结构体参数和结果解析 19 | - 采用native c库连接国密tls 20 | 21 | ### v0.9.3 22 | (2021-03-30) 23 | 24 | **更新** 25 | - 重构`console.py` 26 | - 控制台`console.py`支持数组类型的参数输入 27 | 28 | 29 | ### v0.9.2 30 | 31 | (2020-06-19) 32 | 33 | **新特性** 34 | - 支持国密算法 35 | - 提供合约事件回调接口 36 | 37 | **更新** 38 | 39 | - 支持使用`console.py`部署和调用参数为`bytes`的合约 40 | 41 | **修复** 42 | 43 | - 修复解析Precompiled合约回执前没有判断回执状态导致的解析异常 44 | 45 | 46 | ### v0.9.1 47 | (2020-06-19) 48 | 49 | **更新** 50 | - 支持带参数的合约部署 51 | - 优化交易回执处理流程 52 | - 添加客户端请求超时逻辑 53 | 54 | 55 | ### v0.9.0 56 | 57 | (2019-08-16) 58 | 59 | **新特性** 60 | 61 | - 提供调用FISCO BCOS 2.0 JSON-RPC的Python API。 62 | - 可基于Channel协议与FISCO BCOS进行通信,保证节点与SDK安全加密通信的同时,接收节点推送的消息。 63 | - 支持交易解析功能:包括交易输入、交易输出、Event Log等ABI数据的拼装和解析。 64 | - 支持合约编译,将sol合约编译成abi和bin文件。 65 | - 支持基于keystore的账户管理。 -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.7-alpine 2 | 3 | ENV USER root 4 | 5 | ENV PATH /root/.local/bin/:$PATH 6 | 7 | RUN mkdir /python-sdk 8 | 9 | WORKDIR /python-sdk 10 | 11 | RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories && \ 12 | apk update && \ 13 | apk add --no-cache gcc g++ python python-dev py-pip openssl bash linux-headers libffi-dev openssl-dev curl wget 14 | 15 | COPY requirements.txt /requirements.txt 16 | 17 | RUN pip install -r /requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --no-cache-dir 18 | 19 | RUN curl -LO https://github.com/FISCO-BCOS/FISCO-BCOS/releases/download/"$(curl -s https://api.github.com/repos/FISCO-BCOS/FISCO-BCOS/releases | grep "\"v2\.[0-9]\.[0-9]\"" | sort -u | tail -n 1 | cut -d \" -f 4)"/build_chain.sh && chmod u+x build_chain.sh && \ 20 | bash build_chain.sh -l "127.0.0.1:4" -p 30300,20200,8545 21 | 22 | COPY . /python-sdk 23 | 24 | RUN bash init_env.sh -i && \ 25 | cp /python-sdk/nodes/127.0.0.1/sdk/* bin/ && \ 26 | ln -s /root/.local/bin/register-python-argcomplete /bin/register-python-argcomplete && \ 27 | echo "eval \"\$(register-python-argcomplete ./console.py)\"" >> ~/.bashrc && \ 28 | echo "eval \"/python-sdk/nodes/127.0.0.1/start_all.sh\"" >> ~/.bashrc 29 | 30 | EXPOSE 20200 30300 8545 31 | 32 | CMD ["bash"] 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 kentzhang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include VERSION 3 | include README.md 4 | include requirements.txt 5 | 6 | recursive-exclude * __pycache__ 7 | recursive-exclude * *.py[co] 8 | -------------------------------------------------------------------------------- /README_SOLC.md: -------------------------------------------------------------------------------- 1 | 原理:solc是solidity合约的编译器。采用二进制的solc编译器,对合约进行编译,而不是采用python代码实现的编译器来直接对合约进行编译。 2 | 3 | ## solc的发布地址: 4 | https://github.com/FISCO-BCOS/solidity/releases 5 | 6 | **合约的编译器选择方式包括** 7 | 8 | 1) 操作系统类型,linux/windows 9 | 2) 合约所用的solidity语言版本,如0.4.x,0.5.x ,0.6.x 10 | 3) 是否国密版本 11 | 12 | **操作次序:** 13 | 14 | 1.在以下链接中选择对应的release发布包,下载到python-sdk/bin/solc目录,或其他可访问的目录 15 | 2.将下载的文件解压(如为压缩包),确认其中的solc程序有可执行权限 16 | 3.确认python-sdk/client_config.py 文件里对solc名字或路径的定义和实际的solc能完全匹配,总之目的是使得编译命令行一定能找到对应的solc 17 | -------------------------------------------------------------------------------- /README_bcos3.md: -------------------------------------------------------------------------------- 1 | 支持FISCO BCOS 3.x接口: [JSON-RPC](https://fisco-bcos-doc.readthedocs.io/zh_CN/latest/docs/develop/api.html)。对于FISCO BCOS3.x,客户端采用Python包装C语言开发的底层SDK库,由SDK库负责网络协议封装和安全通信细节。 2 | 3 | 4 | ## 代码实现 5 | 在bcos3sdk目录: 6 | 7 | - bcos3sdk_wrap.py : 将C语言库包装到Python的实现,基本上是对[C语言SDK的接口](https://fisco-bcos-doc.readthedocs.io/zh_CN/latest/docs/develop/sdk/c_sdk/api.html)逐一进行映射,熟悉python ctypes的话看起来毫无压力 8 | - bcos3client.py : 基于bcos3sdk_wrap.py,增加可配置特性,适当简化接口 9 | 10 | 其他 11 | - console3.py : 面向FISCO BCOS 3.x的控制台入口文件 12 | - console_utils/cmd_bcos3_transaction,cmd_bcos3_rpc 等包含"bcos3"关键字的文件,是面向控制台的命令实现,基本上就是解析输入参数,调用bcos3client.py,并在屏幕上打印信息 13 | 14 | 15 | ## 编解码实现 16 | 17 | - 面向合约的abi编解码采用Python实现,这部分FISCO BCOS 3.x和2.x没有区别 18 | - 面向通信的协议编解码采用开源tars框架协议,不再适用2.x的RLP。由底层库实现,在python层无需关注细节。 19 | 20 | 21 | 配置说明参见 [README.md](./README.md) 里的相关段落 22 | 23 | -------------------------------------------------------------------------------- /attrdict/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | attrdict contains several mapping objects that allow access to their 3 | keys as attributes. 4 | """ 5 | from attrdict.mapping import AttrMap 6 | from attrdict.dictionary import AttrDict 7 | from attrdict.default import AttrDefault 8 | 9 | 10 | __all__ = ['AttrMap', 'AttrDict', 'AttrDefault'] 11 | -------------------------------------------------------------------------------- /attrdict/dictionary.py: -------------------------------------------------------------------------------- 1 | """ 2 | A dict that implements MutableAttr. 3 | """ 4 | from attrdict.mixins import MutableAttr 5 | 6 | import six 7 | 8 | 9 | __all__ = ['AttrDict'] 10 | 11 | 12 | class AttrDict(dict, MutableAttr): 13 | """ 14 | A dict that implements MutableAttr. 15 | """ 16 | def __init__(self, *args, **kwargs): 17 | super(AttrDict, self).__init__(*args, **kwargs) 18 | 19 | self._setattr('_sequence_type', tuple) 20 | self._setattr('_allow_invalid_attributes', False) 21 | 22 | def _configuration(self): 23 | """ 24 | The configuration for an attrmap instance. 25 | """ 26 | return self._sequence_type 27 | 28 | def __getstate__(self): 29 | """ 30 | Serialize the object. 31 | """ 32 | return ( 33 | self.copy(), 34 | self._sequence_type, 35 | self._allow_invalid_attributes 36 | ) 37 | 38 | def __setstate__(self, state): 39 | """ 40 | Deserialize the object. 41 | """ 42 | mapping, sequence_type, allow_invalid_attributes = state 43 | self.update(mapping) 44 | self._setattr('_sequence_type', sequence_type) 45 | self._setattr('_allow_invalid_attributes', allow_invalid_attributes) 46 | 47 | def __repr__(self): 48 | return six.u('AttrDict({contents})').format( 49 | contents=super(AttrDict, self).__repr__() 50 | ) 51 | 52 | @classmethod 53 | def _constructor(cls, mapping, configuration): 54 | """ 55 | A standardized constructor. 56 | """ 57 | attr = cls(mapping) 58 | attr._setattr('_sequence_type', configuration) 59 | 60 | return attr 61 | -------------------------------------------------------------------------------- /attrdict/merge.py: -------------------------------------------------------------------------------- 1 | """ 2 | A right-favoring Mapping merge. 3 | """ 4 | from collections.abc import Mapping 5 | 6 | 7 | __all__ = ['merge'] 8 | 9 | 10 | def merge(left, right): 11 | """ 12 | Merge two mappings objects together, combining overlapping Mappings, 13 | and favoring right-values 14 | 15 | left: The left Mapping object. 16 | right: The right (favored) Mapping object. 17 | 18 | NOTE: This is not commutative (merge(a,b) != merge(b,a)). 19 | """ 20 | merged = {} 21 | 22 | left_keys = frozenset(left) 23 | right_keys = frozenset(right) 24 | 25 | # Items only in the left Mapping 26 | for key in left_keys - right_keys: 27 | merged[key] = left[key] 28 | 29 | # Items only in the right Mapping 30 | for key in right_keys - left_keys: 31 | merged[key] = right[key] 32 | 33 | # in both 34 | for key in left_keys & right_keys: 35 | left_value = left[key] 36 | right_value = right[key] 37 | 38 | if (isinstance(left_value, Mapping) and 39 | isinstance(right_value, Mapping)): # recursive merge 40 | merged[key] = merge(left_value, right_value) 41 | else: # overwrite with right value 42 | merged[key] = right_value 43 | 44 | return merged 45 | -------------------------------------------------------------------------------- /bcos3sdk/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/bcos3sdk/__init__.py -------------------------------------------------------------------------------- /bcos3sdk/bcos3sdkconfig.py: -------------------------------------------------------------------------------- 1 | #读一下bcos3 c sdk 的config文件 2 | import configparser 3 | 4 | 5 | 6 | class Bcos3SDKConfig: 7 | thread_pool_size = 8 8 | message_timeout_ms = 10000 9 | cert = dict() 10 | peers = dict() 11 | def __init__(self,configfile): 12 | 13 | try: 14 | ini = configparser.ConfigParser() 15 | ini.read(configfile) 16 | self.thread_pool_size = ini["common"]["thread_pool_size"] 17 | self.message_timeout_ms = ini["common"]["message_timeout_ms"] 18 | for item in ini["cert"].items(): 19 | self.cert[item[0]]=item[1] 20 | for item in ini["peers"].items(): 21 | self.peers[item[0]]=item[1] 22 | except Exception as e: 23 | print(f"load bcos3 sdk config error! file:{configfile}") 24 | return 25 | 26 | 27 | def getdetail(self): 28 | detail=f"thread_pool_size={self.thread_pool_size};message_timeout_ms={self.message_timeout_ms};" 29 | detail=detail+f"cert:{self.cert};" 30 | detail=detail+f"peers:{self.peers}" 31 | return detail 32 | 33 | 34 | #config = Bcos3SDKConfig("bcos3sdklib/bcos3_sdk_config.ini") 35 | #print(config.getdetail()) 36 | 37 | 38 | ''' 39 | [common] 40 | ; if ssl connection is disabled, default: false 41 | ; disable_ssl = true 42 | ; thread pool size for network message sending recving handing 43 | thread_pool_size = 8 44 | ; send message timeout(ms) 45 | message_timeout_ms = 10000 46 | 47 | ; ssl cert config items, 48 | [cert] 49 | ; ssl_type: ssl or sm_ssl, default: ssl 50 | ssl_type = ssl 51 | ; directory the certificates located in, defaul: ./conf 52 | ca_path=./bcos3sdklib 53 | ; the ca certificate file 54 | ca_cert=ca.crt 55 | ; the node private key file 56 | sdk_key=sdk.key 57 | ; the node certificate file 58 | sdk_cert=sdk.crt 59 | 60 | [peers] 61 | # supported ipv4 and ipv6 62 | node.0=127.0.0.1:20200 63 | 64 | ''' -------------------------------------------------------------------------------- /bcos3sdk/precompile_def.py: -------------------------------------------------------------------------------- 1 | from client.datatype_parser import DatatypeParser 2 | 3 | SYS_CONFIG_PRECOMPILED_ADDRESS = "0000000000000000000000000000000000001000" 4 | TABLE_MANAGER_PRECOMPILED_ADDRESS = "0000000000000000000000000000000000001002" 5 | 6 | CONSENSUS_PRECOMPILED_ADDRESS = "0000000000000000000000000000000000001003" 7 | 8 | CONTRACT_AUTH_ADDRESS = "0000000000000000000000000000000000001005" 9 | 10 | BFS_PRECOMPILED_ADDRESS = "000000000000000000000000000000000000100e" 11 | 12 | COMMITTEE_MANAGER_ADDRESS = "0000000000000000000000000000000000010001" 13 | 14 | ACCOUNT_MANAGER_ADDRESS = "0000000000000000000000000000000000010003" 15 | 16 | PRECOMPILED_SOL_PATH = "bcos3sdk/sol" 17 | PRECOMPILED_ABI_PATH = f"{PRECOMPILED_SOL_PATH}/abi" 18 | 19 | 20 | class PrecompileHelper: 21 | 22 | address = "" 23 | abi_file = "" 24 | abi_parser = None 25 | 26 | def __init__(self,filename:str,address): 27 | self.address = address 28 | if not filename.endswith(".abi"): 29 | filename = filename + ".abi" 30 | abipath = PRECOMPILED_ABI_PATH 31 | self.abi_file = f"{abipath}/{filename}" 32 | self.abi_parser = DatatypeParser(self.abi_file) 33 | 34 | -------------------------------------------------------------------------------- /bcos3sdk/sol/BfsPrecompiled.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.6.0; 3 | pragma experimental ABIEncoderV2; 4 | 5 | struct BfsInfo{ 6 | string file_name; 7 | string file_type; 8 | string[] ext; 9 | } 10 | 11 | contract BfsPrecompiled { 12 | function list(string memory absolutePath) public view returns (int256,BfsInfo[] memory){} 13 | function mkdir(string memory absolutePath) public returns (int256){} 14 | function link(string memory name, string memory version, address _address, string memory _abi) public returns (int256){} 15 | function readlink(string memory absolutePath) public view returns (address) {} 16 | function touch(string memory absolutePath, string memory fileType) public returns (int256){} 17 | } -------------------------------------------------------------------------------- /bcos3sdk/sol/Cast.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | abstract contract Cast { 6 | function stringToS256(string memory) public virtual view returns (int256); 7 | function stringToS64(string memory) public virtual view returns (int64); 8 | function stringToU256(string memory) public virtual view returns (uint256); 9 | function stringToAddr(string memory) public virtual view returns (address); 10 | function stringToBytes32(string memory) public virtual view returns (bytes32); 11 | 12 | function s256ToString(int256) public virtual view returns (string memory); 13 | function s64ToString(int64) public virtual view returns (string memory); 14 | function u256ToString(uint256) public virtual view returns (string memory); 15 | function addrToString(address) public virtual view returns (string memory); 16 | function bytes32ToString(bytes32) public virtual view returns (string memory); 17 | } -------------------------------------------------------------------------------- /bcos3sdk/sol/ConsensusPrecompiled.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.6.0; 3 | 4 | contract ConsensusPrecompiled { 5 | function addSealer(string memory,uint256) public returns (int256){} 6 | function addObserver(string memory) public returns (int256){} 7 | function remove(string memory) public returns (int256){} 8 | function setWeight(string memory,uint256) public returns (int256){} 9 | } 10 | -------------------------------------------------------------------------------- /bcos3sdk/sol/ContractAuthPrecompiled.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.6.0; 3 | 4 | abstract contract ContractAuthPrecompiled { 5 | function getAdmin(address path) public view returns (address); 6 | function resetAdmin(address path, address admin) public returns (int256); 7 | function setMethodAuthType(address path, bytes4 func, uint8 authType) public returns (int256); 8 | function openMethodAuth(address path, bytes4 func, address account) public returns (int256); 9 | function closeMethodAuth(address path, bytes4 func, address account) public returns (int256); 10 | function checkMethodAuth(address path, bytes4 func, address account) public view returns (bool); 11 | function getMethodAuth(address path, bytes4 func) public view returns (uint8,string[] memory,string[] memory); 12 | function setContractStatus(address _address, bool isFreeze) public returns(int); 13 | function contractAvailable(address _address) public view returns (bool); 14 | 15 | function deployType() public view returns (uint256); 16 | function setDeployAuthType(uint8 _type) public returns (int256); 17 | function openDeployAuth(address account) public returns (int256); 18 | function closeDeployAuth(address account) public returns (int256); 19 | function hasDeployAuth(address account) public view returns (bool); 20 | } 21 | -------------------------------------------------------------------------------- /bcos3sdk/sol/Crypto.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.6.0; 3 | 4 | contract Crypto 5 | { 6 | function sm3(bytes memory data) public view returns(bytes32){} 7 | function keccak256Hash(bytes memory data) public view returns(bytes32){} 8 | function sm2Verify(bytes memory message, bytes memory sign) public view returns(bool, address){} 9 | // not support now 10 | function curve25519VRFVerify(string memory input, string memory vrfPublicKey, string memory vrfProof) public view returns(bool,uint256){} 11 | } -------------------------------------------------------------------------------- /bcos3sdk/sol/SystemConfigPrecompiled.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.6.0; 3 | 4 | contract SystemConfigPrecompiled 5 | { 6 | function setValueByKey(string memory key, string memory value) public returns(int256){} 7 | function getValueByKey(string memory key) public view returns(string memory,int256){} 8 | } 9 | -------------------------------------------------------------------------------- /bcos3sdk/sol/abi/BfsPrecompiled.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"address","name":"_address","type":"address"},{"internalType":"string","name":"_abi","type":"string"}],"name":"link","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"absolutePath","type":"string"}],"name":"list","outputs":[{"internalType":"int256","name":"","type":"int256"},{"components":[{"internalType":"string","name":"file_name","type":"string"},{"internalType":"string","name":"file_type","type":"string"},{"internalType":"string[]","name":"ext","type":"string[]"}],"internalType":"struct BfsInfo[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"absolutePath","type":"string"}],"name":"mkdir","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"absolutePath","type":"string"}],"name":"readlink","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"absolutePath","type":"string"},{"internalType":"string","name":"fileType","type":"string"}],"name":"touch","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"}] -------------------------------------------------------------------------------- /bcos3sdk/sol/abi/Cast.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"addrToString","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"bytes32ToString","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"","type":"int256"}],"name":"s256ToString","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int64","name":"","type":"int64"}],"name":"s64ToString","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"stringToAddr","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"stringToBytes32","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"stringToS256","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"stringToS64","outputs":[{"internalType":"int64","name":"","type":"int64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"stringToU256","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"u256ToString","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}] -------------------------------------------------------------------------------- /bcos3sdk/sol/abi/ConsensusPrecompiled.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"addObserver","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"addSealer","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"remove","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"setWeight","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"}] -------------------------------------------------------------------------------- /bcos3sdk/sol/abi/Crypto.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"string","name":"input","type":"string"},{"internalType":"string","name":"vrfPublicKey","type":"string"},{"internalType":"string","name":"vrfProof","type":"string"}],"name":"curve25519VRFVerify","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"keccak256Hash","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"message","type":"bytes"},{"internalType":"bytes","name":"sign","type":"bytes"}],"name":"sm2Verify","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"sm3","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"}] -------------------------------------------------------------------------------- /bcos3sdk/sol/abi/KVTable.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"string","name":"key","type":"string"}],"name":"get","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"key","type":"string"},{"internalType":"string","name":"value","type":"string"}],"name":"set","outputs":[{"internalType":"int32","name":"","type":"int32"}],"stateMutability":"nonpayable","type":"function"}] -------------------------------------------------------------------------------- /bcos3sdk/sol/abi/SystemConfigPrecompiled.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"string","name":"key","type":"string"}],"name":"getValueByKey","outputs":[{"internalType":"string","name":"","type":"string"},{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"key","type":"string"},{"internalType":"string","name":"value","type":"string"}],"name":"setValueByKey","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"}] -------------------------------------------------------------------------------- /bcos3sdk/sol/abi/TableManager.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"string","name":"path","type":"string"},{"internalType":"string[]","name":"newColumns","type":"string[]"}],"name":"appendColumns","outputs":[{"internalType":"int32","name":"","type":"int32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tableName","type":"string"},{"internalType":"string","name":"keyField","type":"string"},{"internalType":"string","name":"valueField","type":"string"}],"name":"createKVTable","outputs":[{"internalType":"int32","name":"","type":"int32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"path","type":"string"},{"components":[{"internalType":"enum KeyOrder","name":"keyOrder","type":"uint8"},{"internalType":"string","name":"keyColumn","type":"string"},{"internalType":"string[]","name":"valueColumns","type":"string[]"}],"internalType":"struct TableInfo","name":"tableInfo","type":"tuple"}],"name":"createTable","outputs":[{"internalType":"int32","name":"","type":"int32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tableName","type":"string"}],"name":"descWithKeyOrder","outputs":[{"components":[{"internalType":"enum KeyOrder","name":"keyOrder","type":"uint8"},{"internalType":"string","name":"keyColumn","type":"string"},{"internalType":"string[]","name":"valueColumns","type":"string[]"}],"internalType":"struct TableInfo","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"path","type":"string"}],"name":"openTable","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}] -------------------------------------------------------------------------------- /bcos3sdklib/bcos3_sdk_config_sample.ini: -------------------------------------------------------------------------------- 1 | 2 | [common] 3 | ; if ssl connection is disabled, default: false 4 | ; disable_ssl = true 5 | ; thread pool size for network message sending recving handing 6 | thread_pool_size = 8 7 | ; send message timeout(ms) 8 | message_timeout_ms = 10000 9 | 10 | ; ssl cert config items, 11 | [cert] 12 | ; ssl_type: ssl or sm_ssl, default: ssl 13 | ssl_type = ssl 14 | ; directory the certificates located in, defaul: ./conf 15 | ca_path=./bcos3sdklib 16 | ; the ca certificate file.Filename only,NOT the full path 17 | ca_cert=ca.crt 18 | ; the node private key file.Filename only,NOT the full path 19 | sdk_key=sdk.key 20 | ; the node certificate file.Filename only,NOT the full path 21 | sdk_cert=sdk.crt 22 | 23 | [peers] 24 | # supported ipv4 and ipv6 25 | node.0=127.0.0.1:20200 26 | -------------------------------------------------------------------------------- /bin/accounts/gm_account.json: -------------------------------------------------------------------------------- 1 | { 2 | "address": "0x7fe7097870bb7C63b3718096dd7EB08ADC85b57F", 3 | "encrypt": true, 4 | "private_key": "qzBCfflxrZgHAVYyPemTr6xhXU4ovDrpxXaAyU+CjdsuemGm+C98HLN3L5cj5vrVwvGor9o/0YC3Hw6xEBn6lJcrxukIIBAOg+H6EL3fQRw=", 5 | "type": "gm", 6 | "mac": "0dd56145b6604312f036d2b35fc8199f0270f5101a013a5e5967445772ed761a" 7 | } -------------------------------------------------------------------------------- /bin/accounts/pemtest.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgQSJvXhNPlOJNso486vn/ 3 | pYUnhifCtGgyUeVaaelPdvWhRANCAATthgXrNxXNOlZJTjLmPofiCqWJ2rQ/JgBc 4 | 12cS3p9c0SKKNZHGKWn9zgifTAkBYEpO9eLsuOyMkvtxf9KbkIYt 5 | -----END PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /bin/accounts/pyaccount.keystore: -------------------------------------------------------------------------------- 1 | {"address": "95198b93705e394a916579e048c8a32ddfb900f7", "crypto": {"cipher": "aes-128-ctr", "cipherparams": {"iv": "08914ce9686399cf0b3383a687bda88e"}, "ciphertext": "779ba3be11624e7f3417530f9133b4479d635ce36df00a364f114f4dc2105faa", "kdf": "scrypt", "kdfparams": {"dklen": 32, "n": 262144, "r": 1, "p": 8, "salt": "fbb85bc239b2188b8da3968e20ef09e7"}, "mac": "62db212e67000aae00ea1ca26181f32b54b6330df18acf89bb0a09cf6c3b5065"}, "id": "a2ed5353-f861-4873-95fb-344604c74f63", "version": 3} -------------------------------------------------------------------------------- /ci/code_security_audit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | scan_code_script="python ~/cobra/cobra.py -t " 6 | ignore_files=(ci README.md console.py event_callback.py eth_account eth_abi \ 7 | eth_hash eth_keys eth_rlp eth_typing eth_utils tests gmssl \ 8 | hexbytes utils rlp client eth_account/account.py bin/accounts/gm_account.json) 9 | 10 | LOG_ERROR() { 11 | content=${1} 12 | echo -e "\033[31m${content}\033[0m" 13 | } 14 | 15 | LOG_INFO() { 16 | content=${1} 17 | echo -e "\033[32m${content}\033[0m" 18 | } 19 | 20 | execute_cmd() { 21 | command="${1}" 22 | eval ${command} 23 | ret=$? 24 | if [ $ret -ne 0 ];then 25 | LOG_ERROR "FAILED of command: ${command}" 26 | exit 1 27 | else 28 | LOG_INFO "SUCCESS of command: ${command}" 29 | fi 30 | } 31 | 32 | should_ignore() 33 | { 34 | local file=${1} 35 | for ignore in ${ignore_files[*]}; do 36 | if echo ${file} | grep ${ignore} &>/dev/null; then 37 | echo "ignore ${file} ${ignore}" 38 | return 0 39 | fi 40 | done 41 | return 1 42 | } 43 | 44 | scan_code() 45 | { 46 | # Redirect output to stderr. 47 | exec 1>&2 48 | for file in $(git diff-index --name-status HEAD^ | grep -v .ci | awk '{print $2}'); do 49 | if should_ignore ${file}; then continue; fi 50 | LOG_INFO "check file ${file}" 51 | execute_cmd "${scan_code_script} $file -f json -o /tmp/report.json" 52 | trigger_rules=$(jq -r '.' /tmp/report.json | grep 'trigger_rules' | awk '{print $2}' | sed 's/,//g') 53 | echo "trigger_rules is ${trigger_rules}" 54 | rm /tmp/report.json 55 | if [ ${trigger_rules} -ne 0 ]; then 56 | echo "######### ERROR: Scan code failed, please adjust them before commit" 57 | exit 1 58 | fi 59 | done 60 | } 61 | 62 | install_cobra() { 63 | git clone https://github.com/WhaleShark-Team/cobra.git ~/cobra 64 | pip install -r ~/cobra/requirements.txt 65 | cp ~/cobra/config.template ~/cobra/config 66 | } 67 | 68 | install_cobra 69 | scan_code 70 | -------------------------------------------------------------------------------- /client/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/client/__init__.py -------------------------------------------------------------------------------- /client/bcoskeypair.py: -------------------------------------------------------------------------------- 1 | 2 | class BcosKeyPair: 3 | private_key = None 4 | public_key = None 5 | address = None 6 | 7 | def getdetail(self, sep="\n"): 8 | strmsg = "private key: %s%spublic key: %s%saddress: %s" % ( 9 | self.private_key, sep, self.public_key, sep, self.address) 10 | return strmsg 11 | -------------------------------------------------------------------------------- /client/clientlogger.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 5 | FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the 6 | terms of the MIT License as published by the Free Software Foundation. This project is 7 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 8 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for 9 | authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils, 10 | rlp, eth-rlp , hexbytes ... and relative projects 11 | @author: kentzhang 12 | @date: 2019-06 13 | ''' 14 | 15 | 16 | import logging 17 | from logging import handlers 18 | import os 19 | 20 | from client_config import client_config 21 | log_config = client_config 22 | logger = logging.getLogger(__name__) 23 | logger.setLevel(level=logging.DEBUG) 24 | logdir = log_config.logdir 25 | logfile = logdir + "/client.log" 26 | if os.path.exists(logdir) is False: 27 | os.makedirs(logdir) 28 | # handler = logging.FileHandler(logfile) 29 | handler = logging.handlers.TimedRotatingFileHandler(logfile, 'D', 1, 0) # 切割日志 30 | handler.suffix = '%Y%m%d' # 切割后的日志设置后缀 31 | # handler.setLevel(logging.DEBUG) 32 | # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 33 | formatter = logging.Formatter('%(asctime)s %(levelname)s - %(message)s') 34 | handler.setFormatter(formatter) 35 | logger.addHandler(handler) 36 | 37 | 38 | statlogger = logging.getLogger("STAT") 39 | statlogger.setLevel(level=logging.DEBUG) 40 | logfile = logdir + "/stat.log" 41 | # handler = logging.FileHandler(logfile) 42 | handler = logging.handlers.TimedRotatingFileHandler(logfile, 'D', 1, 0) # 切割日志 43 | handler.suffix = '%Y%m%d' # 切割后的日志设置后缀 44 | # handler.setLevel(logging.DEBUG) 45 | # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 46 | formatter = logging.Formatter('%(asctime)s %(levelname)s - %(message)s') 47 | handler.setFormatter(formatter) 48 | statlogger.addHandler(handler) 49 | -------------------------------------------------------------------------------- /client/codegen_template.py: -------------------------------------------------------------------------------- 1 | # template for codegen 2 | from client.bcosclient import ( 3 | BcosClient 4 | ) 5 | from client.datatype_parser import DatatypeParser 6 | import json 7 | 8 | 9 | class TEMPLATE_CLASSNAME: # name of abi 10 | address = None 11 | contract_abi_string = '''TEMPLATE_CONTRACT_ABI''' 12 | contract_abi = None 13 | data_parser = DatatypeParser() 14 | client = None 15 | 16 | def __init__(self, address): 17 | self.client = BcosClient() 18 | self.address = address 19 | self.contract_abi = json.loads(self.contract_abi_string) 20 | self.data_parser.set_abi(self.contract_abi) 21 | 22 | def deploy(self, contract_bin_file): 23 | result = self.client.deployFromFile(contract_bin_file) 24 | self.address = result["contractAddress"] 25 | return result 26 | -------------------------------------------------------------------------------- /client/common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/client/common/__init__.py -------------------------------------------------------------------------------- /client/common/transaction_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the 5 | is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 6 | FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the 7 | is free software: you can redistribute it and/or modify it under the 8 | terms of the MIT License as published by the Free Software Foundation. This project is 9 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 10 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for 11 | authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils, 12 | rlp, eth-rlp , hexbytes ... and relative projects 13 | @file: transaction_exception.py 14 | @function: 15 | @author: yujiechen 16 | @date: 2019-07 17 | ''' 18 | 19 | 20 | class TransactionException(Exception): 21 | """ 22 | define common transaction exception 23 | """ 24 | 25 | def __init__(self, receipt_json=None, err='TransactionException'): 26 | """ 27 | define exception 28 | """ 29 | Exception.__init__(self, err) 30 | self.receipt = receipt_json 31 | 32 | def get_status_error_info(self): 33 | """ 34 | get status information 35 | """ 36 | if int(self.receipt['status'], 16) != 0: 37 | return '''transaction failure for non-zero status, 38 | status:{}'''.format(self.receipt['status']) 39 | return "valid transaction receipt, status: {}".format(self.receipt['status']) 40 | 41 | def get_output_error_info(self): 42 | """ 43 | get output information 44 | """ 45 | if self.receipt['output'] is None: 46 | return "transaction failure for empty output" 47 | return "valid transaction receipt, output: {}".format(self.receipt['output']) 48 | -------------------------------------------------------------------------------- /client/filedownloader.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from tqdm import tqdm 3 | 4 | 5 | 6 | 7 | def download_file(url, local_path,proxies=None): 8 | response = requests.get(url,proxies=proxies) 9 | # 检查请求是否成功 10 | if response.status_code == 200: 11 | with open(local_path, 'wb') as file: 12 | file.write(response.content) 13 | print(f"File download to :{local_path}") 14 | else: 15 | print(f"File download FAIL,status :{response.status_code}") 16 | 17 | 18 | def download_file_with_progress(url, local_path,proxies=None): 19 | response = requests.get(url, stream=True,proxies=proxies) 20 | 21 | # 获取文件大小(以字节为单位) 22 | file_size = int(response.headers.get('Content-Length', 0)) 23 | 24 | # 设置进度条 25 | progress_bar = tqdm(total=file_size, unit='B', unit_scale=True) 26 | 27 | # 写入文件 28 | with open(local_path, 'wb') as file: 29 | for data in response.iter_content(chunk_size=1024): 30 | progress_bar.update(len(data)) 31 | file.write(data) 32 | progress_bar.close() 33 | print(f"File download to :{local_path}") 34 | 35 | 36 | 37 | 38 | ''' 39 | # 例子:下载图片 40 | url = 'https://example.com/image.jpg' 41 | local_path = 'path/to/save/image.jpg' 42 | 43 | download_file(url, local_path) 44 | 45 | 46 | 47 | # 例子:下载图片 48 | url = 'https://example.com/image.jpg' 49 | local_path = 'path/to/save/image.jpg' 50 | 51 | download_file_with_progress(url, local_path) 52 | ''' 53 | -------------------------------------------------------------------------------- /client/precompile/cns/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/client/precompile/cns/__init__.py -------------------------------------------------------------------------------- /client/precompile/common.py: -------------------------------------------------------------------------------- 1 | ''' 2 | FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 3 | FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the 4 | terms of the MIT License as published by the Free Software Foundation. This project is 5 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 6 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for 7 | authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils, 8 | rlp, eth-rlp , hexbytes ... and relative projects 9 | @file: consensus_precompile.py 10 | @function: 11 | @author: yujiechen 12 | @date: 2019-07 13 | ''' 14 | 15 | 16 | class PrecompileCommon: 17 | """ 18 | define common values related to precompile 19 | """ 20 | SYS_TABLE = "_sys_tables_" 21 | SYS_TABLE_KEY = "table_name" 22 | USER_TABLE_PREFIX = "u_" 23 | SYS_TABLE_ACCESS = "_sys_table_access_" 24 | SYS_CONSENSUS = "_sys_consensus_" 25 | SYS_CNS = "_sys_cns_" 26 | SYS_CONFIG = "_sys_config_" 27 | # define the error information 28 | error_code = {} 29 | error_code["-50000"] = "PermissionPrecompiled: Permission Denied" 30 | error_code["-50001"] = "CRUD: Table Exist" 31 | error_code["-51502"] = "CRUD: Undefined operator" 32 | error_code["-51501"] = "CRUD: Parse condition error" 33 | error_code["-51500"] = "CRUD: Parse Entry error" 34 | error_code["-51000"] = "PermissionPrecompiled: Already Granted" 35 | error_code["-51001"] = "PermissionPrecompiled: TableName And Account Not Exist" 36 | error_code["-51100"] = "Invalid NodeId" 37 | error_code["-51101"] = "Last Sealer" 38 | error_code["-51102"] = "P2p Network" 39 | error_code["-51103"] = "Group Peers" 40 | error_code["-51104"] = "Sealer List" 41 | error_code["-51105"] = "Observer List" 42 | error_code["-51200"] = "CNS: ContractNameAndVersion Exist" 43 | error_code["-51201"] = "CNS: Version Exceeds" 44 | error_code["-51300"] = "SysConfig: Invalid Key, must be tx_gas_limit or tx_count_limit" 45 | -------------------------------------------------------------------------------- /client/precompile/config/config_precompile.py: -------------------------------------------------------------------------------- 1 | ''' 2 | FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 3 | FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the 4 | terms of the MIT License as published by the Free Software Foundation. This project is 5 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 6 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for 7 | authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils, 8 | rlp, eth-rlp , hexbytes ... and relative projects 9 | @file: config_precompile.py 10 | @function: 11 | @author: yujiechen 12 | @date: 2019-07 13 | ''' 14 | 15 | from client.common import transaction_common 16 | 17 | 18 | class ConfigPrecompile: 19 | """ 20 | implementation of ConfigPrecompile 21 | """ 22 | 23 | def __init__(self, contract_path): 24 | """ 25 | init the address for SystemConfig contract 26 | """ 27 | self._config_address = "0x0000000000000000000000000000000000001000" 28 | self.gasPrice = 300000000 29 | self.client = transaction_common.TransactionCommon( 30 | self._config_address, contract_path, "SystemConfig") 31 | 32 | def setValueByKey(self, key, value): 33 | """ 34 | set value for the givn key 35 | """ 36 | fn_name = "setValueByKey" 37 | fn_args = [key, value] 38 | return self.client.send_transaction_getReceipt(fn_name, fn_args, self.gasPrice) 39 | -------------------------------------------------------------------------------- /client/stattool.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 5 | FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the 6 | terms of the MIT License as published by the Free Software Foundation. This project is 7 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 8 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for 9 | authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils, 10 | rlp, eth-rlp , hexbytes ... and relative projects 11 | @author: kentzhang 12 | @date: 2019-06 13 | ''' 14 | from client import clientlogger 15 | import time 16 | 17 | 18 | class StatTool: 19 | time_begin = time.time() 20 | time_end = 0 21 | time_used = 0 22 | unit = "ms" 23 | @staticmethod 24 | def begin(unit="ms"): 25 | stat = StatTool() 26 | stat.time_begin = time.time() 27 | stat.unit = unit 28 | return stat 29 | 30 | def done(self): 31 | self.time_end = time.time() 32 | return self.till_now() 33 | 34 | def till_now(self): 35 | self.time_used = self.time_end - self.time_begin 36 | return self.time_used 37 | 38 | def make_statmsg(self, msg): 39 | if self.time_end == 0: 40 | self.done() 41 | timeused_toshow = self.time_used 42 | 43 | if self.unit == "ms": 44 | timeused_toshow = timeused_toshow * 1000 45 | 46 | statmsg = "%.3f%s,%s" % (timeused_toshow, self.unit, msg) 47 | return statmsg 48 | 49 | def debug(self, msg): 50 | clientlogger.statlogger.debug(self.make_statmsg(msg)) 51 | 52 | def info(self, msg): 53 | clientlogger.statlogger.info(self.make_statmsg(msg)) 54 | 55 | def error(self, msg): 56 | clientlogger.statlogger.info(self.make_statmsg(msg)) 57 | -------------------------------------------------------------------------------- /client/tassl_sock_wrap_impl.py: -------------------------------------------------------------------------------- 1 | # 国密的实现,引入对TASSL的cython包装 2 | 3 | import sys 4 | 5 | from client.ssl_sock_wrap import CommonSSLSockWrap 6 | 7 | sys.path.append("./client") 8 | 9 | ECHO_NONE = 0x0000 10 | ECHO_PRINTF = 0x0001 11 | ECHO_LOG = 0x0010 12 | 13 | 14 | class TasslSockWrap(CommonSSLSockWrap): 15 | ssock: CommonSSLSockWrap = None 16 | 17 | def __init__(self): 18 | from cython_tassl_wrap.tassl_ssock_wrap_factory import tassl_ssock_wrap_factory 19 | self.ssock = tassl_ssock_wrap_factory() 20 | print("INFO >> SSL using tassl ssock : ", type(self.ssock)) 21 | 22 | def try_connect(self, host=None, port=0): 23 | # print("try_connect") 24 | return self.ssock.try_connect(host, port) 25 | 26 | def recv(self, recvsize) -> bytes: 27 | # print("---DO RECV----",recvsize) 28 | # traceback.print_stack() 29 | r = self.ssock.recv(recvsize) 30 | # print("IMPL-RECV----->",r) 31 | return r 32 | 33 | def send(self, buffer): 34 | # print("---DO SEND----",buffer) 35 | return self.ssock.send(buffer) 36 | 37 | def finish(self): 38 | # traceback.print_stack() 39 | self.ssock.finish() 40 | 41 | def init(self, ca_file, node_crt_file, node_key_file, en_crt_file=None, en_key_file=None, 42 | protocol=None, verify_mode=None): 43 | self.ssock.set_echo_mode(ECHO_NONE) 44 | r = self.ssock.init(ca_file, node_crt_file, node_key_file, en_crt_file, en_key_file) 45 | 46 | return r 47 | -------------------------------------------------------------------------------- /clog.ini: -------------------------------------------------------------------------------- 1 | [log] 2 | enable=true 3 | log_path=./log 4 | ; network statistics interval, unit is second, default is 60s 5 | stat_flush_interval=60 6 | ; info debug trace 7 | level=DEBUG 8 | ; MB 9 | max_log_file_size=200 -------------------------------------------------------------------------------- /console.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # PYTHON_ARGCOMPLETE_OK 3 | # -*- coding: utf-8 -*- 4 | """ 5 | FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 6 | FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the 7 | terms of the MIT License as published by the Free Software Foundation. This project is 8 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 9 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for 10 | authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils, 11 | rlp, eth-rlp , hexbytes ... and relative projects 12 | @author: kentzhang 13 | @date: 2019-06 14 | 15 | """ 16 | hint = ''' 17 | python sdk 适配FISCO BCOS 2.x/3.x版本,控制台的实现文件做了分离。 18 | 19 | README文档的命令行示例里未做版本区分,仅供演示参考,实际使用时: 20 | 21 | * 如面向FISCO BCOS2.x,把console.py换成console2.py。如: python console2.py getBlockNumber 22 | 23 | * 如面向FISCO BCOS3.x,把console.py换成console3.py。如: python console3.py getBlockNumber 24 | 25 | demo目录里的demo_get2/3, demo_transaction2/3的逻辑与此类似。 26 | 27 | ''' 28 | 29 | print(hint) -------------------------------------------------------------------------------- /console_utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/console_utils/__init__.py -------------------------------------------------------------------------------- /contracts/ArrayDemo.sol: -------------------------------------------------------------------------------- 1 | pragma solidity>=0.4.24 <0.6.11; 2 | pragma experimental ABIEncoderV2; 3 | 4 | 5 | contract ArrayDemo{ 6 | event on_set(uint256 value,string[] data); 7 | uint256 value; 8 | string[] data; 9 | 10 | constructor() public { 11 | value = 0; 12 | } 13 | 14 | function total() public view returns (uint256) { 15 | return data.length; 16 | } 17 | 18 | function get(uint256 index)public view returns (uint256,string) { 19 | return (value,data[index]); 20 | } 21 | 22 | 23 | function add(uint256 v,string[] inputdata) public returns (uint256) { 24 | 25 | value = v; 26 | for(uint i=0; i=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | import "./Table.sol"; 6 | 7 | contract KVTableTest { 8 | 9 | TableManager tm; 10 | KVTable table; 11 | string constant tableName = "t_kv_test"; 12 | event SetEvent(int256 count); 13 | constructor () public{ 14 | tm = TableManager(address(0x1002)); 15 | 16 | // create table 17 | tm.createKVTable(tableName, "id", "item_name"); 18 | 19 | // get table address 20 | address t_address = tm.openTable(tableName); 21 | table = KVTable(t_address); 22 | } 23 | 24 | function desc() public view returns(string memory, string memory){ 25 | TableInfo memory tf = tm.desc(tableName); 26 | return (tf.keyColumn, tf.valueColumns[0]); 27 | } 28 | 29 | function get(string memory id) public view returns (bool, string memory) { 30 | bool ok = false; 31 | string memory value; 32 | (ok, value) = table.get(id); 33 | return (ok, value); 34 | } 35 | 36 | function set(string memory id, string memory item_name) 37 | public 38 | returns (int32) 39 | { 40 | int32 result = table.set(id,item_name); 41 | emit SetEvent(result); 42 | return result; 43 | } 44 | 45 | function createKVTableTest(string memory _tableName,string memory keyName,string memory fieldName) public returns(int32){ 46 | int32 result = tm.createKVTable(_tableName, keyName, fieldName); 47 | return result; 48 | } 49 | } -------------------------------------------------------------------------------- /contracts/KVTableTest20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.24; 2 | import "./Table20.sol"; 3 | 4 | contract KVTableTest20 { 5 | event SetResult(int256 count); 6 | 7 | KVTableFactory tableFactory; 8 | string constant TABLE_NAME = "t_kvtest"; 9 | 10 | constructor() public { 11 | //The fixed address is 0x1010 for KVTableFactory 12 | tableFactory = KVTableFactory20(0x1010); 13 | // the parameters of createTable are tableName,keyField,"vlaueFiled1,vlaueFiled2,vlaueFiled3,..." 14 | tableFactory.createTable(TABLE_NAME, "id", "item_price,item_name"); 15 | } 16 | 17 | //get record 18 | function get(string id) public view returns (bool, int256, string) { 19 | KVTable table = tableFactory.openTable(TABLE_NAME); 20 | bool ok = false; 21 | Entry entry; 22 | (ok, entry) = table.get(id); 23 | int256 item_price; 24 | string memory item_name; 25 | if (ok) { 26 | item_price = entry.getInt("item_price"); 27 | item_name = entry.getString("item_name"); 28 | } 29 | return (ok, item_price, item_name); 30 | } 31 | 32 | //set record 33 | function set(string id, int256 item_price, string item_name) 34 | public 35 | returns (int256) 36 | { 37 | KVTable table = tableFactory.openTable(TABLE_NAME); 38 | Entry entry = table.newEntry(); 39 | // the length of entry's field value should < 16MB 40 | entry.set("id", id); 41 | entry.set("item_price", item_price); 42 | entry.set("item_name", item_name); 43 | // the first parameter length of set should <= 255B 44 | int256 count = table.set(id, entry); 45 | emit SetResult(count); 46 | return count; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /contracts/NeedInit.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.24; 2 | 3 | contract NeedInit{ 4 | string name; 5 | uint256 value; 6 | event onset(string newname); 7 | constructor(string name_,uint256 v_) public{ 8 | name = name_; 9 | value = v_; 10 | } 11 | 12 | function get() constant public returns(string,uint256){ 13 | return (name,value); 14 | } 15 | 16 | function set(string n) public{ 17 | emit onset(n); 18 | name = n; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /contracts/NoteItem.sol: -------------------------------------------------------------------------------- 1 | pragma solidity>=0.4.24 <0.6.11; 2 | 3 | contract NoteItem{ 4 | string public timestamp; 5 | string public title; 6 | string public content; 7 | 8 | constructor() public 9 | { 10 | } 11 | 12 | function set_time(string memory t) public 13 | { 14 | timestamp =t; 15 | } 16 | 17 | function set_title(string memory t) public 18 | { 19 | title = t; 20 | } 21 | 22 | function set_content(string memory c) public 23 | { 24 | content = c; 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /contracts/Ok.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.24; 2 | contract Ok{ 3 | 4 | struct Account{ 5 | address account; 6 | uint balance; 7 | } 8 | 9 | struct Translog { 10 | string time; 11 | address from; 12 | address to; 13 | uint amount; 14 | } 15 | 16 | Account from; 17 | Account to; 18 | event TransEvent(uint num); 19 | Translog[] log; 20 | 21 | function Ok(){ 22 | from.account=0x1; 23 | from.balance=10000000000; 24 | to.account=0x2; 25 | to.balance=0; 26 | 27 | } 28 | 29 | function get()constant returns(uint){ 30 | return to.balance; 31 | } 32 | 33 | function trans(uint num){ 34 | if (from.balance < num || to.balance + num < to.balance) 35 | return; // Deny overflow 36 | 37 | from.balance=from.balance-num; 38 | to.balance+=num; 39 | TransEvent(num); 40 | log.push(Translog("20170413",from.account,to.account,num)); 41 | } 42 | } -------------------------------------------------------------------------------- /contracts/ParallelContract.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.25; 2 | 3 | contract ParallelConfigPrecompiled 4 | { 5 | function registerParallelFunctionInternal(address, string, uint256) public returns (int); 6 | function unregisterParallelFunctionInternal(address, string) public returns (int); 7 | } 8 | 9 | contract ParallelContract 10 | { 11 | ParallelConfigPrecompiled precompiled = ParallelConfigPrecompiled(0x1006); 12 | 13 | function registerParallelFunction(string functionName, uint256 criticalSize) public 14 | { 15 | precompiled.registerParallelFunctionInternal(address(this), functionName, criticalSize); 16 | } 17 | 18 | function unregisterParallelFunction(string functionName) public 19 | { 20 | precompiled.unregisterParallelFunctionInternal(address(this), functionName); 21 | } 22 | 23 | function enableParallel() public; 24 | function disableParallel() public; 25 | } -------------------------------------------------------------------------------- /contracts/ParallelOk.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.25; 2 | 3 | import "./ParallelContract.sol"; 4 | 5 | // A parallel contract example 6 | contract ParallelOk is ParallelContract 7 | { 8 | mapping (string => uint256) _balance; 9 | 10 | // Just an example, overflow is ok, use 'SafeMath' if needed 11 | function transfer(string from, string to, uint256 num) public 12 | { 13 | _balance[from] -= num; 14 | _balance[to] += num; 15 | } 16 | 17 | // Just for testing whether the parallel revert function is working well, no practical use 18 | function transferWithRevert(string from, string to, uint256 num) public 19 | { 20 | _balance[from] -= num; 21 | _balance[to] += num; 22 | require(num <= 100); 23 | } 24 | 25 | function set(string name, uint256 num) public 26 | { 27 | _balance[name] = num; 28 | } 29 | 30 | function balanceOf(string name) public view returns (uint256) 31 | { 32 | return _balance[name]; 33 | } 34 | 35 | // Register parallel function 36 | function enableParallel() public 37 | { 38 | // critical number is to define how many critical params from start 39 | registerParallelFunction("transfer(string,string,uint256)", 2); // critical: string string 40 | registerParallelFunction("set(string,uint256)", 1); // critical: string 41 | } 42 | 43 | // Disable register parallel function 44 | function disableParallel() public 45 | { 46 | unregisterParallelFunction("transfer(string,string,uint256)"); 47 | unregisterParallelFunction("set(string,uint256)"); 48 | } 49 | } -------------------------------------------------------------------------------- /contracts/TestStruct.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.3; 2 | pragma experimental ABIEncoderV2; 3 | 4 | contract TestStruct { 5 | 6 | struct User { 7 | string name; 8 | uint256 age; 9 | } 10 | 11 | event onadd(string newname); 12 | event onadduser(string newname,User u); 13 | event onaddusers(uint256 len,User[] u); 14 | 15 | mapping (string => User) users; 16 | 17 | constructor() public 18 | { 19 | User memory u = User("alice",25); 20 | addUser(u); 21 | } 22 | 23 | 24 | function addUser (User memory _user) public { 25 | 26 | addbyname(_user.name,_user); 27 | 28 | 29 | } 30 | 31 | function addbyname (string memory name,User memory _user) public { 32 | 33 | users[name] = _user; 34 | emit onadd(name); 35 | emit onadduser(name,_user); 36 | 37 | } 38 | 39 | function addUsers (User [] memory _users) public { 40 | 41 | for (uint i = 0; i < _users.length; i++) { 42 | //users[_users[i].name] = _users[i]; 43 | addUser(_users[i]); 44 | } 45 | emit onaddusers(_users.length,_users); 46 | } 47 | 48 | function getUser (string memory username) public view returns (User memory) { 49 | 50 | //bytes32 hash = keccak256(abi.encode(username)); 51 | return users[username]; 52 | } 53 | event on_putbytes(string n,bytes32 b); 54 | function putbytes(string memory uname,bytes32 br) public 55 | { 56 | emit on_putbytes(uname,br); 57 | } 58 | } -------------------------------------------------------------------------------- /contracts/hello_world.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"constant":true,"inputs":[],"name":"get","outputs":[{"type":"string","name":""}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"type":"string","name":"name"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}] -------------------------------------------------------------------------------- /contracts/hello_world.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/contracts/hello_world.wasm -------------------------------------------------------------------------------- /contracts/precompile/CNS.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.24; 2 | contract CNS 3 | { 4 | function selectByName(string name) public constant returns(string); 5 | function selectByNameAndVersion(string name, string version) public constant returns(string); 6 | function insert(string name, string version, string addr, string cnsAbi) public returns(int); 7 | } 8 | -------------------------------------------------------------------------------- /contracts/precompile/CRUD.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.2; 2 | 3 | contract CRUD 4 | { 5 | function insert(string tableName, string key, string entry, string optional) public returns(int); 6 | function update(string tableName, string key, string entry, string condition, string optional) public returns(int); 7 | function remove(string tableName, string key, string condition, string optional) public returns(int); 8 | function select(string tableName, string key, string condition, string optional) public constant returns(string); 9 | } -------------------------------------------------------------------------------- /contracts/precompile/Consensus.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.2; 2 | 3 | contract Consensus { 4 | function addSealer(string nodeID) public returns(int); 5 | function addObserver(string nodeID) public returns(int); 6 | function remove(string nodeID) public returns(int); 7 | } 8 | -------------------------------------------------------------------------------- /contracts/precompile/Permission.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.2; 2 | 3 | contract Permission { 4 | function insert(string table_name, string addr) public returns(int); 5 | function remove(string table_name, string addr) public returns(int); 6 | function queryByName(string table_name) public constant returns(string); 7 | } 8 | -------------------------------------------------------------------------------- /contracts/precompile/SystemConfig.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.2; 2 | 3 | contract SystemConfig { 4 | 5 | function setValueByKey(string key, string value) public returns(int); 6 | } 7 | -------------------------------------------------------------------------------- /contracts/precompile/TableFactory.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.2; 2 | 3 | contract TableFactory { 4 | function createTable(string tableName, string key, string valueField) public returns (int); 5 | } 6 | -------------------------------------------------------------------------------- /cython_tassl_wrap/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 kentzhang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /cython_tassl_wrap/build_all.sh: -------------------------------------------------------------------------------- 1 | sysname=`uname -s` 2 | ext='so' 3 | cpp_path="" 4 | echo -e current dev environment is: "\033[33m $sysname\033[0m" 5 | echo ----------------------- 6 | case $sysname in 7 | Linux*) 8 | echo -e Using "\033[33m [Linux] \033[0m" configuration '---------->' 9 | cpp_path="cpp_linux" 10 | echo "goto" $cpp_path 11 | cd cpp_linux 12 | source ./fetch_tassl_obj.sh 13 | make 14 | cp *.so .. 15 | cd .. 16 | ;; 17 | MINGW64*) 18 | echo -e Using "\033[33m [Windows] $sysname \033[0m" configuration '---------->' 19 | cpp_path="cpp_win" 20 | echo "goto" $cpp_path 21 | cd cpp_win 22 | make 23 | ext=dll 24 | cp *.dll ../ 25 | cd .. 26 | ;; 27 | *) echo "unknown system"; exit 1;; 28 | esac 29 | echo ------------------------- 30 | echo return to : `pwd` 31 | 32 | CFLAGS="" LDFLAGS="-L`pwd` -L$TASSL -L./$cpp_path" python setup_tassl_sock_wrap.py build_ext --inplace 33 | echo 34 | echo "---- after build: --->" 35 | echo 36 | ls -l *.$ext 37 | #ldd *.$ext 38 | #cp *$ext .. 39 | -------------------------------------------------------------------------------- /cython_tassl_wrap/clean.sh: -------------------------------------------------------------------------------- 1 | rm -f libtassl_sock_wrap.so 2 | rm -f cython_tassl_sock_wrap.*.so 3 | rm -f cython_tassl_sock_wrap*.dll 4 | rm -f libtassl_*.so 5 | rm -f libnative_*.so 6 | rm -f libssl.so 7 | rm -f libcryto.so 8 | rm -f cython_tassl_sock_wrap.cpp 9 | rm -rf build 10 | rm -rf dist 11 | rm -rf __pycache__ 12 | cd cpp_linux 13 | make clean 14 | cd .. 15 | cd cpp_win 16 | make clean 17 | cd .. 18 | -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_common/client_tools.cpp: -------------------------------------------------------------------------------- 1 | 2 | //仅供测试使用的小方法 3 | #include 4 | #include 5 | #include 6 | #ifdef __WINDOWS__ 7 | #include 8 | #endif 9 | #ifdef __LINUX__ 10 | #include 11 | #endif 12 | void printhex(char *str, int len) 13 | { 14 | char buff[4096]="\0"; 15 | int i; 16 | for(i=0;i= $objcount " 27 | echo !!! MAKE SURE DONE this : '"config shared;make;make install"' in $TASSL !!! 28 | exit -2 29 | fi 30 | fi 31 | 32 | 33 | -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_linux/runtime_libs_linux/cython_tassl_sock_wrap.cpython-38-x86_64-linux-gnu.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_linux/runtime_libs_linux/cython_tassl_sock_wrap.cpython-38-x86_64-linux-gnu.so -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_linux/runtime_libs_linux/libcrypto.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_linux/runtime_libs_linux/libcrypto.so -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_linux/runtime_libs_linux/libnative_tassl_sock_wrap.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_linux/runtime_libs_linux/libnative_tassl_sock_wrap.so -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_linux/runtime_libs_linux/libssl.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_linux/runtime_libs_linux/libssl.so -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_linux/runtime_libs_linux/libtassl_sock_wrap.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_linux/runtime_libs_linux/libtassl_sock_wrap.so -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_linux/tassl_sock_wrap.h: -------------------------------------------------------------------------------- 1 | /* 2 | This lib is a tls client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 3 | This lib is free software: you can redistribute it and/or modify it under the 4 | terms of the MIT License as published by the Free Software Foundation. This project is 5 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 6 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 7 | @author: kentzhang 8 | @date: 2021-03 9 | */ 10 | #ifndef TASSL_SOCK_WRAP 11 | #define TASSL_SOCK_WRAP 12 | #include 13 | #include 14 | 15 | 16 | namespace fisco_tassl_sock_wrap{ 17 | #define ECHO_NONE 0x0000 18 | #define ECHO_PRINTF 0x0001 19 | #define ECHO_LOG 0x0010 20 | 21 | class TasslSockWrap{ 22 | char host[256]; 23 | int port; 24 | char ca_crt_file[256]; 25 | char sign_crt_file[256]; 26 | char sign_key_file[256]; 27 | char en_crt_file[256]; 28 | char en_key_file[256]; 29 | SSL *ssl ; 30 | SSL_CTX *ctx ; 31 | int load_ca_files(); 32 | bool is_connected; 33 | int sock; 34 | int echo_mode ; 35 | protected: 36 | int init_openssl(); 37 | void print_ssl_error(int err,const char *memo); 38 | int create_socket(); 39 | void close_socket(); 40 | void set_host_port(const char *host_, int port_); 41 | int connect_socket_async(); 42 | int handshake(); 43 | //type : 0: read,1:write,2:both 44 | int select_socket(int sock_fd,int type, int timeout_msec);//超时时间:毫秒 45 | public : 46 | TasslSockWrap(); 47 | ~TasslSockWrap(); 48 | 49 | 50 | int init(const char *ca_crt_file_, 51 | const char * sign_crt_file_, 52 | const char * sign_key_file_, 53 | const char * en_crt_file_, 54 | const char * en_key_file_ 55 | ); 56 | 57 | int try_connect(const char *host_,const int port_); 58 | int finish(); 59 | void set_echo_mode(int mode); 60 | 61 | 62 | 63 | 64 | int send(const char * buffer,const int len); 65 | int recv(char *buffer,const int buffersize); 66 | }; 67 | 68 | 69 | } 70 | 71 | #endif -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runfast.sh: -------------------------------------------------------------------------------- 1 | make clean 2 | make 3 | ./test_tassl_sock 4 | -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runtime_libs_mingw64/cython_tassl_sock_wrap-cpython-38.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_win/runtime_libs_mingw64/cython_tassl_sock_wrap-cpython-38.dll -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libgcc_s_seh-1.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libgcc_s_seh-1.dll -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libpython3.8.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libpython3.8.dll -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libstdc++-6.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libstdc++-6.dll -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libtassl_sock_wrap.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libtassl_sock_wrap.dll -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libwinpthread-1.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_win/runtime_libs_mingw64/libwinpthread-1.dll -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/runtime_libs_mingw64/native_tassl_sock_wrap.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/cpp_win/runtime_libs_mingw64/native_tassl_sock_wrap.dll -------------------------------------------------------------------------------- /cython_tassl_wrap/cpp_win/tassl_sock_wrap.h: -------------------------------------------------------------------------------- 1 | /* 2 | This lib is a tls client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) 3 | This lib is free software: you can redistribute it and/or modify it under the 4 | terms of the MIT License as published by the Free Software Foundation. This project is 5 | distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even 6 | the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 7 | @author: kentzhang 8 | @date: 2021-03 9 | */ 10 | #ifndef TASSL_SOCK_WRAP 11 | #define TASSL_SOCK_WRAP 12 | #include 13 | #include 14 | 15 | 16 | namespace fisco_tassl_sock_wrap{ 17 | #define ECHO_NONE 0x0000 18 | #define ECHO_PRINTF 0x0001 19 | #define ECHO_LOG 0x0010 20 | 21 | class TasslSockWrap{ 22 | char host[256]; 23 | int port; 24 | char ca_crt_file[256]; 25 | char sign_crt_file[256]; 26 | char sign_key_file[256]; 27 | char en_crt_file[256]; 28 | char en_key_file[256]; 29 | SSL *ssl ; 30 | SSL_CTX *ctx ; 31 | int load_ca_files(); 32 | bool is_connected; 33 | int sock; 34 | int echo_mode ; 35 | protected: 36 | void print_ssl_error(int err,const char *memo); 37 | int create_socket(); 38 | void close_socket(); 39 | void set_host_port(const char *host_, int port_); 40 | int connect_socket_async(); 41 | int handshake(); 42 | //type : 0: read,1:write,2:both 43 | int select_socket(int sock_fd,int type, int timeout_msec);//超时时间:毫秒 44 | public : 45 | TasslSockWrap(); 46 | ~TasslSockWrap(); 47 | 48 | int init(const char *ca_crt_file_, 49 | const char * sign_crt_file_, 50 | const char * sign_key_file_, 51 | const char * en_crt_file_, 52 | const char * en_key_file_ 53 | ); 54 | 55 | int try_connect(const char *host_,const int port_); 56 | int finish(); 57 | void set_echo_mode(int mode); 58 | 59 | 60 | 61 | 62 | int send(const char * buffer,const int len); 63 | int recv(char *buffer,const int buffersize); 64 | }; 65 | 66 | 67 | } 68 | 69 | #endif -------------------------------------------------------------------------------- /cython_tassl_wrap/cython_tassl_sock_wrap.pxd: -------------------------------------------------------------------------------- 1 | # cython: language_level=3 2 | # Declare the class with cdef 3 | cdef extern from "tassl_sock_wrap.h" namespace "fisco_tassl_sock_wrap": 4 | cdef cppclass TasslSockWrap: 5 | TasslSockWrap() except + 6 | 7 | int init(const char *ca_crt_file_, 8 | const char * sign_crt_file_, 9 | const char * sign_key_file_, 10 | const char * en_crt_file_, 11 | const char * en_key_file_ 12 | ); 13 | 14 | int try_connect(const char *host_,const int port_); 15 | int finish(); 16 | 17 | void set_echo_mode(int mode); 18 | 19 | int send(const char * buffer,const int len); 20 | int recv(char *buffer,const int buffersize); -------------------------------------------------------------------------------- /cython_tassl_wrap/cython_tassl_sock_wrap.pyx: -------------------------------------------------------------------------------- 1 | # cython: language_level=3 2 | # distutils: language = c++ 3 | # import traceback 4 | # traceback.print_stack() 5 | 6 | from cpython.bytes cimport PyBytes_FromStringAndSize 7 | from cython_tassl_sock_wrap cimport TasslSockWrap 8 | 9 | import time 10 | 11 | 12 | cdef class PyTasslSockWrap: 13 | cdef TasslSockWrap* ssock # Hold a C++ instance which we're wrapping 14 | 15 | def __cinit__(self): 16 | #print("in pyx ->cinit") 17 | self.ssock = new TasslSockWrap() 18 | 19 | 20 | def __dealloc__(self): 21 | del self.ssock 22 | 23 | 24 | 25 | def finish(self): 26 | self.ssock.finish() 27 | 28 | 29 | def init(self, 30 | ca_crt_file_, 31 | sign_crt_file_, 32 | sign_key_file_, 33 | en_crt_file_, 34 | en_key_file_ 35 | ): 36 | return self.ssock.init( 37 | ca_crt_file_.encode("UTF-8"), 38 | sign_crt_file_.encode("UTF-8"), 39 | sign_key_file_.encode("UTF-8"), 40 | en_crt_file_.encode("UTF-8"), 41 | en_key_file_.encode("UTF-8") 42 | ) 43 | 44 | def try_connect(self,host,port): 45 | self.ssock.try_connect(host.encode("UTF-8"),port) 46 | 47 | ECHO_MODE_NONE = 0 48 | ECHO_MODE_PRINTF = 0x01 49 | ECHO_MODE_LOG = 0x10 50 | 51 | def set_echo_mode(self,mode): 52 | self.ssock.set_echo_mode(mode) 53 | 54 | def send(self,buffer: bytes,bufferlen=None): 55 | # print("{ in pyx -->} ssock send :",buffer) 56 | if bufferlen is None: 57 | bufferlen = len(buffer) 58 | for i in range(0,3): 59 | r = self.ssock.send(buffer,bufferlen) 60 | if r>0: 61 | break 62 | time.sleep(0.1) 63 | return r; 64 | 65 | 66 | def recv(self,buffersize=None) -> bytes: 67 | 68 | buffersize = 102400 # must = char buffer[SIZE] 69 | cdef char buffer[102400]; 70 | r = self.ssock.recv(buffer,buffersize) 71 | # print("{ in pyx -->} after recv ,len ", r ) 72 | bytebuffer:bytes = b'' 73 | if(r>0): 74 | bytebuffer = PyBytes_FromStringAndSize(buffer,r) 75 | # print(bytebuffer) 76 | return bytebuffer 77 | 78 | -------------------------------------------------------------------------------- /cython_tassl_wrap/doc/total.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/doc/total.jpg -------------------------------------------------------------------------------- /cython_tassl_wrap/exec_setup.sh: -------------------------------------------------------------------------------- 1 | CFLAGS="-I`pwd` -I./cpp_linux -I$TASSL/include/openssl " LDFLAGS="-L`pwd` -L$TASSL" python setup_tassl_sock_wrap.py $* 2 | -------------------------------------------------------------------------------- /cython_tassl_wrap/run_tassl.sh: -------------------------------------------------------------------------------- 1 | echo 2 | echo "build python Extension" 3 | source build_all.sh 4 | echo 5 | #echo "run cpp test --->" 6 | #cpp_linux/test_tassl_sock 7 | echo 8 | echo "start python test -->" 9 | echo 10 | python test_tassl_sock_wrap.py 11 | echo 12 | echo "<--python test done" 13 | -------------------------------------------------------------------------------- /cython_tassl_wrap/setup_tassl_sock_wrap.py: -------------------------------------------------------------------------------- 1 | import os 2 | import platform 3 | from distutils.core import Extension 4 | from distutils.core import setup 5 | 6 | from Cython.Build import cythonize 7 | 8 | if "TASSL" in os.environ: 9 | TASSL_ENV = os.environ["TASSL"] 10 | else: 11 | TASSL_ENV = "./" 12 | target_platform = "linux" 13 | include_dir = "./cpp_linux" 14 | platsys = platform.system() 15 | if platsys.lower().startswith("win"): 16 | target_platform = "win64" 17 | include_dir = "./cpp_win" 18 | 19 | print("set target platform = {} ,on system :{}\n".format(target_platform, platsys)) 20 | 21 | extension = Extension( 22 | "cython_tassl_sock_wrap", 23 | ["cython_tassl_sock_wrap.pyx"], 24 | include_dirs=["./", include_dir, TASSL_ENV + "/include/openssl"], 25 | extra_link_args=["-L./ -L" + TASSL_ENV], 26 | libraries=["tassl_sock_wrap"], 27 | ) 28 | 29 | setup( 30 | name='cython_tassl_sock_wrap', 31 | version='0.2.0', 32 | description='use TASSL to connect fisco bcos , wrap cpp code by @cython', 33 | url='https://github.com/fisco-bcos/python-sdk', 34 | license='MIT', 35 | platforms=[target_platform], 36 | ext_modules=cythonize([extension]) 37 | ) 38 | -------------------------------------------------------------------------------- /cython_tassl_wrap/tassl_ssock_wrap_factory.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | 5 | def tassl_ssock_wrap_factory(print_err=False): 6 | wrap = None 7 | sys.path.append(os.path.dirname(__file__)) 8 | # print(os.path.dirname(__file__)) 9 | # print(sys.path) 10 | try: 11 | from cython_tassl_sock_wrap import PyTasslSockWrap 12 | wrap = PyTasslSockWrap() 13 | except Exception as e: 14 | if print_err: 15 | print("init PyTasslSockWrap fail") 16 | import traceback 17 | traceback.print_exc() 18 | pass 19 | 20 | if wrap is not None: 21 | return wrap 22 | # --------------try native_tassl_sock_wrap ------------------------ 23 | try: 24 | from native_tassl_sock_wrap import NativeTasslSockWrap 25 | wrap = NativeTasslSockWrap() 26 | except Exception as e: 27 | print("init PyTasslSockWrap fail") 28 | import traceback 29 | traceback.print_exc() 30 | pass 31 | return wrap 32 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/litenote/litenote.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "litenote.h" 5 | int write_note(char * text) 6 | { 7 | 8 | printf("in c code : %s \n",text); 9 | return 99; 10 | } 11 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/litenote/litenote.h: -------------------------------------------------------------------------------- 1 | #ifdef __cplusplus 2 | extern "C" { 3 | #endif 4 | 5 | int write_note(char * text); 6 | 7 | 8 | #ifdef __cplusplus 9 | } 10 | #endif -------------------------------------------------------------------------------- /cython_tassl_wrap/test/litenote/litenote.pyx: -------------------------------------------------------------------------------- 1 | def say_hello_to(name): 2 | print("Hello %s!" % name) 3 | 4 | cdef extern from "litenote.h": 5 | int write_note(char * text) 6 | 7 | def py_write_note(text): 8 | return write_note(text) -------------------------------------------------------------------------------- /cython_tassl_wrap/test/litenote/run_me.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -xe 4 | rm -f *.o 5 | rm -f *.so 6 | gcc -fPIC -shared -g *.cpp -o liblitenote.so 7 | 8 | 9 | CFLAGS="-I`pwd`" LDFLAGS="-L`pwd`" python setup.py build_ext --inplace 10 | 11 | LD_LIBRARY_PATH=`pwd` python testlitenote.py 12 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/litenote/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup, Extension 2 | from Cython.Build import cythonize 3 | 4 | 5 | # setup(name='cython litenote app', 6 | # ext_modules=cythonize("litenote.pyx")) 7 | 8 | 9 | extension = Extension( 10 | "litenote", 11 | ["litenote.pyx"], 12 | libraries=["litenote"] 13 | ) 14 | 15 | setup( 16 | ext_modules=cythonize([extension]) 17 | ) 18 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/litenote/testlitenote.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import litenote 3 | litenote.say_hello_to("test") 4 | 5 | litenote.py_write_note(b'open open mmm') 6 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/simplessl/Makefile: -------------------------------------------------------------------------------- 1 | LINUX_CFLAGS=-Wall -pedantic -g -O2 2 | LINUX_LIBS= 3 | 4 | all: test_tassl 5 | 6 | 7 | #common flags 8 | CC=gcc 9 | SYSCFLAGS= 10 | SYSLIBS= 11 | LDFLAGS=$(SYSLIBS) 12 | INCLUDES= 13 | CFLAGS=$(SYSCFLAGS) $(INCLUDES) 14 | LINUX_CFLAGS=-Wall -pedantic -g -O2 15 | 16 | #for openssl & tassl 17 | OPENSSL_DIR=../../../TASSL 18 | OPENSSL_INCLUDES=-I$(OPENSSL_DIR)/include 19 | OPENSSL_LIBS=-L$(OPENSSL_DIR) -lssl -lcrypto -ldl 20 | OPENSSL_LDFLAGS=$(SYSLIBS) $(OPENSSL_LIBS) 21 | LIB_TASSL_SOCK_WRAP_CFLAGS=$(CFLAGS) $(OPENSSL_INCLUDES) $(LINUX_CFLAGS) -fPIC 22 | 23 | 24 | TEST_SOURCES=test_tassl.c 25 | TEST_OBJS=test_tassl.o 26 | TEST_CFLAGS= $(LIB_TASSL_SOCK_WRAP_CFLAGS) 27 | TEST_LDFLAGS=-lstdc++ -L./ 28 | test_tassl: $(TEST_SOURCES) 29 | @echo "-->Build test" 30 | $(CC) $(TEST_CFLAGS) -c test_tassl.c 31 | $(CC) $(TEST_CFLAGS) $(TEST_LDFLAGS) $(OPENSSL_LDFLAGS) test_tassl.o -o test_tassl 32 | 33 | 34 | 35 | clean: 36 | @rm -f *.o 37 | @rm -f test_tassl -------------------------------------------------------------------------------- /cython_tassl_wrap/test/simplessl/test.h: -------------------------------------------------------------------------------- 1 | #ifndef TEST_TASSL 2 | #define TEST_TASSL 3 | #endif 4 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/Makefile: -------------------------------------------------------------------------------- 1 | LINUX_CFLAGS=-Wall -pedantic -g -O2 2 | LINUX_LIBS= 3 | 4 | all: lib native libtest.exe 5 | 6 | test: wrap_test 7 | lib: libssock_wrap.dll 8 | native: native_lib.dll 9 | 10 | #common flags 11 | CC=gcc 12 | SYSCFLAGS= 13 | SYSLIBS= 14 | LDFLAGS=$(SYSLIBS) 15 | INCLUDES= 16 | CFLAGS=$(SYSCFLAGS) $(INCLUDES) 17 | LINUX_CFLAGS=-Wall -pedantic -g -O2 18 | 19 | 20 | 21 | 22 | TEST_SOURCES=wrap_test.cpp 23 | TEST_OBJS=wrap_test.o 24 | TEST_CFLAGS=$(CFLAGS) 25 | TEST_LDFLAGS=-L./ -lssock_wrap -lstdc++ 26 | wrap_test: $(TEST_SOURCES) libssock_wrap.so 27 | @echo "-->Build test" 28 | $(CC) $(TEST_CFLAGS) $(LINUX_CFLAGS) -c wrap_test.cpp -o wrap_test.o 29 | $(CC) $(TEST_OBJS) $(TEST_CFLAGS) $(TEST_LDFLAGS) -o wrap_test 30 | 31 | 32 | libtest.exe :libtest.cpp 33 | @echo "-->Build lib test" 34 | $(CC) $(TEST_CFLAGS) $(LINUX_CFLAGS) -c libtest.cpp -o libtest.o 35 | $(CC) libtest.o $(TEST_CFLAGS) -o libtest 36 | 37 | 38 | 39 | LIB_SOURCES=ssock_wrap.cpp clib.cpp 40 | LIB_OBJS=ssock_wrap.o 41 | LIB_CFLAGS=$(CFLAGS) 42 | LIB_LDFLAGS=-shared -Wl,--output-def,ssock_wrap.def,--out-implib,ssock_wrap.lib 43 | libssock_wrap.dll: $(LIB_SOURCES) 44 | @echo "-->Build ssock lib" 45 | $(CC) $(LIB_CFLAGS) $(LINUX_CFLAGS) -fPIC -c ssock_wrap.cpp 46 | $(CC) ssock_wrap.o $(LIB_LDFLAGS) -lstdc++ -o ssock_wrap.dll 47 | 48 | NATIVE_LIB_LDFLAGS=-shared -Wl,--output-def,native_lib.def,--out-implib,native_lib.lib 49 | native_lib.dll:clib.cpp 50 | @echo "-->Build native lib" 51 | $(CC) $(LIB_CFLAGS) $(LINUX_CFLAGS) -fPIC -c clib.cpp 52 | $(CC) clib.o ssock_wrap.o $(NATIVE_LIB_LDFLAGS) -lstdc++ -o native_lib.dll 53 | 54 | 55 | clean: 56 | @rm -f wrap_test 57 | @rm -f libssock_wrap.so 58 | @rm -f ssock_wrap.o 59 | @rm -f *.o 60 | @rm -f *.so 61 | @rm -f ssock_wrap.dll 62 | @rm -f *.def 63 | @rm -f *.lib 64 | @rm -r *.exe 65 | @rm -r native_lib.dll 66 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/buildext.sh: -------------------------------------------------------------------------------- 1 | LDFLAGS="-L./" python setup.py build_ext --inplace 2 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/clib.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "ssock_wrap.h" 4 | #include 5 | #include "clib.h" 6 | 7 | //using namespace clibtest; 8 | using namespace py_ssock_wrap; 9 | namespace clib_space 10 | { 11 | SSockWrap sw; 12 | int testprint(const char *info) 13 | { 14 | printf(info); 15 | 16 | char buff[256]="dll testing\n"; 17 | int retval = 0; 18 | retval = sw.init(23); 19 | printf("[in testprint] init ret %d\n",retval); 20 | retval = sw.write(buff,strlen(buff)); 21 | fflush(stdout); 22 | return 99; 23 | } 24 | 25 | void * create(int param,int * retval) 26 | { 27 | SSockWrap *psw =new SSockWrap(); 28 | *retval = psw->init(param); 29 | printf("create pointer %ld\n",psw); 30 | fflush(stdout); 31 | return psw; 32 | 33 | } 34 | 35 | 36 | int create_pp(int param,void **pp) 37 | { 38 | SSockWrap *psw =new SSockWrap(); 39 | int retval = psw->init(param); 40 | printf("create pointer %ld\n",psw); 41 | *pp = psw; 42 | fflush(stdout); 43 | return retval; 44 | 45 | } 46 | int call(const void * obj,const char *buff) 47 | { 48 | SSockWrap *psw = (SSockWrap *)obj; 49 | printf("call pointer %ld\n",psw); 50 | fflush(stdout); 51 | int retval = 0; 52 | retval = psw->write(buff,strlen(buff)); 53 | 54 | return retval; 55 | 56 | } 57 | 58 | void release(void *obj) 59 | { 60 | SSockWrap *psw = (SSockWrap *)obj; 61 | delete psw; 62 | } 63 | } -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/clib.h: -------------------------------------------------------------------------------- 1 | #ifndef __CLIB_TEST__ 2 | #define __CLIB_TEST__ 3 | namespace clib_space 4 | { 5 | extern "C" { 6 | __declspec(dllexport) int __cdecl testprint(const char *info); 7 | __declspec(dllexport) void* __cdecl create(int param,int * retval); 8 | __declspec(dllexport) int __cdecl create_pp(int param,void ** pp_obj); 9 | __declspec(dllexport) int __cdecl call(const void * obj,const char *buff); 10 | __declspec(dllexport) void __cdecl release(void *obj); 11 | } 12 | } 13 | #endif 14 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/lib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import ctypes 3 | import os 4 | from ctypes import * 5 | print("testing") 6 | dllname='kernel32.dll' 7 | dll = windll.LoadLibrary(dllname) 8 | print("load dll",dll) 9 | currpath = os.path.dirname(os.path.realpath(__file__) ) 10 | print(currpath) 11 | os.add_dll_directory(currpath) 12 | dllname="./native_lib.dll" 13 | dll = windll.LoadLibrary(dllname) 14 | print("load dll",dll) 15 | 16 | a=dll.testprint(b"abcdefg\n") 17 | print(type(a)) 18 | print(a) 19 | ret=c_int(0) 20 | param=c_int(199); 21 | 22 | pt = ctypes.c_void_p 23 | 24 | dll.create.restype = ctypes.c_void_p 25 | pt = dll.create(param,pointer(ret)) 26 | print("create ret {},pt {}:type{}".format(ret.value,pt,type(pt))) 27 | dll.call.argtypes =[ctypes.c_void_p,ctypes.c_char_p] 28 | ret = dll.call(pt,b"this is a test "); 29 | print("call: ",ret) 30 | dll.release.argtypes=[ctypes.c_void_p] 31 | dll.release(pt); 32 | 33 | 34 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/libtest.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | typedef int (* PrintFunc)(const char * ); 7 | typedef void * (* FN_create)(int param,int * retval); 8 | typedef int (* FN_create_pp)(int param,void ** pp); 9 | typedef int (* FN_call)(const void * obj,const char *input); 10 | typedef void (* FN_release)(void *obj); 11 | 12 | int main(int argc, char **argv) 13 | { 14 | 15 | printf("try load module\n"); 16 | //HMODULE module = LoadLibrary("native_lib.dll"); 17 | HMODULE module = LoadLibraryEx("./native_lib.dll",NULL, LOAD_WITH_ALTERED_SEARCH_PATH); 18 | if (module == NULL) 19 | { 20 | printf("load module fail\n"); 21 | printf("last error %d\n",GetLastError()); 22 | 23 | return -1; 24 | } 25 | printf("after load module =%ld\n",module); 26 | fflush(stdout); 27 | 28 | PrintFunc pf=(PrintFunc)GetProcAddress(module, "testprint"); 29 | printf("load func %ld\n",pf); 30 | fflush(stdout); 31 | if (pf!=NULL) 32 | { 33 | int r=pf("this is a test\n"); 34 | printf("dll return %d\n",r); 35 | } 36 | FN_create fncreate = (FN_create)GetProcAddress(module, "create"); 37 | FN_call fncall = (FN_call)GetProcAddress(module, "call"); 38 | FN_release fnrelease = (FN_release)GetProcAddress(module, "release"); 39 | printf("create %ld,call %ld,release %ld\n",fncreate,fncall,fnrelease); 40 | int ret=0; 41 | void * p = fncreate(998,&ret); 42 | printf("create ret %d, pointer %ld\n",ret,p); 43 | ret = fncall(p,"write from pointer"); 44 | printf("call ret %d\n",ret); 45 | fnrelease(p); 46 | p=NULL; 47 | 48 | printf("test [2]\n"); 49 | FN_create_pp fn_create_pp = (FN_create_pp)GetProcAddress(module, "create_pp"); 50 | void * pp = NULL; 51 | printf("pppp %ld\n",&pp); 52 | ret = fn_create_pp(1999,&pp); 53 | printf("create pp ret=%d, pp %ld\n",ret,pp); 54 | ret = fncall(pp,"pp write from pointer"); 55 | printf("pp call ret %d\n",ret); 56 | fnrelease(pp); 57 | 58 | return 0; 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/py_ssock_wrap.pxd: -------------------------------------------------------------------------------- 1 | # cython: language_level=3 2 | # Declare the class with cdef 3 | cdef extern from "ssock_wrap.h" namespace "py_ssock_wrap": 4 | cdef cppclass SSockWrap: 5 | SSockWrap() except + 6 | int init(); 7 | int shutdown(); 8 | int close(); 9 | int write(const char * buffer,const int len); 10 | int read(char *buffer,const int buffersize); -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/py_ssock_wrap.pyx: -------------------------------------------------------------------------------- 1 | # cython: language_level=3 2 | # distutils: language = c++ 3 | 4 | from py_ssock_wrap cimport SSockWrap 5 | 6 | cdef class PySSockWrap: 7 | cdef SSockWrap ssock # Hold a C++ instance which we're wrapping 8 | 9 | def __cinit__(self): 10 | self.ssock = SSockWrap() 11 | 12 | def __dealloc__(self): 13 | #del self.ssock 14 | pass 15 | 16 | def init(self): 17 | self.ssock.init() 18 | 19 | def shutdown(self): 20 | self.ssock.shutdown() 21 | 22 | 23 | def close(self): 24 | self.ssock.close() 25 | 26 | def write(self,buffer,len): 27 | print("in pyx ssock write :",buffer) 28 | r = self.ssock.write(buffer,len) 29 | return r; 30 | 31 | def read(self,size=4096): 32 | print("in pyx ssock read :",size) 33 | cdef char buffer[4096]; 34 | cdef int buffersize=4096; 35 | r = self.ssock.read(buffer,buffersize) 36 | return buffer 37 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/pyssocktest.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/test/wrap_sample/pyssocktest.py -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/run_ssock.sh: -------------------------------------------------------------------------------- 1 | make 2 | CFLAGS="-I`pwd`" LDFLAGS="-L`pwd`" python setup_pyssockwrap.py build_ext --inplace 3 | python testssock.py -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup, Extension 2 | from Cython.Build import cythonize 3 | 4 | extension = Extension( 5 | "py_ssock_wrap", 6 | ["py_ssock_wrap.pyx"], 7 | libraries=["ssock_wrap"] , 8 | extra_link_args=["-L./ "], 9 | 10 | ) 11 | 12 | setup( 13 | ext_modules=cythonize([extension]) 14 | ) -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/ssock_wrap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "ssock_wrap.h" 5 | 6 | using namespace py_ssock_wrap; 7 | 8 | 9 | SSockWrap::SSockWrap(void) 10 | { 11 | 12 | } 13 | 14 | SSockWrap::~SSockWrap(void) 15 | { 16 | printf("ssockobj released %d\n",param); 17 | fflush(stdout); 18 | } 19 | 20 | 21 | int SSockWrap::init(int param_) 22 | { 23 | int retval = param_+1000; 24 | param = param_; 25 | return retval; 26 | } 27 | 28 | 29 | int SSockWrap::shutdown() 30 | { 31 | printf("SSockWrap::shutdown!!\n"); 32 | return 0; 33 | } 34 | 35 | int SSockWrap::close() 36 | { 37 | printf("SSockWrap::close.\n"); 38 | return 0; 39 | } 40 | 41 | int SSockWrap::write(const char * buffer,const int len) 42 | { 43 | printf("[ in cpp ]param = %d,write len %d : %s\n",param,len,buffer); 44 | return len+100; 45 | } 46 | 47 | int SSockWrap::read(char *buffer, const int buffersize) 48 | { 49 | snprintf(buffer,buffersize,"[ in cpp ] >>on read ,buffersize %d ",buffersize); 50 | return buffersize; 51 | } 52 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/ssock_wrap.exp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/cython_tassl_wrap/test/wrap_sample/ssock_wrap.exp -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/ssock_wrap.h: -------------------------------------------------------------------------------- 1 | #ifndef PY_SSOCK_WRAP 2 | #define PY_SSOCK_WRAP 3 | 4 | namespace py_ssock_wrap{ 5 | 6 | 7 | 8 | class SSockWrap{ 9 | int param; 10 | public : 11 | SSockWrap(); 12 | ~SSockWrap(); 13 | int init(int param_); 14 | int shutdown(); 15 | int close(); 16 | int write(const char * buffer,const int len); 17 | int read(char *buffer,const int buffersize); 18 | 19 | }; 20 | 21 | 22 | } 23 | 24 | #endif -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/testlib.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from py_ssock_wrap import PySSockWrap 4 | wrap = PySSockWrap(); 5 | wrap.init() 6 | wrap.write(b"this is a test ",10) 7 | result = wrap.read(4096) 8 | print("read from lib : ",result) -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/testssock.py: -------------------------------------------------------------------------------- 1 | from py_ssock_wrap import PySSockWrap 2 | 3 | wrap = PySSockWrap(); 4 | wrap.init() 5 | wrap.write(b"this is a test ",10) 6 | result = wrap.read(4096) 7 | print("read from lib : ",result) -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/wrap_test.c: -------------------------------------------------------------------------------- 1 | #include "py_ssock_wrap.h" 2 | 3 | 4 | -------------------------------------------------------------------------------- /cython_tassl_wrap/test/wrap_sample/wrap_test.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include "ssock_wrap.h" 6 | #include 7 | using namespace py_ssock_wrap; 8 | 9 | int main(int argc, char **argv) 10 | { 11 | 12 | printf("wrap test start->\n"); 13 | SSockWrap sw; 14 | char buff[256]="wrap test aaccbb"; 15 | int retval = 0; 16 | retval = sw.init(); 17 | printf("init ret %d\n",retval); 18 | retval = sw.write(buff,strlen(buff)); 19 | 20 | retval = sw.read(buff,sizeof(buff)); 21 | printf("!after read %s\n",buff); 22 | sw.shutdown(); 23 | sw.close(); 24 | printf("try load module"); 25 | HMODULE module = LoadLibrary("ssock_wrap.dll"); 26 | fflush(stdout); 27 | if (module == NULL) 28 | { 29 | printf("load module fail"); 30 | return -1; 31 | } 32 | 33 | typedef int (* PrintFunc)(const char * ); 34 | PrintFunc pf=(PrintFunc)GetProcAddress(module, "testprint"); 35 | int r=(*pf)("this is a test\n"); 36 | printf("dll return %d\n",r); 37 | 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /eth_abi/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Piper Merriam 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /eth_abi/README.md: -------------------------------------------------------------------------------- 1 | # Ethereum Contract 2 | 3 | [![Build Status](https://circleci.com/gh/ethereum/eth-abi.svg?style=shield)](https://circleci.com/gh/ethereum/eth-abi) 4 | [![Documentation Status](https://readthedocs.org/projects/eth-abi/badge/?version=latest)](https://readthedocs.org/projects/eth-abi/?badge=latest) 5 | [![PyPi version](https://img.shields.io/pypi/v/eth-abi.svg)](https://pypi.python.org/pypi/eth-abi) 6 | 7 | Python utilities for working with the Ethereum ABI 8 | 9 | ## Installation 10 | 11 | ```sh 12 | pip install eth-abi 13 | ``` 14 | 15 | ## Documentation 16 | 17 | For documentation, visit [https://eth-abi.readthedocs.io/en/latest/](https://eth-abi.readthedocs.io/en/latest/). 18 | 19 | ## Development 20 | 21 | Clone the repository and then run: 22 | 23 | ```sh 24 | pip install -e .[dev] 25 | ``` 26 | 27 | You might want to do this inside a virtualenv. 28 | 29 | ### Running the tests 30 | 31 | You can run the tests with: 32 | 33 | ```sh 34 | py.test tests 35 | ``` 36 | 37 | Or you can install `tox` to run the full test suite. 38 | 39 | ### Releasing 40 | 41 | Pandoc is required for transforming the markdown README to the proper format to 42 | render correctly on pypi. 43 | 44 | For Debian-like systems: 45 | 46 | ``` 47 | apt install pandoc 48 | ``` 49 | 50 | Or on OSX: 51 | 52 | ```sh 53 | brew install pandoc 54 | ``` 55 | 56 | To release a new version: 57 | 58 | ```sh 59 | make release bump=$$VERSION_PART_TO_BUMP$$ 60 | ``` 61 | 62 | #### How to bumpversion 63 | 64 | The version format for this repo is `{major}.{minor}.{patch}` for stable, and 65 | `{major}.{minor}.{patch}-{stage}.{devnum}` for unstable (`stage` can be alpha or beta). 66 | 67 | To issue the next version in line, specify which part to bump, 68 | like `make release bump=minor` or `make release bump=devnum`. 69 | 70 | If you are in a beta version, `make release bump=stage` will switch to a stable. 71 | 72 | To issue an unstable version when the current version is stable, specify the 73 | new version explicitly, like `make release bump="--new-version 4.0.0-alpha.1 devnum"` 74 | -------------------------------------------------------------------------------- /eth_abi/__init__.py: -------------------------------------------------------------------------------- 1 | import pkg_resources 2 | 3 | from eth_abi.abi import ( # NOQA 4 | decode_abi, 5 | decode_single, 6 | encode_abi, 7 | encode_single, 8 | is_encodable, 9 | is_encodable_type, 10 | ) 11 | 12 | __version__ = "1.0" 13 | -------------------------------------------------------------------------------- /eth_abi/abi.py: -------------------------------------------------------------------------------- 1 | from eth_abi.codec import ( 2 | ABICodec, 3 | ) 4 | from eth_abi.registry import ( 5 | registry, 6 | ) 7 | 8 | default_codec = ABICodec(registry) 9 | 10 | encode_abi = default_codec.encode_abi 11 | encode_single = default_codec.encode_single 12 | decode_abi = default_codec.decode_abi 13 | decode_single = default_codec.decode_single 14 | is_encodable = default_codec.is_encodable 15 | is_encodable_type = default_codec.is_encodable_type 16 | -------------------------------------------------------------------------------- /eth_abi/constants.py: -------------------------------------------------------------------------------- 1 | TT256 = 2 ** 256 2 | TT256M1 = 2 ** 256 - 1 3 | TT255 = 2 ** 255 4 | -------------------------------------------------------------------------------- /eth_abi/packed.py: -------------------------------------------------------------------------------- 1 | from .codec import ( 2 | ABIEncoder, 3 | ) 4 | from .registry import ( 5 | registry_packed, 6 | ) 7 | 8 | default_encoder_packed = ABIEncoder(registry_packed) 9 | 10 | encode_single_packed = default_encoder_packed.encode_single 11 | encode_abi_packed = default_encoder_packed.encode_abi 12 | is_encodable_packed = default_encoder_packed.is_encodable 13 | -------------------------------------------------------------------------------- /eth_abi/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_abi/py.typed -------------------------------------------------------------------------------- /eth_abi/tools/__init__.py: -------------------------------------------------------------------------------- 1 | from ._strategies import ( # noqa: F401 2 | get_abi_strategy, 3 | ) 4 | -------------------------------------------------------------------------------- /eth_abi/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_abi/utils/__init__.py -------------------------------------------------------------------------------- /eth_abi/utils/padding.py: -------------------------------------------------------------------------------- 1 | from eth_utils.toolz import ( 2 | curry, 3 | ) 4 | 5 | 6 | @curry 7 | def zpad(value: bytes, length: int) -> bytes: 8 | return value.rjust(length, b'\x00') 9 | 10 | 11 | zpad32 = zpad(length=32) 12 | 13 | 14 | @curry 15 | def zpad_right(value: bytes, length: int) -> bytes: 16 | return value.ljust(length, b'\x00') 17 | 18 | 19 | zpad32_right = zpad_right(length=32) 20 | 21 | 22 | @curry 23 | def fpad(value: bytes, length: int) -> bytes: 24 | return value.rjust(length, b'\xff') 25 | 26 | 27 | fpad32 = fpad(length=32) 28 | -------------------------------------------------------------------------------- /eth_abi/utils/string.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Any, 3 | ) 4 | 5 | 6 | def abbr(value: Any, limit: int = 20) -> str: 7 | """ 8 | Converts a value into its string representation and abbreviates that 9 | representation based on the given length `limit` if necessary. 10 | """ 11 | rep = repr(value) 12 | 13 | if len(rep) > limit: 14 | if limit < 3: 15 | raise ValueError('Abbreviation limit may not be less than 3') 16 | 17 | rep = rep[:limit - 3] + '...' 18 | 19 | return rep 20 | -------------------------------------------------------------------------------- /eth_account/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 The Ethereum Foundation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /eth_account/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | from eth_account.account import ( # noqa: F401 3 | Account, 4 | )''' 5 | -------------------------------------------------------------------------------- /eth_account/_utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_account/_utils/__init__.py -------------------------------------------------------------------------------- /eth_account/_utils/structured_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_account/_utils/structured_data/__init__.py -------------------------------------------------------------------------------- /eth_account/_utils/validation.py: -------------------------------------------------------------------------------- 1 | from eth_utils import ( 2 | is_binary_address, 3 | is_checksum_address, 4 | ) 5 | 6 | 7 | def is_valid_address(value): 8 | if is_binary_address(value): 9 | return True 10 | elif is_checksum_address(value): 11 | return True 12 | else: 13 | return False 14 | -------------------------------------------------------------------------------- /eth_account/datastructures.py: -------------------------------------------------------------------------------- 1 | from attrdict import ( 2 | AttrDict, 3 | ) 4 | 5 | 6 | class AttributeDict(AttrDict): 7 | """ 8 | See `AttrDict docs `_ 9 | 10 | This class differs only in that it is made immutable. This immutability 11 | is **not** a security guarantee. It is only a style-check convenience. 12 | """ 13 | 14 | def __setitem__(self, attr, val): 15 | raise TypeError( 16 | 'This data is immutable -- create a copy instead of modifying. ' 17 | 'For example, AttributeDict(old, replace_key=replace_val).' 18 | ) 19 | 20 | def _repr_pretty_(self, builder, cycle): 21 | """ 22 | Custom pretty output for the IPython console 23 | """ 24 | builder.text(self.__class__.__name__ + "(") 25 | if cycle: 26 | builder.text("") 27 | else: 28 | builder.pretty(dict(self)) 29 | builder.text(")") 30 | -------------------------------------------------------------------------------- /eth_account/signers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_account/signers/__init__.py -------------------------------------------------------------------------------- /eth_hash/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Jason Carver 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /eth_hash/__init__.py: -------------------------------------------------------------------------------- 1 | from .main import Keccak256 # noqa: F401 2 | -------------------------------------------------------------------------------- /eth_hash/auto.py: -------------------------------------------------------------------------------- 1 | from eth_hash.backends.auto import ( 2 | AutoBackend, 3 | ) 4 | from eth_hash.main import ( 5 | Keccak256, 6 | ) 7 | 8 | keccak = Keccak256(AutoBackend()) 9 | -------------------------------------------------------------------------------- /eth_hash/backends/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A collection of optional backends. You must manually select and 3 | install the backend you want. If the backend is not installed, 4 | then trying to import the module for that backend will cause 5 | an :class:`ImportError`. 6 | 7 | See :ref:`Choose a hashing backend` for more. 8 | ''' 9 | 10 | SUPPORTED_BACKENDS = [ 11 | 'pycryptodome', # prefer this over pysha3, for pypy3 support 12 | 'pysha3', 13 | ] 14 | -------------------------------------------------------------------------------- /eth_hash/backends/auto.py: -------------------------------------------------------------------------------- 1 | from eth_hash.utils import ( 2 | auto_choose_backend, 3 | ) 4 | 5 | 6 | class AutoBackend: 7 | _keccak256 = None 8 | _preimage = None 9 | 10 | def _initialize(self): 11 | backend = auto_choose_backend() 12 | self._keccak256 = backend.keccak256 13 | self._preimage = backend.preimage 14 | 15 | @property 16 | def keccak256(self): 17 | if self._keccak256 is None: 18 | self._initialize() 19 | return self._keccak256 20 | 21 | @property 22 | def preimage(self): 23 | if self._preimage is None: 24 | self._initialize() 25 | return self._preimage 26 | -------------------------------------------------------------------------------- /eth_hash/backends/pycryptodome.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import ( 2 | keccak, 3 | ) 4 | 5 | from eth_hash.preimage import ( 6 | BasePreImage, 7 | ) 8 | 9 | 10 | def keccak256(prehash: bytes) -> bytes: 11 | hasher = keccak.new(data=prehash, digest_bits=256) 12 | return hasher.digest() 13 | 14 | 15 | class preimage(BasePreImage): 16 | _hash = None 17 | 18 | def __init__(self, prehash) -> None: 19 | self._hash = keccak.new(data=prehash, digest_bits=256, update_after_digest=True) 20 | # pycryptodome doesn't expose a `copy` mechanism for it's hash objects 21 | # so we keep a record of all of the parts for when/if we need to copy 22 | # them. 23 | self._parts = [prehash] 24 | 25 | def update(self, prehash) -> None: 26 | self._hash.update(prehash) 27 | self._parts.append(prehash) 28 | 29 | def digest(self) -> bytes: 30 | return self._hash.digest() 31 | 32 | def copy(self) -> 'preimage': 33 | return preimage(b''.join(self._parts)) 34 | -------------------------------------------------------------------------------- /eth_hash/backends/pysha3.py: -------------------------------------------------------------------------------- 1 | from sha3 import ( 2 | keccak_256 as _keccak_256, 3 | ) 4 | 5 | from eth_hash.preimage import ( 6 | BasePreImage, 7 | ) 8 | 9 | 10 | def keccak256(prehash: bytes) -> bytes: 11 | return _keccak_256(prehash).digest() 12 | 13 | 14 | class preimage(BasePreImage): 15 | _hash = None 16 | 17 | def __init__(self, prehash) -> None: 18 | self._hash = _keccak_256(prehash) 19 | 20 | def update(self, prehash) -> None: 21 | return self._hash.update(prehash) 22 | 23 | def digest(self) -> bytes: 24 | return self._hash.digest() 25 | 26 | def copy(self) -> 'preimage': 27 | dup = preimage(b'') 28 | dup._hash = self._hash.copy() 29 | return dup 30 | -------------------------------------------------------------------------------- /eth_hash/main.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Union, 3 | ) 4 | 5 | from .preimage import ( 6 | BasePreImage, 7 | ) 8 | 9 | 10 | class Keccak256: 11 | def __init__(self, backend): 12 | self._backend = backend 13 | self.hasher = self._hasher_first_run 14 | self.preimage = self._preimage_first_run 15 | 16 | def _hasher_first_run(self, preimage): 17 | ''' 18 | Invoke the backend on-demand, and check an expected hash result, 19 | then replace this first run with the new hasher method. 20 | This is a bit of a hacky way to minimize overhead on hash calls after this first one. 21 | ''' 22 | new_hasher = self._backend.keccak256 23 | assert new_hasher(b'') == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501 24 | self.hasher = new_hasher 25 | return new_hasher(preimage) 26 | 27 | def _preimage_first_run(self, data): 28 | new_preimage = self._backend.preimage 29 | self.preimage = new_preimage 30 | return new_preimage(data) 31 | 32 | def __call__(self, preimage: Union[bytes, bytearray]) -> bytes: 33 | if not isinstance(preimage, (bytes, bytearray)): 34 | raise TypeError( 35 | "Can only compute the hash of `bytes` or `bytearray` values, not %r" % preimage 36 | ) 37 | 38 | return self.hasher(preimage) 39 | 40 | def new(self, preimage: (Union[bytes, bytearray])) -> BasePreImage: 41 | if not isinstance(preimage, (bytes, bytearray)): 42 | raise TypeError( 43 | "Can only compute the hash of `bytes` or `bytearray` values, not %r" % preimage 44 | ) 45 | return self.preimage(preimage) 46 | -------------------------------------------------------------------------------- /eth_hash/preimage.py: -------------------------------------------------------------------------------- 1 | from abc import ( 2 | ABCMeta, 3 | abstractmethod, 4 | ) 5 | 6 | 7 | class BasePreImage(metaclass=ABCMeta): 8 | @abstractmethod 9 | def __init__(self, value: bytes) -> None: 10 | pass 11 | 12 | @abstractmethod 13 | def update(self, value: bytes) -> None: 14 | pass 15 | 16 | @abstractmethod 17 | def digest(self) -> bytes: 18 | return self.keccak_fn(b''.join(self.preimage_parts)) 19 | 20 | @abstractmethod 21 | def copy(self) -> 'PreImage': 22 | pass 23 | -------------------------------------------------------------------------------- /eth_hash/utils.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import os 3 | 4 | from eth_hash.backends import ( 5 | SUPPORTED_BACKENDS, 6 | ) 7 | 8 | 9 | def auto_choose_backend(): 10 | env_backend = get_backend_in_environment() 11 | 12 | if env_backend: 13 | return load_environment_backend(env_backend) 14 | else: 15 | return choose_available_backend() 16 | 17 | 18 | def get_backend_in_environment(): 19 | return os.environ.get('ETH_HASH_BACKEND', None) 20 | 21 | 22 | def load_backend(backend_name): 23 | return importlib.import_module('eth_hash.backends.%s' % backend_name) 24 | 25 | 26 | def load_environment_backend(env_backend): 27 | if env_backend in SUPPORTED_BACKENDS: 28 | try: 29 | return load_backend(env_backend) 30 | except ImportError as e: 31 | raise ImportError( 32 | "The backend specified in ETH_HASH_BACKEND, '{0}', is not installed. " 33 | "Install with `pip install eth-hash[{0}]`.".format(env_backend) 34 | ) 35 | else: 36 | raise ValueError( 37 | "The backend specified in ETH_HASH_BACKEND, %r, is not supported. " 38 | "Choose one of: %r" % (env_backend, SUPPORTED_BACKENDS) 39 | ) 40 | 41 | 42 | def choose_available_backend(): 43 | for backend in SUPPORTED_BACKENDS: 44 | try: 45 | return load_backend(backend) 46 | except ImportError: 47 | pass 48 | raise ImportError( 49 | "None of these hashing backends are installed: %r.\n" 50 | "Install with `pip install eth-hash[%s]`." % ( 51 | SUPPORTED_BACKENDS, 52 | SUPPORTED_BACKENDS[0], 53 | ) 54 | ) 55 | -------------------------------------------------------------------------------- /eth_keys/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Piper Merriam 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /eth_keys/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import warnings 5 | 6 | 7 | if sys.version_info.major < 3: 8 | warnings.simplefilter('always', DeprecationWarning) 9 | warnings.warn(DeprecationWarning( 10 | "The `eth-keys` library is dropping support for Python 2. Upgrade to Python 3." 11 | )) 12 | warnings.resetwarnings() 13 | 14 | 15 | from .main import ( # noqa: F401 16 | KeyAPI, 17 | lazy_key_api as keys, 18 | ) 19 | -------------------------------------------------------------------------------- /eth_keys/backends/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import os 4 | from typing import Type 5 | 6 | from eth_keys.utils.module_loading import ( 7 | import_string, 8 | ) 9 | 10 | from .base import BaseECCBackend # noqa: F401 11 | from .coincurve import ( # noqa: F401 12 | CoinCurveECCBackend, 13 | is_coincurve_available, 14 | ) 15 | from .native import NativeECCBackend # noqa: F401 16 | 17 | 18 | def get_default_backend_class() -> str: 19 | if is_coincurve_available(): 20 | return 'eth_keys.backends.CoinCurveECCBackend' 21 | else: 22 | return 'eth_keys.backends.NativeECCBackend' 23 | 24 | 25 | def get_backend_class(import_path: str = None) -> Type[BaseECCBackend]: 26 | if import_path is None: 27 | import_path = os.environ.get( 28 | 'ECC_BACKEND_CLASS', 29 | get_default_backend_class(), 30 | ) 31 | return import_string(import_path) 32 | 33 | 34 | def get_backend(import_path: str = None) -> BaseECCBackend: 35 | backend_class = get_backend_class(import_path) 36 | return backend_class() 37 | -------------------------------------------------------------------------------- /eth_keys/backends/base.py: -------------------------------------------------------------------------------- 1 | from typing import Any # noqa: F401 2 | 3 | from eth_keys.datatypes import ( 4 | BaseSignature, 5 | NonRecoverableSignature, 6 | PrivateKey, 7 | PublicKey, 8 | Signature, 9 | ) 10 | 11 | 12 | class BaseECCBackend(object): 13 | def ecdsa_sign(self, 14 | msg_hash: bytes, 15 | private_key: PrivateKey) -> Signature: 16 | raise NotImplementedError() 17 | 18 | def ecdsa_sign_non_recoverable(self, 19 | msg_hash: bytes, 20 | private_key: PrivateKey) -> NonRecoverableSignature: 21 | raise NotImplementedError() 22 | 23 | def ecdsa_verify(self, 24 | msg_hash: bytes, 25 | signature: BaseSignature, 26 | public_key: PublicKey) -> bool: 27 | raise NotImplementedError() 28 | 29 | def ecdsa_recover(self, 30 | msg_hash: bytes, 31 | signature: Signature) -> PublicKey: 32 | raise NotImplementedError() 33 | 34 | def private_key_to_public_key(self, 35 | private_key: PrivateKey) -> PublicKey: 36 | raise NotImplementedError() 37 | 38 | def decompress_public_key_bytes(self, 39 | compressed_public_key_bytes: bytes) -> bytes: 40 | raise NotImplementedError() 41 | 42 | def compress_public_key_bytes(self, 43 | uncompressed_public_key_bytes: bytes) -> bytes: 44 | raise NotImplementedError() 45 | -------------------------------------------------------------------------------- /eth_keys/backends/native/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .main import ( # noqa: F401 4 | NativeECCBackend, 5 | ) 6 | -------------------------------------------------------------------------------- /eth_keys/constants.py: -------------------------------------------------------------------------------- 1 | from typing import Tuple # noqa: F401 2 | 3 | 4 | # 5 | # SECPK1N 6 | # 7 | SECPK1_P = 2**256 - 2**32 - 977 # type: int 8 | SECPK1_N = 115792089237316195423570985008687907852837564279074904382605163141518161494337 # type: int # noqa: E501 9 | SECPK1_A = 0 # type: int # noqa: E501 10 | SECPK1_B = 7 # type: int # noqa: E501 11 | SECPK1_Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240 # type: int # noqa: E501 12 | SECPK1_Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424 # type: int # noqa: E501 13 | SECPK1_G = (SECPK1_Gx, SECPK1_Gy) # type: Tuple[int, int] 14 | -------------------------------------------------------------------------------- /eth_keys/exceptions.py: -------------------------------------------------------------------------------- 1 | class ValidationError(Exception): 2 | pass 3 | 4 | 5 | class BadSignature(Exception): 6 | pass 7 | -------------------------------------------------------------------------------- /eth_keys/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_keys/py.typed -------------------------------------------------------------------------------- /eth_keys/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_keys/utils/__init__.py -------------------------------------------------------------------------------- /eth_keys/utils/address.py: -------------------------------------------------------------------------------- 1 | from eth_utils import ( 2 | keccak, 3 | ) 4 | 5 | 6 | def public_key_bytes_to_address(public_key_bytes: bytes) -> bytes: 7 | return keccak(public_key_bytes)[-20:] 8 | -------------------------------------------------------------------------------- /eth_keys/utils/module_loading.py: -------------------------------------------------------------------------------- 1 | import operator 2 | from typing import (Any, Tuple) 3 | from importlib import import_module 4 | 5 | 6 | def import_string(dotted_path: str) -> Any: 7 | """ 8 | Source: django.utils.module_loading 9 | Import a dotted module path and return the attribute/class designated by the 10 | last name in the path. Raise ImportError if the import failed. 11 | """ 12 | try: 13 | module_path, class_name = dotted_path.rsplit('.', 1) 14 | except ValueError: 15 | msg = "%s doesn't look like a module path" % dotted_path 16 | raise ImportError(msg) 17 | 18 | module = import_module(module_path) 19 | 20 | try: 21 | return getattr(module, class_name) 22 | except AttributeError: 23 | msg = 'Module "%s" does not define a "%s" attribute/class' % ( 24 | module_path, class_name) 25 | raise ImportError(msg) 26 | 27 | 28 | def split_at_longest_importable_path(dotted_path: str) -> Tuple[str, str]: 29 | num_path_parts = len(dotted_path.split('.')) 30 | 31 | for i in range(1, num_path_parts): 32 | path_parts = dotted_path.rsplit('.', i) 33 | import_part = path_parts[0] 34 | remainder = '.'.join(path_parts[1:]) 35 | 36 | try: 37 | module = import_module(import_part) 38 | except ImportError: 39 | continue 40 | 41 | try: 42 | operator.attrgetter(remainder)(module) 43 | except AttributeError: 44 | raise ImportError( 45 | "Unable to derive appropriate import path for {0}".format( 46 | dotted_path, 47 | ) 48 | ) 49 | else: 50 | return import_part, remainder 51 | else: 52 | return '', dotted_path 53 | -------------------------------------------------------------------------------- /eth_keys/utils/numeric.py: -------------------------------------------------------------------------------- 1 | from eth_keys.constants import ( 2 | SECPK1_N, 3 | ) 4 | 5 | 6 | def int_to_byte(value: int) -> bytes: 7 | return bytes([value]) 8 | 9 | 10 | def coerce_low_s(value: int) -> int: 11 | """Coerce the s component of an ECDSA signature into its low-s form. 12 | 13 | See https://bitcoin.stackexchange.com/questions/83408/in-ecdsa-why-is-r-%E2%88%92s-mod-n-complementary-to-r-s # noqa: W501 14 | or https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md. 15 | """ 16 | return min(value, -value % SECPK1_N) 17 | -------------------------------------------------------------------------------- /eth_keys/utils/padding.py: -------------------------------------------------------------------------------- 1 | def pad32(value: bytes) -> bytes: 2 | return value.rjust(32, b'\x00') 3 | -------------------------------------------------------------------------------- /eth_rlp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_rlp/__init__.py -------------------------------------------------------------------------------- /eth_typing/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 The eth-typing contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /eth_typing/__init__.py: -------------------------------------------------------------------------------- 1 | from .abi import ( # noqa: F401 2 | Decodable, 3 | TypeStr, 4 | ) 5 | from .bls import ( # noqa: F401 6 | BLSPubkey, 7 | BLSSignature, 8 | ) 9 | from .encoding import ( # noqa: F401 10 | HexStr, 11 | Primitives, 12 | ) 13 | from .enums import ( # noqa: F401 14 | ForkName, 15 | ) 16 | from .ethpm import ( # noqa: F401 17 | URI, 18 | ContractName, 19 | Manifest, 20 | ) 21 | from .evm import ( # noqa: F401 22 | Address, 23 | AnyAddress, 24 | BlockIdentifier, 25 | BlockNumber, 26 | ChecksumAddress, 27 | Hash32, 28 | HexAddress, 29 | ) 30 | -------------------------------------------------------------------------------- /eth_typing/abi.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Union, 3 | ) 4 | 5 | TypeStr = str 6 | Decodable = Union[bytes, bytearray] 7 | -------------------------------------------------------------------------------- /eth_typing/bls.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | NewType, 3 | ) 4 | 5 | BLSPubkey = NewType('BLSPubkey', bytes) # bytes48 6 | BLSSignature = NewType('BLSSignature', bytes) # bytes96 7 | -------------------------------------------------------------------------------- /eth_typing/encoding.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | NewType, 3 | Union, 4 | ) 5 | 6 | HexStr = NewType('HexStr', str) 7 | Primitives = Union[bytes, int, bool] 8 | -------------------------------------------------------------------------------- /eth_typing/enums.py: -------------------------------------------------------------------------------- 1 | class ForkName: 2 | Frontier = 'Frontier' 3 | Homestead = 'Homestead' 4 | EIP150 = 'EIP150' 5 | EIP158 = 'EIP158' 6 | Byzantium = 'Byzantium' 7 | Constantinople = 'Constantinople' 8 | Metropolis = 'Metropolis' 9 | -------------------------------------------------------------------------------- /eth_typing/ethpm.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Any, 3 | Dict, 4 | NewType, 5 | ) 6 | 7 | ContractName = NewType('ContractName', str) 8 | Manifest = NewType('Manifest', Dict[str, Any]) 9 | URI = NewType('URI', str) 10 | -------------------------------------------------------------------------------- /eth_typing/evm.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | NewType, 3 | TypeVar, 4 | Union, 5 | ) 6 | 7 | Hash32 = NewType('Hash32', bytes) 8 | BlockNumber = NewType('BlockNumber', int) 9 | BlockIdentifier = Union[BlockNumber, Hash32] 10 | 11 | Address = NewType('Address', bytes) 12 | HexAddress = NewType('HexAddress', str) 13 | ChecksumAddress = NewType('ChecksumAddress', HexAddress) 14 | AnyAddress = TypeVar('AnyAddress', Address, HexAddress, ChecksumAddress) 15 | -------------------------------------------------------------------------------- /eth_typing/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_typing/py.typed -------------------------------------------------------------------------------- /eth_utils/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 The eth-typing contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /eth_utils/__main__.py: -------------------------------------------------------------------------------- 1 | from .debug import get_environment_summary 2 | 3 | print(get_environment_summary()) 4 | -------------------------------------------------------------------------------- /eth_utils/abi.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict 2 | 3 | from .crypto import keccak 4 | 5 | 6 | def collapse_if_tuple(abi): 7 | """Converts a tuple from a dict to a parenthesized list of its types. 8 | 9 | >>> from eth_utils.abi import collapse_if_tuple 10 | >>> collapse_if_tuple( 11 | ... { 12 | ... 'components': [ 13 | ... {'name': 'anAddress', 'type': 'address'}, 14 | ... {'name': 'anInt', 'type': 'uint256'}, 15 | ... {'name': 'someBytes', 'type': 'bytes'}, 16 | ... ], 17 | ... 'type': 'tuple', 18 | ... } 19 | ... ) 20 | '(address,uint256,bytes)' 21 | """ 22 | typ = abi["type"] 23 | if not typ.startswith("tuple"): 24 | return typ 25 | 26 | delimited = ",".join(collapse_if_tuple(c) for c in abi["components"]) 27 | # Whatever comes after "tuple" is the array dims. The ABI spec states that 28 | # this will have the form "", "[]", or "[k]". 29 | array_dim = typ[5:] 30 | collapsed = "({}){}".format(delimited, array_dim) 31 | 32 | return collapsed 33 | 34 | 35 | def _abi_to_signature(abi: Dict[str, Any]) -> str: 36 | function_signature = "{fn_name}({fn_input_types})".format( 37 | fn_name=abi["name"], 38 | fn_input_types=",".join( 39 | [collapse_if_tuple(abi_input) for abi_input in abi.get("inputs", [])] 40 | ), 41 | ) 42 | return function_signature 43 | 44 | 45 | def function_signature_to_4byte_selector(event_signature: str) -> bytes: 46 | return keccak(text=event_signature.replace(" ", ""))[:4] 47 | 48 | 49 | def function_abi_to_4byte_selector(function_abi: Dict[str, Any]) -> bytes: 50 | function_signature = _abi_to_signature(function_abi) 51 | return function_signature_to_4byte_selector(function_signature) 52 | 53 | 54 | def event_signature_to_log_topic(event_signature: str) -> bytes: 55 | return keccak(text=event_signature.replace(" ", "")) 56 | 57 | 58 | def event_abi_to_log_topic(event_abi: Dict[str, Any]) -> bytes: 59 | event_signature = _abi_to_signature(event_abi) 60 | return event_signature_to_log_topic(event_signature) 61 | -------------------------------------------------------------------------------- /eth_utils/crypto.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | from eth_hash.auto import keccak as keccak_256 4 | 5 | from .conversions import to_bytes 6 | 7 | from gmssl.sm3 import sm3_hash 8 | 9 | from eth_utils.hexadecimal import decode_hex 10 | CRYPTO_TYPE = 'keccak' 11 | CRYPTO_TYPE_GM = "GM" 12 | CRYPTO_TYPE_ECDSA = "ECDSA" 13 | 14 | 15 | def set_crypto_type(crypto_type): 16 | global CRYPTO_TYPE 17 | CRYPTO_TYPE = crypto_type.upper() 18 | 19 | # 国密实现,注意sm_hash接受的时候bytearray数组,返回的是已经hex化的结果如 'a75feb...',调用者期望的是binary的结果,需要decode为二进制 20 | 21 | 22 | def gmhash(primitive: Union[bytes, int, bool] = None, hexstr: str = None, text: str = None 23 | ) -> bytes: 24 | forhash = bytearray(to_bytes(primitive, hexstr, text)) 25 | gmhash = sm3_hash(forhash) 26 | gmhash_bytes = decode_hex(gmhash) 27 | return gmhash_bytes 28 | 29 | # 原来的是所有的hash都用keccak算法,是个总入口,后续重构 30 | 31 | 32 | def keccak( 33 | primitive: Union[bytes, int, bool] = None, hexstr: str = None, text: str = None 34 | ) -> bytes: 35 | global CRYPTO_TYPE 36 | global CRYPTO_TYPE_GM 37 | # print("hashtype",CRYPTO_TYPE) 38 | if CRYPTO_TYPE == CRYPTO_TYPE_GM: 39 | return gmhash(primitive, hexstr, text) 40 | return keccak_256(to_bytes(primitive, hexstr, text)) 41 | -------------------------------------------------------------------------------- /eth_utils/debug.py: -------------------------------------------------------------------------------- 1 | import platform 2 | import subprocess 3 | import sys 4 | 5 | 6 | def pip_freeze() -> str: 7 | result = subprocess.run("pip freeze".split(), stdout=subprocess.PIPE) 8 | return "pip freeze result:\n%s" % result.stdout.decode() 9 | 10 | 11 | def python_version() -> str: 12 | return "Python version:\n%s" % sys.version 13 | 14 | 15 | def platform_info() -> str: 16 | return "Operating System: %s" % platform.platform() 17 | 18 | 19 | def get_environment_summary() -> str: 20 | return "\n\n".join([python_version(), platform_info(), pip_freeze()]) 21 | -------------------------------------------------------------------------------- /eth_utils/encoding.py: -------------------------------------------------------------------------------- 1 | def int_to_big_endian(value: int) -> bytes: 2 | return value.to_bytes((value.bit_length() + 7) // 8 or 1, "big") 3 | 4 | 5 | def big_endian_to_int(value: bytes) -> int: 6 | return int.from_bytes(value, "big") 7 | -------------------------------------------------------------------------------- /eth_utils/exceptions.py: -------------------------------------------------------------------------------- 1 | class ValidationError(Exception): 2 | """ 3 | Raised when something does not pass a validation check. 4 | """ 5 | 6 | pass 7 | -------------------------------------------------------------------------------- /eth_utils/humanize.py: -------------------------------------------------------------------------------- 1 | from typing import Iterator, Tuple, Union 2 | 3 | from eth_typing import Hash32 4 | 5 | from .toolz import take 6 | 7 | 8 | def humanize_seconds(seconds: Union[float, int]) -> str: 9 | if int(seconds) == 0: 10 | return "0s" 11 | 12 | unit_values = _consume_leading_zero_units(_humanize_seconds(int(seconds))) 13 | 14 | return "".join( 15 | ("{0}{1}".format(amount, unit) for amount, unit in take(3, unit_values)) 16 | ) 17 | 18 | 19 | SECOND = 1 20 | MINUTE = 60 21 | HOUR = 60 * 60 22 | DAY = 24 * HOUR 23 | YEAR = 365 * DAY 24 | MONTH = YEAR // 12 25 | WEEK = 7 * DAY 26 | 27 | 28 | UNITS = ( 29 | (YEAR, "y"), 30 | (MONTH, "m"), 31 | (WEEK, "w"), 32 | (DAY, "d"), 33 | (HOUR, "h"), 34 | (MINUTE, "m"), 35 | (SECOND, "s"), 36 | ) 37 | 38 | 39 | def _consume_leading_zero_units( 40 | units_iter: Iterator[Tuple[int, str]] 41 | ) -> Iterator[Tuple[int, str]]: 42 | for amount, unit in units_iter: 43 | if amount == 0: 44 | continue 45 | else: 46 | yield (amount, unit) 47 | break 48 | 49 | yield from units_iter 50 | 51 | 52 | def _humanize_seconds(seconds: int) -> Iterator[Tuple[int, str]]: 53 | remainder = seconds 54 | 55 | for duration, unit in UNITS: 56 | if not remainder: 57 | break 58 | 59 | num = remainder // duration 60 | yield num, unit 61 | 62 | remainder %= duration 63 | 64 | 65 | DISPLAY_HASH_CHARS = 4 66 | 67 | 68 | def humanize_hash(value: Hash32) -> str: 69 | value_as_hex = value.hex() 70 | head = value_as_hex[:DISPLAY_HASH_CHARS] 71 | tail = value_as_hex[-1 * DISPLAY_HASH_CHARS:] 72 | return "{0}..{1}".format(head, tail) 73 | -------------------------------------------------------------------------------- /eth_utils/module_loading.py: -------------------------------------------------------------------------------- 1 | from importlib import import_module 2 | 3 | from typing import Any 4 | 5 | 6 | def import_string(dotted_path: str) -> Any: 7 | """ 8 | Source: django.utils.module_loading 9 | Import a dotted module path and return the attribute/class designated by the 10 | last name in the path. Raise ImportError if the import failed. 11 | """ 12 | try: 13 | module_path, class_name = dotted_path.rsplit(".", 1) 14 | except ValueError: 15 | msg = "%s doesn't look like a module path" % dotted_path 16 | raise ImportError(msg) 17 | 18 | module = import_module(module_path) 19 | 20 | try: 21 | return getattr(module, class_name) 22 | except AttributeError: 23 | msg = 'Module "%s" does not define a "%s" attribute/class' % ( 24 | module_path, 25 | class_name, 26 | ) 27 | raise ImportError(msg) 28 | -------------------------------------------------------------------------------- /eth_utils/numeric.py: -------------------------------------------------------------------------------- 1 | from abc import abstractmethod, ABC 2 | from typing import Any, TypeVar 3 | 4 | 5 | class Comparable(ABC): 6 | @abstractmethod 7 | def __lt__(self, other: Any) -> bool: 8 | ... 9 | 10 | @abstractmethod 11 | def __gt__(self, other: Any) -> bool: 12 | ... 13 | 14 | 15 | TValue = TypeVar("TValue", bound=Comparable) 16 | 17 | 18 | def clamp(lower_bound: TValue, upper_bound: TValue, value: TValue) -> TValue: 19 | if value < lower_bound: 20 | return lower_bound 21 | elif value > upper_bound: 22 | return upper_bound 23 | else: 24 | return value 25 | -------------------------------------------------------------------------------- /eth_utils/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/eth_utils/py.typed -------------------------------------------------------------------------------- /eth_utils/types.py: -------------------------------------------------------------------------------- 1 | import numbers 2 | import collections 3 | 4 | from typing import Any 5 | 6 | 7 | bytes_types = (bytes, bytearray) 8 | integer_types = (int,) 9 | text_types = (str,) 10 | string_types = (bytes, str, bytearray) 11 | 12 | 13 | def is_integer(value: Any) -> bool: 14 | return isinstance(value, integer_types) and not isinstance(value, bool) 15 | 16 | 17 | def is_bytes(value: Any) -> bool: 18 | return isinstance(value, bytes_types) 19 | 20 | 21 | def is_text(value: Any) -> bool: 22 | return isinstance(value, text_types) 23 | 24 | 25 | def is_string(value: Any) -> bool: 26 | return isinstance(value, string_types) 27 | 28 | 29 | def is_boolean(value: Any) -> bool: 30 | return isinstance(value, bool) 31 | 32 | 33 | def is_dict(obj: Any) -> bool: 34 | return isinstance(obj, collections.abc.Mapping) 35 | 36 | 37 | def is_list_like(obj: Any) -> bool: 38 | return not is_string(obj) and isinstance(obj, collections.abc.Sequence) 39 | 40 | 41 | def is_list(obj: Any) -> bool: 42 | return isinstance(obj, list) 43 | 44 | 45 | def is_tuple(obj: Any) -> bool: 46 | return isinstance(obj, tuple) 47 | 48 | 49 | def is_null(obj: Any) -> bool: 50 | return obj is None 51 | 52 | 53 | def is_number(obj: Any) -> bool: 54 | return isinstance(obj, numbers.Number) 55 | -------------------------------------------------------------------------------- /eth_utils/typing/__init__.py: -------------------------------------------------------------------------------- 1 | from .misc import ( # noqa: F401 2 | Address, 3 | AnyAddress, 4 | ChecksumAddress, 5 | HexAddress, 6 | HexStr, 7 | Primitives, 8 | T, 9 | ) 10 | -------------------------------------------------------------------------------- /eth_utils/typing/misc.py: -------------------------------------------------------------------------------- 1 | from typing import NewType, TypeVar, Union 2 | import warnings 3 | 4 | from eth_typing import Address 5 | 6 | try: 7 | from eth_typing import AnyAddress, ChecksumAddress, HexAddress, HexStr, Primitives 8 | except ImportError: 9 | warnings.warn("Old version of 'eth-typing', please update.") 10 | 11 | # for hex encoded addresses 12 | HexAddress = NewType("HexAddress", str) # type: ignore 13 | ChecksumAddress = NewType( # type: ignore 14 | "ChecksumAddress", HexAddress 15 | ) # for hex addresses with checksums 16 | AnyAddress = TypeVar( # type: ignore 17 | "AnyAddress", Address, HexAddress, ChecksumAddress 18 | ) 19 | HexStr = NewType("HexStr", str) # type: ignore 20 | Primitives = Union[bytes, int, bool] # type: ignore 21 | 22 | 23 | T = TypeVar("T") 24 | -------------------------------------------------------------------------------- /eth_utils/units.py: -------------------------------------------------------------------------------- 1 | import decimal 2 | 3 | # Units are in their own module here, so that they can keep this 4 | # formatting, as this module is excluded from black in pyproject.toml 5 | # fmt: off 6 | units = { 7 | 'wei': decimal.Decimal('1'), # noqa: E241 8 | 'kwei': decimal.Decimal('1000'), # noqa: E241 9 | 'babbage': decimal.Decimal('1000'), # noqa: E241 10 | 'femtoether': decimal.Decimal('1000'), # noqa: E241 11 | 'mwei': decimal.Decimal('1000000'), # noqa: E241 12 | 'lovelace': decimal.Decimal('1000000'), # noqa: E241 13 | 'picoether': decimal.Decimal('1000000'), # noqa: E241 14 | 'gwei': decimal.Decimal('1000000000'), # noqa: E241 15 | 'shannon': decimal.Decimal('1000000000'), # noqa: E241 16 | 'nanoether': decimal.Decimal('1000000000'), # noqa: E241 17 | 'nano': decimal.Decimal('1000000000'), # noqa: E241 18 | 'szabo': decimal.Decimal('1000000000000'), # noqa: E241 19 | 'microether': decimal.Decimal('1000000000000'), # noqa: E241 20 | 'micro': decimal.Decimal('1000000000000'), # noqa: E241 21 | 'finney': decimal.Decimal('1000000000000000'), # noqa: E241 22 | 'milliether': decimal.Decimal('1000000000000000'), # noqa: E241 23 | 'milli': decimal.Decimal('1000000000000000'), # noqa: E241 24 | 'ether': decimal.Decimal('1000000000000000000'), # noqa: E241 25 | 'kether': decimal.Decimal('1000000000000000000000'), # noqa: E241 26 | 'grand': decimal.Decimal('1000000000000000000000'), # noqa: E241 27 | 'mether': decimal.Decimal('1000000000000000000000000'), # noqa: E241 28 | 'gether': decimal.Decimal('1000000000000000000000000000'), # noqa: E241 29 | 'tether': decimal.Decimal('1000000000000000000000000000000'), # noqa: E241 30 | } 31 | # fmt: on 32 | -------------------------------------------------------------------------------- /gmssl/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @File : __init__.py 4 | # @Author: yubo 5 | # @Date : 2019/12/16 6 | # @Desc : -------------------------------------------------------------------------------- /gmssl/func.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | 4 | def xor(a, b): return list(map(lambda x, y: x ^ y, a, b)) 5 | 6 | 7 | def rotl(x, n): return ((x << n) & 0xffffffff) | ((x >> (32 - n)) & 0xffffffff) 8 | 9 | 10 | def get_uint32_be(key_data): return ( 11 | (key_data[0] << 24) | ( 12 | key_data[1] << 16) | ( 13 | key_data[2] << 8) | ( 14 | key_data[3])) 15 | 16 | 17 | def put_uint32_be(n): return [ 18 | ((n >> 24) & 0xff), 19 | ((n >> 16) & 0xff), 20 | ((n >> 8) & 0xff), 21 | ((n) & 0xff)] 22 | 23 | 24 | def padding(data, block=16): return data + \ 25 | [(16 - len(data) % block)for _ in range(16 - len(data) % block)] 26 | 27 | 28 | def unpadding(data): return data[:-data[-1]] 29 | 30 | 31 | def list_to_bytes(data): return b''.join([bytes((i,)) for i in data]) 32 | 33 | 34 | def bytes_to_list(data): return [i for i in data] 35 | 36 | 37 | def random_hex(x): return ''.join([choice('0123456789abcdef') for _ in range(x)]) 38 | -------------------------------------------------------------------------------- /gmssl/libsm3/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 bigfish 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /gmssl/libsm3/README.md: -------------------------------------------------------------------------------- 1 | # pysm3 2 | sm3 算法,调用C语言接口 3 | 4 | 5 | 6 | ## 编译 sm3 7 | - linux 8 | `gcc -fPIC -shared -o libsm3.so sm3.c` 9 | 10 | - windows 11 | `gcc -fPIC -shared -o libsm3.dll sm3.c` 12 | 使用 msys64 版本的 mingw64 的 gcc 编译 13 | 14 | ## 注意 15 | 16 | 当前已编译的 libsm3.dll libsm3.so 适用于 64 位 python 平台 -------------------------------------------------------------------------------- /gmssl/libsm3/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @File : __init__.py 4 | # @Author: yubo 5 | # @Date : 2019/12/16 6 | # @Desc : 7 | from .sm3 import sm3_hash, SM3 8 | from .libsm3 import lib_sm3 -------------------------------------------------------------------------------- /gmssl/libsm3/sm3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @File : sm3.py.py 4 | # @Author: yubo 5 | # @Date : 2019/12/16 6 | # @Desc : 7 | 8 | import ctypes 9 | from .libsm3 import * 10 | 11 | 12 | def sm3_hash(in_msg): 13 | sm3_ctx = SM3Context() 14 | hash_buffer = (ctypes.c_ubyte * 32)() 15 | sm3_starts(ctypes.POINTER(SM3Context)(sm3_ctx)) 16 | array_type = ctypes.c_ubyte * len(in_msg) 17 | sm3_update(ctypes.POINTER(SM3Context)(sm3_ctx), array_type(*in_msg), ctypes.c_int(len(in_msg))) 18 | sm3_finish(ctypes.POINTER(SM3Context)(sm3_ctx), hash_buffer) 19 | return bytes([i for i in hash_buffer]) 20 | 21 | 22 | def sm3_hmac(key, in_msg): 23 | pass 24 | 25 | 26 | class SM3: 27 | def __init__(self): 28 | self._sm3_ctx = SM3Context() 29 | 30 | def start(self, msg=None): 31 | sm3_starts(ctypes.POINTER(SM3Context)(self._sm3_ctx)) 32 | self.update(msg) 33 | 34 | def update(self, msg): 35 | if msg is not None: 36 | array_type = ctypes.c_ubyte * len(msg) 37 | sm3_update( 38 | ctypes.POINTER(SM3Context)( 39 | self._sm3_ctx), 40 | array_type( 41 | *msg), 42 | ctypes.c_int( 43 | len(msg))) 44 | 45 | def finish(self, msg=None): 46 | self.update(msg) 47 | hash_buffer = (ctypes.c_ubyte * 32)() 48 | sm3_finish(ctypes.POINTER(SM3Context)(self._sm3_ctx), hash_buffer) 49 | return bytes([i for i in hash_buffer]).hex() 50 | -------------------------------------------------------------------------------- /gmssl/sm2_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @File : sm2_integer.py 4 | # @Author: yubo 5 | # @Date : 2019/11/14 6 | # @Desc : 7 | import math 8 | import random 9 | 10 | 11 | # 快速模指数算法 # 12 | ''' 13 | input: 底数 g , 指数 a 和模数 p 14 | output: (g**a)mod p 15 | ''' 16 | 17 | 18 | def fast_pow(g, a, p): 19 | e = int(a % (p - 1)) 20 | if e == 0: 21 | return 1 22 | r = int(math.log2(e)) # + 1 - 1 23 | x = g 24 | for i in range(0, r): 25 | x = int((x ** 2) % p) 26 | if (e & (1 << (r - 1 - i))) == (1 << (r - 1 - i)): 27 | x = (g * x) % p 28 | return int(x) 29 | 30 | 31 | ### test fast_pow ### 32 | # print(fast_pow(5, 12, 23)) 33 | 34 | # Miller-Rabin检测 # 35 | ''' 36 | input: 大奇数 u 和大正整数 T 37 | output: 若 u 通过测试则输出 True,否则输出 False 38 | ''' 39 | 40 | 41 | def isPrime_MR(u, T): 42 | # 计算 v 和 w ,使得 u - 1 = w * 2^v 43 | v = 0 44 | w = u - 1 45 | while w % 2 == 0: 46 | v += 1 47 | w = w // 2 48 | for j in range(1, T + 1): 49 | nextj = False 50 | a = random.randint(2, u - 1) 51 | b = fast_pow(a, w, u) 52 | if b == 1 or b == u - 1: 53 | nextj = True 54 | continue 55 | for i in range(1, v): 56 | b = (b ** 2) % u 57 | if b == u - 1: 58 | nextj = True 59 | break 60 | if b == 1: 61 | return False 62 | if not nextj: 63 | return False 64 | return True 65 | 66 | 67 | ### test isPrime_MR ### 68 | # print(isPrime_MR(0xBDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F, 10)) 69 | # print(isPrime_MR(23, 10)) 70 | # print(isPrime_MR(17, 10)) 71 | 72 | # 判断是否为2的幂 73 | def is_Power_of_two(n): 74 | if n > 0: 75 | if (n & (n - 1)) == 0: 76 | return True 77 | return False 78 | 79 | 80 | # if is_Power_of_two(45): 81 | # print('true') 82 | 83 | # 求逆元 84 | def inverse(a, n): 85 | a_ = fast_pow(a, n - 2, n) % n 86 | return a_ 87 | ### test inverse ### 88 | # print(inverse(3,7)) 89 | -------------------------------------------------------------------------------- /gmssl/sm2_parameter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @File : sm2_parameter.py 4 | # @Author: yubo 5 | # @Date : 2019/11/14 6 | # @Desc : 7 | from .sm2 import default_ecc_table 8 | from .sm2_integer import * 9 | 10 | 11 | sm2_param_entla = "0080" 12 | sm2_param_ida = "31323334353637383132333435363738" 13 | 14 | sm2_param_p = default_ecc_table["p"] 15 | sm2_param_n = default_ecc_table["n"] 16 | sm2_param_a = default_ecc_table["a"] 17 | sm2_param_b = default_ecc_table["b"] 18 | sm2_param_gx = default_ecc_table["g"][:64] 19 | sm2_param_gy = default_ecc_table["g"][64:] 20 | 21 | # 有限域参数 q # 22 | q = 0 23 | q_prime = False 24 | q_2m = False 25 | 26 | 27 | def is_q_prime(): 28 | return q_prime 29 | 30 | 31 | def is_q_power_of_two(): 32 | return q_2m 33 | 34 | 35 | def set_q(a): 36 | global q 37 | global q_prime 38 | global q_2m 39 | if isPrime_MR(a, 15): 40 | q = a 41 | q_prime = True 42 | if is_Power_of_two(q): 43 | q_2m = True 44 | else: 45 | q_2m = False 46 | elif is_Power_of_two(a): 47 | q = a 48 | q_2m = True 49 | if isPrime_MR(q, 15): 50 | q_prime = True 51 | else: 52 | q_prime = False 53 | else: 54 | print("*** ERROR: q必须为奇素数或2的幂 *** function: set_q") 55 | 56 | 57 | def get_q(): 58 | return q 59 | 60 | 61 | def get_a(): 62 | return int(sm2_param_a, 16) 63 | 64 | 65 | def get_b(): 66 | return int(sm2_param_b, 16) 67 | 68 | 69 | def get_Gx(): 70 | return int(sm2_param_gx, 16) 71 | 72 | 73 | def get_Gy(): 74 | return int(sm2_param_gy, 16) 75 | 76 | 77 | def get_n(): 78 | return int(sm2_param_n, 16) 79 | 80 | 81 | set_q(int(sm2_param_p, 16)) 82 | -------------------------------------------------------------------------------- /gmssl/sm3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @File : sm3.py 4 | # @Author: yubo 5 | # @Date : 2019/12/16 6 | # @Desc : 7 | 8 | from .libsm3 import lib_sm3, sm3_hash 9 | 10 | if lib_sm3 is None: 11 | from .sm3_implement import * 12 | from .sm3_implement import sm3_kdf 13 | else: 14 | from .libsm3 import * 15 | 16 | 17 | assert sm3_hash(b'01').upper( 18 | ) == "7f4528abbaeb75420d8ae5842f12b221deb73722d49e02fccb461450e0c1d7ad".upper() 19 | -------------------------------------------------------------------------------- /hexbytes/__init__.py: -------------------------------------------------------------------------------- 1 | from .main import ( # noqa: F401 2 | HexBytes, 3 | ) 4 | -------------------------------------------------------------------------------- /hexbytes/main.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Type, 3 | Union, 4 | cast, 5 | overload, 6 | ) 7 | 8 | from eth_utils import ( 9 | hexstr_if_str, 10 | to_bytes, 11 | ) 12 | 13 | 14 | class HexBytes(bytes): 15 | """ 16 | HexBytes is a *very* thin wrapper around the python 17 | built-in :class:`bytes` class. It has these three changes: 18 | 19 | 1. Accepts hex strings as an initializing value 20 | 2. Returns hex with prefix '0x' from :meth:`HexBytes.hex` 21 | 3. The string representation at console is in hex 22 | """ 23 | def __new__(cls: Type[bytes], val: Union[bytes, int, str]) -> "HexBytes": 24 | bytesval = hexstr_if_str(to_bytes, val) 25 | return cast(HexBytes, super().__new__(cls, bytesval)) # type: ignore # https://github.com/python/typeshed/issues/2630 # noqa: E501 26 | 27 | def hex(self) -> str: 28 | """ 29 | Just like :meth:`bytes.hex`, but prepends "0x" 30 | """ 31 | return '0x' + super().hex() 32 | 33 | @overload 34 | def __getitem__(self, key: int) -> int: 35 | ... 36 | 37 | @overload # noqa: F811 38 | def __getitem__(self, key: slice) -> 'HexBytes': 39 | ... 40 | 41 | def __getitem__(self, key: Union[int, slice]) -> Union[int, bytes, 'HexBytes']: # noqa: F811 42 | result = super().__getitem__(key) 43 | if hasattr(result, 'hex'): 44 | return type(self)(result) 45 | else: 46 | return result 47 | 48 | def __repr__(self) -> str: 49 | return 'HexBytes(%r)' % self.hex() 50 | -------------------------------------------------------------------------------- /hexbytes/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/hexbytes/py.typed -------------------------------------------------------------------------------- /images/qr_code1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/images/qr_code1.png -------------------------------------------------------------------------------- /parsimonious/__init__.py: -------------------------------------------------------------------------------- 1 | """Parsimonious's public API. Import from here. 2 | 3 | Things may move around in modules deeper than this one. 4 | 5 | """ 6 | from parsimonious.exceptions import (ParseError, IncompleteParseError, 7 | VisitationError, UndefinedLabel, 8 | BadGrammar) 9 | from parsimonious.grammar import Grammar, TokenGrammar 10 | from parsimonious.nodes import NodeVisitor, VisitationError, rule 11 | -------------------------------------------------------------------------------- /parsimonious/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/parsimonious/tests/__init__.py -------------------------------------------------------------------------------- /parsimonious/tests/test_benchmarks.py: -------------------------------------------------------------------------------- 1 | """Tests to show that the benchmarks we based our speed optimizations on are 2 | still valid""" 3 | 4 | from functools import partial 5 | from timeit import timeit 6 | 7 | from nose.tools import ok_ 8 | 9 | 10 | timeit = partial(timeit, number=500000) 11 | 12 | 13 | def test_lists_vs_dicts(): 14 | """See what's faster at int key lookup: dicts or lists.""" 15 | list_time = timeit('item = l[9000]', 'l = [0] * 10000') 16 | dict_time = timeit('item = d[9000]', 'd = {x: 0 for x in range(10000)}') 17 | 18 | # Dicts take about 1.6x as long as lists in Python 2.6 and 2.7. 19 | ok_(list_time < dict_time, '%s < %s' % (list_time, dict_time)) 20 | 21 | 22 | def test_call_vs_inline(): 23 | """How bad is the calling penalty?""" 24 | no_call = timeit('l[0] += 1', 'l = [0]') 25 | call = timeit('add(); l[0] += 1', 'l = [0]\n' 26 | 'def add():\n' 27 | ' pass') 28 | 29 | # Calling a function is pretty fast; it takes just 1.2x as long as the 30 | # global var access and addition in l[0] += 1. 31 | ok_(no_call < call, '%s (no call) < %s (call)' % (no_call, call)) 32 | 33 | 34 | def test_startswith_vs_regex(): 35 | """Can I beat the speed of regexes by special-casing literals?""" 36 | re_time = timeit( 37 | 'r.match(t, 19)', 38 | 'import re\n' 39 | "r = re.compile('hello')\n" 40 | "t = 'this is the finest hello ever'") 41 | startswith_time = timeit("t.startswith('hello', 19)", 42 | "t = 'this is the finest hello ever'") 43 | 44 | # Regexes take 2.24x as long as simple string matching. 45 | ok_(startswith_time < re_time, 46 | '%s (startswith) < %s (re)' % (startswith_time, re_time)) 47 | -------------------------------------------------------------------------------- /parsimonious/utils.py: -------------------------------------------------------------------------------- 1 | """General tools which don't depend on other parts of Parsimonious""" 2 | 3 | import ast 4 | 5 | from six import python_2_unicode_compatible 6 | 7 | 8 | class StrAndRepr(object): 9 | """Mix-in which gives the class the same __repr__ and __str__.""" 10 | 11 | def __repr__(self): 12 | return self.__str__() 13 | 14 | 15 | def evaluate_string(string): 16 | """Piggyback on Python's string support so we can have backslash escaping 17 | and niceties like \n, \t, etc. string.decode('string_escape') would have 18 | been a lower-level possibility. 19 | 20 | """ 21 | return ast.literal_eval(string) 22 | 23 | 24 | @python_2_unicode_compatible 25 | class Token(StrAndRepr): 26 | """A class to represent tokens, for use with TokenGrammars 27 | 28 | You will likely want to subclass this to hold additional information, like 29 | the characters that you lexed to create this token. Alternately, feel free 30 | to create your own class from scratch. The only contract is that tokens 31 | must have a ``type`` attr. 32 | 33 | """ 34 | __slots__ = ['type'] 35 | 36 | def __init__(self, type): 37 | self.type = type 38 | 39 | def __str__(self): 40 | return u'' % (self.type,) 41 | 42 | def __eq__(self, other): 43 | return self.type == other.type 44 | -------------------------------------------------------------------------------- /py_vesion_checker.py: -------------------------------------------------------------------------------- 1 | import platform 2 | py_version_min = 3.6 3 | py_version_max = 4.0 4 | 5 | 6 | def compare_py_version(): 7 | ver_tuple = platform.python_version_tuple() 8 | floatver = float(ver_tuple[0]) + float(ver_tuple[1]) / 10 9 | if floatver < py_version_min: 10 | return -1 11 | if floatver > py_version_max: 12 | return 1 13 | return 0 14 | 15 | 16 | def check_py_version_with_exception(): 17 | res = compare_py_version() 18 | desc = "" 19 | if res < 0: 20 | desc = "version {} lower than {}".format(platform.python_version(), py_version_min) 21 | raise Exception(desc) 22 | if res > 0: 23 | desc = "version {} higher than {}".format(platform.python_version(), py_version_max) 24 | raise Exception(desc) 25 | return True 26 | 27 | # check_py_version_with_exception() 28 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts= -v --hypothesis-show-statistics --showlocals 3 | python_paths= . 4 | xfail_strict=true 5 | 6 | [pytest-watch] 7 | runner= pytest --failed-first --maxfail=1 --no-success-flaky-report 8 | -------------------------------------------------------------------------------- /release_note.txt: -------------------------------------------------------------------------------- 1 | v0.9.3 2 | -------------------------------------------------------------------------------- /requirements-ref.txt: -------------------------------------------------------------------------------- 1 | parsimonious 2 | attrdict 3 | bumpversion 4 | configobj 5 | cytoolz 6 | lru-dict 7 | pycryptodome 8 | cryptography>=3.3.1 9 | requests 10 | toolz 11 | hypothesis>=3.6.1 12 | argcomplete 13 | pymitter 14 | asyncio 15 | promise 16 | rsa 17 | ecdsa 18 | pyOpenSSL==20.0.0 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | argcomplete==2.0.0 2 | asyncio==3.4.3 3 | #attrdict==2.0.1 4 | attrs==22.2.0 5 | bump2version==1.0.1 6 | bumpversion==0.6.0 7 | certifi==2022.12.7 8 | cffi==1.15.1 9 | charset_normalizer==3.0.1 10 | configobj==5.0.8 11 | cryptography==39.0.1 12 | cytoolz==0.12.1 13 | ecdsa==0.18.0 14 | exceptiongroup==1.1.0 15 | hypothesis==6.68.2 16 | lru_dict==1.1.8 17 | #parsimonious==0.8.1 18 | promise==2.3 19 | pyasn1==0.4.8 20 | pycparser==2.21 21 | pycryptodome==3.17 22 | pymitter==0.4.0 23 | pyOpenSSL==20.0.0 24 | requests==2.28.2 25 | rsa==4.9 26 | six==1.16.0 27 | sortedcontainers==2.4.0 28 | toolz==0.12.0 29 | urllib3==1.26.14 30 | tqdm==4.66.1 31 | 32 | -------------------------------------------------------------------------------- /rlp/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Jnnk, Vitalik Buterin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /rlp/README.md: -------------------------------------------------------------------------------- 1 | # pyrlp 2 | 3 | [![Build Status](https://travis-ci.org/ethereum/pyrlp.svg?branch=develop)](https://travis-ci.org/ethereum/pyrlp) 4 | [![Coverage Status](https://coveralls.io/repos/ethereum/pyrlp/badge.svg)](https://coveralls.io/r/ethereum/pyrlp) 5 | [![PyPI version](https://badge.fury.io/py/rlp.svg)](http://badge.fury.io/py/rlp) 6 | 7 | A Python implementation of Recursive Length Prefix encoding (RLP). You can find 8 | the specification of the standard in the 9 | [Ethereum wiki](https://github.com/ethereum/wiki/wiki/RLP) and the 10 | documentation of this package on 11 | [readthedocs](http://pyrlp.readthedocs.org/en/latest/). 12 | 13 | 14 | ### Release setup 15 | 16 | For Debian-like systems: 17 | ``` 18 | apt install pandoc 19 | ``` 20 | 21 | To release a new version: 22 | 23 | ```sh 24 | make release bump=$$VERSION_PART_TO_BUMP$$ 25 | ``` 26 | 27 | #### How to bumpversion 28 | 29 | The version format for this repo is `{major}.{minor}.{patch}` for stable, and 30 | `{major}.{minor}.{patch}-{stage}.{devnum}` for unstable (`stage` can be alpha or beta). 31 | 32 | To issue the next version in line, specify which part to bump, 33 | like `make release bump=minor` or `make release bump=devnum`. 34 | 35 | If you are in a beta version, `make release bump=stage` will switch to a stable. 36 | 37 | To issue an unstable version when the current version is stable, specify the 38 | new version explicitly, like `make release bump="--new-version 4.0.0-alpha.1 devnum"` 39 | -------------------------------------------------------------------------------- /rlp/__init__.py: -------------------------------------------------------------------------------- 1 | from . import sedes # noqa: F401 2 | from .codec import ( # noqa: F401 3 | encode, 4 | decode, 5 | infer_sedes, 6 | ) 7 | from .exceptions import ( # noqa: F401 8 | RLPException, 9 | EncodingError, 10 | DecodingError, 11 | SerializationError, 12 | DeserializationError, 13 | ) 14 | from .lazy import decode_lazy, peek, LazyList # noqa: F401 15 | from .sedes import Serializable # noqa: F401 16 | -------------------------------------------------------------------------------- /rlp/atomic.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | 4 | class Atomic(metaclass=abc.ABCMeta): 5 | """ABC for objects that can be RLP encoded as is.""" 6 | pass 7 | 8 | 9 | Atomic.register(bytes) 10 | Atomic.register(bytearray) 11 | -------------------------------------------------------------------------------- /rlp/sedes/__init__.py: -------------------------------------------------------------------------------- 1 | from . import raw # noqa: F401 2 | from .binary import Binary, binary # noqa: F401 3 | from .boolean import Boolean, boolean # noqa: F401 4 | from .big_endian_int import BigEndianInt, big_endian_int # noqa: F401 5 | from .lists import CountableList, List # noqa: F401 6 | from .serializable import Serializable # noqa: F401 7 | from .text import Text, text # noqa: #401 8 | -------------------------------------------------------------------------------- /rlp/sedes/big_endian_int.py: -------------------------------------------------------------------------------- 1 | from eth_utils import ( 2 | int_to_big_endian, 3 | big_endian_to_int, 4 | ) 5 | 6 | from rlp.exceptions import DeserializationError, SerializationError 7 | 8 | 9 | class BigEndianInt(object): 10 | """A sedes for big endian integers. 11 | 12 | :param l: the size of the serialized representation in bytes or `None` to 13 | use the shortest possible one 14 | """ 15 | 16 | def __init__(self, l=None): 17 | self.l = l 18 | 19 | def serialize(self, obj): 20 | if isinstance(obj, bool) or not isinstance(obj, int): 21 | raise SerializationError('Can only serialize integers', obj) 22 | if self.l is not None and obj >= 256**self.l: 23 | raise SerializationError('Integer too large (does not fit in {} ' 24 | 'bytes)'.format(self.l), obj) 25 | if obj < 0: 26 | raise SerializationError('Cannot serialize negative integers', obj) 27 | 28 | if obj == 0: 29 | s = b'' 30 | else: 31 | s = int_to_big_endian(obj) 32 | 33 | if self.l is not None: 34 | return b'\x00' * max(0, self.l - len(s)) + s 35 | else: 36 | return s 37 | 38 | def deserialize(self, serial): 39 | if self.l is not None and len(serial) != self.l: 40 | raise DeserializationError('Invalid serialization (wrong size)', 41 | serial) 42 | if self.l is None and len(serial) > 0 and serial[0:1] == b'\x00': 43 | raise DeserializationError('Invalid serialization (not minimal ' 44 | 'length)', serial) 45 | 46 | serial = serial or b'\x00' 47 | return big_endian_to_int(serial) 48 | 49 | 50 | big_endian_int = BigEndianInt() 51 | -------------------------------------------------------------------------------- /rlp/sedes/binary.py: -------------------------------------------------------------------------------- 1 | from rlp.exceptions import SerializationError, DeserializationError 2 | from rlp.atomic import Atomic 3 | 4 | 5 | class Binary(object): 6 | """A sedes object for binary data of certain length. 7 | 8 | :param min_length: the minimal length in bytes or `None` for no lower limit 9 | :param max_length: the maximal length in bytes or `None` for no upper limit 10 | :param allow_empty: if true, empty strings are considered valid even if 11 | a minimum length is required otherwise 12 | """ 13 | 14 | def __init__(self, min_length=None, max_length=None, allow_empty=False): 15 | self.min_length = min_length or 0 16 | if max_length is None: 17 | self.max_length = float('inf') 18 | else: 19 | self.max_length = max_length 20 | self.allow_empty = allow_empty 21 | 22 | @classmethod 23 | def fixed_length(cls, l, allow_empty=False): 24 | """Create a sedes for binary data with exactly `l` bytes.""" 25 | return cls(l, l, allow_empty=allow_empty) 26 | 27 | @classmethod 28 | def is_valid_type(cls, obj): 29 | return isinstance(obj, (bytes, bytearray)) 30 | 31 | def is_valid_length(self, l): 32 | return any((self.min_length <= l <= self.max_length, 33 | self.allow_empty and l == 0)) 34 | 35 | def serialize(self, obj): 36 | if not Binary.is_valid_type(obj): 37 | raise SerializationError('Object is not a serializable ({})'.format(type(obj)), obj) 38 | 39 | if not self.is_valid_length(len(obj)): 40 | raise SerializationError('Object has invalid length', obj) 41 | 42 | return obj 43 | 44 | def deserialize(self, serial): 45 | if not isinstance(serial, Atomic): 46 | m = 'Objects of type {} cannot be deserialized' 47 | raise DeserializationError(m.format(type(serial).__name__), serial) 48 | 49 | if self.is_valid_length(len(serial)): 50 | return serial 51 | else: 52 | raise DeserializationError('{} has invalid length'.format(type(serial)), serial) 53 | 54 | 55 | binary = Binary() 56 | -------------------------------------------------------------------------------- /rlp/sedes/boolean.py: -------------------------------------------------------------------------------- 1 | from rlp.exceptions import ( 2 | DeserializationError, 3 | SerializationError, 4 | ) 5 | 6 | 7 | class Boolean: 8 | """A sedes for booleans 9 | """ 10 | 11 | def serialize(self, obj): 12 | if not isinstance(obj, bool): 13 | raise SerializationError('Can only serialize integers', obj) 14 | 15 | if obj is False: 16 | return b'' 17 | elif obj is True: 18 | return b'\x01' 19 | else: 20 | raise Exception("Invariant: no other options for boolean values") 21 | 22 | def deserialize(self, serial): 23 | if serial == b'': 24 | return False 25 | elif serial == b'\x01': 26 | return True 27 | else: 28 | raise DeserializationError( 29 | 'Invalid serialized boolean. Must be either 0x01 or 0x00', 30 | serial 31 | ) 32 | 33 | 34 | boolean = Boolean() 35 | -------------------------------------------------------------------------------- /rlp/sedes/raw.py: -------------------------------------------------------------------------------- 1 | """ 2 | A sedes that does nothing. Thus, everything that can be directly encoded by RLP 3 | is serializable. This sedes can be used as a placeholder when deserializing 4 | larger structures. 5 | """ 6 | from collections.abc import Sequence 7 | 8 | from rlp.exceptions import SerializationError 9 | from rlp.atomic import Atomic 10 | 11 | 12 | def serializable(obj): 13 | if isinstance(obj, Atomic): 14 | return True 15 | elif not isinstance(obj, str) and isinstance(obj, Sequence): 16 | return all(map(serializable, obj)) 17 | else: 18 | return False 19 | 20 | 21 | def serialize(obj): 22 | if not serializable(obj): 23 | raise SerializationError('Can only serialize nested lists of strings', 24 | obj) 25 | return obj 26 | 27 | 28 | def deserialize(serial): 29 | return serial 30 | -------------------------------------------------------------------------------- /rlp/utils.py: -------------------------------------------------------------------------------- 1 | import struct 2 | 3 | 4 | ALL_BYTES = tuple( 5 | struct.pack('B', i) 6 | for i in range(256) 7 | ) 8 | -------------------------------------------------------------------------------- /sample/AddrTableWorker.abi: -------------------------------------------------------------------------------- 1 | [{"constant":false,"inputs":[{"name":"name","type":"string"},{"name":"balance","type":"uint256"},{"name":"city","type":"address"}],"name":"create","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"name","type":"string"}],"name":"is_exist","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"dectectAddr","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"name","type":"string"}],"name":"select","outputs":[{"name":"","type":"int256"},{"name":"","type":"uint256"},{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"ret","type":"int256"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"orgin","type":"address"},{"indexed":false,"name":"memo","type":"string"}],"name":"permissionEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"ret","type":"int256"},{"indexed":false,"name":"name","type":"string"},{"indexed":false,"name":"balance","type":"uint256"},{"indexed":false,"name":"city","type":"address"},{"indexed":false,"name":"memo","type":"string"}],"name":"createEvent","type":"event"}] -------------------------------------------------------------------------------- /sample/contract.ini: -------------------------------------------------------------------------------- 1 | [address] 2 | SimpleInfo = 0x0b8ae6ce3850cedf8ebf6b6a7b949bb085d3ad17 3 | [history] 4 | 0x027bfda3a4374d6a153c46bdec4efbdb10c7ae03 = "SimpleInfo:2019-06-20 19:16:48,block:158,tx:0x488b3708e98aed16ad16bfcc1fb2b3c5f7e613f39a3a4cf35db3f99dd4120dfe" 5 | 0xff10f2020a91e9ba8ff0a1aa98c8ef2e845ce6fb = "SimpleInfo:2019-06-20 19:17:16,block:160,tx:0xb30fc47caa1520203e51c0d90b23fe0f6ceab9b9fe0c59d218610c85ef6f0a86" 6 | 0x1165299c539304d662f0934a3f794d1bc4c33694 = "SimpleInfo:2019-06-20 19:19:51,block:162,tx:0xdda2524e46933ec849701d139db371cdcb717853c26aa461864a93081f7b196a" 7 | 0xf71c964454c9cedbde666ee86b8a277fdaed19d9 = "SimpleInfo:2019-06-20 19:27:50,block:164,tx:0x775f5217bf10a2c7152882874f24049e270ca7acecf68e81c1f6508ac98db575" 8 | 0xcda895ec53a73fbc3777648cb4c87b38e252f876 = "SimpleInfo:2019-06-20 22:35:51,block:166,tx:0x564cfb5fc41f2e1e5611aaac6a28a5be784421e7692147bae2a52ccd1b502a3b" 9 | 0xcab316ebdfef9fd9a959171baec2bb91d9fa5481 = "SimpleInfo:2019-06-20 23:08:08,block:168,tx:0xbd6a2d4b7187ecf8b4c4e32e107d0c66f214c9ddbbf3c51a1376be50c337e707" 10 | 0xf74c2c7131c2461db2e67362a8e7fca6dc0a66bf = "SimpleInfo:2019-06-20 23:28:41,block:170,tx:0x3fd192227ab76a6705b3cc62641ba3b006323a6ff277910c0f33fb0a37f5b73b" 11 | 0xb7a506877cd874b0dc0ed1a43762193b60a7b6d4 = "SimpleInfo:2019-06-20 23:42:35,block:172,tx:0x0f2687a111d6edc3351241d5e2f6f6b66657d6a87c3832823d549a0032405bbc" 12 | 0x35ea6ab6035449acc289fdc313835e7c154ddb41 = "SimpleInfo:2019-06-20 23:45:52,block:174,tx:0x1f24b26965de878347d24a1ad57928c885d037f6384ec27a38705b30a85ecd30" 13 | 0xbbe16a7054c0f1d3b71f4efdb51b9e40974ad651 = "SimpleInfo:2019-06-20 23:57:01,block:176,tx:0x0c4cfcb323b34881bee4a107a7430dd41c555e85dd4c6245d0487500c41703d4" 14 | 0x75673e6859e6a4f791d583a6874e97adafb9b923 = "SimpleInfo:2019-06-21 00:00:23,block:178,tx:0x79beac8572493ff1c4f570cd3b931a91af147f1d509ec43e912b7bb5c263f4b1" 15 | 0xb74cc12c185b349c4285515ab212f5b9b8cfff5e = "SimpleInfo:2019-06-21 00:01:17,block:180,tx:0x2afea21dcc6f7a4f5ac9779553acc55ebae26f09a8093e75c9a2fb65f65bced5" 16 | 0xf2c07c98a6829ae61f3cb40c69f6b2f035dd63fc = "SimpleInfo:2019-06-21 00:11:07,block:182,tx:0x39a6b7fa62317eab72fcfda6fc5c2dc3d21fb5240f67b1c089533e57c08f6453" 17 | -------------------------------------------------------------------------------- /sample/error.json: -------------------------------------------------------------------------------- 1 | { 2 | "error": { 3 | "code": 7, 4 | "data": null, 5 | "message": "Only pbft consensus supports the view property" 6 | }, "id": 1, "jsonrpc": "2.0" 7 | } -------------------------------------------------------------------------------- /sample/posttxbyhash.txt: -------------------------------------------------------------------------------- 1 | POST / HTTP/1.1 2 | Content-Type: text/json 3 | User-Agent: tester 4 | Host: 127.0.0.1 5 | Content-Type: application/json 6 | Content-Length: 146 7 | 8 | {"jsonrpc": "2.0", "method": "getTransactionByHash", "params": [1, "0x27a7e7c14470a534cbf491310d85ad8e5620a893637cc47cfac964413bb08bf9"], "id": 0} -------------------------------------------------------------------------------- /sample/tx_simpleinfo_set.json: -------------------------------------------------------------------------------- 1 | { 2 | "blockHash":"0x2a5547dca996a38975ea4f2a037926eba66bdc94d21320f3c98f0885a6cbbca2", 3 | "blockNumber":"0x7a", 4 | "from":"0x72e5952597fac29dd923c9e2aa651f057fbb1585", 5 | "gas":"0x1c9c380", 6 | "gasPrice":"0x1c9c380", 7 | "hash":"0xc86d0282f223aaf96b7af0e5c7b1ce82345352678c5129c200e9f6584d5cf3b1", 8 | "input":"0xce58621e000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000007e80000000000000000000000007029c502b4f824d19bd7921e9cb74ef92392fb1c000000000000000000000000000000000000000000000000000000000000000a73696d706c656e616d6500000000000000000000000000000000000000000000", 9 | "nonce":"0x2eb5f5d9", 10 | "to":"0x9a1644d2158922f5f2d4e04cb21da3b3e6d05a38", 11 | "transactionIndex":"0x0", 12 | "value":"0x0" 13 | } -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/python-sdk/4c3b00f4fd85dfab5e9be3acaa348741552f9c3d/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_helloworld.py: -------------------------------------------------------------------------------- 1 | from contracts.HelloWorld import HelloWorld 2 | 3 | address = "0x7b6cb85c667c6ec8a4d81be837270ddfcf1838d5" 4 | cli = HelloWorld(address) 5 | (outputresult, receipt) = cli.set("testeraaa") 6 | # outputresult = si.data_parser.parse_receipt_output("set", receipt['output']) 7 | print("receipt output :", outputresult) 8 | logresult = cli.data_parser.parse_event_logs(receipt["logs"]) 9 | i = 0 10 | for log in logresult: 11 | if 'eventname' in log: 12 | i = i + 1 13 | print("{}): log name: {} , data: {}".format(i, log['eventname'], log['eventdata'])) 14 | print(cli.get()) 15 | 16 | -------------------------------------------------------------------------------- /tests/test_info.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import platform 4 | print("python_version", platform.python_version()) 5 | print("java_ver", platform.java_ver()) 6 | print("libc_ver", platform.libc_ver()) 7 | print("machine", platform.machine()) 8 | print("mac_ver", platform.mac_ver()) 9 | print("architecture", platform.architecture()) 10 | print("processor", platform.processor()) 11 | print("python_branch", platform.python_branch()) 12 | print("python_compiler", platform.python_compiler()) 13 | print("python_version_tuple", platform.python_version_tuple()) 14 | print("system", platform.system()) 15 | print("uname", platform.uname()) 16 | print("version", platform.version()) 17 | print("python_implementation", platform.python_implementation()) 18 | 19 | 20 | -------------------------------------------------------------------------------- /tests/test_simpleinfo.py: -------------------------------------------------------------------------------- 1 | from contracts.SimpleInfo import SimpleInfo 2 | import json 3 | address = "0x0b441629d3c6d297165a10a137cf105bfbf89e89" 4 | si = SimpleInfo("") 5 | result = si.deploy("contracts/SimpleInfo.bin") 6 | address = result['contractAddress'] 7 | print("new address = ", address) 8 | 9 | (outputresult, receipt) = si.set("testeraaa", 888, '0x7029c502b4f824d19bd7921e9cb74ef92392fb1F') 10 | logresult = si.data_parser.parse_event_logs(receipt["logs"]) 11 | print("receipt output :", outputresult) 12 | i = 0 13 | for log in logresult: 14 | if 'eventname' in log: 15 | i = i + 1 16 | print("{}): log name: {} , data: {}".format(i, log['eventname'], log['eventdata'])) 17 | 18 | print("test setbalance") 19 | (output, receipt) = si.setbalance(999) 20 | json.dumps(receipt, indent=4) 21 | logresult = si.data_parser.parse_event_logs(receipt["logs"]) 22 | print("receipt output :", outputresult) 23 | i = 0 24 | for log in logresult: 25 | if 'eventname' in log: 26 | i = i + 1 27 | print("{}): log name: {} , data: {}".format(i, log['eventname'], log['eventdata'])) 28 | 29 | 30 | print(si.getall()) 31 | print(si.getbalance1(100)) 32 | -------------------------------------------------------------------------------- /tests/test_sm2.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import binascii 3 | from gmssl import sm2, func 4 | from gmssl import sm2_helper 5 | from eth_utils import decode_hex,encode_hex 6 | import os 7 | 8 | 9 | 10 | if __name__ == '__main__': 11 | private_key = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5' 12 | private_key = encode_hex( os.urandom(4) ) 13 | print("key seed is ",private_key) 14 | #public_key = 'B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207' 15 | 16 | kp = sm2_helper.sm2_key_pair_gen() 17 | print("key_pair_gen:", kp) 18 | public_key = sm2_helper.sm2_privkey_to_pub(private_key, True) 19 | print("key gen by privatekey:") 20 | print(public_key) 21 | print(public_key) 22 | sm2_crypt = sm2.CryptSM2( 23 | public_key=public_key, private_key=private_key) 24 | data = b"12345678" 25 | enc_data = sm2_crypt.encrypt(data) 26 | 27 | #print("enc_data:%s" % enc_data) 28 | #print("enc_data_base64:%s" % base64.b64encode(bytes.fromhex(enc_data))) 29 | dec_data = sm2_crypt.decrypt(enc_data) 30 | print(b"dec_data:%s" % dec_data) 31 | assert data == dec_data 32 | print(len(encode_hex(enc_data))) 33 | 34 | print("-----------------test sign and verify---------------") 35 | #random_hex_str = func.random_hex(sm2_crypt.para_len) 36 | (R, S) = sm2_crypt.sign(data) 37 | 38 | print("signed r s = ", R, S) 39 | sign = sm2_crypt.combine_signed_R_S(R, S) 40 | print('sign:%s' % sign) 41 | verify = sm2_crypt.verify(sign, data) 42 | print('verify:%s' % verify) 43 | assert verify 44 | -------------------------------------------------------------------------------- /tests/test_sm3.py: -------------------------------------------------------------------------------- 1 | from gmssl import sm3, func 2 | 3 | if __name__ == '__main__': 4 | y = sm3.sm3_hash(func.bytes_to_list(b"abc")) 5 | print(y) 6 | -------------------------------------------------------------------------------- /tests/test_sm4.py: -------------------------------------------------------------------------------- 1 | from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT 2 | from eth_utils import decode_hex,encode_hex 3 | # key = b'3l5butlj26hvv313' 4 | key = "0x142d340c0f4df64bf56bbc0a3931e5228c7836add09cf8ff3cefeb3d7e610deb458ec871a9da86bae1ffc029f5aba41e725786ecb7f93ad2670303bf2db27b8a" 5 | key= decode_hex(key) 6 | value = b'12345678901234561234567890123456' 7 | iv = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 8 | crypt_sm4 = CryptSM4() 9 | 10 | crypt_sm4.set_key(key, SM4_ENCRYPT) 11 | encrypt_value = crypt_sm4.crypt_ecb(value) 12 | crypt_sm4.set_key(key, SM4_DECRYPT) 13 | decrypt_value = crypt_sm4.crypt_ecb(encrypt_value) 14 | assert value == decrypt_value 15 | 16 | crypt_sm4.set_key(key, SM4_ENCRYPT) 17 | encrypt_value = crypt_sm4.crypt_cbc(iv, value) 18 | crypt_sm4.set_key(key, SM4_DECRYPT) 19 | decrypt_value = crypt_sm4.crypt_cbc(iv, encrypt_value) 20 | assert value == decrypt_value 21 | hexen = encode_hex(encrypt_value) 22 | print(hexen) 23 | print("len= ",len(hexen)) 24 | print("plain : ", crypt_sm4.crypt_cbc(iv,encrypt_value)) -------------------------------------------------------------------------------- /tests/testchannelpack.py: -------------------------------------------------------------------------------- 1 | from client.channelpack import ChannelPack 2 | from eth_utils import encode_hex 3 | import json; 4 | seq = b"123456789012345678900123456789012"; 5 | data = "{\"jsonrpc\":\"2.0\",\"method\":\"getClientVersion\",\"params\":[],\"id\":1}"; 6 | json.loads(data) 7 | print("datalen ",len(data)) 8 | pack = ChannelPack(0x12, seq, 0, data) 9 | packres = pack.pack() 10 | 11 | print(encode_hex(packres) ) 12 | 13 | aa = [] 14 | b = dict() 15 | aa.append({"test",1}) 16 | aa.append({"test",2}) 17 | print(b) 18 | print(json.dumps(b)) 19 | -------------------------------------------------------------------------------- /tests/testconfig.py: -------------------------------------------------------------------------------- 1 | ''' 2 | @author: kentzhang 3 | @date: 2019-06 4 | ''' 5 | from configobj import ConfigObj 6 | 7 | config = ConfigObj("sample/contract.ini", encoding='UTF8') 8 | 9 | config['address'] = {} 10 | config['address']['SimpleInfo'] = "0x0b8ae6ce3850cedf8ebf6b6a7b949bb085d3ad17" 11 | config['address']['testnode'] = "this is a test" 12 | 13 | 14 | # 写入 15 | config.write() 16 | # 读配置文件 17 | print(config['address']) 18 | print(config['address']['SimpleInfo']) 19 | print(config['address']['testnode']) 20 | 21 | 22 | del config['address']['testnode'] 23 | config.write() 24 | -------------------------------------------------------------------------------- /tests/testconsensus.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append("./") 3 | import json 4 | 5 | from bcos3sdk.bcos3client import Bcos3Client 6 | from bcos3sdk.consensus_precompile import ConsensusPrecompile 7 | 8 | bcos3client =Bcos3Client() 9 | 10 | client = ConsensusPrecompile(bcos3client) 11 | 12 | nodeid = "0384bdf82b9f33a326a9c67c06b4e52f3afee7c596e7bc0b38083eef42e3921c3c7ce1ad2eaa8f8c9cf66a4dfcff3c54d9a443b35cd626a9943ca914c67fe15b" 13 | response = client.setWeight(nodeid,1) 14 | 15 | print("response is",json.dumps(response,indent=4)) 16 | 17 | nodeid = "testid" 18 | 19 | response = client.addSealer(nodeid,1) 20 | print("response is",json.dumps(response,indent=4)) 21 | 22 | response = client.addObserver(nodeid) 23 | print("response is",json.dumps(response,indent=4)) 24 | 25 | 26 | response = client.removeNode(nodeid) 27 | print("response is",json.dumps(response,indent=4)) 28 | 29 | -------------------------------------------------------------------------------- /tests/testcrypto.py: -------------------------------------------------------------------------------- 1 | from client.signer_impl import Signer_ECDSA 2 | from eth_account.account import Account 3 | from eth_utils.crypto import keccak 4 | from eth_utils import decode_hex,encode_hex 5 | data = b"WeDPR TEST" 6 | hashres = keccak(data) 7 | print(encode_hex(hashres)) 8 | privkey = decode_hex("82dcd33c98a23d5d06f9331554e14ab4044a1d71b169b7a38b61c214f0690f80") 9 | ac = Account().from_key(privkey) 10 | print("privkey:",privkey) 11 | print("public key:",ac.publickey) 12 | print("address:",ac.address) 13 | 14 | signer = Signer_ECDSA(ac) 15 | sign_res =signer.sign(hashres) 16 | print("sign:",sign_res) -------------------------------------------------------------------------------- /tests/testdatatypeparser.py: -------------------------------------------------------------------------------- 1 | ''' 2 | @author: kentzhang 3 | @date: 2019-06 4 | ''' 5 | from client.datatype_parser import DatatypeParser 6 | 7 | import json 8 | 9 | if(True): 10 | parser = DatatypeParser() 11 | parser.load_abi_file("sample/SimpleInfo.abi") 12 | parser.parse_abi() 13 | 14 | with open("sample/receipt.json", "r") as f: 15 | receipt = json.load(f) 16 | f.close() 17 | logs = receipt["logs"] 18 | parser.parse_event_logs(logs) 19 | print("parse result") 20 | for log in logs: 21 | print(log) 22 | result = parser.parse_receipt_output("set", receipt['output']) 23 | print("output :", result) 24 | 25 | if True: 26 | parser = DatatypeParser() 27 | parser.load_abi_file("sample/SimpleInfo.abi") 28 | parser.parse_abi() 29 | with open("sample/tx_simpleinfo_set.json", "r") as f: 30 | tx = json.load(f) 31 | f.close() 32 | result = parser.parse_transaction_input(tx["input"]) 33 | print(result) 34 | -------------------------------------------------------------------------------- /tests/testhello.py: -------------------------------------------------------------------------------- 1 | addr = '0xceaf70129ce627a825b2c0ad60402b72a5a359ef' 2 | 3 | import sys 4 | sys.path.append("./") 5 | from client.bcosclient import BcosClient 6 | 7 | client = BcosClient() 8 | crtAddr = "0xceaf70129ce627a825b2c0ad60402b72a5a359ef" 9 | abi = [{"inputs":[],"name":"getMsg","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_m","type":"string"}],"name":"setMsg","outputs":[],"stateMutability":"nonpayable","type":"function"}] 10 | print(abi) 11 | 12 | abi1 = [{'inputs': [], 'name': 'getMsg', 'outputs': [{'internalType': 'string', 'name': '', 'type': 'string'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'string', 'name': '_m', 'type': 'string'}], 'name': 'setMsg', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}] 13 | data = client.call(crtAddr,abi1,"getMsg") 14 | print(data) 15 | #data = client.sendRawTransactionGetReceipt(crtAddr,helloabi,"setMsg",["hello,yekai007!"]) 16 | #print(data) 17 | #data = client.call(crtAddr,helloabi,"getMsg") 18 | #print("test:",data) 19 | 20 | client.finish() 21 | -------------------------------------------------------------------------------- /tests/testjscall.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from ctypes import byref 3 | 4 | from bcos3sdk.bcos3callbackfuture import BcosCallbackFuture 5 | from bcos3sdk.bcos3client import Bcos3Client 6 | from bcos3sdk.bcos3datadef import s2b 7 | from client.datatype_parser import DatatypeParser 8 | from client.signer_impl import Signer_ECDSA 9 | from eth_account.account import Account 10 | from eth_keys.backends.native.ecdsa import ecdsa_raw_recover 11 | from eth_utils import decode_hex, keccak, encode_hex 12 | rawTxData = "" 13 | bindata = "0x6d4ce63c" 14 | 15 | 16 | 17 | bcos3client = Bcos3Client() 18 | cbfuture = BcosCallbackFuture(sys._getframe().f_code.co_name, "") 19 | group="group0"; 20 | node=""; 21 | to_address = "0xbe6e9bef148d9c3ac77f28c426e609ea7b7e437a"; 22 | 23 | bcos3client.bcossdk.bcos_rpc_call(bcos3client.bcossdk.sdk, s2b(group), s2b(node),s2b(to_address), 24 | s2b(bindata), 25 | #signedtx, 26 | cbfuture.callback, byref(cbfuture.context)) 27 | (is_timeout,resp) = cbfuture.wait(); 28 | print("resp: ",resp) 29 | result = bcos3client.get_result(resp.data); 30 | print("result",result); 31 | 32 | -------------------------------------------------------------------------------- /tests/testrpc.py: -------------------------------------------------------------------------------- 1 | import ssl 2 | import utils.rpc 3 | import sys 4 | print(sys.path) 5 | 6 | url = "http://127.0.0.1:8545" 7 | rpc = utils.rpc.HTTPProvider(url) 8 | rpc.isConnected() 9 | param = [1] 10 | 11 | 12 | bn = rpc.make_request("getBlockNumber", param) 13 | if "error" in bn: 14 | print("error %d, [%s]" % (bn["error"]["code"], bn["error"]["message"])) 15 | else: 16 | print(int(bn['result'], 16)) 17 | 18 | 19 | txhash = "0x27a7e7c14470a534cbf491310d85ad8e5620a893637cc47cfac964413bb08bf9" 20 | tx = rpc.make_request("getTransactionByHash", [1, txhash]) 21 | input = tx["result"]["input"] 22 | print(input) 23 | -------------------------------------------------------------------------------- /tests/testsigner.py: -------------------------------------------------------------------------------- 1 | from client.signer_impl import Signer_ECDSA,Signer_GM 2 | 3 | data = b'1234567890' 4 | 5 | account = Signer_ECDSA.load_from_keyfile("bin/accounts/pyaccount.keystore","123456") 6 | signer = Signer_ECDSA(account) 7 | 8 | res = signer.sign(data) 9 | print(res) 10 | res = signer.sign(data) 11 | print(res) 12 | res = signer.sign(data,2) 13 | print(res) 14 | print("----GM----") 15 | accountgm = Signer_GM.from_key_file("bin/accounts/gm_account.json","123456") 16 | signergm= Signer_GM(accountgm) 17 | res = signergm.sign(data) 18 | print(res) 19 | res = signergm.sign(data) 20 | print(res) -------------------------------------------------------------------------------- /tests/teststructclient.py: -------------------------------------------------------------------------------- 1 | #这个py文件对应的合约是contracts/TestStruct.sol 2 | #注意:TestStruct.sol 的编译器版本是solc6以上 3 | from client.contractnote import ContractNote 4 | from client.bcosclient import ( 5 | BcosClient, 6 | BcosError 7 | ) 8 | import os 9 | from eth_utils import to_checksum_address, decode_hex, keccak 10 | from client.datatype_parser import DatatypeParser 11 | from console_utils.console_common import print_receipt_logs_and_txoutput 12 | client = BcosClient() 13 | info = client.getinfo() 14 | print(info) 15 | 16 | # 从文件加载abi定义 17 | contractname = "TestStruct" 18 | contractFile = "contracts\\"+contractname+".abi" 19 | abi_parser = DatatypeParser() 20 | abi_parser.load_abi_file(contractFile) 21 | contract_abi = abi_parser.contract_abi 22 | print(client.getNodeVersion()) 23 | 24 | #如合约未部署,用python console.py deploy TestStruct 部署一次 25 | #或者自行定位链上既有的合约地址 26 | #address = "0x901250d3fcb6cf282134b12acdd0f1d67f265566" 27 | address = ContractNote.get_last(client.get_full_name(),contractname) 28 | print(address) 29 | 30 | res = client.call(address,contract_abi,"getUser",["alice"]) 31 | print ("call:",res) 32 | 33 | # User结构体参数示例。合约接口里的结构体,对应python的tuple数据类型 34 | # 注:调用合约时的入参一定是个python数组,因为合约接口参数可能有一到多个 35 | args=[("zero",78)] 36 | res = client.sendRawTransactionGetReceipt(address,contract_abi,"addUser",args) 37 | #print("addUser",res) 38 | print_receipt_logs_and_txoutput(client,res,contractname) 39 | res = client.call(address,contract_abi,"getUser",["zero"]) 40 | print ("call:",res) 41 | 42 | #对应第一个参数User[] memory _users,这个参数本身是个数组,所以,_users是参数数组里的’数组‘ [[]] 43 | args=[[("zero",78),("yark",55),("xar",23)]] 44 | res = client.sendRawTransactionGetReceipt(address,contract_abi,"addUsers",args) 45 | print_receipt_logs_and_txoutput(client,res,contractname) 46 | 47 | res = client.call(address,contract_abi,"getUser",["yark"]) 48 | print ("call:",res) 49 | 50 | print("address is",address) 51 | b = keccak(bytes(address, "utf-8")) 52 | print(b) 53 | args = ["name123",b] 54 | res = client.sendRawTransactionGetReceipt(address,contract_abi,"putbytes",args) 55 | print_receipt_logs_and_txoutput(client,res,contractname) 56 | 57 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist= 3 | py{36,37}-core 4 | lint 5 | doctest 6 | 7 | [isort] 8 | combine_as_imports=True 9 | force_sort_within_sections=True 10 | include_trailing_comma=True 11 | known_third_party=hypothesis,pytest 12 | known_first_party=fisco-bcos-python-sdk 13 | line_length=21 14 | multi_line_output=3 15 | use_parentheses=True 16 | 17 | [flake8] 18 | max-line-length= 100 19 | exclude= venv*,.tox,docs,build 20 | ignore= 21 | 22 | [testenv] 23 | usedevelop=True 24 | commands= 25 | core: pytest {posargs:tests} 26 | doctest: make -C {toxinidir}/docs doctest 27 | basepython = 28 | doctest: python 29 | py36: python3.6 30 | py37: python3.7 31 | extras= 32 | test 33 | doctest: doc 34 | whitelist_externals=make 35 | passenv=PYTEST_ADDOPTS 36 | 37 | [testenv:lint] 38 | basepython=python 39 | extras=lint 40 | commands= 41 | flake8 {toxinidir}/tests 42 | isort --recursive --check-only --diff {toxinidir}/tests 43 | mypy --follow-imports=silent --ignore-missing-imports --check-untyped-defs --disallow-incomplete-defs -p client 44 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | import pkg_resources 2 | import sys 3 | import warnings -------------------------------------------------------------------------------- /utils/blocks.py: -------------------------------------------------------------------------------- 1 | from eth_utils import ( 2 | is_bytes, 3 | is_hex, 4 | is_integer, 5 | is_string, 6 | is_text, 7 | remove_0x_prefix, 8 | ) 9 | 10 | 11 | def is_predefined_block_number(value): 12 | if is_text(value): 13 | value_text = value 14 | elif is_bytes(value): 15 | # `value` could either be random bytes or the utf-8 encoding of 16 | # one of the words in: {"latest", "pending", "earliest"} 17 | # We cannot decode the bytes as utf8, because random bytes likely won't be valid. 18 | # So we speculatively decode as 'latin-1', which cannot fail. 19 | value_text = value.decode('latin-1') 20 | elif is_integer(value): 21 | return False 22 | else: 23 | raise TypeError("unrecognized block reference: %r" % value) 24 | 25 | return value_text in {"latest", "pending", "earliest"} 26 | 27 | 28 | def is_hex_encoded_block_hash(value): 29 | if not is_string(value): 30 | return False 31 | return len(remove_0x_prefix(value)) == 64 and is_hex(value) 32 | 33 | 34 | def is_hex_encoded_block_number(value): 35 | if not is_string(value): 36 | return False 37 | elif is_hex_encoded_block_hash(value): 38 | return False 39 | try: 40 | value_as_int = int(value, 16) 41 | except ValueError: 42 | return False 43 | return 0 <= value_as_int < 2**256 44 | 45 | 46 | def select_method_for_block_identifier(value, if_hash, if_number, if_predefined): 47 | if is_predefined_block_number(value): 48 | return if_predefined 49 | elif isinstance(value, bytes): 50 | return if_hash 51 | elif is_hex_encoded_block_hash(value): 52 | return if_hash 53 | elif is_integer(value) and (0 <= value < 2**256): 54 | return if_number 55 | elif is_hex_encoded_block_number(value): 56 | return if_number 57 | else: 58 | raise ValueError( 59 | "Value did not match any of the recognized block identifiers: {0}".format(value) 60 | ) 61 | -------------------------------------------------------------------------------- /utils/caching.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import hashlib 3 | 4 | from eth_utils import ( 5 | is_boolean, 6 | is_bytes, 7 | is_dict, 8 | is_list_like, 9 | is_null, 10 | is_number, 11 | is_text, 12 | to_bytes, 13 | ) 14 | 15 | 16 | def generate_cache_key(value): 17 | """ 18 | Generates a cache key for the *args and **kwargs 19 | """ 20 | if is_bytes(value): 21 | return hashlib.md5(value).hexdigest() 22 | elif is_text(value): 23 | return generate_cache_key(to_bytes(text=value)) 24 | elif is_boolean(value) or is_null(value) or is_number(value): 25 | return generate_cache_key(repr(value)) 26 | elif is_dict(value): 27 | return generate_cache_key(( 28 | (key, value[key]) 29 | for key 30 | in sorted(value.keys()) 31 | )) 32 | elif is_list_like(value) or isinstance(value, collections.abc.Generator): 33 | return generate_cache_key("".join(( 34 | generate_cache_key(item) 35 | for item 36 | in value 37 | ))) 38 | else: 39 | raise TypeError("Cannot generate cache key for value {0} of type {1}".format( 40 | value, 41 | type(value), 42 | )) 43 | -------------------------------------------------------------------------------- /utils/datatypes.py: -------------------------------------------------------------------------------- 1 | from eth_utils.toolz import ( 2 | concat, 3 | ) 4 | 5 | import utils.formatters 6 | 7 | 8 | def verify_attr(class_name, key, namespace): 9 | if key not in namespace: 10 | raise AttributeError( 11 | "Property {0} not found on {1} class. " 12 | "`{1}.factory` only accepts keyword arguments which are " 13 | "present on the {1} class".format(key, class_name) 14 | ) 15 | 16 | 17 | class PropertyCheckingFactory(type): 18 | def __init__(cls, name, bases, namespace, **kargs): 19 | # see PEP487. To accept kwargs in __new__, they need to be 20 | # filtered out here. 21 | super().__init__(name, bases, namespace) 22 | 23 | def __new__(mcs, name, bases, namespace, normalizers=None): 24 | all_bases = set(concat(base.__mro__ for base in bases)) 25 | all_keys = set(concat(base.__dict__.keys() for base in all_bases)) 26 | 27 | for key in namespace: 28 | verify_attr(name, key, all_keys) 29 | 30 | if normalizers: 31 | processed_namespace = utils.formatters.apply_formatters_to_dict( 32 | normalizers, 33 | namespace, 34 | ) 35 | else: 36 | processed_namespace = namespace 37 | 38 | return super().__new__(mcs, name, bases, processed_namespace) 39 | -------------------------------------------------------------------------------- /utils/decorators.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import threading 3 | import warnings 4 | 5 | 6 | class combomethod: 7 | def __init__(self, method): 8 | self.method = method 9 | 10 | def __get__(self, obj=None, objtype=None): 11 | @functools.wraps(self.method) 12 | def _wrapper(*args, **kwargs): 13 | if obj is not None: 14 | return self.method(obj, *args, **kwargs) 15 | else: 16 | return self.method(objtype, *args, **kwargs) 17 | return _wrapper 18 | 19 | 20 | def reject_recursive_repeats(to_wrap): 21 | """ 22 | Prevent simple cycles by returning None when called recursively with same instance 23 | """ 24 | to_wrap.__already_called = {} 25 | 26 | @functools.wraps(to_wrap) 27 | def wrapped(*args): 28 | arg_instances = tuple(map(id, args)) 29 | thread_id = threading.get_ident() 30 | thread_local_args = (thread_id,) + arg_instances 31 | if thread_local_args in to_wrap.__already_called: 32 | raise ValueError('Recursively called %s with %r' % (to_wrap, args)) 33 | to_wrap.__already_called[thread_local_args] = True 34 | try: 35 | wrapped_val = to_wrap(*args) 36 | finally: 37 | del to_wrap.__already_called[thread_local_args] 38 | return wrapped_val 39 | return wrapped 40 | 41 | 42 | def deprecated_for(replace_message): 43 | """ 44 | Decorate a deprecated function, with info about what to use instead, like: 45 | 46 | @deprecated_for("toBytes()") 47 | def toAscii(arg): 48 | ... 49 | """ 50 | def decorator(to_wrap): 51 | @functools.wraps(to_wrap) 52 | def wrapper(*args, **kwargs): 53 | warnings.warn( 54 | "%s is deprecated in favor of %s" % (to_wrap.__name__, replace_message), 55 | category=DeprecationWarning, 56 | stacklevel=2) 57 | return to_wrap(*args, **kwargs) 58 | return wrapper 59 | return decorator 60 | -------------------------------------------------------------------------------- /utils/function_identifiers.py: -------------------------------------------------------------------------------- 1 | class FallbackFn: 2 | pass 3 | -------------------------------------------------------------------------------- /utils/http.py: -------------------------------------------------------------------------------- 1 | def construct_user_agent(class_name): 2 | 3 | user_agent = 'liteclient.py/{version}/{class_name}'.format( 4 | version="1.0", 5 | class_name=class_name, 6 | ) 7 | return user_agent 8 | -------------------------------------------------------------------------------- /utils/request.py: -------------------------------------------------------------------------------- 1 | 2 | import requests 3 | import lru 4 | 5 | from utils.caching import ( 6 | generate_cache_key, 7 | ) 8 | 9 | 10 | def _remove_session(key, session): 11 | session.close() 12 | 13 | 14 | _session_cache = lru.LRU(8, callback=_remove_session) 15 | 16 | 17 | def _get_session(*args, **kwargs): 18 | cache_key = generate_cache_key((args, kwargs)) 19 | if cache_key not in _session_cache: 20 | _session_cache[cache_key] = requests.Session() 21 | return _session_cache[cache_key] 22 | 23 | 24 | def make_post_request(endpoint_uri, method, params, data, *args, **kwargs): 25 | kwargs.setdefault('timeout', 10) 26 | session = _get_session(endpoint_uri, method, params, kwargs) 27 | response = session.post(endpoint_uri, data=data, *args, **kwargs) 28 | response.raise_for_status() 29 | #增加一些兼容性逻辑 30 | if hasattr(response,"cb_context"): 31 | return response.cb_context 32 | if hasattr(response, "context"): 33 | return response.context 34 | if hasattr(response, "content"): 35 | return response.content 36 | --------------------------------------------------------------------------------