├── .ci ├── ci_check.sh └── ci_check_commit.sh ├── .circleci └── config.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build-hsm.gradle ├── build.gradle ├── docs ├── CONTRIBUTING_CN.md ├── README_EN.md └── images │ └── FISCO_BCOS_Logo.svg ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew └── src ├── main └── java │ └── org │ └── fisco │ └── bcos │ └── sdk │ └── demo │ ├── ChainContinuityTester.java │ ├── amop │ ├── Broadcast.java │ ├── Publish.java │ └── Subscribe.java │ ├── codegen │ ├── CompileSolidityException.java │ └── DemoSolcToJava.java │ ├── contract │ ├── Account.java │ ├── BalanceBank.java │ ├── ComplexCodecTest.java │ ├── CpuHeavy.java │ ├── CpuHeavyContract.java │ ├── CpuHeavyPrecompiled.java │ ├── Crypto.java │ ├── Curve25519VRFVerifyTest.java │ ├── DagTransfer.java │ ├── DelegateCallTest.java │ ├── DmcTransfer.java │ ├── Economic.java │ ├── EventSubDemo.java │ ├── Evidence.java │ ├── EvidenceOne.java │ ├── EvidenceSignersData.java │ ├── EvidenceVerify.java │ ├── HelloExternal.java │ ├── HelloWorld.java │ ├── HelloWorldLiquid.java │ ├── KVTableTest.java │ ├── MapTest.java │ ├── MultiMapTest.java │ ├── MultiTableTest.java │ ├── Ok.java │ ├── OkD.java │ ├── PaillierPrecompiled.java │ ├── ParallelCpuHeavy.java │ ├── ParallelOk.java │ ├── ParallelOkLiquid.java │ ├── ParallelSmallbank.java │ ├── SM2EvidenceVerify.java │ ├── SimpleEvidenceFactory.java │ ├── SmallBank.java │ ├── SmallBankPrecompiled.java │ ├── TableTest.java │ ├── TableTestLiquid.java │ ├── TableTestV320.java │ ├── TigerHoleV2.java │ ├── WeIdContract.java │ ├── dgms │ │ ├── Counters.java │ │ ├── Factory.java │ │ ├── OneToMore.java │ │ ├── OneToOne.java │ │ ├── Roles.java │ │ ├── SafeMath.java │ │ └── Suspendable.java │ ├── liquid │ │ ├── .gitignore │ │ ├── hello_world │ │ │ ├── Cargo.toml │ │ │ └── src │ │ │ │ └── lib.rs │ │ ├── parallel_ok │ │ │ ├── Cargo.toml │ │ │ └── src │ │ │ │ └── lib.rs │ │ └── table_test │ │ │ ├── Cargo.toml │ │ │ └── src │ │ │ └── lib.rs │ ├── sol │ │ ├── Account.sol │ │ ├── AnonymousVotingInterface.sol │ │ ├── BalanceBank.sol │ │ ├── BalancePrecompiledTest.sol │ │ ├── BalanceReceiveTest.sol │ │ ├── BalanceTest.sol │ │ ├── BlobHashExample.sol │ │ ├── Cast.sol │ │ ├── CodeOp.sol │ │ ├── ComplexCodecTest.sol │ │ ├── ContractA.sol │ │ ├── ContractB.sol │ │ ├── ContractTestAll.sol │ │ ├── CpuHeavy.sol │ │ ├── CpuHeavyPrecompiled.sol │ │ ├── Create2.sol │ │ ├── Crypto.sol │ │ ├── Curve25519VRFVerifyTest.sol │ │ ├── DagTransfer.sol │ │ ├── DelegateCall.sol │ │ ├── DeployTreeTest.sol │ │ ├── DmcTransfer.sol │ │ ├── ECRecoverSMTest.sol │ │ ├── ECRecoverTest.sol │ │ ├── Economic.sol │ │ ├── EntryWrapper.sol │ │ ├── EventTest.sol │ │ ├── Evidence.sol │ │ ├── EvidenceOne.sol │ │ ├── EvidenceSignersData.sol │ │ ├── EvidenceVerify.sol │ │ ├── Incremental.sol │ │ ├── KVTableTest.sol │ │ ├── LibraryTest.sol │ │ ├── MainContract.sol │ │ ├── MapTest.sol │ │ ├── MultiMapTest.sol │ │ ├── MultiTableTest.sol │ │ ├── Ok.sol │ │ ├── OkD.sol │ │ ├── ParallelContract.sol │ │ ├── ParallelCpuHeavy.sol │ │ ├── ParallelOk.sol │ │ ├── ProxyTest.sol │ │ ├── RecursiveDelegateCallTest.sol │ │ ├── SM2EvidenceVerify.sol │ │ ├── SafeMath.sol │ │ ├── SimpleEvidence.sol │ │ ├── SimpleEvidenceFactory.sol │ │ ├── SmallBank.sol │ │ ├── StaticCall.sol │ │ ├── StorageSlot.sol │ │ ├── Table.sol │ │ ├── TablePrecompiledTest.sol │ │ ├── TableTest.sol │ │ ├── TableTestV320.sol │ │ ├── TableV320.sol │ │ ├── WeIdContract.sol │ │ ├── blobBaseFee.sol │ │ ├── mcopy.sol │ │ └── transientStorageContract.sol │ └── transactionv1 │ │ ├── Incremental.java │ │ └── SmallBank.java │ ├── contractTest │ └── EconomicTest.java │ ├── eventsub │ └── EventSub.java │ ├── perf │ ├── Collector.java │ ├── DMCTransferDag.java │ ├── DMCTransferMyself.java │ ├── DMCTransferRing.java │ ├── DMCTransferStar.java │ ├── ParallelLiquidPerf.java │ ├── ParallelOkPerf.java │ ├── PerformanceAuthContractTest.java │ ├── PerformanceAuthTransferTest.java │ ├── PerformanceBFS.java │ ├── PerformanceBalance.java │ ├── PerformanceCRUDTable.java │ ├── PerformanceCpuHeavy.java │ ├── PerformanceDMC.java │ ├── PerformanceDelegateCall.java │ ├── PerformanceDeployTest.java │ ├── PerformanceEvidence.java │ ├── PerformanceEvidenceOne.java │ ├── PerformanceEvidenceVerify.java │ ├── PerformanceKVTable.java │ ├── PerformanceMultiContracts.java │ ├── PerformanceOk.java │ ├── PerformanceOkD.java │ ├── PerformancePaillierPrecompiled.java │ ├── PerformancePrecompiledCpuHeavy.java │ ├── PerformancePrecompiledSmallBank.java │ ├── PerformanceRPC.java │ ├── PerformanceSM2EvidenceVerify.java │ ├── PerformanceShardingCpuHeavy.java │ ├── PerformanceSimpleEvidence.java │ ├── PerformanceSmallBank.java │ ├── PerformanceTable.java │ ├── PerformanceTableLiquid.java │ ├── PerformanceTableV320.java │ ├── PerformanceTiger.java │ ├── PerformanceTransferDMC.java │ ├── PerformanceVRFVerify.java │ ├── PerformanceWeID.java │ ├── ShardingOkPerf.java │ ├── TarsParallelOkPerf.java │ ├── callback │ │ ├── ParallelOkCallback.java │ │ └── PerformanceCallback.java │ ├── collector │ │ └── PerformanceCollector.java │ ├── dgms │ │ ├── PerformanceDGMS.java │ │ └── User.java │ ├── model │ │ ├── DagTransferUser.java │ │ └── DagUserInfo.java │ ├── paillier │ │ ├── CommonUtils.java │ │ ├── PaillierCipher.java │ │ └── PaillierKeyPair.java │ ├── parallel │ │ ├── DagPrecompiledDemo.java │ │ ├── ParallelLiquidDemo.java │ │ └── ParallelOkDemo.java │ ├── tiger │ │ └── User.java │ └── transactionv1 │ │ ├── NonceCheckTest.java │ │ ├── PerformanceSmallBank.java │ │ └── TransactionManagerTest.java │ └── transaction │ ├── AssembleTransactionDemo.java │ ├── BasicAbiTransaction.java │ ├── BcosClientWrapper.java │ ├── HelloWorldLiquidDemo.java │ ├── ISignTransaction.java │ ├── ISignedTransactionCallback.java │ ├── KeyToolSignTransaction.java │ ├── LegoTransaction.java │ └── LegoTransactionDemo.java └── test └── resources ├── amop ├── config-full.toml ├── config-publisher-for-test.toml ├── config-subscriber-for-test.toml ├── consumer_private_key.p12 └── consumer_public_key_1.pem ├── clog.ini ├── config-example.toml └── log4j2.xml /.ci/ci_check.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | LOG_INFO() { 5 | local content=${1} 6 | echo -e "\033[32m ${content}\033[0m" 7 | } 8 | check_basic() 9 | { 10 | # check code format 11 | # bash gradlew verifyGoogleJavaFormat 12 | # build 13 | bash gradlew build --info 14 | } 15 | check_basic 16 | -------------------------------------------------------------------------------- /.ci/ci_check_commit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | scan_code_script="cobra/cobra.py -f json -o /tmp/report.json -t " 6 | ignore_files=(sh crt key json toml SignatureTest.java Ok.java bin abi ChannelTest.java ParallelOkDemo.java PerformanceAmop.java DagPrecompiledDemo.java KeyToolTest.java CryptoSuite.java AmopMsgHandlerTest.java TopicManager.java PrivateTopicVerifyTest.java AmopMsgBuilder.java TopicManagerTest.java AmopSubscribe.java AmopPublisher.java AmopPublisherPrivate.java AmopSubscribePrivate.java AmopPublisherFile.java AmopPublisherPrivateFile.java DemoAmopCallback.java FileToByteArrayHelper.java OkD.java TableTest.java PerformanceTable.java HelloWorld.java PerformanceRPC.java CodecTest.java ResponseTest.java ConfigTest.java) 7 | commit_limit=6 8 | 9 | LOG_ERROR() { 10 | content=${1} 11 | echo -e "\033[31m${content}\033[0m" 12 | } 13 | 14 | LOG_INFO() { 15 | content=${1} 16 | echo -e "\033[32m${content}\033[0m" 17 | } 18 | 19 | should_ignore() { 20 | local file=${1} 21 | for ignore in ${ignore_files[*]}; do 22 | if echo "${file}" | grep "${ignore}" &>/dev/null; then 23 | echo "ignore ${file} ${ignore}" 24 | return 0 25 | fi 26 | done 27 | return 1 28 | } 29 | 30 | scan_code() { 31 | # Redirect output to stderr. 32 | exec 1>&2 33 | for file in $(git diff-index --name-status HEAD^ | awk '{print $2}'); do 34 | if should_ignore "${file}"; then continue; fi 35 | if [ ! -f "${file}" ]; then continue; fi 36 | LOG_INFO "check file ${file}" 37 | python ${scan_code_script} "$file" 38 | trigger_rules=$(jq -r '.' /tmp/report.json | grep 'trigger_rules' | awk '{print $2}' | sed 's/,//g') 39 | echo "trigger_rules is ${trigger_rules}" 40 | rm /tmp/report.json 41 | if [ ${trigger_rules} -ne 0 ]; then 42 | echo "######### ERROR: Scan code failed, please adjust them before commit" 43 | exit 1 44 | fi 45 | done 46 | } 47 | 48 | install_cobra() { 49 | git clone https://github.com/WhaleShark-Team/cobra.git 50 | pip install -r cobra/requirements.txt 51 | cp cobra/config.template cobra/config 52 | } 53 | 54 | check_commit_message() 55 | { 56 | local commits=$(git rev-list --count HEAD^..HEAD) 57 | if [ ${commit_limit} -lt ${commits} ]; then 58 | LOG_ERROR "${commits} commits, limit is ${commit_limit}" 59 | exit 1 60 | fi 61 | local unique_commit=$(git log --format=%s HEAD^..HEAD | sort -u | wc -l) 62 | if [ ${unique_commit} -ne ${commits} ]; then 63 | LOG_ERROR "${commits} != ${unique_commit}, please make commit message unique!" 64 | exit 1 65 | fi 66 | local merges=$(git log --format=%s HEAD^..HEAD | grep -i merge | wc -l) 67 | if [ ${merges} -gt 2 ]; then 68 | LOG_ERROR "PR contain merge : ${merges}, Please rebase!" 69 | exit 1 70 | fi 71 | } 72 | 73 | check_commit_message 74 | install_cobra 75 | scan_code 76 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | jobs: 3 | build: 4 | working_directory: /java-sdk-demo 5 | docker: 6 | - image: centos:7 7 | environment: 8 | PATH=$PATH:/usr/bin 9 | steps: 10 | - run: 11 | name: Setup dependencies 12 | command: | 13 | yum install -y epel-release centos-release-scl which python python-devel 14 | yum install -y git openssl-devel openssl java java-devel 15 | - checkout 16 | - run: 17 | name: Compile 18 | command: | 19 | bash gradlew build 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## workspace folders. 2 | .gradle 3 | build 4 | dist 5 | .idea 6 | conf 7 | build_chain.sh 8 | nodes 9 | initEnv.sh 10 | tassl 11 | # macOS 12 | .DS_Store 13 | bin/ 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # safe list 2 | branches: 3 | only: 4 | - /.*/ 5 | - 6 | jobs: 7 | fast_finish: true 8 | include: 9 | - language: python 10 | python: 3.6 11 | dist: bionic 12 | before_cache: 13 | cache: 14 | before_install: 15 | script: | 16 | # bash .ci/ci_check_commit.sh 17 | 18 | # ubuntu 16, openjdk 8 19 | - language: java 20 | jdk: openjdk8 21 | os: linux 22 | dist: xenial 23 | sudo: required 24 | env: 25 | - CACHE_NAME=ubuntu16_openjdk8 26 | 27 | # ubuntu 16, openjdk 11 28 | - language: java 29 | jdk: openjdk11 30 | os: linux 31 | dist: xenial 32 | sudo: required 33 | env: 34 | - CACHE_NAME=ubuntu16_openjdk11 35 | 36 | # ubuntu 18, openjdk 8 37 | - language: java 38 | jdk: openjdk8 39 | os: linux 40 | dist: bionic 41 | sudo: required 42 | env: 43 | - CACHE_NAME=ubuntu18_openjdk8 44 | 45 | # ubuntu 18, openjdk 11 46 | - language: java 47 | jdk: openjdk11 48 | os: linux 49 | dist: bionic 50 | sudo: required 51 | env: 52 | - CACHE_NAME=ubuntu18_openjdk11 53 | 54 | # ubuntu 16, openjdk 14 55 | - language: java 56 | jdk: openjdk14 57 | os: linux 58 | dist: xenial 59 | sudo: required 60 | env: 61 | - CACHE_NAME=ubuntu16_openjdk14 62 | 63 | # ubuntu 18, openjdk 14 64 | - language: java 65 | jdk: openjdk14 66 | os: linux 67 | dist: bionic 68 | sudo: required 69 | env: 70 | - CACHE_NAME=ubuntu18_openjdk14 71 | 72 | # ubuntu 18, oraclejdk 14 73 | - language: java 74 | jdk: oraclejdk14 75 | os: linux 76 | dist: bionic 77 | sudo: required 78 | env: 79 | - CACHE_NAME=ubuntu18_oraclejdk14 80 | 81 | # ubuntu 18, oraclejdk 11 82 | - language: java 83 | jdk: oraclejdk11 84 | os: linux 85 | dist: bionic 86 | sudo: required 87 | env: 88 | - CACHE_NAME=ubuntu18_oraclejdk11 89 | 90 | # ubuntu 16, oraclejdk 11 91 | - language: java 92 | jdk: oraclejdk11 93 | os: linux 94 | dist: xenial 95 | sudo: required 96 | env: 97 | - CACHE_NAME=ubuntu16_oraclejdk11 98 | 99 | # ubuntu 16, oraclejdk 14 100 | - language: java 101 | jdk: oraclejdk14 102 | os: linux 103 | dist: xenial 104 | sudo: required 105 | env: 106 | - CACHE_NAME=ubuntu16_oraclejdk14 107 | addons: 108 | apt: 109 | packages: 110 | - openssl 111 | - libssl-dev 112 | before_cache: 113 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 114 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 115 | cache: 116 | directories: 117 | - $HOME/.gradle/caches/ 118 | - $HOME/.gradle/wrapper/ 119 | script: | 120 | bash .ci/ci_check.sh 121 | after_success: 122 | - ./gradlew jacocoTestReport 123 | - bash <(curl -s https://codecov.io/bash) 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](./docs/images/FISCO_BCOS_Logo.svg) 2 | 3 | [English](./docs/README_EN.md) / 中文 4 | 5 | # Java SDK Demo 6 | 7 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) 8 | [![Build Status](https://travis-ci.org/FISCO-BCOS/java-sdk-demo.svg?branch=master)](https://travis-ci.org/FISCO-BCOS/java-sdk-demo) 9 | [![CodeFactor](https://www.codefactor.io/repository/github/fisco-bcos/java-sdk/badge)](https://www.codefactor.io/repository/github/fisco-bcos/java-sdk-demo) 10 | [![GitHub All Releases](https://img.shields.io/github/downloads/FISCO-BCOS/java-sdk-demo/total.svg)](https://github.com/FISCO-BCOS/java-sdk-demo) 11 | 12 | 13 | Java SDK的基准测试集合,基于[Java SDK](https://github.com/FISCO-BCOS/java-sdk)提供了对FISCO BCOS节点的压测程序。 14 | 15 | 16 | ## 功能 17 | 18 | * 提供多合约并行转账压测Demo 19 | * 提供转账压测Demo 20 | * 提供AMOP测试Demo 21 | * 提供KV合约压测Demo 22 | * 提供合约编译功能,将Solidity合约文件转换成Java合约文件 23 | * 提供合约编译功能,将Liquid合约文件编译后的WASM和ABI文件转换成Java合约文件 24 | 25 | ## 使用手册 26 | 27 | **编译源码** 28 | 29 | ```bash 30 | # 下载源码 31 | $ git clone https://github.com/FISCO-BCOS/java-sdk-demo 32 | $ cd java-sdk-demo 33 | 34 | # 编译源码 35 | $ bash gradlew build 36 | ``` 37 | 38 | **配置Demo** 39 | 40 | 使用Java SDK Demo之前,首先要配置Java SDK,包括证书拷贝以及端口配置,详细请参考[这里](https://fisco-bcos-doc.readthedocs.io/zh_CN/latest/docs/develop/sdk/java_sdk/quick_start.html#sdk). 41 | 42 | ```bash 43 | # 拷贝证书(设SDK证书位于~/fisco/nodes/127.0.0.1/sdk目录) 44 | $ cp -r ~/fisco/nodes/127.0.0.1/sdk/* conf 45 | 46 | # 拷贝配置文件 47 | # 注: 48 | # 默认搭建的FISCO BCOS区块链系统RPC端口是20200,若修改了该端口,请同步修改config.toml中的[network.peers]配置选项 49 | $ cp conf/config-example.toml conf/config.toml 50 | ``` 51 | 52 | **执行压测Demo** 53 | 54 | Java SDK Demo提供了一系列压测程序,包括串行转账合约压测、并行转账合约压测、AMOP压测等,具体使用示例如下: 55 | 注意:下面的压力测试程序均为EVM的节点执行环境,节点配置详情请参考:[节点配置](https://fisco-bcos-doc.readthedocs.io/zh_CN/latest/docs/tutorial/air/config.html) 56 | 57 | ```shell 58 | # 进入dist目录 59 | $ cd dist 60 | 61 | # 多合约-合约内并行转账合约: 62 | # groupId: 压测的群组ID 63 | # userCount: 创建账户的个数,建议(4~32个) 64 | # count: 压测的交易总量 65 | # qps: 压测QPS 66 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceDMC [groupId] [userCount] [count] [qps] 67 | 68 | # 多合约-跨合约并行转账 69 | # groupId: 压测的群组ID 70 | # userCount: 创建账户的个数,建议(4~32个) 71 | # count: 压测的交易总量 72 | # qps: 压测QPS 73 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceTransferDMC [groupId] [userCount] [count] [qps] 74 | 75 | # 压测串行转账合约: 76 | # count: 压测的交易总量 77 | # tps: 压测QPS 78 | # groupId: 压测的群组ID 79 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceOk [count] [tps] [groupId] 80 | 81 | # 压测并行转账合约 82 | # -------------------------- 83 | # 基于Solidity并行合约parallelok添加账户: 84 | # groupID: 压测的群组ID 85 | # count: 压测的交易总量 86 | # tps: 压测QPS 87 | # file: 保存生成账户的文件名 88 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [parallelok] [groupID] [add] [count] [tps] [file] 89 | # 基于Precompiled并行合约precompiled添加账户 90 | # (参数含义同上) 91 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [precompiled] [groupID] [add] [count] [tps] [file] 92 | # -------------------------- 93 | # 基于Solidity并行合约parallelok发起转账交易压测 94 | # groupID: 压测的群组ID 95 | # count: 压测的交易总量 96 | # tps: 压测的QPS 97 | # file: 转账用户文件 98 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [parallelok] [groupID] [transfer] [count] [tps] [file] 99 | # 基于Precompiled并行合约Precompiled发起转账压测 100 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [precompiled] [groupID] [transfer] [count] [tps] [file] 101 | 102 | 103 | # KVTable合约压测 104 | # 压测KV 105 | # count: 压测的交易总量 106 | # tps: 压测QPS 107 | # groupId: 压测群组 108 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceKVTable [count] [tps] [groupId] [useKVTable] [valueLength] 109 | ``` 110 | 111 | **以下是WASM环境的压力测试** 112 | 113 | ```shell 114 | # 压测并行转账合约 115 | # -------------------------- 116 | # 基于Liquid并行合约parallelok添加账户: 117 | # groupID: 压测的群组ID 118 | # count: 压测的交易总量 119 | # tps: 压测QPS 120 | # file: 保存生成账户的文件名 121 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelLiquidPerf [groupId] [add] [count] [tps] [file] 122 | 123 | # 基于Liquid并行合约parallelok发起转账交易压测 124 | # groupID: 压测的群组ID 125 | # count: 压测的交易总量 126 | # tps: 压测的QPS 127 | # file: 转账用户文件 128 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelLiquidPerf [groupId] [transfer] [count] [tps] [file] 129 | ``` 130 | 131 | ## 贡献代码 132 | 欢迎参与FISCO BCOS的社区建设: 133 | - 点亮我们的小星星(点击项目左上方Star按钮)。 134 | - 提交代码(Pull requests),参考我们的[代码贡献流程](CONTRIBUTING_CN.md)。 135 | - [提问和提交BUG](https://github.com/FISCO-BCOS/java-sdk-demo/issues)。 136 | 137 | ## 加入我们的社区 138 | 139 | FISCO BCOS开源社区是国内活跃的开源社区,社区长期为机构和个人开发者提供各类支持与帮助。已有来自各行业的数千名技术爱好者在研究和使用FISCO BCOS。如您对FISCO BCOS开源技术及应用感兴趣,欢迎加入社区获得更多支持与帮助。 140 | 141 | ## License 142 | 143 | ![license](https://img.shields.io/badge/license-Apache%20v2-blue.svg) 144 | 145 | Web3SDK的开源协议为[Apache License 2.0](http://www.apache.org/licenses/). 详情参考[LICENSE](../LICENSE)。 146 | -------------------------------------------------------------------------------- /build-hsm.gradle: -------------------------------------------------------------------------------- 1 | // Apply the java-library plugin to add support for Java Library 2 | plugins { 3 | id 'java' 4 | id 'idea' 5 | id 'java-library' 6 | id 'jacoco' 7 | id 'maven-publish' 8 | id 'org.ajoberstar.grgit' version '4.1.0' 9 | } 10 | println("Notice: current gradle version is " + gradle.gradleVersion) 11 | // Additional attribute definition 12 | ext { 13 | // jackson version 14 | javaSDKVersion="2.8.0-hsm-SNAPSHOT" 15 | solcJVersion = "0.4.25.1" 16 | //solcJVersion = "0.5.2.0" 17 | //solcJVersion = "0.6.10.0" 18 | guavaVersion = "29.0-jre" 19 | commonsCollections4Version = "4.4" 20 | springVersion = "4.3.27.RELEASE" 21 | } 22 | 23 | archivesBaseName = 'java-sdk-demo' 24 | version = '1.0.0' 25 | 26 | sourceCompatibility = 1.8 27 | targetCompatibility = 1.8 28 | 29 | // In this section you declare where to find the dependencies of your project 30 | repositories { 31 | mavenCentral() 32 | maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } 33 | maven { url "https://oss.sonatype.org/service/local/staging/deploy/maven2"} 34 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 35 | } 36 | 37 | sourceSets { 38 | main { 39 | java { 40 | srcDir 'src/main/java' 41 | } 42 | 43 | resources { 44 | srcDir 'src/main/resources' 45 | } 46 | } 47 | integrationTest { 48 | copy { 49 | from file('src/test/resources/amop/') 50 | into 'conf/amop' 51 | } 52 | java { 53 | compileClasspath += main.output + test.output 54 | runtimeClasspath += main.output + test.output 55 | srcDir file('src/integration-test/java') 56 | } 57 | resources.srcDir file('src/integration-test/resources') 58 | } 59 | } 60 | 61 | configurations { 62 | integrationTestCompile.extendsFrom testCompile 63 | integrationTestRuntime.extendsFrom testRuntime 64 | } 65 | 66 | configurations.all { 67 | resolutionStrategy.cacheChangingModulesFor 30, 'seconds' 68 | } 69 | 70 | task integrationTest(type: Test) { 71 | testClassesDirs = sourceSets.integrationTest.output.classesDirs 72 | classpath = sourceSets.integrationTest.runtimeClasspath 73 | } 74 | 75 | List spring = [ 76 | "org.springframework:spring-core:$springVersion", 77 | "org.springframework:spring-beans:$springVersion", 78 | "org.springframework:spring-context:$springVersion", 79 | "org.springframework:spring-tx:$springVersion", 80 | ] 81 | dependencies { 82 | compile ("org.fisco-bcos.java-sdk:fisco-bcos-java-sdk:${javaSDKVersion}") 83 | compile ("org.fisco-bcos:solcJ:${solcJVersion}") 84 | compile ("com.google.guava:guava:${guavaVersion}") 85 | compile ("org.apache.commons:commons-collections4:${commonsCollections4Version}") 86 | compile spring 87 | } 88 | 89 | configurations.all { 90 | resolutionStrategy.cacheChangingModulesFor 30, 'seconds' 91 | } 92 | 93 | javadoc { 94 | options.addStringOption('Xdoclint:none', '-quiet') 95 | options.addStringOption('encoding', 'UTF-8') 96 | options.addStringOption('charSet', 'UTF-8') 97 | } 98 | 99 | task sourcesJar(type: Jar) { 100 | from sourceSets.main.allJava 101 | archiveClassifier = 'sources' 102 | } 103 | 104 | task javadocJar(type: Jar) { 105 | from javadoc 106 | archiveClassifier = 'javadoc' 107 | } 108 | 109 | jar { 110 | // destinationDir file('dist/apps') 111 | // archiveName project.name + '-' + project.version + '.jar' 112 | exclude '**/*.xml' 113 | exclude '**/*.properties' 114 | doLast { 115 | copy { 116 | from destinationDir 117 | into 'dist/apps' 118 | } 119 | copy { 120 | from configurations.runtimeClasspath 121 | into 'dist/lib' 122 | } 123 | copy { 124 | from file('src/test/resources/') 125 | into 'dist/conf' 126 | } 127 | } 128 | } 129 | jacocoTestReport { 130 | reports { 131 | xml.enabled true 132 | html.enabled false 133 | } 134 | } 135 | check.dependsOn jacocoTestReport 136 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'idea' 4 | id 'java-library' 5 | id 'jacoco' 6 | id 'maven-publish' 7 | id 'com.github.sherter.google-java-format' version '0.9' 8 | } 9 | 10 | println("Notice: current gradle version is " + gradle.gradleVersion) 11 | // Additional attribute definition 12 | ext { 13 | // jackson version 14 | javaSDKVersion="3.7.0" 15 | //solcJVersion = "0.4.25.1" 16 | //solcJVersion = "0.5.2.1" 17 | //solcJVersion = "0.6.10.1" 18 | solcJVersion = "0.8.11.1" 19 | guavaVersion = "32.0.1-jre" 20 | commonsCollections4Version = "4.4" 21 | springVersion = '5.3.32' 22 | } 23 | 24 | tasks.withType(JavaCompile) { 25 | options.encoding = "UTF-8" 26 | } 27 | 28 | archivesBaseName = 'java-sdk-demo' 29 | version = '3.6.0' 30 | 31 | sourceCompatibility = 1.8 32 | targetCompatibility = 1.8 33 | 34 | // In this section you declare where to find the dependencies of your project 35 | repositories { 36 | mavenCentral() 37 | maven { url "https://maven.aliyun.com/nexus/content/groups/public/" } 38 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 39 | maven { url "https://oss.sonatype.org/service/local/staging/deploy/maven2"} 40 | 41 | } 42 | 43 | sourceSets { 44 | main { 45 | java { 46 | srcDir 'src/main/java' 47 | } 48 | } 49 | integrationTest { 50 | copy { 51 | from file('src/test/resources/amop/') 52 | into 'conf/amop' 53 | } 54 | java { 55 | compileClasspath += main.output + test.output 56 | runtimeClasspath += main.output + test.output 57 | srcDir file('src/integration-test/java') 58 | } 59 | resources.srcDir file('src/integration-test/resources') 60 | } 61 | } 62 | 63 | configurations { 64 | integrationTestCompile.extendsFrom testCompile 65 | integrationTestRuntime.extendsFrom testRuntime 66 | } 67 | 68 | configurations.all { 69 | resolutionStrategy.cacheChangingModulesFor 0, 'seconds' 70 | } 71 | 72 | task integrationTest(type: Test) { 73 | testClassesDirs = sourceSets.integrationTest.output.classesDirs 74 | classpath = sourceSets.integrationTest.runtimeClasspath 75 | } 76 | 77 | List spring = [ 78 | "org.springframework:spring-core:$springVersion", 79 | "org.springframework:spring-beans:$springVersion", 80 | "org.springframework:spring-context:$springVersion", 81 | "org.springframework:spring-tx:$springVersion", 82 | ] 83 | 84 | def log4j_version= '2.22.1' 85 | List logger = [ 86 | "org.apache.logging.log4j:log4j-api:$log4j_version", 87 | "org.apache.logging.log4j:log4j-core:$log4j_version", 88 | "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version", 89 | "org.apache.logging.log4j:log4j-web:$log4j_version" 90 | ] 91 | 92 | googleJavaFormat { 93 | toolVersion = '1.7' 94 | options style: 'AOSP' 95 | source = sourceSets*.allJava 96 | include '**/*.java' 97 | exclude '**/*Test.java' 98 | exclude '**/Test*.java' 99 | exclude '**/Mock*.java' 100 | } 101 | 102 | dependencies { 103 | implementation ('com.fasterxml.jackson.core:jackson-databind:2.14.3'){ 104 | force true 105 | } 106 | api ("org.fisco-bcos.java-sdk:fisco-bcos-java-sdk:${javaSDKVersion}") 107 | api('org.fisco-bcos.code-generator:bcos-code-generator:1.4.0') { 108 | exclude group : "org.fisco-bcos.java-sdk" 109 | exclude group : "org.slf4j" 110 | exclude group : " com.fasterxml.jackson.core" 111 | } 112 | api ("org.fisco-bcos:solcJ:${solcJVersion}"){ 113 | exclude group : " com.fasterxml.jackson.core" 114 | } 115 | api ("com.google.guava:guava:${guavaVersion}") 116 | api ("org.apache.commons:commons-collections4:${commonsCollections4Version}") 117 | api ("me.tongfei:progressbar:0.9.2") 118 | api spring 119 | api logger 120 | } 121 | 122 | configurations.all { 123 | resolutionStrategy.cacheChangingModulesFor 0, 'seconds' 124 | } 125 | 126 | javadoc { 127 | options.addStringOption('Xdoclint:none', '-quiet') 128 | options.addStringOption('encoding', 'UTF-8') 129 | options.addStringOption('charSet', 'UTF-8') 130 | } 131 | 132 | task sourcesJar(type: Jar) { 133 | from sourceSets.main.allJava 134 | archiveClassifier = 'sources' 135 | } 136 | 137 | task javadocJar(type: Jar) { 138 | from javadoc 139 | archiveClassifier = 'javadoc' 140 | } 141 | 142 | jar { 143 | destinationDir file('dist/apps') 144 | archiveName project.name + '-' + project.version + '.jar' 145 | exclude '**/*.xml' 146 | exclude '**/*.properties' 147 | doLast { 148 | copy { 149 | from configurations.runtimeClasspath 150 | into 'dist/lib' 151 | } 152 | copy { 153 | from file('src/test/resources/') 154 | into 'dist/conf' 155 | } 156 | } 157 | } 158 | jacocoTestReport { 159 | reports { 160 | xml.enabled true 161 | html.enabled false 162 | } 163 | } 164 | check.dependsOn jacocoTestReport 165 | 166 | 167 | -------------------------------------------------------------------------------- /docs/CONTRIBUTING_CN.md: -------------------------------------------------------------------------------- 1 | # 贡献代码 2 | 3 | 非常感谢能有心为FISCO-BCOS社区贡献代码! 4 | 5 | ## 分支策略 6 | 7 | 项目采用[git-flow](https://jeffkreeftmeijer.com/git-flow/)的分支策略。 8 | 9 | * master:最新的稳定分支 10 | * dev:待发布的稳定分支 11 | * feature-xxxx:一个正在开发xxxx特性分支 12 | * bugfix-xxxx:一个正在修bug xxxx的分支 13 | 14 | ## 贡献方法 15 | 16 | ### Issue 17 | 18 | 可直接去[issues page](https://github.com/FISCO-BCOS/java-sdk/issues)提issue。 19 | 20 | ### 修复bug 21 | 22 | 1. Fork本仓库到个人仓库 23 | 2. 从个人仓库的master分支拉出一个bugfix-xxxx分支 24 | 3. 在bugfix-xxxx上修复bug 25 | 4. 测试修复的bug 26 | 5. PR(Pull Request)到本仓库的dev分支 27 | 6. 等待社区review这个PR 28 | 7. PR合入,bug修复完成! 29 | 30 | ### 开发新特性 31 | 32 | 1. Fork本仓库到个人仓库 33 | 2. 从个人仓库的dev分支拉出一个feature-xxxx分支 34 | 3. 在feature-xxxx上进行特性开发 35 | 4. 不定期的从本仓库的dev分支pull最新的改动到feature-xxxx分支 36 | 5. 测试新特性 37 | 6. PR(Pull Request)到本参考的dev分支 38 | 7. 等待社区review这个PR 39 | 8. PR合入,特性开发完成! 40 | 41 | ## 代码格式化 42 | 43 | 代码格式化gradle插件[google-java-format-gradle-plugin](https://github.com/sherter/google-java-format-gradle-plugin). 44 | 45 | 执行任务 `googleJavaFormat`格式化java文件。 46 | ``` 47 | ./gradlew goJF 48 | ``` 49 | 执行任务 `verifyGoogleJavaFormat`验证java文件是否格式化完成 50 | ``` 51 | ./gradlew verGJF 52 | ``` 53 | 54 | ## 持续集成(CI) 55 | 56 | 持续集成框架 57 | 58 | * travis-ci: [![Build Status](https://travis-ci.org/FISCO-BCOS/java-sdk.svg?branch=master)](https://travis-ci.org/FISCO-BCOS/java-sdk) 59 | 60 | 61 | 代码质量 62 | 63 | * Codacy: [![Codacy Badge](https://app.codacy.com/project/badge/Grade/d830a3be25c04b04b032870e4184482a)](https://www.codacy.com/gh/FISCO-BCOS/java-sdk/dashboard?utm_source=github.com&utm_medium=referral&utm_content=FISCO-BCOS/java-sdk&utm_campaign=Badge_Grade) 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/README_EN.md: -------------------------------------------------------------------------------- 1 | ![](./images/FISCO_BCOS_Logo.svg) 2 | 3 | English / [Chinese](../README.md) 4 | 5 | # Java SDK 6 | 7 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) 8 | [![Build Status](https://travis-ci.org/FISCO-BCOS/java-sdk-demo.svg?branch=master)](https://travis-ci.org/FISCO-BCOS/java-sdk-demo) 9 | [![CodeFactor](https://www.codefactor.io/repository/github/fisco-bcos/java-sdk/badge)](https://www.codefactor.io/repository/github/fisco-bcos/java-sdk-demo) 10 | [![GitHub All Releases](https://img.shields.io/github/downloads/FISCO-BCOS/java-sdk-demo/total.svg)](https://github.com/FISCO-BCOS/java-sdk-demo) 11 | 12 | The benchmark test collection of Java SDK, based on [Java SDK](https://github.com/FISCO-BCOS/java-sdk) provides a stress test program for FISCO BCOS nodes. 13 | 14 | 15 | ## Functions 16 | 17 | * Provide multi-contract transfer stress test demo. 18 | * Provide transfer stress test demo. 19 | * Provide AMOP test demo. 20 | * Provide KV contract stress test demo. 21 | * Provide contract compilation function, convert Solidity contract files into Java contract files. 22 | * Provide transfer compiled Liquid contracts, WASM bin and ABI, into Java contract files. 23 | 24 | ## manual 25 | 26 | **Compile source code** 27 | 28 | ```shell 29 | # clone the source code 30 | $ git clone https://github.com/FISCO-BCOS/java-sdk-demo 31 | $ cd java-sdk-demo 32 | 33 | # compile the source code 34 | $ bash gradlew build 35 | ``` 36 | 37 | **Configure Demo** 38 | 39 | Before using the Java SDK Demo, you must first configure the Java SDK, including certificate copy and port configuration. For details, please refer to [here](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/sdk/java_sdk/quick_start.html#sdk). 40 | 41 | ```bash 42 | # Copy the certificate (suppose the SDK certificate is located in ~/fisco/nodes/127.0.0.1/sdk directory) 43 | $ cp -r ~/fisco/nodes/127.0.0.1/sdk/* conf 44 | 45 | # Copy configuration file 46 | # Note: 47 | # The RPC port of the FISCO BCOS blockchain system built by default is 20200. 48 | # If you modify this port, please modify the [network.peers] configuration option in config.toml 49 | $ cp conf/config-example.toml conf/config.toml 50 | ``` 51 | 52 | **Execute stress test Demo** 53 | 54 | Java SDK Demo provides a series of stress testing programs, including serial transfer contract stress testing, parallel transfer contract stress testing, AMOP stress testing, etc. The specific usage examples are as follows: 55 | 56 | ```shell 57 | # Enter the dist directory 58 | $ cd dist 59 | 60 | # Multi-contract transfer: 61 | # groupId: the group name 62 | # userCount: count of user (recommend 4~32) 63 | # count: count of transactions 64 | # qps: qps 65 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceDMC [groupId] [userCount] [count] [qps] 66 | 67 | # Multi-contract cross contract transfer: 68 | # groupId: the group name 69 | # userCount: count of user (recommend 4~32) 70 | # count: count of transactions 71 | # qps: qps 72 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceTransferDMC [groupId] [userCount] [count] [qps] 73 | 74 | # Stress test PerformanceOk contract: 75 | # count: total transaction count 76 | # tps: qps 77 | # groupId: the group name 78 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceOk [count] [tps] [groupId] 79 | 80 | # Pressure test parallel transfer contract 81 | # -------------------------- 82 | # Add accounts based on the Solidity parallel contract parallel_ok: 83 | # groupID: the group name 84 | # count: total transaction count 85 | # tps: qps 86 | # file: the file of the generated account saved in 87 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [parallelok] [groupID] [add] [count] [tps] [file] 88 | # Add accounts based on Precompiled parallel contract precompiled 89 | # (Parameter meaning is the same as above) 90 | java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [precompiled] [groupID] [add] [count] [tps] [file] 91 | # -------------------------- 92 | # Based on the Solidity parallel contract parallelok to initiate a transfer transaction stress test 93 | # groupID: Group ID of pressure test 94 | # count: total amount of transactions 95 | # tps: qps 96 | # file: User file for transfer 97 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [parallelok] [groupID] [transfer] [count] [tps] [file] 98 | # Precompiled contract transfer 99 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [precompiled] [groupID] [transfer] [count] [tps] [file] 100 | 101 | 102 | # KVTable contract stress test: 103 | # KV set 104 | # count: total amount of transactions 105 | # tps: qps 106 | # groupId: the groupId 107 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceKVTable [set] [count] [tps] [groupId] 108 | # KV get 109 | # (Parameter explanation is the same as above) 110 | $ java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceKVTable [get] [count] [tps] [groupId] 111 | ``` 112 | 113 | ## Join Our Community 114 | 115 | The FISCO BCOS community is one of the most active open-source blockchain communities in China. It provides long-term technical support for both institutional and individual developers and users of FISCO BCOS. Thousands of technical enthusiasts from numerous industry sectors have joined this community, studying and using FISCO BCOS platform. If you are also interested, you are most welcome to join us for more support and fun. 116 | 117 | ## License 118 | ![license](http://img.shields.io/badge/license-Apache%20v2-blue.svg) 119 | 120 | All contributions are made under the [Apache License 2.0](http://www.apache.org/licenses/). See [LICENSE](LICENSE). -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/java-sdk-demo/aaad7a3d64fa7569a26ce5f78792e6344ce2ffaa/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | #distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-bin.zip 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/amop/Broadcast.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.amop; 2 | 3 | import java.net.URL; 4 | import org.fisco.bcos.sdk.demo.perf.ParallelOkPerf; 5 | import org.fisco.bcos.sdk.jni.common.JniException; 6 | import org.fisco.bcos.sdk.v3.amop.Amop; 7 | import org.fisco.bcos.sdk.v3.config.Config; 8 | import org.fisco.bcos.sdk.v3.config.ConfigOption; 9 | import org.fisco.bcos.sdk.v3.config.exceptions.ConfigException; 10 | import org.fisco.bcos.sdk.v3.model.ConstantConfig; 11 | 12 | public class Broadcast { 13 | public static void usage() { 14 | System.out.println("\tUsage: "); 15 | System.out.println( 16 | "\t\tjava -cp \"conf/:lib/*:apps/*\" org.fisco.bcos.sdk.demo.amop.Broadcast topic msg"); 17 | System.out.println("\tExample:"); 18 | System.out.println( 19 | "\t\tjava -cp \"conf/:lib/*:apps/*\" org.fisco.bcos.sdk.demo.amop.Broadcast topic HelloWorld"); 20 | System.exit(0); 21 | } 22 | 23 | public static void main(String[] args) 24 | throws InterruptedException, JniException, ConfigException { 25 | 26 | String configFileName = ConstantConfig.CONFIG_FILE_NAME; 27 | URL configUrl = ParallelOkPerf.class.getClassLoader().getResource(configFileName); 28 | if (configUrl == null) { 29 | System.out.println("The configFile " + configFileName + " doesn't exist!"); 30 | return; 31 | } 32 | 33 | if (args.length < 2) { 34 | usage(); 35 | } 36 | 37 | String topic = args[0]; 38 | String msg = args[1]; 39 | 40 | System.out.println(" ====== AMOP broadcast, topic: " + topic + " ,msg: " + msg); 41 | 42 | String configFile = configUrl.getPath(); 43 | ConfigOption configOption = Config.load(configFile); 44 | 45 | org.fisco.bcos.sdk.v3.amop.Amop amop = Amop.build(configOption); 46 | amop.start(); 47 | 48 | while (true) { 49 | System.out.println(" ==> try to broadcast message: " + msg); 50 | amop.broadcastAmopMsg(topic, msg.getBytes()); 51 | Thread.sleep(10000); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/amop/Publish.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.amop; 2 | 3 | import java.net.URL; 4 | import org.fisco.bcos.sdk.demo.perf.ParallelOkPerf; 5 | import org.fisco.bcos.sdk.jni.amop.AmopResponseCallback; 6 | import org.fisco.bcos.sdk.jni.common.JniException; 7 | import org.fisco.bcos.sdk.jni.common.Response; 8 | import org.fisco.bcos.sdk.v3.amop.Amop; 9 | import org.fisco.bcos.sdk.v3.config.Config; 10 | import org.fisco.bcos.sdk.v3.config.ConfigOption; 11 | import org.fisco.bcos.sdk.v3.config.exceptions.ConfigException; 12 | import org.fisco.bcos.sdk.v3.model.ConstantConfig; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | public class Publish { 17 | private static final Logger logger = LoggerFactory.getLogger(Publish.class); 18 | 19 | public static void usage() { 20 | System.out.println("\tUsage: "); 21 | System.out.println( 22 | "\t\tjava -cp \"conf/:lib/*:apps/*\" org.fisco.bcos.sdk.demo.amop.Publish topic msg"); 23 | System.out.println("\tExample:"); 24 | System.out.println( 25 | "\t\tjava -cp \"conf/:lib/*:apps/*\" org.fisco.bcos.sdk.demo.amop.Publish topic HelloWorld"); 26 | System.exit(0); 27 | } 28 | 29 | public static void main(String[] args) 30 | throws InterruptedException, JniException, ConfigException { 31 | 32 | String configFileName = ConstantConfig.CONFIG_FILE_NAME; 33 | URL configUrl = ParallelOkPerf.class.getClassLoader().getResource(configFileName); 34 | if (configUrl == null) { 35 | System.out.println("The configFile " + configFileName + " doesn't exist!"); 36 | return; 37 | } 38 | 39 | if (args.length < 2) { 40 | usage(); 41 | } 42 | 43 | String topic = args[0]; 44 | String msg = args[1]; 45 | 46 | System.out.println(" ====== AMOP publish, topic: " + topic + " ,msg: " + msg); 47 | 48 | String configFile = configUrl.getPath(); 49 | ConfigOption configOption = Config.load(configFile); 50 | 51 | org.fisco.bcos.sdk.v3.amop.Amop amop = Amop.build(configOption); 52 | amop.start(); 53 | 54 | while (true) { 55 | System.out.println(" ====== AMOP publish send message"); 56 | amop.sendAmopMsg( 57 | topic, 58 | msg.getBytes(), 59 | 0, 60 | new AmopResponseCallback() { 61 | @Override 62 | public void onResponse(Response response) { 63 | System.out.println(" ==> receive response message from server"); 64 | if (response.getErrorCode() == 0) { 65 | System.out.println( 66 | " \t responseData: " + new String(response.getData())); 67 | } else { 68 | System.out.println(" \t errorCode: " + response.getErrorCode()); 69 | System.out.println( 70 | " \t errorMessage: " + response.getErrorMessage()); 71 | } 72 | } 73 | }); 74 | 75 | Thread.sleep(5000); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/amop/Subscribe.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.amop; 2 | 3 | import java.net.URL; 4 | import org.fisco.bcos.sdk.demo.perf.ParallelOkPerf; 5 | import org.fisco.bcos.sdk.jni.common.JniException; 6 | import org.fisco.bcos.sdk.v3.amop.Amop; 7 | import org.fisco.bcos.sdk.v3.config.Config; 8 | import org.fisco.bcos.sdk.v3.config.ConfigOption; 9 | import org.fisco.bcos.sdk.v3.config.exceptions.ConfigException; 10 | import org.fisco.bcos.sdk.v3.model.ConstantConfig; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | public class Subscribe { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(Subscribe.class); 17 | 18 | public static void usage() { 19 | System.out.println("\tUsage: "); 20 | System.out.println( 21 | "\t\tjava -cp \"conf/:lib/*:apps/*\" org.fisco.bcos.sdk.demo.amop.Subscribe topic"); 22 | System.out.println("\tExample:"); 23 | System.out.println( 24 | "\t\tjava -cp \"conf/:lib/*:apps/*\" org.fisco.bcos.sdk.demo.amop.Subscribe topic"); 25 | System.exit(0); 26 | } 27 | 28 | public static void main(String[] args) 29 | throws InterruptedException, JniException, ConfigException { 30 | 31 | String configFileName = ConstantConfig.CONFIG_FILE_NAME; 32 | URL configUrl = ParallelOkPerf.class.getClassLoader().getResource(configFileName); 33 | if (configUrl == null) { 34 | System.out.println("The configFile " + configFileName + " doesn't exist!"); 35 | return; 36 | } 37 | 38 | if (args.length < 1) { 39 | usage(); 40 | } 41 | 42 | String topic = args[0]; 43 | 44 | System.out.println(" ====== AMOP subscribe, topic: " + topic); 45 | 46 | String configFile = configUrl.getPath(); 47 | ConfigOption configOption = Config.load(configFile); 48 | 49 | Amop amop = Amop.build(configOption); 50 | amop.start(); 51 | 52 | amop.subscribeTopic( 53 | topic, 54 | (endpoint, seq, data) -> { 55 | System.out.println(" ==> receive message from client"); 56 | System.out.println(" \t==> endpoint: " + endpoint); 57 | System.out.println(" \t==> seq: " + seq); 58 | System.out.println(" \t==> data: " + new String(data)); 59 | 60 | amop.sendResponse(endpoint, seq, data); 61 | }); 62 | 63 | while (true) { 64 | 65 | Thread.sleep(10000); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/codegen/CompileSolidityException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2020 [fisco-dev] 3 | * 4 | *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | *

http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | *

Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | * express or implied. See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | package org.fisco.bcos.sdk.demo.codegen; 15 | 16 | /** Exceptioned when calling hash. */ 17 | public class CompileSolidityException extends RuntimeException { 18 | public CompileSolidityException(String message) { 19 | super(message); 20 | } 21 | 22 | public CompileSolidityException(String message, Throwable cause) { 23 | super(message, cause); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/CpuHeavyContract.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.contract; 2 | 3 | import java.math.BigInteger; 4 | import org.fisco.bcos.sdk.v3.client.Client; 5 | import org.fisco.bcos.sdk.v3.contract.Contract; 6 | import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; 7 | import org.fisco.bcos.sdk.v3.model.callback.TransactionCallback; 8 | import org.fisco.bcos.sdk.v3.transaction.manager.TransactionProcessor; 9 | 10 | public abstract class CpuHeavyContract extends Contract { 11 | public CpuHeavyContract( 12 | String contractBinary, 13 | String contractAddress, 14 | Client client, 15 | CryptoKeyPair credential, 16 | TransactionProcessor transactionProcessor) { 17 | super(contractBinary, contractAddress, client, credential, transactionProcessor); 18 | } 19 | 20 | public CpuHeavyContract( 21 | String contractBinary, 22 | String contractAddress, 23 | Client client, 24 | CryptoKeyPair credential) { 25 | super(contractBinary, contractAddress, client, credential); 26 | } 27 | 28 | public abstract void sort(BigInteger size, BigInteger signature, TransactionCallback callback); 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/CpuHeavyPrecompiled.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.contract; 2 | 3 | import static java.lang.Integer.toHexString; 4 | 5 | import java.math.BigInteger; 6 | import java.util.Arrays; 7 | import java.util.Collections; 8 | import java.util.List; 9 | import org.fisco.bcos.sdk.v3.client.Client; 10 | import org.fisco.bcos.sdk.v3.codec.datatypes.Function; 11 | import org.fisco.bcos.sdk.v3.codec.datatypes.Type; 12 | import org.fisco.bcos.sdk.v3.codec.datatypes.TypeReference; 13 | import org.fisco.bcos.sdk.v3.codec.datatypes.generated.Uint256; 14 | import org.fisco.bcos.sdk.v3.codec.datatypes.generated.tuples.generated.Tuple2; 15 | import org.fisco.bcos.sdk.v3.crypto.CryptoSuite; 16 | import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; 17 | import org.fisco.bcos.sdk.v3.model.CryptoType; 18 | import org.fisco.bcos.sdk.v3.model.TransactionReceipt; 19 | import org.fisco.bcos.sdk.v3.model.callback.TransactionCallback; 20 | 21 | @SuppressWarnings("unchecked") 22 | public class CpuHeavyPrecompiled extends CpuHeavyContract { 23 | public static final String CONTRACT_ADDRESS_PREFIX = "0x000000000000000000000000000000000000"; 24 | public static final Integer ADDRESS_STARTER = Integer.valueOf("5200", 16); 25 | 26 | public static final String[] BINARY_ARRAY = {""}; 27 | 28 | public static final String BINARY = 29 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", BINARY_ARRAY); 30 | 31 | public static final String[] SM_BINARY_ARRAY = {""}; 32 | 33 | public static final String SM_BINARY = 34 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", SM_BINARY_ARRAY); 35 | 36 | public static final String[] ABI_ARRAY = { 37 | "[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"size\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"signature\",\"type\":\"uint256\"}],\"name\":\"sort\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" 38 | }; 39 | 40 | public static final String ABI = org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", ABI_ARRAY); 41 | 42 | public static final String FUNC_SORT = "sort"; 43 | 44 | protected CpuHeavyPrecompiled(String contractAddress, Client client, CryptoKeyPair credential) { 45 | super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); 46 | } 47 | 48 | public static String getBinary(CryptoSuite cryptoSuite) { 49 | return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); 50 | } 51 | 52 | public static String getABI() { 53 | return ABI; 54 | } 55 | 56 | public TransactionReceipt sort(BigInteger size, BigInteger signature) { 57 | final Function function = 58 | new Function( 59 | FUNC_SORT, 60 | Arrays.asList(new Uint256(size), new Uint256(signature)), 61 | Collections.>emptyList()); 62 | return executeTransaction(function); 63 | } 64 | 65 | @Override 66 | public void sort(BigInteger size, BigInteger signature, TransactionCallback callback) { 67 | final Function function = 68 | new Function( 69 | FUNC_SORT, 70 | Arrays.asList(new Uint256(size), new Uint256(signature)), 71 | Collections.>emptyList()); 72 | asyncExecuteTransaction(function, callback); 73 | } 74 | 75 | public String getSignedTransactionForSort(BigInteger size, BigInteger signature) { 76 | final Function function = 77 | new Function( 78 | FUNC_SORT, 79 | Arrays.asList(new Uint256(size), new Uint256(signature)), 80 | Collections.>emptyList()); 81 | return createSignedTransaction(function); 82 | } 83 | 84 | public Tuple2 getSortInput(TransactionReceipt transactionReceipt) { 85 | String data = transactionReceipt.getInput().substring(10); 86 | final Function function = 87 | new Function( 88 | FUNC_SORT, 89 | Arrays.asList(), 90 | Arrays.>asList( 91 | new TypeReference() {}, new TypeReference() {})); 92 | List results = 93 | this.functionReturnDecoder.decode(data, function.getOutputParameters()); 94 | return new Tuple2( 95 | (BigInteger) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); 96 | } 97 | 98 | public static String getAddress(int id) { 99 | return CONTRACT_ADDRESS_PREFIX + toHexString(ADDRESS_STARTER + id); 100 | }; 101 | 102 | public static CpuHeavyPrecompiled load(int id, Client client, CryptoKeyPair credential) { 103 | String address = getAddress(id); 104 | System.out.println("Load precompiled address: " + address); 105 | return new CpuHeavyPrecompiled(address, client, credential); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/dgms/Counters.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.contract.dgms; 2 | 3 | import org.fisco.bcos.sdk.v3.client.Client; 4 | import org.fisco.bcos.sdk.v3.contract.Contract; 5 | import org.fisco.bcos.sdk.v3.crypto.CryptoSuite; 6 | import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; 7 | import org.fisco.bcos.sdk.v3.model.CryptoType; 8 | import org.fisco.bcos.sdk.v3.transaction.model.exception.ContractException; 9 | 10 | @SuppressWarnings("unchecked") 11 | public class Counters extends Contract { 12 | public static final String[] BINARY_ARRAY = { 13 | "604c602c600b82828239805160001a60731460008114601c57601e565bfe5b5030600052607381538281f30073000000000000000000000000000000000000000030146080604052600080fd00a165627a7a723058208b8b00d18656131bcb7ffb26364c7cb287712e64351b80e2983ea3fff4881fd20029" 14 | }; 15 | 16 | public static final String BINARY = 17 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", BINARY_ARRAY); 18 | 19 | public static final String[] SM_BINARY_ARRAY = { 20 | "604c602c600b82828239805160001a60731460008114601c57601e565bfe5b5030600052607381538281f30073000000000000000000000000000000000000000030146080604052600080fd00a165627a7a723058202ecf0f2f49959d2172ab2f7ecb18b23412d20a03d8b9980b83bbb89754f64a6c0029" 21 | }; 22 | 23 | public static final String SM_BINARY = 24 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", SM_BINARY_ARRAY); 25 | 26 | public static final String[] ABI_ARRAY = {"[]"}; 27 | 28 | public static final String ABI = org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", ABI_ARRAY); 29 | 30 | protected Counters(String contractAddress, Client client, CryptoKeyPair credential) { 31 | super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); 32 | } 33 | 34 | public static String getBinary(CryptoSuite cryptoSuite) { 35 | return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); 36 | } 37 | 38 | public static String getABI() { 39 | return ABI; 40 | } 41 | 42 | public static Counters load(String contractAddress, Client client, CryptoKeyPair credential) { 43 | return new Counters(contractAddress, client, credential); 44 | } 45 | 46 | public static Counters deploy(Client client, CryptoKeyPair credential) 47 | throws ContractException { 48 | return deploy( 49 | Counters.class, 50 | client, 51 | credential, 52 | getBinary(client.getCryptoSuite()), 53 | getABI(), 54 | null, 55 | null); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/dgms/Roles.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.contract.dgms; 2 | 3 | import org.fisco.bcos.sdk.v3.client.Client; 4 | import org.fisco.bcos.sdk.v3.contract.Contract; 5 | import org.fisco.bcos.sdk.v3.crypto.CryptoSuite; 6 | import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; 7 | import org.fisco.bcos.sdk.v3.model.CryptoType; 8 | import org.fisco.bcos.sdk.v3.transaction.model.exception.ContractException; 9 | 10 | @SuppressWarnings("unchecked") 11 | public class Roles extends Contract { 12 | public static final String[] BINARY_ARRAY = { 13 | "604c602c600b82828239805160001a60731460008114601c57601e565bfe5b5030600052607381538281f30073000000000000000000000000000000000000000030146080604052600080fd00a165627a7a723058208072f60fdcb394d8820bf27edca64fc23db1cb301ff7dab2bf9ce314d27b43330029" 14 | }; 15 | 16 | public static final String BINARY = 17 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", BINARY_ARRAY); 18 | 19 | public static final String[] SM_BINARY_ARRAY = { 20 | "604c602c600b82828239805160001a60731460008114601c57601e565bfe5b5030600052607381538281f30073000000000000000000000000000000000000000030146080604052600080fd00a165627a7a72305820d5733fdbb5a9398a088bc1e011e5d2db921197bb7455032374667c1d898c10820029" 21 | }; 22 | 23 | public static final String SM_BINARY = 24 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", SM_BINARY_ARRAY); 25 | 26 | public static final String[] ABI_ARRAY = {"[]"}; 27 | 28 | public static final String ABI = org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", ABI_ARRAY); 29 | 30 | protected Roles(String contractAddress, Client client, CryptoKeyPair credential) { 31 | super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); 32 | } 33 | 34 | public static String getBinary(CryptoSuite cryptoSuite) { 35 | return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); 36 | } 37 | 38 | public static String getABI() { 39 | return ABI; 40 | } 41 | 42 | public static Roles load(String contractAddress, Client client, CryptoKeyPair credential) { 43 | return new Roles(contractAddress, client, credential); 44 | } 45 | 46 | public static Roles deploy(Client client, CryptoKeyPair credential) throws ContractException { 47 | return deploy( 48 | Roles.class, 49 | client, 50 | credential, 51 | getBinary(client.getCryptoSuite()), 52 | getABI(), 53 | null, 54 | null); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/dgms/SafeMath.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.contract.dgms; 2 | 3 | import org.fisco.bcos.sdk.v3.client.Client; 4 | import org.fisco.bcos.sdk.v3.contract.Contract; 5 | import org.fisco.bcos.sdk.v3.crypto.CryptoSuite; 6 | import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; 7 | import org.fisco.bcos.sdk.v3.model.CryptoType; 8 | import org.fisco.bcos.sdk.v3.transaction.model.exception.ContractException; 9 | 10 | @SuppressWarnings("unchecked") 11 | public class SafeMath extends Contract { 12 | public static final String[] BINARY_ARRAY = { 13 | "604c602c600b82828239805160001a60731460008114601c57601e565bfe5b5030600052607381538281f30073000000000000000000000000000000000000000030146080604052600080fd00a165627a7a723058207fc4d2d2a2fdb4818ddbab25fca4ecd969f708ecf2e4c69a184db80a3886109d0029" 14 | }; 15 | 16 | public static final String BINARY = 17 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", BINARY_ARRAY); 18 | 19 | public static final String[] SM_BINARY_ARRAY = { 20 | "604c602c600b82828239805160001a60731460008114601c57601e565bfe5b5030600052607381538281f30073000000000000000000000000000000000000000030146080604052600080fd00a165627a7a7230582099096ed3fdad3ce8fc7f182ed532f49472b0d130da773e016921c6a0631529e60029" 21 | }; 22 | 23 | public static final String SM_BINARY = 24 | org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", SM_BINARY_ARRAY); 25 | 26 | public static final String[] ABI_ARRAY = {"[]"}; 27 | 28 | public static final String ABI = org.fisco.bcos.sdk.v3.utils.StringUtils.joinAll("", ABI_ARRAY); 29 | 30 | protected SafeMath(String contractAddress, Client client, CryptoKeyPair credential) { 31 | super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); 32 | } 33 | 34 | public static String getBinary(CryptoSuite cryptoSuite) { 35 | return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); 36 | } 37 | 38 | public static String getABI() { 39 | return ABI; 40 | } 41 | 42 | public static SafeMath load(String contractAddress, Client client, CryptoKeyPair credential) { 43 | return new SafeMath(contractAddress, client, credential); 44 | } 45 | 46 | public static SafeMath deploy(Client client, CryptoKeyPair credential) 47 | throws ContractException { 48 | return deploy( 49 | SafeMath.class, 50 | client, 51 | credential, 52 | getBinary(client.getCryptoSuite()), 53 | getABI(), 54 | null, 55 | null); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/liquid/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/liquid/hello_world/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello_world" 3 | version = "0.1.0" 4 | authors = ["[your_name] "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | scale = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive", "full"] } 11 | 12 | liquid_lang = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_lang", default-features = false, features = ["contract"] } 13 | liquid_primitives = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_primitives", default-features = false } 14 | liquid_prelude = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_prelude", default-features = false } 15 | liquid_macro = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_macro", default-features = false } 16 | liquid_abi_gen = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_abi_gen", default-features = false, optional = true } 17 | 18 | [dev-dependencies] 19 | predicates = "1.0.5" 20 | 21 | [lib] 22 | name = "hello_world" 23 | crate-type = [ 24 | # Used for normal contract Wasm blobs. 25 | "cdylib", 26 | # Used for ABI generation. 27 | "rlib", 28 | ] 29 | 30 | [features] 31 | default = ["std"] 32 | std = [ 33 | "liquid_lang/std", 34 | "scale/std", 35 | "liquid_primitives/std", 36 | "liquid_prelude/std", 37 | "liquid_macro/std", 38 | ] 39 | liquid-abi-gen = [ 40 | "std", 41 | "liquid_abi_gen", 42 | "liquid_lang/contract-abi-gen", 43 | ] 44 | gm = [ 45 | "liquid_lang/gm", 46 | "liquid_primitives/gm", 47 | ] 48 | 49 | [profile.release] 50 | panic = "abort" 51 | lto = true 52 | opt-level = "z" 53 | overflow-checks = true 54 | 55 | [workspace] 56 | members = [ 57 | ".liquid/abi_gen", 58 | ] 59 | exclude = [ 60 | ".liquid", 61 | ] 62 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/liquid/hello_world/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | use liquid::storage; 4 | use liquid_lang as liquid; 5 | 6 | #[liquid::contract] 7 | mod hello_world { 8 | use super::*; 9 | 10 | #[liquid(storage)] 11 | struct HelloWorld { 12 | name: storage::Value, 13 | } 14 | 15 | #[liquid(methods)] 16 | impl HelloWorld { 17 | pub fn new(&mut self) { 18 | self.name.initialize(String::from("Alice")); 19 | } 20 | 21 | pub fn get(&self) -> String { 22 | self.name.clone() 23 | } 24 | 25 | pub fn set(&mut self, name: String) { 26 | self.name.set(name) 27 | } 28 | } 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | 34 | #[test] 35 | fn get_works() { 36 | let contract = HelloWorld::new(); 37 | assert_eq!(contract.get(), "Alice"); 38 | } 39 | 40 | #[test] 41 | fn set_works() { 42 | let mut contract = HelloWorld::new(); 43 | 44 | let new_name = String::from("Bob"); 45 | contract.set(new_name.clone()); 46 | assert_eq!(contract.get(), "Bob"); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/liquid/parallel_ok/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "parallel_ok" 3 | version = "0.1.0" 4 | authors = ["[your_name] "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | scale = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive", "full"] } 11 | 12 | liquid_lang = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_lang", default-features = false, features = ["contract"] } 13 | liquid_primitives = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_primitives", default-features = false } 14 | liquid_prelude = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_prelude", default-features = false } 15 | liquid_macro = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_macro", default-features = false } 16 | liquid_abi_gen = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_abi_gen", default-features = false, optional = true } 17 | 18 | [dev-dependencies] 19 | predicates = "1.0.5" 20 | 21 | [lib] 22 | name = "parallel_ok" 23 | crate-type = [ 24 | # Used for normal contract Wasm blobs. 25 | "cdylib", 26 | # Used for ABI generation. 27 | "rlib", 28 | ] 29 | 30 | [features] 31 | default = ["std"] 32 | std = [ 33 | "liquid_lang/std", 34 | "scale/std", 35 | "liquid_primitives/std", 36 | "liquid_prelude/std", 37 | "liquid_macro/std", 38 | ] 39 | liquid-abi-gen = [ 40 | "std", 41 | "liquid_abi_gen", 42 | "liquid_lang/contract-abi-gen", 43 | ] 44 | gm = [ 45 | "liquid_lang/gm", 46 | "liquid_primitives/gm", 47 | ] 48 | 49 | [profile.release] 50 | panic = "abort" 51 | lto = true 52 | opt-level = "z" 53 | overflow-checks = true 54 | 55 | [workspace] 56 | members = [ 57 | ".liquid/abi_gen", 58 | ] 59 | exclude = [ 60 | ".liquid", 61 | ] 62 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/liquid/parallel_ok/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | use liquid::storage; 4 | use liquid_lang as liquid; 5 | 6 | #[liquid::contract] 7 | mod parallel_ok { 8 | use super::*; 9 | 10 | type Balance = u128; 11 | 12 | #[liquid(storage)] 13 | struct ParallelOk { 14 | balances: storage::Mapping, 15 | } 16 | 17 | #[liquid(methods)] 18 | impl ParallelOk { 19 | pub fn new(&mut self) { 20 | self.balances.initialize(); 21 | } 22 | 23 | pub fn balance_of(&self, name: String) -> Balance { 24 | *self.balances.get(&name).unwrap_or(&0) 25 | } 26 | 27 | pub fn set(&mut self, name: String, num: Balance) { 28 | self.balances.insert(name, num); 29 | } 30 | 31 | pub fn transfer(&mut self, from: String, to: String, value: Balance) -> bool { 32 | let from_balance = self.balance_of(from.clone()); 33 | if from_balance < value { 34 | return false; 35 | } 36 | 37 | self.balances.insert(from.clone(), from_balance - value); 38 | let to_balance = self.balance_of(to.clone()); 39 | self.balances.insert(to.clone(), to_balance + value); 40 | true 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/liquid/table_test/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "table_test" 3 | version = "0.1.0" 4 | authors = ["[your_name] "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | scale = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive", "full"] } 11 | 12 | liquid_lang = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_lang", default-features = false, features = ["contract"] } 13 | liquid_primitives = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_primitives", default-features = false } 14 | liquid_prelude = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_prelude", default-features = false } 15 | liquid_macro = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_macro", default-features = false } 16 | liquid_abi_gen = { version = "1.0.0-rc2", git = "https://github.com/WeBankBlockchain/liquid", branch = "dev", package = "liquid_abi_gen", default-features = false, optional = true } 17 | 18 | [dev-dependencies] 19 | predicates = "1.0.5" 20 | 21 | [lib] 22 | name = "table_test" 23 | crate-type = [ 24 | # Used for normal contract Wasm blobs. 25 | "cdylib", 26 | # Used for ABI generation. 27 | "rlib", 28 | ] 29 | 30 | [features] 31 | default = ["std"] 32 | std = [ 33 | "liquid_lang/std", 34 | "scale/std", 35 | "liquid_primitives/std", 36 | "liquid_prelude/std", 37 | "liquid_macro/std", 38 | ] 39 | liquid-abi-gen = [ 40 | "std", 41 | "liquid_abi_gen", 42 | "liquid_lang/contract-abi-gen", 43 | ] 44 | gm = [ 45 | "liquid_lang/gm", 46 | "liquid_primitives/gm", 47 | ] 48 | 49 | [profile.release] 50 | panic = "abort" 51 | lto = true 52 | opt-level = "z" 53 | overflow-checks = true 54 | 55 | [workspace] 56 | members = [ 57 | ".liquid/abi_gen", 58 | ] 59 | exclude = [ 60 | ".liquid", 61 | ] 62 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/liquid/table_test/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | use liquid::storage; 4 | use liquid_lang as liquid; 5 | use liquid_lang::InOut; 6 | use liquid_prelude::{string::String, vec::Vec}; 7 | 8 | #[derive(InOut)] 9 | pub struct TableInfo { 10 | key_column: String, 11 | value_columns: Vec, 12 | } 13 | 14 | #[derive(InOut)] 15 | pub struct Entry { 16 | key: String, 17 | fields: Vec, 18 | } 19 | 20 | #[derive(InOut)] 21 | pub struct UpdateField { 22 | field_name: String, 23 | value: String, 24 | } 25 | 26 | #[derive(InOut)] 27 | pub enum ConditionOP { 28 | GT(u8), 29 | GE(u8), 30 | LT(u8), 31 | LE(u8), 32 | } 33 | 34 | #[derive(InOut)] 35 | pub struct Condition { 36 | op: ConditionOP, 37 | value: String, 38 | } 39 | 40 | #[derive(InOut)] 41 | pub struct Limit { 42 | offset: u32, 43 | count: u32, 44 | } 45 | 46 | #[liquid::interface(name = auto)] 47 | mod table_manager { 48 | use super::*; 49 | 50 | extern "liquid" { 51 | fn createTable(&mut self, path: String, table_info: TableInfo) -> i32; 52 | } 53 | } 54 | #[liquid::interface(name = auto)] 55 | mod table { 56 | use super::*; 57 | 58 | extern "liquid" { 59 | fn select(&self, key: String) -> Entry; 60 | fn insert(&mut self, entry: Entry) -> i32; 61 | fn update(&mut self, key: String, update_fields: Vec) -> i32; 62 | fn remove(&mut self, key: String) -> i32; 63 | } 64 | } 65 | 66 | #[liquid::contract] 67 | mod table_test { 68 | use super::{table::*, table_manager::*, *}; 69 | 70 | #[liquid(event)] 71 | struct InsertResult { 72 | count: i32, 73 | } 74 | 75 | #[liquid(event)] 76 | struct UpdateResult { 77 | count: i32, 78 | } 79 | #[liquid(event)] 80 | struct RemoveResult { 81 | count: i32, 82 | } 83 | 84 | #[liquid(storage)] 85 | struct TableTest { 86 | table: storage::Value, 87 | tm: storage::Value, 88 | table_name: storage::Value, 89 | } 90 | 91 | #[liquid(methods)] 92 | impl TableTest { 93 | pub fn new(&mut self) { 94 | self.table_name.initialize(String::from("t_test")); 95 | self.tm 96 | .initialize(TableManager::at("/sys/table_manager".parse().unwrap())); 97 | 98 | let mut column_names = Vec::new(); 99 | column_names.push(String::from("name")); 100 | column_names.push(String::from("age")); 101 | let ti = TableInfo { 102 | key_column: String::from("id"), 103 | value_columns: column_names, 104 | }; 105 | 106 | self.tm.createTable(self.table_name.clone(), ti); 107 | self.table 108 | .initialize(Table::at("/tables/t_test".parse().unwrap())); 109 | } 110 | 111 | pub fn select(&self, id: String) -> (String, String) { 112 | let entry = self.table.select(id).unwrap(); 113 | 114 | if entry.fields.len() < 1 { 115 | return (Default::default(), Default::default()); 116 | } 117 | 118 | return (entry.fields[0].clone(), entry.fields[1].clone()); 119 | } 120 | 121 | pub fn insert(&mut self, id: String, name: String, age: String) -> i32 { 122 | let mut values = Vec::new(); 123 | values.push(name); 124 | values.push(age); 125 | 126 | let entry = Entry { 127 | key: id, 128 | fields: values, 129 | }; 130 | let result = self.table.insert(entry).unwrap(); 131 | self.env().emit(InsertResult { 132 | count: result.clone(), 133 | }); 134 | return result; 135 | } 136 | 137 | pub fn update(&mut self, id: String, name: String, age: String) -> i32 { 138 | let mut update_fields = Vec::new(); 139 | update_fields.push(UpdateField { 140 | field_name: String::from("name"), 141 | value: name, 142 | }); 143 | 144 | update_fields.push(UpdateField { 145 | field_name: String::from("age"), 146 | value: age, 147 | }); 148 | 149 | let result = self.table.update(id, update_fields).unwrap(); 150 | self.env().emit(UpdateResult { 151 | count: result.clone(), 152 | }); 153 | return result; 154 | } 155 | 156 | pub fn remove(&mut self, id: String) -> i32 { 157 | let result = self.table.remove(id).unwrap(); 158 | self.env().emit(RemoveResult { 159 | count: result.clone(), 160 | }); 161 | return result; 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Account.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.0; 2 | pragma experimental ABIEncoderV2; 3 | 4 | import "./SafeMath.sol"; 5 | 6 | contract Account 7 | { 8 | using SafeMath for uint256; 9 | 10 | function balance() public view returns(uint256) { 11 | return m_balance; 12 | } 13 | 14 | function addBalance(uint256 num) public { 15 | m_balance = m_balance.add(num); 16 | } 17 | 18 | function subBalance(uint256 num) public { 19 | m_balance = m_balance.sub(num); 20 | } 21 | 22 | function transfer(address to, uint256 num) public 23 | { 24 | if (to != address(this)) { 25 | uint256 _balance = m_balance; 26 | 27 | Account toAccount = Account(to); // DMC out 28 | toAccount.addBalance(num); 29 | 30 | // To check the _balance is the same after DMC scheduling out 31 | m_balance = _balance - num; 32 | } else { 33 | subBalance(num); 34 | Account toAccount = Account(to); // DMC out 35 | toAccount.addBalance(num); 36 | } 37 | } 38 | 39 | uint256 m_balance; 40 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/AnonymousVotingInterface.sol: -------------------------------------------------------------------------------- 1 | // Copyright (C) @2014-2022 Webank 2 | // SPDX-License-Identifier: Apache-2.0 3 | pragma solidity >=0.6.10 <0.8.20; 4 | pragma experimental ABIEncoderV2; 5 | 6 | import "./ZkpPrecompiled.sol"; 7 | import "./WedprUtils.sol"; 8 | import "./Crypto.sol"; 9 | 10 | struct SystemParameters { 11 | int256 itemId; // the itemId 12 | string itemMeta; // item meta data 13 | string[] candidates; 14 | bytes hpoint; 15 | } 16 | 17 | struct Ballot{ 18 | string candidateId; 19 | bytes cipher1; 20 | bytes cipher2; 21 | bool isAssigned; 22 | } 23 | // the ballot proof 24 | struct BallotProof{ 25 | bytes formatProof; 26 | bytes eitherEqualityProof; 27 | Ballot ballot; 28 | } 29 | 30 | struct UnlistedBallot 31 | { 32 | bytes cipher1; 33 | bytes cipher2; 34 | Ballot ballot; 35 | bool isAssigned; 36 | } 37 | // the candiate ballot proof 38 | struct UnlistedCandidateBallotProof 39 | { 40 | UnlistedBallot ballot; 41 | BallotProof unlisted_ballot_proof; 42 | } 43 | struct VoteRequest{ 44 | Ballot blankBallot; 45 | Ballot zeroBallot; 46 | // bytes publicKey; 47 | // bytes32 signatureR; 48 | // bytes32 signatureS; 49 | } 50 | struct VoteStorage{ 51 | bool isAssigned; 52 | VoteRequest voteRequest; 53 | string[] candidateListForBallot; 54 | bytes[] cipherCandidateListForUnlistedBallot; 55 | } 56 | struct CounterStorage 57 | { 58 | // 计票公钥分片 59 | bytes hpointShare; 60 | // 计票公钥是否被聚合 61 | bool setted; 62 | // 计票服务状态,1:计票中,2:计票完成 63 | int8 counterStatus; 64 | // 计票服务实例的心跳时间 65 | uint256 updateTime; 66 | // 一个投票item中投票密文的聚合值 67 | string voteStorageSum; 68 | // 使用acv-core的公钥加密的计票服务sm4密钥 69 | string sm4SecretKeyCipherText; 70 | // 使用计票服务的sm4密钥加密的计票分片 71 | string countingPartResultCipherText; 72 | // 计票分片哈希值 73 | bytes decryptedPartResultHash; 74 | } 75 | 76 | contract AnonymousVotingInterface { 77 | function initialize(bytes memory basePointG1, bytes memory basePointG2) public virtual; 78 | function setSystemParameters(int256 itemId, string memory itemMeta, string[] memory candidates, bytes memory hpoint) public virtual; 79 | function getSystemParameters() public view virtual returns(SystemParameters memory); 80 | function setCounterNumber(uint256 counterNumber) public virtual; 81 | function getCounterNumber() public view virtual returns(uint256); 82 | function setContractState(uint8 state) public virtual; 83 | function getContractState() public view virtual returns(uint8); 84 | function setVoterIdList(string[] memory voterIdList) public virtual; 85 | function getVoterIdList() public view virtual returns(string[] memory); 86 | function setVoterIdToVoteStorage(string memory voterId, VoteStorage memory voteStorage) public virtual; 87 | function getVoterIdToVoteStorage(string memory voterId) public view virtual returns(VoteStorage memory); 88 | function setVoterIDToCandidateIDToBallot(string memory voterId, string memory candidateId, Ballot memory ballot) public virtual; 89 | function getVoterIDToCandidateIDToBallot(string memory voterId, string memory candidateId) public view virtual returns(Ballot memory); 90 | function setVoterIDToCandidateIDToUnlistedBallot(string memory voterId, bytes memory candidateId, UnlistedBallot memory unlistedBallot) public virtual; 91 | function getVoterIDToCandidateIDToUnlistedBallot(string memory voterId, bytes memory candidateId) public view virtual returns(UnlistedBallot memory); 92 | function setCounterIdToCounterStorage(string memory counterId, CounterStorage memory counterStorage) public virtual; 93 | function getCounterIdToCounterStorage(string memory counterId) public view virtual returns(CounterStorage memory); 94 | function setCounterStatus(string memory counterId, int8 status) public virtual; 95 | function getCounterStatus(string memory counterId) public view virtual returns(int8); 96 | function setCounterUpdateTime(string memory counterId, uint256 updateTime) public virtual; 97 | function getCounterUpdateTime(string memory counterId) public view virtual returns(uint256); 98 | function setVoteStorageSum(string memory counterId, string memory voteStorageSum) public virtual; 99 | function getVoteStorageSum(string memory counterId) public view virtual returns(string memory); 100 | function setSm4SecretKeyCipherText(string memory counterId, string memory sm4SecretKeyCipherText) public virtual; 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/BalanceBank.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | contract BalanceBank { 5 | 6 | // Use transfer method to withdraw an amount of money and for updating automatically the balance 7 | function transfer(address _to, uint256 _value) public { 8 | payable(_to).transfer(_value); 9 | } 10 | 11 | // Getter smart contract Balance 12 | function getSmartContractBalance() external view returns(uint256) { 13 | return address(this).balance; 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/BlobHashExample.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.6.10 <=0.8.26; 3 | 4 | contract BlobHashExample { 5 | bytes public largeData = "This is a very large data blob that needs to be hashed efficiently."; 6 | 7 | function hashData() public view returns (bytes32) { 8 | bytes32 result; 9 | assembly { 10 | result := blobhash(add(sload(largeData.slot), largeData.offset)) 11 | } 12 | return result; 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/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 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/CodeOp.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.0 <0.8.12; 2 | 3 | contract CodeOp { 4 | // CODESIZE 5 | 6 | // CODECOPY 7 | 8 | // EXTCODESIZE 9 | 10 | // EXTCODECOPY 11 | 12 | // EXTCODEHASH 13 | 14 | function getCode(address _contractAddress) public view returns (bytes memory) { 15 | uint256 codeSize; 16 | assembly { 17 | codeSize := extcodesize(_contractAddress) 18 | } 19 | require(codeSize > 0, "Contract does not exist"); 20 | 21 | bytes memory code = new bytes(codeSize); 22 | assembly { 23 | extcodecopy(_contractAddress, add(code, 32), 0, codeSize) 24 | } 25 | return code; 26 | } 27 | 28 | function getSelfCode() public view returns (bytes memory) { 29 | uint256 codeSize; 30 | assembly { 31 | codeSize := codesize() 32 | } 33 | require(codeSize > 0, "Contract does not exist"); 34 | 35 | bytes memory code = new bytes(codeSize); 36 | assembly { 37 | codecopy(add(code, 32), 0, codeSize) 38 | mstore(code, codeSize) 39 | } 40 | return code; 41 | } 42 | 43 | function codeHashAt(address addr) public view returns(bytes32){ 44 | bytes32 codeHash; 45 | assembly { 46 | codeHash := extcodehash(addr) 47 | } 48 | return codeHash; 49 | } 50 | 51 | function codeSize() public view returns(uint256) { 52 | uint256 size; 53 | assembly { 54 | size := codesize() 55 | } 56 | return size; 57 | } 58 | 59 | function extcodeSize(address a) public view returns(uint256) { 60 | uint256 size; 61 | assembly { 62 | size := extcodesize(a) 63 | } 64 | return size; 65 | } 66 | 67 | function checkEthPrecompiledCode() public view returns(uint256){ 68 | require(extcodeSize(0x0000000000000000000000000000000000000001) == 0, "eth precompiled code size must be 0"); 69 | require(codeHashAt(0x0000000000000000000000000000000000000001) == bytes32(0), "eth precompiled code hash must be 0"); 70 | } 71 | 72 | function checkSelfCode() public returns(bytes32, bytes32) { 73 | bytes32 codeHash = codeHashAt(address(this)); 74 | bytes memory extcode = getCode(address(this)); 75 | bytes memory selfCode = getSelfCode(); 76 | 77 | require(keccak256(extcode) == codeHash, "extcode must same"); 78 | require(keccak256(selfCode) == codeHash, "selfCode must same"); 79 | return (codeHash, keccak256(extcode)); 80 | } 81 | 82 | function checkCodeSize() public { 83 | bytes memory code = getSelfCode(); 84 | require(code.length == codeSize(), "codeSize must same"); 85 | require(code.length == extcodeSize(address(this)), "extcodeSize must same"); 86 | } 87 | 88 | function check() public { 89 | checkSelfCode(); 90 | checkCodeSize(); 91 | checkEthPrecompiledCode(); 92 | } 93 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ComplexCodecTest.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | struct StructA { 6 | string[] value_str; 7 | bytes32[] bytes32_in_struct; 8 | } 9 | 10 | struct StructB { 11 | string[] d_str; 12 | StructA[] a_struct; 13 | } 14 | 15 | struct StaticStruct{ 16 | int128 i1; 17 | uint128 u1; 18 | int32[1] b1; 19 | } 20 | 21 | contract ComplexCodecTest { 22 | 23 | bytes[][] public b_array_array; 24 | bytes32[][] public b32_array_array; 25 | bytes[2][] public b_s_array_array; 26 | bytes32[2][] public b32_s_array_array; 27 | 28 | StructA a_struct; 29 | StaticStruct static_struct; 30 | 31 | // constructor() public{ 32 | // bytes32[] memory b = new bytes32[](1); 33 | // string[] memory s = new string[](1); 34 | // s[0] = "test"; 35 | // a_struct = StructA(s,b); 36 | // } 37 | 38 | constructor(StructA memory a) public{ 39 | a_struct = a; 40 | } 41 | 42 | function getStructA(StructA memory a) public view returns (StructA[] memory){ 43 | StructA[] memory s = new StructA[](2); 44 | s[0] = a_struct; 45 | s[1] = a; 46 | return s; 47 | } 48 | 49 | function getStructA() public view returns (StructA[] memory){ 50 | StructA[] memory s = new StructA[](2); 51 | s[0] = a_struct; 52 | s[1] = a_struct; 53 | return s; 54 | } 55 | 56 | function buildStructA(string memory value_str, bytes32[] memory _b) public returns (StructA memory) 57 | { 58 | string[] memory s = new string[](1); 59 | s[0] = value_str; 60 | a_struct = StructA(s, _b); 61 | return a_struct; 62 | } 63 | 64 | function buildStructA(string memory value_str, bytes32[] memory _b, uint8 size) public returns (StructA[] memory) 65 | { 66 | string[] memory s = new string[](2); 67 | s[0] = value_str; 68 | a_struct = StructA(s, _b); 69 | StructA[] memory ss = new StructA[](size); 70 | ss[0] = a_struct; 71 | return ss; 72 | } 73 | 74 | function buildStructB(StructA memory a) public returns (StructB memory, StructA[] memory){ 75 | StructB memory b_struct; 76 | a_struct = a; 77 | b_struct.a_struct = new StructA[](2); 78 | b_struct.a_struct[0] = a; 79 | b_struct.a_struct[1] = a; 80 | return (b_struct,b_struct.a_struct); 81 | } 82 | 83 | function getStructAInStructB(StructB memory b) public returns (StructA memory){ 84 | require(b.a_struct.length > 0); 85 | a_struct = b.a_struct[0]; 86 | return a_struct; 87 | } 88 | 89 | function setBytesArrayArray(bytes[][] memory b) public returns (bytes[][] memory){ 90 | b_array_array = b; 91 | return b_array_array; 92 | } 93 | 94 | function setBytes32ArrayArray(bytes32[][] memory b) public returns (bytes32[][] memory){ 95 | b32_array_array = b; 96 | return b32_array_array; 97 | } 98 | 99 | function setBytesStaticArrayArray(bytes[2][] memory b) public returns (bytes[2][] memory){ 100 | b_s_array_array = b; 101 | return b_s_array_array; 102 | } 103 | 104 | function setBytes32StaticArrayArray(bytes32[2][] memory b) public returns (bytes32[2][] memory){ 105 | b32_s_array_array = b; 106 | return b32_s_array_array; 107 | } 108 | 109 | function buildStaticStruct(int128 i1, uint128 u1) public returns(StaticStruct[] memory){ 110 | int32[1] memory b = [int32(1)]; 111 | b[0] = int32(1); 112 | static_struct = StaticStruct(i1,u1,b); 113 | StaticStruct memory s2 = StaticStruct(i1,u1,b); 114 | StaticStruct[] memory ss = new StaticStruct[](2); 115 | ss[0] = static_struct; 116 | ss[1] = s2; 117 | return ss; 118 | } 119 | 120 | function buildStaticStruct(StaticStruct memory b) public returns(StaticStruct memory){ 121 | static_struct = StaticStruct(b.i1+1,b.u1+1,b.b1); 122 | return static_struct; 123 | } 124 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ContractA.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.8.25; 2 | 3 | import "./StorageSlot.sol"; 4 | import "./ContractB.sol"; 5 | 6 | contract ContractA { 7 | using StorageSlot for *; 8 | 9 | StorageSlot.Int256SlotType private intSlot; 10 | constructor(int256 value){ 11 | StorageSlot.tstore(intSlot, value); 12 | } 13 | 14 | function getData() public view returns (int256) { 15 | return StorageSlot.tload(intSlot); 16 | } 17 | 18 | function callContractB() public returns (int256){ 19 | ContractB b = new ContractB(); 20 | return b.callContractA(address(this)); 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ContractB.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.8.25; 2 | 3 | import "./StorageSlot.sol"; 4 | import "./ContractA.sol"; 5 | 6 | 7 | contract ContractB { 8 | 9 | function callContractA(address a) public returns (int256){ 10 | ContractA a = ContractA(a); 11 | int256 result = a.getData(); 12 | return result; 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ContractTestAll.sol: -------------------------------------------------------------------------------- 1 | import "./CodeOp.sol"; 2 | import "./Create2.sol"; 3 | import "./DelegateCall.sol"; 4 | import "./RecursiveDelegateCallTest.sol"; 5 | import "./EventTest.sol"; 6 | import "./LibraryTest.sol"; 7 | import "./ProxyTest.sol"; 8 | import "./StaticCall.sol"; 9 | import "./TablePrecompiledTest.sol"; 10 | import "./ECRecoverTest.sol"; 11 | import "./DeployTreeTest.sol"; // DMC 12 | import "./BalanceTest.sol"; 13 | import "./BalancePrecompiledTest.sol"; 14 | import "./BalanceReceiveTest.sol"; 15 | 16 | contract ContractTestAll { 17 | event Info(string, uint256, uint256); 18 | 19 | function checkOne(string memory name, address addr, bool needProxyCheck, uint256 callValue) private { 20 | uint256 gasBefore = gasleft(); 21 | (bool success, bytes memory reason) = address(addr).call{value: callValue}(abi.encodeWithSignature("check()")); 22 | require(success, string(abi.encodePacked(name, " check failed: ", reason))); 23 | 24 | uint256 gasBeforeProxy = gasleft(); 25 | 26 | if (needProxyCheck) { 27 | // use proxy to call check() 28 | Proxy proxy = new ProxyImpl(addr); 29 | (success, reason) = address(proxy).call{value: callValue}(abi.encodeWithSignature("check()")); 30 | require(success, string(abi.encodePacked(name, " proxy check failed: ", reason))); 31 | } 32 | uint256 gasAfter = gasleft(); 33 | emit Info(string(abi.encodePacked(name, " gas used ")), gasBefore - gasBeforeProxy, gasBeforeProxy - gasAfter); 34 | } 35 | 36 | function check() public payable { 37 | uint256 thisBalance = address(this).balance; 38 | uint256 callValue = thisBalance > 100000 ? 5000 : 0; 39 | 40 | checkOne("CodeOp", address(new CodeOp()), false, 0); 41 | checkOne("Create2", address(new Create2()), true, 0); 42 | checkOne("DelegateCall", address(new DelegateCall()), true, 0); 43 | checkOne("RecursiveDelegateCallTest", address(new RecursiveDelegateCallTest()), false, 0); 44 | checkOne("EventTest", address(new EventTest()), true, 0); 45 | checkOne("LibraryTest", address(new LibraryTest()), true, 0); 46 | checkOne("ProxyTest", address(new ProxyTest()), true, 0); 47 | checkOne("TablePrecompiledTest", address(new TablePrecompiledTest()), true, 0); 48 | checkOne("ECRecoverTest", address(new ECRecoverTest()), true, 0); 49 | checkOne("DeployTreeTest", address(new DeployTreeTest()), true, 0); // DMC 50 | checkOne("BalanceTest", address(new BalanceTest()), true, callValue); 51 | checkOne("BalancePrecompiledTest", address(new BalancePrecompiledTest()), false, 0); 52 | checkOne("BalanceReceiveTest", address(new BalanceReceiveTest()), true, callValue); 53 | 54 | checkOne("StaticCall", address(new StaticCall()), false, 0); // must at last for gas will be used up by staticcall failed 55 | } 56 | 57 | // fallback 58 | fallback() external payable {} 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/CpuHeavy.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | contract CpuHeavy { 6 | event finish(uint size, uint signature); 7 | 8 | function sort(uint size, uint signature) public { 9 | uint[] memory data = new uint[](size); 10 | for (uint x = 0; x < data.length; x++) { 11 | data[x] = size-x; 12 | } 13 | quickSort(data, 0, int(data.length - 1)); 14 | emit finish(size, signature); 15 | } 16 | 17 | function quickSort(uint[] memory arr, int left, int right) internal { 18 | int i = left; 19 | int j = right; 20 | if (i == j) return; 21 | uint pivot = arr[uint(left + (right - left) / 2)]; 22 | while (i <= j) { 23 | while (arr[uint(i)] < pivot) i++; 24 | while (pivot < arr[uint(j)]) j--; 25 | if (i <= j) { 26 | (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); 27 | i++; 28 | j--; 29 | } 30 | } 31 | if (left < j) 32 | quickSort(arr, left, j); 33 | if (i < right) 34 | quickSort(arr, i, right); 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/CpuHeavyPrecompiled.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.10; 2 | contract CpuHeavyPrecompiled 3 | { 4 | // just to get abi to call this precompiled 5 | function sort(uint size, uint signature) public {} 6 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Create2.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.0 <0.8.12; 2 | 3 | 4 | contract Factory { 5 | // Returns the address of the newly deployed contract 6 | function deploy( 7 | address _owner, 8 | uint _foo, 9 | bytes32 _salt 10 | ) public payable returns (address) { 11 | // This syntax is a newer way to invoke create2 without assembly, you just need to pass salt 12 | // https://docs.soliditylang.org/en/latest/control-structures.html#salted-contract-creations-create2 13 | return address(new TestContract{salt: _salt}(_owner, _foo)); 14 | } 15 | } 16 | 17 | // This is the older way of doing it using assembly 18 | contract Create2 { 19 | event Deployed(address addr, uint salt); 20 | 21 | // 1. Get bytecode of contract to be deployed 22 | // NOTE: _owner and _foo are arguments of the TestContract's constructor 23 | function getBytecode(address _owner, uint _foo) public pure returns (bytes memory) { 24 | bytes memory bytecode = type(TestContract).creationCode; 25 | 26 | return abi.encodePacked(bytecode, abi.encode(_owner, _foo)); 27 | } 28 | 29 | // 2. Compute the address of the contract to be deployed 30 | // NOTE: _salt is a random number used to create an address 31 | function getAddress( 32 | bytes memory bytecode, 33 | uint _salt 34 | ) public view returns (address) { 35 | bytes32 hash = keccak256( 36 | abi.encodePacked(bytes1(0xff), address(this), _salt, keccak256(bytecode)) 37 | ); 38 | 39 | // NOTE: cast last 20 bytes of hash to address 40 | return address(uint160(uint(hash))); 41 | } 42 | 43 | // 3. Deploy the contract 44 | // NOTE: 45 | // Check the event log Deployed which contains the address of the deployed TestContract. 46 | // The address in the log should equal the address computed from above. 47 | function deploy(bytes memory bytecode, uint _salt) public payable returns(address){ 48 | address addr; 49 | 50 | /* 51 | NOTE: How to call create2 52 | 53 | create2(v, p, n, s) 54 | create new contract with code at memory p to p + n 55 | and send v wei 56 | and return the new address 57 | where new address = first 20 bytes of keccak256(0xff + address(this) + s + keccak256(mem[p…(p+n))) 58 | s = big-endian 256-bit value 59 | */ 60 | assembly { 61 | addr := create2( 62 | callvalue(), // wei sent with current call 63 | // Actual code starts after skipping the first 32 bytes 64 | add(bytecode, 0x20), 65 | mload(bytecode), // Load the size of code contained in the first 32 bytes 66 | _salt // Salt from function arguments 67 | ) 68 | 69 | if iszero(extcodesize(addr)) { 70 | revert(0, 0) 71 | } 72 | } 73 | 74 | emit Deployed(addr, _salt); 75 | return addr; 76 | } 77 | 78 | function check() public { 79 | bytes memory bytecode = getBytecode(msg.sender, 66); 80 | uint salt = block.timestamp; 81 | address addr1 = getAddress(bytecode, salt); 82 | address addr2 = deploy(bytecode, salt); 83 | require(addr1 == addr2, "getAddress() and deploy() should be the same"); 84 | } 85 | } 86 | 87 | contract TestContract { 88 | address public owner; 89 | uint public foo; 90 | 91 | constructor(address _owner, uint _foo) public payable { 92 | owner = _owner; 93 | foo = _foo; 94 | } 95 | 96 | function getBalance() public view returns (uint) { 97 | return address(this).balance; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Crypto.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.10 <0.8.20; 2 | pragma experimental ABIEncoderV2; 3 | abstract contract Crypto 4 | { 5 | function sm3(bytes memory data) public view returns(bytes32){} 6 | function keccak256Hash(bytes memory data) public view returns(bytes32){} 7 | function sm2Verify(bytes32 message, bytes memory publicKey, bytes32 r, bytes32 s) public view returns(bool, address){} 8 | function curve25519VRFVerify(bytes memory message, bytes memory publicKey, bytes memory proof) public view returns(bool, uint256){} 9 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Curve25519VRFVerifyTest.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.10 <0.8.20; 2 | pragma experimental ABIEncoderV2; 3 | import "./Crypto.sol"; 4 | 5 | contract Curve25519VRFVerifyTest 6 | { 7 | Crypto crypto; 8 | constructor() public 9 | { 10 | crypto = Crypto(address(0x100a)); 11 | } 12 | function curve25519VRFVerify(bytes memory input, bytes memory vrfPublicKey, bytes memory vrfProof) public returns(bool, uint256) 13 | { 14 | 15 | bool verifyResult; 16 | uint256 randomValue; 17 | (verifyResult, randomValue) = crypto.curve25519VRFVerify(input, vrfPublicKey, vrfProof); 18 | require(verifyResult == true); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/DagTransfer.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.0; 2 | 3 | abstract contract DagTransfer{ 4 | function userAdd(string calldata user, uint256 balance) public virtual returns(uint256); 5 | function userSave(string calldata user, uint256 balance) public virtual returns(uint256); 6 | function userDraw(string calldata user, uint256 balance) public virtual returns(uint256); 7 | function userBalance(string calldata user) public virtual view returns(uint256,uint256); 8 | function userTransfer(string calldata user_a, string calldata user_b, uint256 amount) public virtual returns(uint256); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/DmcTransfer.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.8.0; 2 | import "./SafeMath.sol"; 3 | contract DmcTransfer { 4 | using SafeMath for uint256; 5 | mapping (address => address[]) m_nextContract; 6 | 7 | function balance() public view returns(uint256) { 8 | return m_balance; 9 | } 10 | 11 | function addBalance(uint256 num) public { 12 | m_balance = m_balance.add(num); 13 | } 14 | 15 | function subBalance(uint256 num) public { 16 | m_balance = m_balance.sub(num); 17 | } 18 | 19 | function takeShare(uint256 num, bool allowRevert) public 20 | { 21 | num--; 22 | addBalance(1); 23 | if(num == 0){ 24 | return; 25 | } 26 | address from = msg.sender; 27 | address[] memory toArray = m_nextContract[from]; 28 | uint shareMoney = num/toArray.length; 29 | //add restMoney 30 | uint restMoney = num - shareMoney*toArray.length; 31 | addBalance(restMoney); 32 | uint256 _balance = m_balance; 33 | for(uint i = 0; i < toArray.length; ++i) { 34 | address toAddr = toArray[i]; 35 | DmcTransfer toAccount = DmcTransfer(toAddr); 36 | try toAccount.takeShare(shareMoney, allowRevert) { 37 | // if callMyself, update balance 38 | if (toAddr == address(this)){ 39 | _balance = m_balance; 40 | } 41 | } catch { 42 | if (allowRevert){ 43 | revert(); 44 | } else { 45 | _balance = _balance + shareMoney; 46 | // if callMyself, update balance 47 | if (toAddr == address(this)){ 48 | m_balance = _balance; 49 | } 50 | } 51 | } 52 | } 53 | m_balance = _balance; 54 | } 55 | 56 | function addNextCall(address from, address[] memory to) public{ 57 | m_nextContract[from] = to; 58 | } 59 | 60 | uint256 m_balance; 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Economic.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity ^0.8.0; 3 | 4 | interface BalancePrecompiled { 5 | function getBalance(address account) view external returns (uint256); 6 | function addBalance(address account, uint256 amount) external; 7 | function subBalance(address account, uint256 amount) external; 8 | function transfer(address from, address to, uint256 amount) external; 9 | function registerCaller(address account) external; 10 | function unregisterCaller(address account) external; 11 | } 12 | 13 | interface CommitteeManager { 14 | function isGovernor(address account) external view returns (bool); 15 | } 16 | 17 | struct IndexValue { uint keyIndex; bool value; } 18 | struct KeyFlag { address key; bool deleted; } 19 | 20 | struct itmap { 21 | mapping(address => IndexValue) data; 22 | KeyFlag[] keys; 23 | uint size; 24 | } 25 | 26 | type Iterator is uint; 27 | 28 | library IterableMapping { 29 | function insert(itmap storage self, address key, bool value) internal returns (bool replaced) { 30 | uint keyIndex = self.data[key].keyIndex; 31 | self.data[key].value = value; 32 | if (keyIndex > 0) 33 | return true; 34 | else { 35 | keyIndex = self.keys.length; 36 | self.keys.push(); 37 | self.data[key].keyIndex = keyIndex + 1; 38 | self.keys[keyIndex].key = key; 39 | self.size++; 40 | return false; 41 | } 42 | } 43 | 44 | function remove(itmap storage self, address key) internal returns (bool success) { 45 | uint keyIndex = self.data[key].keyIndex; 46 | if (keyIndex == 0) 47 | return false; 48 | delete self.data[key]; 49 | self.keys[keyIndex - 1].deleted = true; 50 | self.size --; 51 | } 52 | 53 | function contains(itmap storage self, address key) internal view returns (bool) { 54 | return self.data[key].keyIndex > 0; 55 | } 56 | 57 | function iterateStart(itmap storage self) internal view returns (Iterator) { 58 | return iteratorSkipDeleted(self, 0); 59 | } 60 | 61 | function iterateValid(itmap storage self, Iterator iterator) internal view returns (bool) { 62 | return Iterator.unwrap(iterator) < self.keys.length; 63 | } 64 | 65 | function iterateNext(itmap storage self, Iterator iterator) internal view returns (Iterator) { 66 | return iteratorSkipDeleted(self, Iterator.unwrap(iterator) + 1); 67 | } 68 | 69 | function iterateGet(itmap storage self, Iterator iterator) internal view returns (address key, bool value) { 70 | uint keyIndex = Iterator.unwrap(iterator); 71 | key = self.keys[keyIndex].key; 72 | value = self.data[key].value; 73 | } 74 | 75 | function iteratorSkipDeleted(itmap storage self, uint keyIndex) private view returns (Iterator) { 76 | while (keyIndex < self.keys.length && self.keys[keyIndex].deleted) 77 | keyIndex++; 78 | return Iterator.wrap(keyIndex); 79 | } 80 | } 81 | 82 | contract Economic { 83 | BalancePrecompiled balancePrecompiled = BalancePrecompiled(0x0000000000000000000000000000000000001011); 84 | CommitteeManager committeeMgr = CommitteeManager(0x0000000000000000000000000000000000010001); 85 | 86 | address owner; 87 | itmap chargersMap; 88 | using IterableMapping for itmap; 89 | 90 | constructor() { 91 | owner = msg.sender; 92 | } 93 | 94 | modifier onlyGovernor() { 95 | require(committeeMgr.isGovernor(msg.sender), "you must be governor"); 96 | _; 97 | } 98 | 99 | modifier onlyCharger() { 100 | require(chargersMap.contains(msg.sender), "you must be charger"); 101 | _; 102 | } 103 | 104 | modifier onlyOwner() { 105 | require(msg.sender == owner, "you must be owner"); 106 | _; 107 | } 108 | 109 | function charge(address userAccount, uint256 gasValue) onlyCharger public { 110 | balancePrecompiled.addBalance(userAccount, gasValue); 111 | } 112 | function deduct(address userAccount, uint256 gasValue) onlyCharger public { 113 | balancePrecompiled.subBalance(userAccount, gasValue); 114 | } 115 | function getBalance(address userAccount) public view returns(uint256){ 116 | return balancePrecompiled.getBalance(userAccount); 117 | } 118 | function grantCharger(address chargerAccount) onlyOwner public returns(bool success){ 119 | return chargersMap.insert(chargerAccount, true); 120 | } 121 | function revokeCharger(address chargerAccount) onlyOwner public returns(bool success){ 122 | require(chargersMap.contains(chargerAccount), "charger has not been granted before"); 123 | return chargersMap.remove(chargerAccount); 124 | } 125 | function listChargers() public view returns(address[] memory){ 126 | address[] memory output = new address[](chargersMap.size); 127 | uint256 index = 0; 128 | for ( 129 | Iterator i = chargersMap.iterateStart(); 130 | chargersMap.iterateValid(i); 131 | i = chargersMap.iterateNext(i) 132 | ) { 133 | (address charger, ) = chargersMap.iterateGet(i); 134 | output[index] = charger; 135 | index++; 136 | } 137 | return output; 138 | } 139 | 140 | function enable() onlyGovernor public { 141 | balancePrecompiled.registerCaller(address(this)); 142 | } 143 | function disable() onlyGovernor public { 144 | balancePrecompiled.unregisterCaller(address(this)); 145 | } 146 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/EntryWrapper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | import "./Cast.sol"; 5 | 6 | // 记录,用于select和insert 7 | struct Entry { 8 | string key; 9 | string[] fields; // 考虑2.0的Entry接口,临时Precompiled的问题,考虑加工具类接口 10 | } 11 | 12 | contract EntryWrapper { 13 | Cast constant cast = Cast(address(0x100f)); 14 | Entry entry; 15 | constructor(Entry memory _entry) public { 16 | entry = _entry; 17 | } 18 | function setEntry(Entry memory _entry) public { 19 | entry = _entry; 20 | } 21 | function getEntry() public view returns(Entry memory) { 22 | return entry; 23 | } 24 | function fieldSize() public view returns (uint256) { 25 | return entry.fields.length; 26 | } 27 | function getInt(uint256 idx) public view returns (int256) { 28 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 29 | return cast.stringToS256(entry.fields[idx]); 30 | } 31 | function getUInt(uint256 idx) public view returns (uint256) { 32 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 33 | return cast.stringToU256(entry.fields[idx]); 34 | } 35 | function getAddress(uint256 idx) public view returns (address) { 36 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 37 | return cast.stringToAddr(entry.fields[idx]); 38 | } 39 | function getBytes64(uint256 idx) public view returns (bytes1[64] memory) { 40 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 41 | return bytesToBytes64(bytes(entry.fields[idx])); 42 | } 43 | function getBytes32(uint256 idx) public view returns (bytes32) { 44 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 45 | return cast.stringToBytes32(entry.fields[idx]); 46 | } 47 | function getString(uint256 idx) public view returns (string memory) { 48 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 49 | return entry.fields[idx]; 50 | } 51 | function set(uint256 idx, int256 value) public returns(int32) { 52 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 53 | entry.fields[idx] = cast.s256ToString(value); 54 | return 0; 55 | } 56 | function set(uint256 idx, uint256 value) public returns(int32) { 57 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 58 | entry.fields[idx] = cast.u256ToString(value); 59 | return 0; 60 | } 61 | function set(uint256 idx, string memory value) public returns(int32) { 62 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 63 | entry.fields[idx] = value; 64 | return 0; 65 | } 66 | function set(uint256 idx, address value) public returns(int32) { 67 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 68 | entry.fields[idx] = cast.addrToString(value); 69 | return 0; 70 | } 71 | function set(uint256 idx, bytes32 value) public returns(int32) { 72 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 73 | entry.fields[idx] = cast.bytes32ToString(value); 74 | return 0; 75 | } 76 | function set(uint256 idx, bytes1[64] memory value) public returns(int32) { 77 | require(idx >= 0 && idx < fieldSize(), "Index out of range!"); 78 | entry.fields[idx] = string(bytes64ToBytes(value)); 79 | return 0; 80 | } 81 | function setKey(string memory value) public { 82 | entry.key = value; 83 | } 84 | function getKey() public view returns (string memory) { 85 | return entry.key; 86 | } 87 | function bytes64ToBytes(bytes1[64] memory src) private pure returns(bytes memory) { 88 | bytes memory dst = new bytes(64); 89 | for(uint32 i = 0; i < 64; i++) { 90 | dst[i] = src[i][0]; 91 | } 92 | return dst; 93 | } 94 | function bytesToBytes64(bytes memory src) private pure returns(bytes1[64] memory) { 95 | bytes1[64] memory dst; 96 | for(uint32 i = 0; i < 64; i++) { 97 | dst[i] = src[i]; 98 | } 99 | return dst; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/EventTest.sol: -------------------------------------------------------------------------------- 1 | 2 | contract EventTest { 3 | event Echo(uint); 4 | 5 | function check() public { 6 | this.echoDFS(); 7 | } 8 | 9 | function echoDFS() public { 10 | this.dfs(1); 11 | // Event: {"Echo":[[4],[5],[2],[6],[7],[3],[1]]} 12 | } 13 | 14 | function dfs(uint i) public { 15 | if (i >= 8) { 16 | return; 17 | } 18 | 19 | this.dfs(i * 2); 20 | this.dfs(i * 2 + 1); 21 | emit Echo(i); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Evidence.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | contract EvidenceSignersDataABI { 6 | function verify(address addr) public view returns (bool) {} 7 | 8 | function getSigner(uint index) public view returns (address) {} 9 | 10 | function getSignersSize() public view returns (uint) {} 11 | } 12 | 13 | contract Evidence { 14 | string evidence; 15 | string evidenceInfo; 16 | string evidenceId; 17 | uint8[] _v; 18 | bytes32[] _r; 19 | bytes32[] _s; 20 | address[] signers; 21 | address public signersAddr; 22 | 23 | event addSignaturesEvent( 24 | string evi, 25 | string info, 26 | string id, 27 | uint8 v, 28 | bytes32 r, 29 | bytes32 s 30 | ); 31 | event newSignaturesEvent( 32 | string evi, 33 | string info, 34 | string id, 35 | uint8 v, 36 | bytes32 r, 37 | bytes32 s, 38 | address addr 39 | ); 40 | event errorNewSignaturesEvent( 41 | string evi, 42 | string info, 43 | string id, 44 | uint8 v, 45 | bytes32 r, 46 | bytes32 s, 47 | address addr 48 | ); 49 | event errorAddSignaturesEvent( 50 | string evi, 51 | string info, 52 | string id, 53 | uint8 v, 54 | bytes32 r, 55 | bytes32 s, 56 | address addr 57 | ); 58 | event addRepeatSignaturesEvent( 59 | string evi, 60 | string info, 61 | string id, 62 | uint8 v, 63 | bytes32 r, 64 | bytes32 s 65 | ); 66 | event errorRepeatSignaturesEvent( 67 | string evi, 68 | string id, 69 | uint8 v, 70 | bytes32 r, 71 | bytes32 s, 72 | address addr 73 | ); 74 | 75 | function CallVerify(address addr) public view returns (bool) { 76 | return EvidenceSignersDataABI(signersAddr).verify(addr); 77 | } 78 | 79 | constructor( 80 | string memory evi, 81 | string memory info, 82 | string memory id, 83 | uint8 v, 84 | bytes32 r, 85 | bytes32 s, 86 | address addr, 87 | address sender 88 | ) { 89 | signersAddr = addr; 90 | if (CallVerify(sender)) { 91 | evidence = evi; 92 | evidenceInfo = info; 93 | evidenceId = id; 94 | _v.push(v); 95 | _r.push(r); 96 | _s.push(s); 97 | signers.push(sender); 98 | emit newSignaturesEvent(evi, info, id, v, r, s, addr); 99 | } else { 100 | emit errorNewSignaturesEvent(evi, info, id, v, r, s, addr); 101 | } 102 | } 103 | 104 | function getEvidenceInfo() public view returns (string memory) { 105 | return evidenceInfo; 106 | } 107 | 108 | function getEvidence() 109 | public 110 | view 111 | returns ( 112 | string memory, 113 | string memory, 114 | string memory, 115 | uint8[] memory, 116 | bytes32[] memory, 117 | bytes32[] memory, 118 | address[] memory 119 | ) 120 | { 121 | uint length = EvidenceSignersDataABI(signersAddr).getSignersSize(); 122 | address[] memory signerList = new address[](length); 123 | for (uint i = 0; i < length; i++) { 124 | signerList[i] = (EvidenceSignersDataABI(signersAddr).getSigner(i)); 125 | } 126 | return (evidence, evidenceInfo, evidenceId, _v, _r, _s, signerList); 127 | } 128 | 129 | function addSignatures( 130 | uint8 v, 131 | bytes32 r, 132 | bytes32 s 133 | ) public returns (bool) { 134 | for (uint i = 0; i < signers.length; i++) { 135 | if (msg.sender == signers[i]) { 136 | if (_v[i] == v && _r[i] == r && _s[i] == s) { 137 | emit addRepeatSignaturesEvent( 138 | evidence, 139 | evidenceInfo, 140 | evidenceId, 141 | v, 142 | r, 143 | s 144 | ); 145 | return true; 146 | } else { 147 | emit errorRepeatSignaturesEvent( 148 | evidence, 149 | evidenceId, 150 | v, 151 | r, 152 | s, 153 | msg.sender 154 | ); 155 | return false; 156 | } 157 | } 158 | } 159 | if (CallVerify(msg.sender)) { 160 | _v.push(v); 161 | _r.push(r); 162 | _s.push(s); 163 | signers.push(msg.sender); 164 | emit addSignaturesEvent( 165 | evidence, 166 | evidenceInfo, 167 | evidenceId, 168 | v, 169 | r, 170 | s 171 | ); 172 | return true; 173 | } else { 174 | emit errorAddSignaturesEvent( 175 | evidence, 176 | evidenceInfo, 177 | evidenceId, 178 | v, 179 | r, 180 | s, 181 | msg.sender 182 | ); 183 | return false; 184 | } 185 | } 186 | 187 | function getSigners() public view returns (address[] memory) { 188 | uint length = EvidenceSignersDataABI(signersAddr).getSignersSize(); 189 | address[] memory signerList = new address[](length); 190 | for (uint i = 0; i < length; i++) { 191 | signerList[i] = (EvidenceSignersDataABI(signersAddr).getSigner(i)); 192 | } 193 | return signerList; 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/EvidenceOne.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.10 <0.8.20; 2 | pragma experimental ABIEncoderV2; 3 | contract EvidenceOne{ 4 | 5 | mapping (int256 => string) evidence; 6 | // event newEvidenceEvent(string evi, int256 id); 7 | 8 | function getEvidence(int256 id) public view returns(string memory){ 9 | return(evidence[id]); 10 | } 11 | function setEvidence(int256 id, string memory evi) public{ 12 | evidence[id] = evi; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/EvidenceSignersData.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | import "./Evidence.sol"; 5 | 6 | contract EvidenceSignersData { 7 | address[] signers; 8 | event newEvidenceEvent(address addr); 9 | 10 | constructor(address[] memory evidenceSigners) { 11 | for (uint i = 0; i < evidenceSigners.length; ++i) { 12 | signers.push(evidenceSigners[i]); 13 | } 14 | } 15 | 16 | function newEvidence( 17 | string memory evi, 18 | string memory info, 19 | string memory id, 20 | uint8 v, 21 | bytes32 r, 22 | bytes32 s 23 | ) public returns (address) { 24 | Evidence evidence = new Evidence( 25 | evi, 26 | info, 27 | id, 28 | v, 29 | r, 30 | s, 31 | address(this), 32 | msg.sender 33 | ); 34 | emit newEvidenceEvent(address(evidence)); 35 | return address(evidence); 36 | } 37 | 38 | function verify(address addr) public view returns (bool) { 39 | for (uint i = 0; i < signers.length; ++i) { 40 | if (addr == signers[i]) { 41 | return true; 42 | } 43 | } 44 | return false; 45 | } 46 | 47 | function getSigner(uint index) public view returns (address) { 48 | uint listSize = signers.length; 49 | if (index < listSize) { 50 | return signers[index]; 51 | } else { 52 | return address(0); 53 | } 54 | } 55 | 56 | function getSignersSize() public view returns (uint) { 57 | return signers.length; 58 | } 59 | 60 | function getSigners() public view returns (address[] memory) { 61 | return signers; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/EvidenceVerify.sol: -------------------------------------------------------------------------------- 1 | pragma solidity>=0.4.24 <0.6.11; 2 | pragma experimental ABIEncoderV2; 3 | import "./SimpleEvidence.sol"; 4 | 5 | contract EvidenceVerify 6 | { 7 | event newEvidenceEvent(address addr); 8 | function insertEvidence(string evi, string info, string id, address signAddr, bytes32 message, uint8 v, bytes32 r, bytes32 s) public returns(address) 9 | { 10 | address evidence = new SimpleEvidence(evi, info, id); 11 | newEvidenceEvent(evidence); 12 | require(recoverSigner(message,v, r, s) == signAddr); 13 | } 14 | 15 | 16 | function recoverSigner(bytes32 message, uint8 v, bytes32 r, bytes32 s) 17 | internal 18 | pure 19 | returns (address) 20 | { 21 | return ecrecover(message, v, r, s); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Incremental.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity>=0.6.10 <0.8.20; 3 | 4 | contract Incremental { 5 | uint public value = 0; 6 | 7 | event incEvent(string msg); 8 | function inc(string memory msg) public returns(uint) { 9 | value += 1; 10 | emit incEvent(msg); 11 | return value; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/KVTableTest.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=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 | constructor () public{ 13 | tm = TableManager(address(0x1002)); 14 | 15 | // create table 16 | tm.createKVTable(tableName, "key", "value"); 17 | 18 | // get table address 19 | address t_address = tm.openTable(tableName); 20 | table = KVTable(t_address); 21 | } 22 | 23 | function get(string memory id) public view returns (bool, string memory) { 24 | bool ok = false; 25 | string memory value; 26 | (ok, value) = table.get(id); 27 | return (ok, value); 28 | } 29 | 30 | function set(string memory id, string memory item_name) 31 | public 32 | returns (int32) 33 | { 34 | int32 result = table.set(id,item_name); 35 | return result; 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/MainContract.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.8.25; 2 | 3 | import "./StorageSlot.sol"; 4 | import "./ContractA.sol"; 5 | import "./ContractB.sol"; 6 | 7 | contract MainContract { 8 | 9 | function checkAndVerifyIntValue(int256 value) public returns (bool) { 10 | ContractA a = new ContractA(value); 11 | int256 result = a.callContractB(); 12 | require(result == value, "store value not equal tload result"); 13 | return true; 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/MapTest.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.0 < 0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | contract MapTest { 6 | mapping (string => string) _mapSet; 7 | 8 | /////////////////////////string////////////////////// 9 | function get(string memory key) public view returns (string memory) { 10 | return _mapSet[key]; 11 | } 12 | 13 | function set(string memory k, string memory v) public { 14 | _mapSet[k] = v; 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/MultiMapTest.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | import "./Table.sol"; 6 | 7 | contract MultiTableTest { 8 | 9 | 10 | TableManager constant tm = TableManager(address(0x1002)); 11 | Table table; 12 | string constant TABLE_NAME = "t_test"; 13 | constructor () public{ 14 | // create table 15 | string[] memory columnNames = new string[](10); 16 | columnNames[0] = "v0"; 17 | columnNames[1] = "v1"; 18 | columnNames[2] = "v2"; 19 | columnNames[3] = "v3"; 20 | columnNames[4] = "v4"; 21 | columnNames[5] = "v5"; 22 | columnNames[6] = "v6"; 23 | columnNames[7] = "v7"; 24 | columnNames[8] = "v8"; 25 | columnNames[9] = "v9"; 26 | TableInfo memory tf = TableInfo("key", columnNames); 27 | 28 | tm.createTable(TABLE_NAME, tf); 29 | address t_address = tm.openTable(TABLE_NAME); 30 | require(t_address!=address(0x0),""); 31 | table = Table(t_address); 32 | } 33 | 34 | function get(string memory id) public view returns (string memory,string memory 35 | ,string memory,string memory,string memory,string memory,string memory,string memory,string memory 36 | ,string memory) 37 | { 38 | Entry memory entry = table.select(id); 39 | return (entry.fields[0],entry.fields[1],entry.fields[2],entry.fields[3],entry.fields[4],entry.fields[5],entry.fields[6],entry.fields[7],entry.fields[8],entry.fields[9]); 40 | } 41 | 42 | function set(string memory id,string memory v) public{ 43 | string[] memory columns = new string[](10); 44 | columns[0] = v; 45 | columns[1] = v; 46 | columns[2] = v; 47 | columns[3] = v; 48 | columns[4] = v; 49 | columns[5] = v; 50 | columns[6] = v; 51 | columns[7] = v; 52 | columns[8] = v; 53 | columns[9] = v; 54 | Entry memory entry = Entry(id, columns); 55 | table.insert(entry); 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/MultiTableTest.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | import "./Table.sol"; 6 | 7 | contract MultiTableTest { 8 | 9 | TableManager constant tm = TableManager(address(0x1002)); 10 | Table table; 11 | string TABLE_NAME = "t_test"; 12 | constructor (string memory name) public { 13 | // create table 14 | string[] memory columnNames = new string[](10); 15 | columnNames[0] = "v0"; 16 | columnNames[1] = "v1"; 17 | columnNames[2] = "v2"; 18 | columnNames[3] = "v3"; 19 | columnNames[4] = "v4"; 20 | columnNames[5] = "v5"; 21 | columnNames[6] = "v6"; 22 | columnNames[7] = "v7"; 23 | columnNames[8] = "v8"; 24 | columnNames[9] = "v9"; 25 | TableInfo memory tf = TableInfo("key", columnNames); 26 | TABLE_NAME = name; 27 | tm.createTable(TABLE_NAME, tf); 28 | address t_address = tm.openTable(TABLE_NAME); 29 | require(t_address!=address(0x0),""); 30 | table = Table(t_address); 31 | } 32 | 33 | function get(string memory id) public view returns (string memory,string memory 34 | ,string memory,string memory,string memory,string memory,string memory,string memory,string memory 35 | ,string memory) 36 | { 37 | Entry memory entry = table.select(id); 38 | return (entry.fields[0],entry.fields[1],entry.fields[2],entry.fields[3],entry.fields[4],entry.fields[5],entry.fields[6],entry.fields[7],entry.fields[8],entry.fields[9]); 39 | } 40 | 41 | function set(string memory id,string memory v) public{ 42 | string[] memory columns = new string[](10); 43 | columns[0] = v; 44 | columns[1] = v; 45 | columns[2] = v; 46 | columns[3] = v; 47 | columns[4] = v; 48 | columns[5] = v; 49 | columns[6] = v; 50 | columns[7] = v; 51 | columns[8] = v; 52 | columns[9] = v; 53 | Entry memory entry = Entry(id, columns); 54 | table.insert(entry); 55 | } 56 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/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 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/OkD.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.25; 2 | import "./Table.sol"; 3 | 4 | contract OkD{ 5 | event insertResult(int count); 6 | 7 | struct Account{ 8 | address account; 9 | int balance; 10 | } 11 | 12 | Account from; 13 | Account to; 14 | 15 | constructor(){ 16 | 17 | from.account=0x1; 18 | from.balance=10000000000; 19 | to.account=0x2; 20 | to.balance=0; 21 | 22 | TableFactory tf = TableFactory(0x1001); 23 | tf.createTable("t_ok", "from_accout", "from_balance,to_accout,to_balance"); 24 | tf = TableFactory(0x1001); 25 | Table table = tf.openTable("t_ok"); 26 | Entry entry = table.newEntry(); 27 | entry.set("from_accout", "0x1"); 28 | entry.set("from_balance", "10000000000"); 29 | entry.set("to_accout", "0x2"); 30 | entry.set("to_balance", "0"); 31 | table.insert(entry); 32 | } 33 | function get()constant returns(int){ 34 | return to.balance; 35 | } 36 | function trans(string from_accout, int num){ 37 | 38 | if (from.balance < num || to.balance + num < to.balance) 39 | return; // Deny overflow 40 | 41 | from.balance = from.balance - num; 42 | to.balance += num; 43 | 44 | TableFactory tf = TableFactory(0x1001); 45 | Table table = tf.openTable("t_ok"); 46 | Entry entry = table.newEntry(); 47 | entry.set("from_accout", from_accout); 48 | entry.set("from_balance", from.balance); 49 | entry.set("to_accout", "0x2"); 50 | entry.set("to_balance", to.balance); 51 | int count = table.insert(entry); 52 | insertResult(count); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelContract.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.0; 2 | 3 | interface ParallelConfigPrecompiled 4 | { 5 | function registerParallelFunctionInternal(address, string memory, uint256) public virtual returns (int); 6 | function unregisterParallelFunctionInternal(address, string memory) public virtual returns (int); 7 | } 8 | 9 | interface ParallelContract 10 | { 11 | ParallelConfigPrecompiled precompiled = ParallelConfigPrecompiled(0x1006); 12 | 13 | function registerParallelFunction(string memory functionName, uint256 criticalSize) public 14 | { 15 | precompiled.registerParallelFunctionInternal(address(this), functionName, criticalSize); 16 | } 17 | 18 | function unregisterParallelFunction(string memory functionName) public 19 | { 20 | precompiled.unregisterParallelFunctionInternal(address(this), functionName); 21 | } 22 | 23 | function enableParallel() public virtual; 24 | function disableParallel() public virtual; 25 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelCpuHeavy.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.0; 2 | 3 | import "./ParallelContract.sol"; 4 | 5 | contract ParallelCpuHeavy is ParallelContract { 6 | event finish(uint size, uint signature); 7 | 8 | function sort(uint size, uint signature) public { 9 | uint[] memory data = new uint[](size); 10 | for (uint x = 0; x < data.length; x++) { 11 | data[x] = size-x; 12 | } 13 | quickSort(data, 0, int(data.length - 1)); 14 | emit finish(size, signature); 15 | } 16 | 17 | function quickSort(uint[] memory arr, int left, int right) private { 18 | int i = left; 19 | int j = right; 20 | if (i == j) return; 21 | uint pivot = arr[uint(left + (right - left) / 2)]; 22 | while (i <= j) { 23 | while (arr[uint(i)] < pivot) i++; 24 | while (pivot < arr[uint(j)]) j--; 25 | if (i <= j) { 26 | (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); 27 | i++; 28 | j--; 29 | } 30 | } 31 | if (left < j) 32 | quickSort(arr, left, j); 33 | if (i < right) 34 | quickSort(arr, i, right); 35 | } 36 | 37 | // Register parallel function 38 | function enableParallel() public override 39 | { 40 | // critical number is to define how many critical params from start 41 | registerParallelFunction("sort(uint256,uint256)", 0); // full para execution 42 | } 43 | 44 | // Disable register parallel function 45 | function disableParallel() public override 46 | { 47 | unregisterParallelFunction("sort(uint256,uint256)"); 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelOk.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.10 <0.8.20; 2 | pragma experimental ABIEncoderV2; 3 | 4 | // A parallel contract example 5 | contract ParallelOk 6 | { 7 | mapping (string => uint256) _balance; 8 | 9 | // Just an example, overflow is ok, use 'SafeMath' if needed 10 | function transfer(string memory from, string memory to, uint256 num) public 11 | { 12 | _balance[from] -= num; 13 | _balance[to] += num; 14 | } 15 | 16 | // Just for testing whether the parallel revert function is working well, no practical use 17 | function transferWithRevert(string memory from, string memory to, uint256 num) public 18 | { 19 | _balance[from] -= num; 20 | _balance[to] += num; 21 | require(num <= 100); 22 | } 23 | 24 | function set(string memory name, uint256 num) public 25 | { 26 | _balance[name] = num; 27 | } 28 | 29 | function balanceOf(string memory name) public view returns (uint256) 30 | { 31 | return _balance[name]; 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ProxyTest.sol: -------------------------------------------------------------------------------- 1 | 2 | import "./DelegateCall.sol"; 3 | 4 | /** 5 | * @title Proxy 6 | * @dev Gives the possibility to delegate any call to a foreign implementation. 7 | */ 8 | abstract contract Proxy { 9 | /** 10 | * @dev Tells the address of the implementation where every call will be delegated. 11 | * @return address of the implementation to which it will be delegated 12 | */ 13 | function implementation() virtual public view returns (address); 14 | 15 | /** 16 | * @dev Tells the type of proxy (EIP 897) 17 | * @return proxyTypeId Type of proxy, 2 for upgradeable proxy 18 | */ 19 | function proxyType() virtual public pure returns (uint256 proxyTypeId); 20 | 21 | /** 22 | * @dev Fallback function allowing to perform a delegatecall to the given implementation. 23 | * This function will return whatever the implementation call returns 24 | */ 25 | fallback () external payable { 26 | address _impl = implementation(); 27 | require(_impl != address(0), "Proxy implementation required"); 28 | 29 | assembly { 30 | let ptr := mload(0x40) 31 | calldatacopy(ptr, 0, calldatasize()) 32 | let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) 33 | let size := returndatasize() 34 | returndatacopy(ptr, 0, size) 35 | 36 | switch result 37 | case 0 { revert(ptr, size) } 38 | default { return(ptr, size) } 39 | } 40 | } 41 | } 42 | 43 | contract ProxyImpl is Proxy { 44 | // put implementation address as far as possible to make sure that it will not be at the same location as in the Proxy contract 45 | address[1024] private gaps_; 46 | address public implementation_; 47 | 48 | constructor(address implementation) public { 49 | implementation_ = implementation; 50 | } 51 | 52 | function implementation() override public view returns (address) { 53 | return implementation_; 54 | } 55 | 56 | function proxyType() override public pure returns (uint256 proxyTypeId) { 57 | return 2; 58 | } 59 | } 60 | 61 | contract ProxyTest { 62 | event Info(string, address); 63 | event RunInfo(string, string); 64 | Proxy proxy = new ProxyImpl(address(new DelegateCall())); 65 | 66 | 67 | function run(string memory func) private { 68 | (bool success, bytes memory ret) = address(proxy).call(abi.encodeWithSignature(func)); 69 | if (success) { 70 | emit RunInfo(func, "success"); 71 | } else { 72 | emit RunInfo(func, "failed"); 73 | } 74 | } 75 | 76 | function check() public { 77 | run("testFailed()"); 78 | run("testSuccess()"); 79 | run("testFallback()"); 80 | run("testCallInDelegateCall()"); 81 | run("testDelegateCallSender()"); 82 | run("testCallcodeSender()"); 83 | run("testEventInDelegateCall()"); 84 | run("testCatchInDelegateCallThrow()"); 85 | } 86 | 87 | function test() public { 88 | address impl = proxy.implementation(); 89 | emit Info("DelegateCall contract addr", impl); 90 | DelegateCall(impl).testEventInDelegateCall(); 91 | } 92 | 93 | function test1() public { 94 | run("testEventInDelegateCall()"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/SM2EvidenceVerify.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.10 <0.8.20; 2 | pragma experimental ABIEncoderV2; 3 | import "./Evidence.sol"; 4 | import "./Crypto.sol"; 5 | 6 | contract SM2EvidenceVerify 7 | { 8 | Crypto crypto; 9 | event newEvidenceEvent(address addr); 10 | constructor() public 11 | { 12 | crypto = Crypto(address(0x100a)); 13 | } 14 | function insertEvidence(string memory evi, string memory info, string memory id, address signAddr, bytes32 message, bytes memory pubKey, bytes32 r, bytes32 s) public returns(bool, address) 15 | { 16 | Evidence evidence = new Evidence(evi, info, id); 17 | emit newEvidenceEvent(address(evidence)); 18 | address recoverSignAddr; 19 | bool succ = false; 20 | 21 | (succ, recoverSignAddr) = recoverSigner(message, pubKey, r, s); 22 | require( recoverSignAddr == signAddr); 23 | require( succ == true); 24 | } 25 | 26 | function recoverSigner(bytes32 message, bytes memory pubKey, bytes32 r, bytes32 s) 27 | internal 28 | view 29 | returns (bool, address) 30 | { 31 | return crypto.sm2Verify(message, pubKey, r, s); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/SafeMath.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.8.0; 2 | 3 | /** 4 | * @dev Wrappers over Solidity's arithmetic operations with added overflow 5 | * checks. 6 | * 7 | * Arithmetic operations in Solidity wrap on overflow. This can easily result 8 | * in bugs, because programmers usually assume that an overflow raises an 9 | * error, which is the standard behavior in high level programming languages. 10 | * `SafeMath` restores this intuition by reverting the transaction when an 11 | * operation overflows. 12 | * 13 | * Using this library instead of the unchecked operations eliminates an entire 14 | * class of bugs, so it's recommended to use it always. 15 | */ 16 | library SafeMath { 17 | /** 18 | * @dev Returns the addition of two unsigned integers, reverting on 19 | * overflow. 20 | * 21 | * Counterpart to Solidity's `+` operator. 22 | * 23 | * Requirements: 24 | * - Addition cannot overflow. 25 | */ 26 | function add(uint256 a, uint256 b) internal pure returns (uint256) { 27 | uint256 c = a + b; 28 | require(c >= a, "SafeMath: addition overflow"); 29 | 30 | return c; 31 | } 32 | 33 | /** 34 | * @dev Returns the subtraction of two unsigned integers, reverting on 35 | * overflow (when the result is negative). 36 | * 37 | * Counterpart to Solidity's `-` operator. 38 | * 39 | * Requirements: 40 | * - Subtraction cannot overflow. 41 | */ 42 | function sub(uint256 a, uint256 b) internal pure returns (uint256) { 43 | return sub(a, b, "SafeMath: subtraction overflow"); 44 | } 45 | 46 | /** 47 | * @dev Returns the subtraction of two unsigned integers, reverting with custom message on 48 | * overflow (when the result is negative). 49 | * 50 | * Counterpart to Solidity's `-` operator. 51 | * 52 | * Requirements: 53 | * - Subtraction cannot overflow. 54 | */ 55 | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 56 | require(b <= a, errorMessage); 57 | uint256 c = a - b; 58 | 59 | return c; 60 | } 61 | 62 | /** 63 | * @dev Returns the multiplication of two unsigned integers, reverting on 64 | * overflow. 65 | * 66 | * Counterpart to Solidity's `*` operator. 67 | * 68 | * Requirements: 69 | * - Multiplication cannot overflow. 70 | */ 71 | function mul(uint256 a, uint256 b) internal pure returns (uint256) { 72 | // Gas optimization: this is cheaper than requiring 'a' not being zero, but the 73 | // benefit is lost if 'b' is also tested. 74 | // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 75 | if (a == 0) { 76 | return 0; 77 | } 78 | 79 | uint256 c = a * b; 80 | require(c / a == b, "SafeMath: multiplication overflow"); 81 | 82 | return c; 83 | } 84 | 85 | /** 86 | * @dev Returns the integer division of two unsigned integers. Reverts on 87 | * division by zero. The result is rounded towards zero. 88 | * 89 | * Counterpart to Solidity's `/` operator. Note: this function uses a 90 | * `revert` opcode (which leaves remaining gas untouched) while Solidity 91 | * uses an invalid opcode to revert (consuming all remaining gas). 92 | * 93 | * Requirements: 94 | * - The divisor cannot be zero. 95 | */ 96 | function div(uint256 a, uint256 b) internal pure returns (uint256) { 97 | return div(a, b, "SafeMath: division by zero"); 98 | } 99 | 100 | /** 101 | * @dev Returns the integer division of two unsigned integers. Reverts with custom message on 102 | * division by zero. The result is rounded towards zero. 103 | * 104 | * Counterpart to Solidity's `/` operator. Note: this function uses a 105 | * `revert` opcode (which leaves remaining gas untouched) while Solidity 106 | * uses an invalid opcode to revert (consuming all remaining gas). 107 | * 108 | * Requirements: 109 | * - The divisor cannot be zero. 110 | */ 111 | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 112 | // Solidity only automatically asserts when dividing by 0 113 | require(b > 0, errorMessage); 114 | uint256 c = a / b; 115 | // assert(a == b * c + a % b); // There is no case in which this doesn't hold 116 | 117 | return c; 118 | } 119 | 120 | /** 121 | * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), 122 | * Reverts when dividing by zero. 123 | * 124 | * Counterpart to Solidity's `%` operator. This function uses a `revert` 125 | * opcode (which leaves remaining gas untouched) while Solidity uses an 126 | * invalid opcode to revert (consuming all remaining gas). 127 | * 128 | * Requirements: 129 | * - The divisor cannot be zero. 130 | */ 131 | function mod(uint256 a, uint256 b) internal pure returns (uint256) { 132 | return mod(a, b, "SafeMath: modulo by zero"); 133 | } 134 | 135 | /** 136 | * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), 137 | * Reverts with custom message when dividing by zero. 138 | * 139 | * Counterpart to Solidity's `%` operator. This function uses a `revert` 140 | * opcode (which leaves remaining gas untouched) while Solidity uses an 141 | * invalid opcode to revert (consuming all remaining gas). 142 | * 143 | * Requirements: 144 | * - The divisor cannot be zero. 145 | */ 146 | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 147 | require(b != 0, errorMessage); 148 | return a % b; 149 | } 150 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/SimpleEvidence.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.10 <0.8.20; 2 | pragma experimental ABIEncoderV2; 3 | contract SimpleEvidence{ 4 | string evidence; 5 | int256 evidenceId; 6 | // event newEvidenceEvent(string evi, int256 id); 7 | constructor(string memory evi, int256 id) public 8 | { 9 | evidence = evi; 10 | evidenceId = id; 11 | // emit newEvidenceEvent(evi,id); 12 | } 13 | 14 | function getEvidence() public view returns(string memory,int256){ 15 | return(evidence,evidenceId); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/SimpleEvidenceFactory.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | import "./SimpleEvidence.sol"; 5 | 6 | contract SimpleEvidenceFactory { 7 | event newEvidenceEvent(address addr); 8 | 9 | function newEvidence( 10 | string memory evidence, 11 | int256 id 12 | ) public { 13 | SimpleEvidence evi = new SimpleEvidence(evidence, id); 14 | emit newEvidenceEvent(address(evi)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/SmallBank.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | contract SmallBank { 6 | 7 | //uint constant MAX_ACCOUNT = 10000; 8 | //uint constant BALANCE = 10000; 9 | //bytes20 constant accountTab = "account"; 10 | //bytes20 constant savingTab = "saving"; 11 | //bytes20 constant checkingTab = "checking"; 12 | 13 | mapping(string=>uint) savingStore; 14 | mapping(string=>uint) checkingStore; 15 | 16 | function almagate(string memory arg0, string memory arg1) public { 17 | uint bal1 = savingStore[arg0]; 18 | uint bal2 = checkingStore[arg1]; 19 | 20 | checkingStore[arg0] = 0; 21 | savingStore[arg1] = bal1 + bal2; 22 | } 23 | 24 | function getBalance(string memory arg0) public view returns (uint balance) { 25 | uint bal1 = savingStore[arg0]; 26 | uint bal2 = checkingStore[arg0]; 27 | 28 | balance = bal1 + bal2; 29 | return balance; 30 | } 31 | 32 | function updateBalance(string memory arg0, uint arg1) public { 33 | uint bal1 = checkingStore[arg0]; 34 | uint bal2 = arg1; 35 | 36 | checkingStore[arg0] = bal1 + bal2; 37 | } 38 | 39 | function updateSaving(string memory arg0, uint arg1) public { 40 | uint bal1 = savingStore[arg0]; 41 | uint bal2 = arg1; 42 | 43 | savingStore[arg0] = bal1 + bal2; 44 | } 45 | 46 | function sendPayment(string memory arg0, string memory arg1, uint arg2) public { 47 | checkingStore[arg0] -= arg2; 48 | checkingStore[arg1] += arg2; 49 | } 50 | 51 | function writeCheck(string memory arg0, uint arg1) public { 52 | uint bal1 = checkingStore[arg0]; 53 | uint bal2 = savingStore[arg0]; 54 | uint amount = arg1; 55 | 56 | if (amount < bal1 + bal2) { 57 | checkingStore[arg0] = bal1 - amount - 1; 58 | } 59 | else { 60 | checkingStore[arg0] = bal1 - amount; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/StaticCall.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.0 <0.8.12; 2 | 3 | import "./ProxyTest.sol"; 4 | 5 | contract StaticCall { 6 | HelloWorld helloWorld = new HelloWorld(); 7 | event Result(bytes); 8 | event Result(uint); 9 | 10 | modifier initIfNot() { 11 | if (address(helloWorld) == address(0)) { 12 | helloWorld = new HelloWorld(); 13 | } 14 | _; 15 | } 16 | 17 | function staticCallASM(address target, bytes memory data) 18 | internal 19 | view 20 | returns (bool result) 21 | { 22 | assembly { 23 | result := staticcall(gas(), target, add(data, 0x20), mload(data), mload(0x40), 0) 24 | } 25 | return result; 26 | } 27 | 28 | function staticCallUintASM(address target, bytes memory data) 29 | internal 30 | view 31 | returns (bool, uint) 32 | { 33 | uint ret; 34 | bool result; 35 | assembly { 36 | let size := 0x20 37 | let free := mload(0x40) 38 | result := staticcall(gas(), target, add(data, 0x20), mload(data), free, size) 39 | ret := mload(free) 40 | } 41 | return (result, ret); 42 | } 43 | 44 | function getAddress() public view returns (address) { 45 | return address(helloWorld); 46 | } 47 | 48 | function testOk() public returns(bytes memory){ 49 | (bool ok, bytes memory result) = address(helloWorld).staticcall(abi.encodeWithSignature("get()")); 50 | require(ok); 51 | emit Result(result); 52 | return result; 53 | } 54 | 55 | function testFailed() public { 56 | (bool ok, bytes memory result) = address(helloWorld).staticcall(abi.encodeWithSignature("set(string)", "aaa")); 57 | require(ok, "staticcall must call view/pure function"); 58 | } 59 | 60 | function testASMOk() public returns(uint){ 61 | bytes memory data = abi.encodeWithSignature("getNum()"); 62 | bool ok = staticCallASM(address(helloWorld), data); 63 | require(ok); 64 | uint ret; 65 | (ok, ret) = staticCallUintASM(address(helloWorld), data); 66 | require(ok); 67 | require(ret == 100); 68 | emit Result(ret); 69 | return ret; 70 | } 71 | 72 | function testASMFailed() public { 73 | bytes memory data = abi.encodeWithSignature("setNum(uint256)", 222); 74 | bool ok = staticCallASM(address(helloWorld), data); 75 | require(!ok); 76 | } 77 | 78 | function testASMUintFailed() public { 79 | bytes memory data = abi.encodeWithSignature("setNum(uint256)", 222); 80 | (bool ok, uint ret) = staticCallUintASM(address(helloWorld), data); 81 | require(!ok); 82 | } 83 | 84 | function testEmptyAddr() public { 85 | (bool ok, bytes memory result) = address(0x10016666666).staticcall(abi.encodeWithSignature("get()")); 86 | require(ok, "addr not exist but must return ok to be the same as eth"); 87 | require(result.length == 0, "result must be empty"); 88 | } 89 | 90 | function checkOk() public initIfNot { 91 | (bool ok, bytes memory result) = address(helloWorld).staticcall(abi.encodeWithSignature("get()")); 92 | require(ok); 93 | 94 | testASMOk(); 95 | } 96 | 97 | function checkFailed() public { 98 | testEmptyAddr(); 99 | 100 | (bool ok, bytes memory result) = address(helloWorld).staticcall(abi.encodeWithSignature("set(string)", "aaa")); 101 | require(!ok, "staticcall a state write function must return not ok"); 102 | require(result.length == 0, string(abi.encodePacked("staticcall failed for has result: ", result))); 103 | 104 | testASMFailed(); 105 | testASMUintFailed(); 106 | } 107 | 108 | event Info(string, uint256); 109 | function check() public { 110 | uint256 gasBefore = gasleft(); 111 | checkOk(); 112 | uint256 gasAfter = gasleft(); 113 | emit Info("gas used on checkOk(): ", gasBefore - gasAfter); 114 | 115 | Proxy proxy = new ProxyImpl(address(this)); 116 | gasBefore = gasleft(); 117 | (bool success, bytes memory reason) = address(proxy).call(abi.encodeWithSignature("checkOk()")); 118 | gasAfter = gasleft(); 119 | require(success, string(abi.encodePacked("checkOk() by proxy failed: ", reason))); 120 | emit Info("gas used on checkOk() by proxy: ", gasBefore - gasAfter); 121 | 122 | // staticcall failed will cost half of the gas 123 | // There are many staticcall failed in checkFailed(), will cost most of the gas. So we need to put it in the end. 124 | gasBefore = gasleft(); 125 | (success, reason) = address(proxy).call(abi.encodeWithSignature("checkFailed()")); 126 | gasAfter = gasleft(); 127 | require(success, string(abi.encodePacked("checkFailed() by proxy failed: ", reason))); 128 | emit Info("gas used on checkFailed() by proxy: ", gasBefore - gasAfter); 129 | } 130 | 131 | function get() public view returns (string memory) { 132 | return helloWorld.get(); 133 | } 134 | 135 | function set(string memory n) public { 136 | helloWorld.set(n); 137 | } 138 | } 139 | 140 | contract HelloWorld { 141 | string name; 142 | uint num = 100; 143 | 144 | constructor() public { 145 | name = "Hello, World!"; 146 | } 147 | 148 | function get() public view returns (string memory) { 149 | return name; 150 | } 151 | 152 | function set(string memory n) public { 153 | name = n; 154 | } 155 | 156 | function getNum() public view returns (uint) { 157 | return num; 158 | } 159 | 160 | function setNum(uint n) public { 161 | num = n; 162 | } 163 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/StorageSlot.sol: -------------------------------------------------------------------------------- 1 | pragma solidity>=0.6.10 <=0.8.26; 2 | 3 | library StorageSlot { 4 | struct AddressSlot { 5 | address value; 6 | } 7 | 8 | struct BooleanSlot { 9 | bool value; 10 | } 11 | 12 | struct Bytes32Slot { 13 | bytes32 value; 14 | } 15 | 16 | struct Uint256Slot { 17 | uint256 value; 18 | } 19 | 20 | struct Int256Slot { 21 | int256 value; 22 | } 23 | 24 | struct StringSlot { 25 | string value; 26 | } 27 | 28 | struct BytesSlot { 29 | bytes value; 30 | } 31 | 32 | function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { 33 | assembly { 34 | r.slot := slot 35 | } 36 | } 37 | 38 | function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { 39 | /// @solidity memory-safe-assembly 40 | assembly { 41 | r.slot := slot 42 | } 43 | } 44 | 45 | function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { 46 | /// @solidity memory-safe-assembly 47 | assembly { 48 | r.slot := slot 49 | } 50 | } 51 | 52 | function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { 53 | /// @solidity memory-safe-assembly 54 | assembly { 55 | r.slot := slot 56 | } 57 | } 58 | 59 | function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) { 60 | /// @solidity memory-safe-assembly 61 | assembly { 62 | r.slot := slot 63 | } 64 | } 65 | 66 | function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { 67 | /// @solidity memory-safe-assembly 68 | assembly { 69 | r.slot := slot 70 | } 71 | } 72 | 73 | function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { 74 | /// @solidity memory-safe-assembly 75 | assembly { 76 | r.slot := store.slot 77 | } 78 | } 79 | 80 | function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { 81 | /// @solidity memory-safe-assembly 82 | assembly { 83 | r.slot := slot 84 | } 85 | } 86 | 87 | function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { 88 | /// @solidity memory-safe-assembly 89 | assembly { 90 | r.slot := store.slot 91 | } 92 | } 93 | 94 | type AddressSlotType is bytes32; 95 | 96 | function asAddress(bytes32 slot) internal pure returns (AddressSlotType) { 97 | return AddressSlotType.wrap(slot); 98 | } 99 | 100 | type BooleanSlotType is bytes32; 101 | 102 | function asBoolean(bytes32 slot) internal pure returns (BooleanSlotType) { 103 | return BooleanSlotType.wrap(slot); 104 | } 105 | 106 | type Bytes32SlotType is bytes32; 107 | 108 | function asBytes32(bytes32 slot) internal pure returns (Bytes32SlotType) { 109 | return Bytes32SlotType.wrap(slot); 110 | } 111 | 112 | type Uint256SlotType is bytes32; 113 | 114 | function asUint256(bytes32 slot) internal pure returns (Uint256SlotType) { 115 | return Uint256SlotType.wrap(slot); 116 | } 117 | 118 | type Int256SlotType is bytes32; 119 | 120 | function asInt256(bytes32 slot) internal pure returns (Int256SlotType) { 121 | return Int256SlotType.wrap(slot); 122 | } 123 | 124 | function tload(AddressSlotType slot) internal view returns (address value) { 125 | /// @solidity memory-safe-assembly 126 | assembly { 127 | value := tload(slot) 128 | } 129 | } 130 | 131 | function tstore(AddressSlotType slot, address value) internal { 132 | /// @solidity memory-safe-assembly 133 | assembly { 134 | tstore(slot, value) 135 | } 136 | } 137 | 138 | function tload(BooleanSlotType slot) internal view returns (bool value) { 139 | /// @solidity memory-safe-assembly 140 | assembly { 141 | value := tload(slot) 142 | } 143 | } 144 | 145 | function tstore(BooleanSlotType slot, bool value) internal { 146 | /// @solidity memory-safe-assembly 147 | assembly { 148 | tstore(slot, value) 149 | } 150 | } 151 | 152 | function tload(Bytes32SlotType slot) internal view returns (bytes32 value) { 153 | /// @solidity memory-safe-assembly 154 | assembly { 155 | value := tload(slot) 156 | } 157 | } 158 | 159 | function tstore(Bytes32SlotType slot, bytes32 value) internal { 160 | /// @solidity memory-safe-assembly 161 | assembly { 162 | tstore(slot, value) 163 | } 164 | } 165 | 166 | function tload(Uint256SlotType slot) internal view returns (uint256 value) { 167 | /// @solidity memory-safe-assembly 168 | assembly { 169 | value := tload(slot) 170 | } 171 | } 172 | 173 | function tstore(Uint256SlotType slot, uint256 value) internal { 174 | /// @solidity memory-safe-assembly 175 | assembly { 176 | tstore(slot, value) 177 | } 178 | } 179 | 180 | function tload(Int256SlotType slot) internal view returns (int256 value) { 181 | /// @solidity memory-safe-assembly 182 | assembly { 183 | value := tload(slot) 184 | } 185 | } 186 | 187 | function tstore(Int256SlotType slot, int256 value) internal { 188 | /// @solidity memory-safe-assembly 189 | assembly { 190 | tstore(slot, value) 191 | } 192 | } 193 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Table.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | // KeyOrder指定Key的排序规则,字典序和数字序,如果指定为数字序,key只能为数字 6 | // enum KeyOrder {Lexicographic, Numerical} 7 | struct TableInfo { 8 | string keyColumn; 9 | string[] valueColumns; 10 | } 11 | 12 | // 记录,用于select和insert 13 | struct Entry { 14 | string key; 15 | string[] fields; // 考虑2.0的Entry接口,临时Precompiled的问题,考虑加工具类接口 16 | } 17 | 18 | // 更新字段,用于update 19 | struct UpdateField { 20 | string columnName; 21 | // 考虑工具类 22 | string value; 23 | } 24 | 25 | // 筛选条件,大于、大于等于、小于、小于等于 26 | enum ConditionOP {GT, GE, LT, LE} 27 | struct Condition { 28 | ConditionOP op; 29 | // string field; 30 | string value; 31 | } 32 | 33 | // 数量限制 34 | struct Limit { 35 | uint32 offset; 36 | // count limit max is 500 37 | uint32 count; 38 | } 39 | 40 | // 表管理合约,是静态Precompiled,有固定的合约地址 41 | abstract contract TableManager { 42 | // 创建表,传入TableInfo 43 | function createTable(string memory path, TableInfo memory tableInfo) public virtual returns (int32); 44 | 45 | // 创建KV表,传入key和value字段名 46 | function createKVTable(string memory tableName, string memory keyField, string memory valueField) public virtual returns (int32); 47 | 48 | // 只提供给Solidity合约调用时使用 49 | function openTable(string memory path) public view virtual returns (address); 50 | 51 | // 变更表字段 52 | // 只能新增字段,不能删除字段,新增的字段默认值为空,不能与原有字段重复 53 | function appendColumns(string memory path, string[] memory newColumns) public virtual returns (int32); 54 | 55 | // 获取表信息 56 | function desc(string memory tableName) public view virtual returns (TableInfo memory); 57 | } 58 | 59 | // 表合约,是动态Precompiled,TableManager创建时指定地址 60 | abstract contract Table { 61 | // 按key查询entry 62 | function select(string memory key) public virtual view returns (Entry memory); 63 | 64 | // 按条件批量查询entry,condition为空则查询所有记录 65 | function select(Condition[] memory conditions, Limit memory limit) public virtual view returns (Entry[] memory); 66 | 67 | // 按照条件查询count数据 68 | function count(Condition[] memory conditions) public virtual view returns (uint32); 69 | 70 | // 插入数据 71 | function insert(Entry memory entry) public virtual returns (int32); 72 | 73 | // 按key更新entry 74 | function update(string memory key, UpdateField[] memory updateFields) public virtual returns (int32); 75 | 76 | // 按条件批量更新entry,condition为空则更新所有记录 77 | function update(Condition[] memory conditions, Limit memory limit, UpdateField[] memory updateFields) public virtual returns (int32); 78 | 79 | // 按key删除entry 80 | function remove(string memory key) public virtual returns (int32); 81 | // 按条件批量删除entry,condition为空则删除所有记录 82 | function remove(Condition[] memory conditions, Limit memory limit) public virtual returns (int32); 83 | } 84 | 85 | abstract contract KVTable { 86 | function get(string memory key) public view virtual returns (bool, string memory); 87 | 88 | function set(string memory key, string memory value) public virtual returns (int32); 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/TablePrecompiledTest.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | import "./TableTestV320.sol"; 6 | 7 | contract TablePrecompiledTest { 8 | 9 | function check() public { 10 | TableTestV320 test = new TableTestV320(); 11 | test.select(1, 100); // should not revert 12 | } 13 | 14 | 15 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/TableTest.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | import "./Table.sol"; 6 | 7 | contract TableTest { 8 | event CreateResult(int256 count); 9 | event InsertResult(int256 count); 10 | event UpdateResult(int256 count); 11 | event RemoveResult(int256 count); 12 | 13 | TableManager constant tm = TableManager(address(0x1002)); 14 | Table table; 15 | string constant TABLE_NAME = "t_test"; 16 | constructor () public{ 17 | // create table 18 | string[] memory columnNames = new string[](2); 19 | columnNames[0] = "name"; 20 | columnNames[1] = "age"; 21 | TableInfo memory tf = TableInfo("id", columnNames); 22 | 23 | tm.createTable(TABLE_NAME, tf); 24 | address t_address = tm.openTable(TABLE_NAME); 25 | require(t_address!=address(0x0),""); 26 | table = Table(t_address); 27 | } 28 | 29 | function select(string memory id) public view returns (string memory,string memory) 30 | { 31 | Entry memory entry = table.select(id); 32 | 33 | string memory name; 34 | string memory age; 35 | if(entry.fields.length==2){ 36 | name = entry.fields[0]; 37 | age = entry.fields[1]; 38 | } 39 | return (name,age); 40 | } 41 | 42 | function insert(string memory id,string memory name,string memory age) public returns (int32){ 43 | string[] memory columns = new string[](2); 44 | columns[0] = name; 45 | columns[1] = age; 46 | Entry memory entry = Entry(id, columns); 47 | int32 result = table.insert(entry); 48 | emit InsertResult(result); 49 | return result; 50 | } 51 | 52 | function update(string memory id, string memory name, string memory age) public returns (int32){ 53 | UpdateField[] memory updateFields = new UpdateField[](2); 54 | updateFields[0] = UpdateField("name", name); 55 | updateFields[1] = UpdateField("age", age); 56 | 57 | int32 result = table.update(id, updateFields); 58 | emit UpdateResult(result); 59 | return result; 60 | } 61 | 62 | function remove(string memory id) public returns(int32){ 63 | int32 result = table.remove(id); 64 | emit RemoveResult(result); 65 | return result; 66 | } 67 | 68 | function createTable(string memory tableName,string memory key,string[] memory fields) public returns(int256){ 69 | TableInfo memory tf = TableInfo(key, fields); 70 | int32 result = tm.createTable(tableName,tf); 71 | address t_address = tm.openTable(tableName); 72 | require(t_address!=address(0x0),"empty address"); 73 | table = Table(t_address); 74 | emit CreateResult(result); 75 | return result; 76 | } 77 | 78 | function desc() public view returns(string memory, string[] memory){ 79 | TableInfo memory ti = tm.desc(TABLE_NAME); 80 | return (ti.keyColumn,ti.valueColumns); 81 | } 82 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/TableTestV320.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity >=0.6.10 <0.8.20; 3 | pragma experimental ABIEncoderV2; 4 | 5 | import "./TableV320.sol"; 6 | import "./Cast.sol"; 7 | 8 | contract TableTestV320 { 9 | event CreateResult(int256 count); 10 | event InsertResult(int256 count); 11 | event UpdateResult(int256 count); 12 | event RemoveResult(int256 count); 13 | 14 | Cast constant cast = Cast(address(0x100f)); 15 | TableManager constant tm = TableManager(address(0x1002)); 16 | Table table; 17 | string constant TABLE_NAME = "t_testV320"; 18 | constructor () public { 19 | // create table 20 | string[] memory columnNames = new string[](3); 21 | columnNames[0] = "name"; 22 | columnNames[1] = "age"; 23 | columnNames[2] = "status"; 24 | TableInfo memory tf = TableInfo(KeyOrder.Numerical ,"id", columnNames); 25 | 26 | tm.createTable(TABLE_NAME, tf); 27 | address t_address = tm.openTable(TABLE_NAME); 28 | require(t_address!=address(0x0),""); 29 | table = Table(t_address); 30 | } 31 | 32 | function getTableAddress() public view returns (address){ 33 | return address(table); 34 | } 35 | 36 | function select(int64 id) public view returns (string memory, string memory) 37 | { 38 | Entry memory entry = table.select(cast.s64ToString(id)); 39 | string memory name; 40 | string memory age; 41 | if(entry.fields.length == 3){ 42 | name = entry.fields[0]; 43 | age = entry.fields[1]; 44 | } 45 | return (name, age); 46 | } 47 | 48 | function insert(int64 id, string memory name, string memory age) public returns (int32){ 49 | Entry memory entry = Entry(cast.s64ToString(id), new string[](3)); 50 | entry.fields[0] = name; 51 | entry.fields[1] = age; 52 | entry.fields[2] = "init"; 53 | int32 result = table.insert(entry); 54 | emit InsertResult(result); 55 | return result; 56 | } 57 | 58 | function update(int64 id, string memory name, string memory age) public returns (int32){ 59 | UpdateField[] memory updateFields = new UpdateField[](2); 60 | updateFields[0] = UpdateField("name", name); 61 | updateFields[1] = UpdateField("age", age); 62 | 63 | int32 result = table.update(cast.s64ToString(id), updateFields); 64 | emit UpdateResult(result); 65 | return result; 66 | } 67 | 68 | function remove(int64 id) public returns(int32){ 69 | int32 result = table.remove(cast.s64ToString(id)); 70 | emit RemoveResult(result); 71 | return result; 72 | } 73 | 74 | function select(int64 idLow, int64 idHigh) public view returns (string[] memory) 75 | { 76 | Limit memory limit = Limit(0, 500); 77 | Condition[] memory cond = new Condition[](2); 78 | cond[0] = Condition(ConditionOP.GT, "id", cast.s64ToString(idLow)); 79 | cond[1] = Condition(ConditionOP.LE, "id", cast.s64ToString(idHigh)); 80 | Entry[] memory entries = table.select(cond, limit); 81 | string[] memory names = new string[](entries.length); 82 | for(uint i = 0; i < names.length; i++) 83 | { 84 | names[i] = entries[i].fields[0]; 85 | } 86 | return names; 87 | } 88 | 89 | function count(int64 idLow, int64 idHigh) public view returns (uint32) 90 | { 91 | Condition[] memory cond = new Condition[](2); 92 | cond[0] = Condition(ConditionOP.GT, "id", cast.s64ToString(idLow)); 93 | cond[1] = Condition(ConditionOP.LE, "id", cast.s64ToString(idHigh)); 94 | return table.count(cond); 95 | } 96 | 97 | function update(int64 idLow, int64 idHigh) public returns (int32) 98 | { 99 | UpdateField[] memory updateFields = new UpdateField[](1); 100 | updateFields[0] = UpdateField("status", "updated"); 101 | 102 | Limit memory limit = Limit(0, 500); 103 | Condition[] memory cond = new Condition[](2); 104 | cond[0] = Condition(ConditionOP.GT, "id", cast.s64ToString(idLow)); 105 | cond[1] = Condition(ConditionOP.LE, "id", cast.s64ToString(idHigh)); 106 | return table.update(cond, limit, updateFields); 107 | } 108 | 109 | function remove(int64 idLow, int64 idHigh) public returns (int32) 110 | { 111 | Limit memory limit = Limit(0, 500); 112 | Condition[] memory cond = new Condition[](2); 113 | cond[0] = Condition(ConditionOP.GT, "id", cast.s64ToString(idLow)); 114 | cond[1] = Condition(ConditionOP.LE, "id", cast.s64ToString(idHigh)); 115 | return table.remove(cond, limit); 116 | } 117 | 118 | function createTable(string memory tableName, uint8 keyOrder, string memory key,string[] memory fields) public returns(int256){ 119 | require(keyOrder == 0 || keyOrder == 1); 120 | KeyOrder _keyOrder = KeyOrder.Lexicographic; 121 | if (keyOrder == 1) 122 | { 123 | _keyOrder = KeyOrder.Numerical; 124 | } 125 | TableInfo memory tf = TableInfo(_keyOrder, key, fields); 126 | int32 result = tm.createTable(tableName,tf); 127 | emit CreateResult(result); 128 | return result; 129 | } 130 | 131 | function desc() public view returns(string memory, string[] memory){ 132 | TableInfo memory ti = tm.descWithKeyOrder(TABLE_NAME); 133 | return (ti.keyColumn,ti.valueColumns); 134 | } 135 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/TableV320.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // 该接口文件定义了FISCO BCOS v3.2.0及以后版本的接口,使用时需要将该文件放在合约目录下 3 | // 若要使用FISCO BCOS v3.1.0及以前版本的接口,请使用Table.sol,旧合约仍然能在新节点中使用 4 | pragma solidity >=0.6.10 <0.8.20; 5 | pragma experimental ABIEncoderV2; 6 | import "./EntryWrapper.sol"; 7 | 8 | // KeyOrder指定Key的排序规则,字典序和数字序,如果指定为数字序,key只能为数字 9 | enum KeyOrder {Lexicographic, Numerical} 10 | struct TableInfo { 11 | KeyOrder keyOrder; 12 | string keyColumn; 13 | string[] valueColumns; 14 | } 15 | 16 | // 更新字段,用于update 17 | struct UpdateField { 18 | string columnName; 19 | // 考虑工具类 20 | string value; 21 | } 22 | 23 | // 筛选条件,大于、大于等于、小于、小于等于 24 | enum ConditionOP {GT, GE, LT, LE, EQ, NE, STARTS_WITH, ENDS_WITH, CONTAINS} 25 | struct Condition { 26 | ConditionOP op; 27 | string field; 28 | string value; 29 | } 30 | 31 | // 数量限制 32 | struct Limit { 33 | uint32 offset; 34 | // count limit max is 500 35 | uint32 count; 36 | } 37 | 38 | // 表管理合约,是静态Precompiled,有固定的合约地址 39 | abstract contract TableManager { 40 | // 创建表,传入TableInfo 41 | function createTable(string memory path, TableInfo memory tableInfo) public virtual returns (int32); 42 | 43 | // 创建KV表,传入key和value字段名 44 | function createKVTable(string memory tableName, string memory keyField, string memory valueField) public virtual returns (int32); 45 | 46 | // 只提供给Solidity合约调用时使用 47 | function openTable(string memory path) public view virtual returns (address); 48 | 49 | // 变更表字段 50 | // 只能新增字段,不能删除字段,新增的字段默认值为空,不能与原有字段重复 51 | function appendColumns(string memory path, string[] memory newColumns) public virtual returns (int32); 52 | 53 | // 获取表信息 54 | function descWithKeyOrder(string memory tableName) public view virtual returns (TableInfo memory); 55 | } 56 | 57 | // 表合约,是动态Precompiled,TableManager创建时指定地址 58 | abstract contract Table { 59 | // 按key查询entry 60 | function select(string memory key) public virtual view returns (Entry memory); 61 | 62 | // 按条件批量查询entry,condition为空则查询所有记录 63 | function select(Condition[] memory conditions, Limit memory limit) public virtual view returns (Entry[] memory); 64 | 65 | // 按照条件查询count数据 66 | function count(Condition[] memory conditions) public virtual view returns (uint32); 67 | 68 | // 插入数据 69 | function insert(Entry memory entry) public virtual returns (int32); 70 | 71 | // 按key更新entry 72 | function update(string memory key, UpdateField[] memory updateFields) public virtual returns (int32); 73 | 74 | // 按条件批量更新entry,condition为空则更新所有记录 75 | function update(Condition[] memory conditions, Limit memory limit, UpdateField[] memory updateFields) public virtual returns (int32); 76 | 77 | // 按key删除entry 78 | function remove(string memory key) public virtual returns (int32); 79 | // 按条件批量删除entry,condition为空则删除所有记录 80 | function remove(Condition[] memory conditions, Limit memory limit) public virtual returns (int32); 81 | } 82 | 83 | abstract contract KVTable { 84 | function get(string memory key) public view virtual returns (bool, string memory); 85 | 86 | function set(string memory key, string memory value) public virtual returns (int32); 87 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/blobBaseFee.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity >=0.6.10 <=0.8.26; 3 | 4 | contract blobBaseFee { 5 | function getBlobBaseFeeYul() external view returns (uint256 blobBaseFee) { 6 | assembly { 7 | blobBaseFee := blobbasefee() 8 | } 9 | } 10 | 11 | function getBlobBaseFeeSolidity() external view returns (uint256 blobBaseFee) { 12 | blobBaseFee = block.blobbasefee; 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/mcopy.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity >=0.6.10 <=0.8.26; 3 | 4 | contract mcopy { 5 | function memoryCopy() external pure returns (bytes32 x) { 6 | assembly { 7 | mstore(0x20, 0x50) // Store 0x50 at word 1 in memory 8 | mcopy(0, 0x20, 0x20) // Copies 0x50 to word 0 in memory 9 | x := mload(0) // Returns 32 bytes "0x50" 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/contract/sol/transientStorageContract.sol: -------------------------------------------------------------------------------- 1 | pragma solidity>=0.6.10 <=0.8.26; 2 | 3 | import "./StorageSlot.sol"; 4 | 5 | contract StorageContract { 6 | using StorageSlot for *; 7 | 8 | StorageSlot.AddressSlotType private addressSlot = StorageSlot.asAddress(keccak256("address_slot")); 9 | StorageSlot.BooleanSlotType private booleanSlot = StorageSlot.asBoolean(keccak256("boolean_slot")); 10 | StorageSlot.Bytes32SlotType private bytes32Slot = StorageSlot.asBytes32(keccak256("bytes32_slot")); 11 | StorageSlot.Uint256SlotType private uint256Slot = StorageSlot.asUint256(keccak256("uint256_slot")); 12 | StorageSlot.Int256SlotType private int256Slot = StorageSlot.asInt256(keccak256("int256_slot")); 13 | 14 | function setAddress(address _value) public { 15 | addressSlot.tstore(_value); 16 | } 17 | 18 | function getAddress() public view returns (address) { 19 | return addressSlot.tload(); 20 | } 21 | 22 | function setBoolean(bool _value) public { 23 | booleanSlot.tstore(_value); 24 | } 25 | 26 | function getBoolean() public view returns (bool) { 27 | return booleanSlot.tload(); 28 | } 29 | 30 | function setBytes32(bytes32 _value) public { 31 | bytes32Slot.tstore(_value); 32 | } 33 | 34 | function getBytes32() public view returns (bytes32) { 35 | return bytes32Slot.tload(); 36 | } 37 | 38 | function setUint256(uint256 _value) public { 39 | uint256Slot.tstore(_value); 40 | } 41 | 42 | function getUint256() public view returns (uint256) { 43 | return uint256Slot.tload(); 44 | } 45 | 46 | function setInt256(int256 _value) public { 47 | int256Slot.tstore(_value); 48 | } 49 | 50 | function getInt256() public view returns (int256) { 51 | return int256Slot.tload(); 52 | } 53 | 54 | function storeIntTest(int256 _value) public returns (int256) { 55 | int256Slot.tstore(_value); 56 | return int256Slot.tload(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/callback/ParallelOkCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2020 [fisco-dev] 3 | * 4 | *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | *

http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | *

Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | * express or implied. See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | package org.fisco.bcos.sdk.demo.perf.callback; 15 | 16 | import java.math.BigInteger; 17 | import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; 18 | import org.fisco.bcos.sdk.demo.perf.model.DagTransferUser; 19 | import org.fisco.bcos.sdk.demo.perf.model.DagUserInfo; 20 | import org.fisco.bcos.sdk.v3.model.TransactionReceipt; 21 | import org.fisco.bcos.sdk.v3.model.callback.TransactionCallback; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | public class ParallelOkCallback extends TransactionCallback { 26 | private static Logger logger = LoggerFactory.getLogger(ParallelOkCallback.class); 27 | public static final String ADD_USER_CALLBACK = "add"; 28 | public static final String TRANS_CALLBACK = "transfer"; 29 | private Long startTime; 30 | 31 | private final PerformanceCollector collector; 32 | private final DagUserInfo dagUserInfo; 33 | private final String callbackType; 34 | 35 | private DagTransferUser user = null; 36 | private DagTransferUser fromUser = null; 37 | private DagTransferUser toUser = null; 38 | private BigInteger amount = null; 39 | 40 | public ParallelOkCallback( 41 | PerformanceCollector collector, DagUserInfo dagUserInfo, String callbackType) { 42 | this.collector = collector; 43 | this.dagUserInfo = dagUserInfo; 44 | this.callbackType = callbackType; 45 | } 46 | 47 | public void recordStartTime() { 48 | this.startTime = System.currentTimeMillis(); 49 | } 50 | 51 | @Override 52 | public void onResponse(TransactionReceipt receipt) { 53 | Long cost = System.currentTimeMillis() - startTime; 54 | try { 55 | if (receipt.isStatusOK()) { 56 | if (callbackType.compareTo(ADD_USER_CALLBACK) == 0) { // add test 57 | dagUserInfo.addUser(user); 58 | } else if (callbackType.compareTo(TRANS_CALLBACK) == 0) { // transfer test 59 | fromUser.decrease(amount); 60 | toUser.increase(amount); 61 | } 62 | } 63 | collector.onMessage(receipt, cost); 64 | } catch (Exception e) { 65 | logger.error("onMessage error: ", e); 66 | } 67 | } 68 | 69 | public DagTransferUser getFromUser() { 70 | return fromUser; 71 | } 72 | 73 | public void setFromUser(DagTransferUser fromUser) { 74 | this.fromUser = fromUser; 75 | } 76 | 77 | public DagTransferUser getToUser() { 78 | return toUser; 79 | } 80 | 81 | public void setToUser(DagTransferUser toUser) { 82 | this.toUser = toUser; 83 | } 84 | 85 | public BigInteger getAmount() { 86 | return amount; 87 | } 88 | 89 | public void setAmount(BigInteger amount) { 90 | this.amount = amount; 91 | } 92 | 93 | public DagTransferUser getUser() { 94 | return user; 95 | } 96 | 97 | public void setUser(DagTransferUser user) { 98 | this.user = user; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/callback/PerformanceCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2020 [fisco-dev] 3 | * 4 | *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | *

http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | *

Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | * express or implied. See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | package org.fisco.bcos.sdk.demo.perf.callback; 15 | 16 | import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; 17 | import org.fisco.bcos.sdk.v3.model.TransactionReceipt; 18 | import org.fisco.bcos.sdk.v3.model.callback.TransactionCallback; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | public class PerformanceCallback extends TransactionCallback { 23 | 24 | private static Logger logger = LoggerFactory.getLogger(PerformanceCallback.class); 25 | private Long startTime = System.currentTimeMillis(); 26 | 27 | private PerformanceCollector collector; 28 | 29 | public PerformanceCollector getCollector() { 30 | return collector; 31 | } 32 | 33 | public void setCollector(PerformanceCollector collector) { 34 | this.collector = collector; 35 | } 36 | 37 | public PerformanceCallback() {} 38 | 39 | @Override 40 | public void onResponse(TransactionReceipt receipt) { 41 | Long cost = System.currentTimeMillis() - startTime; 42 | 43 | try { 44 | collector.onMessage(receipt, cost); 45 | } catch (Exception e) { 46 | logger.error("onMessage error: ", e); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/dgms/User.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.perf.dgms; 2 | 3 | public class User { 4 | public String getName() { 5 | return name; 6 | } 7 | 8 | public void setName(String name) { 9 | this.name = name; 10 | } 11 | 12 | public int getValue() { 13 | return assetID; 14 | } 15 | 16 | public void setValue(int value) { 17 | this.assetID = value; 18 | } 19 | 20 | private String name; 21 | private int assetID; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagTransferUser.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2020 [fisco-dev] 3 | * 4 | *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | *

http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | *

Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | * express or implied. See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | package org.fisco.bcos.sdk.demo.perf.model; 15 | 16 | import java.math.BigInteger; 17 | 18 | public class DagTransferUser { 19 | private String user; 20 | private BigInteger amount; 21 | 22 | public String getUser() { 23 | return user; 24 | } 25 | 26 | public synchronized void setUser(String user) { 27 | this.user = user; 28 | } 29 | 30 | public synchronized BigInteger getAmount() { 31 | return amount; 32 | } 33 | 34 | public synchronized void setAmount(BigInteger amount) { 35 | this.amount = amount; 36 | } 37 | 38 | public synchronized void increase(BigInteger amount) { 39 | this.amount = this.amount.add(amount); 40 | } 41 | 42 | public synchronized void decrease(BigInteger amount) { 43 | this.amount = this.amount.subtract(amount); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagUserInfo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2020 [fisco-dev] 3 | * 4 | *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 | * except in compliance with the License. You may obtain a copy of the License at 6 | * 7 | *

http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | *

Unless required by applicable law or agreed to in writing, software distributed under the 10 | * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | * express or implied. See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | package org.fisco.bcos.sdk.demo.perf.model; 15 | 16 | import java.io.BufferedReader; 17 | import java.io.BufferedWriter; 18 | import java.io.File; 19 | import java.io.FileReader; 20 | import java.io.FileWriter; 21 | import java.io.IOException; 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | public class DagUserInfo { 28 | private static Logger logger = LoggerFactory.getLogger(DagUserInfo.class); 29 | 30 | private List userList = new ArrayList(); 31 | 32 | private String file = null; 33 | 34 | private String parallelokAddr = ""; 35 | 36 | public void setContractAddr(String addr) { 37 | this.parallelokAddr = addr; 38 | } 39 | 40 | public String getContractAddr() { 41 | return this.parallelokAddr; 42 | } 43 | 44 | public List getUserList() { 45 | return userList; 46 | } 47 | 48 | public void setUserList(List userList) { 49 | this.userList = userList; 50 | } 51 | 52 | public String getFile() { 53 | return file; 54 | } 55 | 56 | public void setFile(String file) { 57 | this.file = file; 58 | } 59 | 60 | public synchronized void addUser(DagTransferUser user) { 61 | userList.add(user); 62 | } 63 | 64 | public boolean isEmpty() { 65 | return userList.isEmpty(); 66 | } 67 | 68 | public DagTransferUser getFrom(int idx) { 69 | assert !isEmpty() : "Has no user."; 70 | return userList.get(idx % userList.size()); 71 | } 72 | 73 | public DagTransferUser getTo(int idx) { 74 | assert !isEmpty() : "Has no user."; 75 | int mid = userList.size() / 2; 76 | return userList.get((idx + mid) % userList.size()); 77 | } 78 | 79 | public DagTransferUser getNext(int idx) { 80 | return userList.get((idx + 1) % userList.size()); 81 | } 82 | 83 | public void writeDagTransferUser() throws IOException { 84 | if (file == null) { 85 | return; 86 | } 87 | logger.info("file {}, begin load.", file); 88 | 89 | BufferedWriter bw = null; 90 | try { 91 | bw = new BufferedWriter(new FileWriter(new File(file))); 92 | 93 | // Write contract address first 94 | bw.write(parallelokAddr + "\n"); 95 | 96 | // And write user 97 | for (int i = 0; i < userList.size(); i++) { 98 | bw.write(userList.get(i).getUser() + "\n"); 99 | logger.trace(" write user , user is {}", userList.get(i).getUser()); 100 | } 101 | 102 | bw.flush(); 103 | 104 | } finally { 105 | if (bw != null) { 106 | bw.close(); 107 | } 108 | } 109 | 110 | logger.info("file {}, load end, count is {}.", file, userList.size()); 111 | System.out.println(" Write DagTransferUser end, count is " + userList.size()); 112 | } 113 | 114 | public void loadDagTransferUser() throws IOException { 115 | if (file == null) { 116 | return; 117 | } 118 | BufferedReader br = null; 119 | try { 120 | br = new BufferedReader(new FileReader(new File(file))); 121 | 122 | String line = null; 123 | 124 | // Get contract addr first 125 | if ((line = br.readLine()) != null) { 126 | parallelokAddr = line; 127 | } 128 | 129 | // And get user 130 | while ((line = br.readLine()) != null) { 131 | line = line.trim(); 132 | if (!line.isEmpty()) { 133 | DagTransferUser user = new DagTransferUser(); 134 | user.setUser(line); 135 | addUser(user); 136 | // System.out.println("load DagTransferUser ==>> " + line); 137 | } 138 | } 139 | 140 | } finally { 141 | if (br != null) { 142 | br.close(); 143 | } 144 | } 145 | 146 | logger.info("file {}, load end, count is {}.", file, userList.size()); 147 | 148 | System.out.println("Load DagTransferUser end, count is " + userList.size()); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/paillier/CommonUtils.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.perf.paillier; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class CommonUtils { 6 | public CommonUtils() {} 7 | 8 | public static byte[] intToByte4(int i) { 9 | byte[] targets = new byte[4]; 10 | targets[3] = (byte) (i & 0xFF); 11 | targets[2] = (byte) (i >> 8 & 0xFF); 12 | targets[1] = (byte) (i >> 16 & 0xFF); 13 | targets[0] = (byte) (i >> 24 & 0xFF); 14 | return targets; 15 | } 16 | 17 | public static byte[] longToByte8(long lo) { 18 | byte[] targets = new byte[8]; 19 | for (int i = 0; i < 8; i++) { 20 | int offset = (targets.length - 1 - i) * 8; 21 | targets[i] = (byte) ((lo >>> offset) & 0xFF); 22 | } 23 | return targets; 24 | } 25 | 26 | public static byte[] unsignedShortToByte2(int s) { 27 | byte[] targets = new byte[2]; 28 | targets[0] = (byte) (s >> 8 & 0xFF); 29 | targets[1] = (byte) (s & 0xFF); 30 | return targets; 31 | } 32 | 33 | public static int byte2ToUnsignedShort(byte[] bytes) { 34 | return byte2ToUnsignedShort(bytes, 0); 35 | } 36 | 37 | public static int byte2ToUnsignedShort(byte[] bytes, int off) { 38 | int high = bytes[off]; 39 | int low = bytes[off + 1]; 40 | return (high << 8 & 0xFF00) | (low & 0xFF); 41 | } 42 | 43 | public static int byte4ToInt(byte[] bytes, int off) { 44 | int b0 = bytes[off] & 0xFF; 45 | int b1 = bytes[off + 1] & 0xFF; 46 | int b2 = bytes[off + 2] & 0xFF; 47 | int b3 = bytes[off + 3] & 0xFF; 48 | return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; 49 | } 50 | 51 | public static byte[] asUnsignedByteArray(BigInteger paramBigInteger) { 52 | byte[] arrayOfByte1 = paramBigInteger.toByteArray(); 53 | if (arrayOfByte1[0] == 0) { 54 | byte[] arrayOfByte2 = new byte[arrayOfByte1.length - 1]; 55 | System.arraycopy(arrayOfByte1, 1, arrayOfByte2, 0, arrayOfByte2.length); 56 | return arrayOfByte2; 57 | } 58 | return arrayOfByte1; 59 | } 60 | 61 | public static byte[] asUnsignedByteArray(BigInteger paramBigInteger, int byteLength) { 62 | byte[] arrayOfByte1 = asUnsignedByteArray(paramBigInteger); 63 | if (arrayOfByte1.length < byteLength) { 64 | byte[] arrayOfByte2 = new byte[byteLength]; 65 | int offset = byteLength - arrayOfByte1.length; 66 | for (int i = 0; i < offset; i++) { 67 | arrayOfByte2[i] = 0; 68 | } 69 | System.arraycopy(arrayOfByte1, 0, arrayOfByte2, offset, arrayOfByte1.length); 70 | return arrayOfByte2; 71 | } 72 | return arrayOfByte1; 73 | } 74 | 75 | public static BigInteger fromUnsignedByteArray(byte[] paramArrayOfByte) { 76 | return new BigInteger(1, paramArrayOfByte); 77 | } 78 | 79 | public static String byteToHexString(byte[] bt) { 80 | StringBuffer sb = new StringBuffer(); 81 | for (int i = 0; i < bt.length; i++) { 82 | String hex = Integer.toHexString(bt[i] & 0xFF); 83 | if (hex.length() == 1) { 84 | hex = '0' + hex; 85 | } 86 | sb.append(hex.toUpperCase()); 87 | } 88 | return sb.toString(); 89 | } 90 | 91 | public static byte[] hexStringToBytes(String hexString) { 92 | if (hexString == null || hexString.equals("")) { 93 | return null; 94 | } 95 | hexString = hexString.toUpperCase(); 96 | int length = hexString.length() / 2; 97 | char[] hexChars = hexString.toCharArray(); 98 | byte[] d = new byte[length]; 99 | for (int i = 0; i < length; i++) { 100 | int pos = i * 2; 101 | d[i] = (byte) (charToByte(hexChars[pos]) << 4 | (charToByte(hexChars[pos + 1]) & 0xff)); 102 | } 103 | return d; 104 | } 105 | 106 | private static byte charToByte(char c) { 107 | return (byte) "0123456789ABCDEF".indexOf(c); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/paillier/PaillierKeyPair.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.perf.paillier; 2 | 3 | import java.io.IOException; 4 | import java.io.StringReader; 5 | import java.io.StringWriter; 6 | import java.security.KeyFactory; 7 | import java.security.KeyPair; 8 | import java.security.KeyPairGenerator; 9 | import java.security.NoSuchAlgorithmException; 10 | import java.security.PrivateKey; 11 | import java.security.PublicKey; 12 | import java.security.SecureRandom; 13 | import java.security.spec.InvalidKeySpecException; 14 | import java.security.spec.PKCS8EncodedKeySpec; 15 | import java.security.spec.X509EncodedKeySpec; 16 | import org.bouncycastle.util.io.pem.PemObject; 17 | import org.bouncycastle.util.io.pem.PemObjectGenerator; 18 | import org.bouncycastle.util.io.pem.PemReader; 19 | import org.bouncycastle.util.io.pem.PemWriter; 20 | 21 | public class PaillierKeyPair { 22 | 23 | public static KeyPair generateGoodKeyPair() { 24 | return generateKeyPair(2048); 25 | } 26 | 27 | public static KeyPair generateStrongKeyPair() { 28 | return generateKeyPair(4096); 29 | } 30 | 31 | public static KeyPair generateKeyPair(int len) { 32 | // if (len < 2048) { 33 | // return null; 34 | // } 35 | 36 | KeyPairGenerator generator; 37 | try { 38 | generator = KeyPairGenerator.getInstance("RSA"); 39 | generator.initialize(len, new SecureRandom()); 40 | return generator.generateKeyPair(); 41 | } catch (NoSuchAlgorithmException e) { 42 | e.printStackTrace(); 43 | } 44 | return null; 45 | } 46 | 47 | public static String publicKeyToPem(PublicKey publicKey) { 48 | StringWriter pemStrWriter = new StringWriter(); 49 | PemWriter pemWriter = null; 50 | try { 51 | pemWriter = new PemWriter(pemStrWriter); 52 | PemObject pemObject = new PemObject("PUBLIC KEY", publicKey.getEncoded()); 53 | pemWriter.writeObject(pemObject); 54 | pemWriter.flush(); 55 | pemWriter.close(); 56 | return pemStrWriter.toString(); 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | return null; 61 | } 62 | 63 | public static PublicKey pemToPublicKey(String publicKeyStr) { 64 | try { 65 | StringReader pemStrReader = new StringReader(publicKeyStr); 66 | PemReader pemReader = new PemReader(pemStrReader); 67 | byte[] pubKey = pemReader.readPemObject().getContent(); 68 | pemReader.close(); 69 | 70 | KeyFactory kf = KeyFactory.getInstance("RSA"); 71 | return kf.generatePublic(new X509EncodedKeySpec(pubKey)); 72 | } catch (IOException e) { 73 | e.printStackTrace(); 74 | return null; 75 | } catch (NoSuchAlgorithmException e) { 76 | e.printStackTrace(); 77 | } catch (InvalidKeySpecException e) { 78 | e.printStackTrace(); 79 | } 80 | return null; 81 | } 82 | 83 | public static String privateKeyToPem(PrivateKey privateKey) { 84 | try { 85 | StringWriter pemStrWriter = new StringWriter(); 86 | PemWriter pemWriter = new PemWriter(pemStrWriter); 87 | PemObjectGenerator pemObjectGenerator = 88 | new PemObject("PRIVATE KEY", privateKey.getEncoded()); 89 | pemWriter.writeObject(pemObjectGenerator); 90 | pemWriter.flush(); 91 | pemWriter.close(); 92 | return pemStrWriter.toString(); 93 | } catch (IOException e) { 94 | e.printStackTrace(); 95 | return null; 96 | } 97 | } 98 | 99 | public static PrivateKey pemToPrivateKey(String privateKeyStr) { 100 | try { 101 | StringReader pemStrReader = new StringReader(privateKeyStr); 102 | PemReader pemReader = new PemReader(pemStrReader); 103 | byte[] priKey = pemReader.readPemObject().getContent(); 104 | pemReader.close(); 105 | 106 | KeyFactory kf = KeyFactory.getInstance("RSA"); 107 | return kf.generatePrivate(new PKCS8EncodedKeySpec(priKey)); 108 | } catch (IOException e) { 109 | e.printStackTrace(); 110 | return null; 111 | } catch (NoSuchAlgorithmException e) { 112 | e.printStackTrace(); 113 | } catch (InvalidKeySpecException e) { 114 | e.printStackTrace(); 115 | } 116 | return null; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/perf/tiger/User.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.perf.tiger; 2 | 3 | class User { 4 | public String getOpenID() { 5 | return openID; 6 | } 7 | 8 | public void setOpenID(String openID) { 9 | this.openID = openID; 10 | } 11 | 12 | public int getTigerID() { 13 | return tigerID; 14 | } 15 | 16 | public void setTigerID(int tigerID) { 17 | this.tigerID = tigerID; 18 | } 19 | 20 | private String openID; 21 | private int tigerID; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/transaction/AssembleTransactionDemo.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.transaction; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import org.fisco.bcos.sdk.v3.codec.ContractCodecException; 6 | import org.fisco.bcos.sdk.v3.codec.wrapper.ABIDefinition; 7 | import org.fisco.bcos.sdk.v3.transaction.model.dto.CallResponse; 8 | import org.fisco.bcos.sdk.v3.transaction.model.dto.TransactionResponse; 9 | import org.fisco.bcos.sdk.v3.transaction.model.exception.NoSuchTransactionFileException; 10 | import org.fisco.bcos.sdk.v3.transaction.model.exception.TransactionBaseException; 11 | 12 | public class AssembleTransactionDemo { 13 | BcosClientWrapper bcosClientWrapper; 14 | 15 | public void init() throws Exception { 16 | bcosClientWrapper = new BcosClientWrapper(); 17 | bcosClientWrapper.init("test_group"); 18 | } 19 | 20 | String contractAddress = "0x31231c2abad03b071b3440268f28194029dad743"; 21 | 22 | public void testDeploy() throws Exception { 23 | // 部署HelloWorld合约。第一个参数为合约名称,第二个参数为合约构造函数的列表,是List类型。 24 | TransactionResponse response = 25 | bcosClientWrapper.transactionProcessor.deployByContractLoader( 26 | "HelloWorld", new ArrayList<>()); 27 | System.out.println("deploy result:" + response.getContractAddress()); 28 | contractAddress = response.getContractAddress(); 29 | } 30 | 31 | public void testABIInfo() throws NoSuchTransactionFileException { 32 | String contractName = "HelloWorld"; 33 | List abilst = 34 | bcosClientWrapper 35 | .transactionProcessor 36 | .getContractLoader() 37 | .getFunctionABIListByContractName(contractName); 38 | for (ABIDefinition de : abilst) { 39 | System.out.println( 40 | "name:" 41 | + de.getName() 42 | + ",type:" 43 | + de.getType() 44 | + ",mutability:" 45 | + de.getStateMutability()); 46 | } 47 | } 48 | 49 | public void testCall() throws TransactionBaseException, ContractCodecException { 50 | // 查询HelloWorld合约的『name』函数,合约地址为helloWorldAddress,参数为空 51 | String contractName = "HelloWorld"; 52 | // contractAddress = "0x6aa57232d12f4b516cafc4919219ed56f996613e"; 53 | System.out.println("call address: " + contractAddress); 54 | CallResponse callResponse = 55 | bcosClientWrapper.transactionProcessor.sendCallByContractLoader( 56 | contractName, contractAddress, "get", new ArrayList<>()); 57 | 58 | System.out.println(callResponse.getValues()); 59 | } 60 | 61 | public void testTx() throws ContractCodecException, TransactionBaseException { 62 | String contractName = "HelloWorld"; 63 | String contractAddress = "0x31231c2abad03b071b3440268f28194029dad743"; 64 | List params = new ArrayList(); 65 | params.add("my test"); 66 | TransactionResponse txResp = 67 | bcosClientWrapper.transactionProcessor 68 | .sendTransactionAndGetResponseByContractLoader( 69 | contractName, contractAddress, "set", params); 70 | System.out.println(txResp.getEvents()); 71 | System.out.println(txResp.getReturnMessage()); 72 | System.out.println(txResp.getReturnCode()); 73 | 74 | testCall(); 75 | } 76 | 77 | public static void main(String[] args) throws Exception { 78 | // TODO Auto-generated method stub 79 | AssembleTransactionDemo demo = new AssembleTransactionDemo(); 80 | demo.init(); 81 | demo.testDeploy(); 82 | demo.testCall(); 83 | demo.bcosClientWrapper.finish(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/transaction/BcosClientWrapper.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.transaction; 2 | 3 | import org.fisco.bcos.sdk.v3.BcosSDK; 4 | import org.fisco.bcos.sdk.v3.client.Client; 5 | import org.fisco.bcos.sdk.v3.crypto.CryptoSuite; 6 | import org.fisco.bcos.sdk.v3.transaction.manager.AssembleTransactionProcessor; 7 | import org.fisco.bcos.sdk.v3.transaction.manager.TransactionProcessorFactory; 8 | import org.fisco.bcos.sdk.v3.transaction.tools.ContractLoader; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.context.support.ClassPathXmlApplicationContext; 11 | 12 | public class BcosClientWrapper { 13 | private BcosSDK bcosSDK; 14 | private String abipath = "bin/main/abi"; 15 | private String binpath = "bin/main/bin"; 16 | private Client client; 17 | private CryptoSuite txCryptoSuite; 18 | private String groupId; 19 | 20 | public String getGroupId() { 21 | return groupId; 22 | } 23 | 24 | public void setGroupId(String groupId) { 25 | this.groupId = groupId; 26 | } 27 | 28 | AssembleTransactionProcessor transactionProcessor; 29 | ContractLoader contractLoader; 30 | 31 | public BcosSDK getBcosSDK() { 32 | return bcosSDK; 33 | } 34 | 35 | public void setBcosSDK(BcosSDK bcosSDK) { 36 | this.bcosSDK = bcosSDK; 37 | } 38 | 39 | public String getAbipath() { 40 | return abipath; 41 | } 42 | 43 | public void setAbipath(String abipath) { 44 | this.abipath = abipath; 45 | } 46 | 47 | public String getBinpath() { 48 | return binpath; 49 | } 50 | 51 | public void setBinpath(String binpath) { 52 | this.binpath = binpath; 53 | } 54 | 55 | public Client getClient() { 56 | return client; 57 | } 58 | 59 | public void setClient(Client client) { 60 | this.client = client; 61 | } 62 | 63 | public CryptoSuite getTxCryptoSuite() { 64 | return txCryptoSuite; 65 | } 66 | 67 | public void setTxCryptoSuite(CryptoSuite txCryptoSuite) { 68 | this.txCryptoSuite = txCryptoSuite; 69 | } 70 | 71 | public AssembleTransactionProcessor getTransactionProcessor() { 72 | return transactionProcessor; 73 | } 74 | 75 | public void setTransactionProcessor(AssembleTransactionProcessor transactionProcessor) { 76 | this.transactionProcessor = transactionProcessor; 77 | } 78 | 79 | public void init(String groupId) throws Exception { 80 | // 初始化BcosSDK对象 81 | // String realPath =BcosClientWrapper.class.getClassLoader().getResource("").getFile(); 82 | // System.out.println("运行目录: " + realPath); 83 | ApplicationContext context = 84 | new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 85 | bcosSDK = context.getBean(BcosSDK.class); 86 | client = bcosSDK.getClient(groupId); 87 | 88 | String eccPrivateKeySample = 89 | "28018238ac7eec853401dfc3f31133330e78ac27a2f53481270083abb1a126f9"; 90 | txCryptoSuite = new CryptoSuite(client.getCryptoType()); 91 | txCryptoSuite.loadKeyPair(eccPrivateKeySample); 92 | txCryptoSuite = client.getCryptoSuite(); 93 | 94 | transactionProcessor = 95 | TransactionProcessorFactory.createAssembleTransactionProcessor( 96 | client, txCryptoSuite.getCryptoKeyPair(), abipath, binpath); 97 | 98 | contractLoader = new ContractLoader(abipath, binpath); 99 | } 100 | 101 | public void finish() { 102 | bcosSDK.stopAll(); 103 | } 104 | 105 | public static void main(String[] args) { 106 | // TODO Auto-generated method stub 107 | 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/transaction/HelloWorldLiquidDemo.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.transaction; 2 | 3 | import java.net.URL; 4 | import org.fisco.bcos.sdk.demo.contract.HelloWorldLiquid; 5 | import org.fisco.bcos.sdk.demo.perf.ParallelLiquidPerf; 6 | import org.fisco.bcos.sdk.v3.BcosSDK; 7 | import org.fisco.bcos.sdk.v3.client.Client; 8 | import org.fisco.bcos.sdk.v3.model.ConstantConfig; 9 | import org.fisco.bcos.sdk.v3.model.TransactionReceipt; 10 | import org.fisco.bcos.sdk.v3.transaction.model.exception.ContractException; 11 | 12 | public class HelloWorldLiquidDemo { 13 | private static Client client; 14 | 15 | public static void Usage() { 16 | System.out.println(" Usage:"); 17 | System.out.println("===== HelloWorldLiquidDemo ====="); 18 | System.out.println("Note: you SHOULD deploy first."); 19 | System.out.println( 20 | " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.transaction.HelloWorldLiquidDemo [group] [path] [deploy]."); 21 | System.out.println( 22 | " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.transaction.HelloWorldLiquidDemo [group] [path] [get]."); 23 | System.out.println( 24 | " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.transaction.HelloWorldLiquidDemo [group] [path] [set] [something]."); 25 | } 26 | 27 | public static void main(String[] args) throws ContractException { 28 | String configFileName = ConstantConfig.CONFIG_FILE_NAME; 29 | URL configUrl = ParallelLiquidPerf.class.getClassLoader().getResource(configFileName); 30 | if (configUrl == null) { 31 | System.out.println("The configFile " + configFileName + " doesn't exist!"); 32 | return; 33 | } 34 | if (args.length < 3) { 35 | Usage(); 36 | return; 37 | } 38 | String groupId = args[0]; 39 | String path = args[1]; 40 | String method = args[2]; 41 | String configFile = configUrl.getPath(); 42 | BcosSDK sdk = BcosSDK.build(configFile); 43 | client = sdk.getClient(groupId); 44 | 45 | if (method.equals(HelloWorldLiquid.FUNC_GET)) { 46 | HelloWorldLiquid helloWorldLiquid = 47 | HelloWorldLiquid.load(path, client, client.getCryptoSuite().getCryptoKeyPair()); 48 | System.out.println(helloWorldLiquid.get()); 49 | } else if (method.equals("deploy")) { 50 | try { 51 | HelloWorldLiquid helloWorldLiquid = 52 | HelloWorldLiquid.deploy( 53 | client, 54 | client.getCryptoSuite().getCryptoKeyPair(), 55 | path, 56 | "Hello World!"); 57 | if (helloWorldLiquid != null 58 | && helloWorldLiquid.getDeployReceipt() != null 59 | && helloWorldLiquid.getDeployReceipt().getStatus() == 0) { 60 | System.out.println("Deploy success!"); 61 | } else { 62 | System.out.println("Deploy failed!"); 63 | assert helloWorldLiquid != null; 64 | System.out.println( 65 | "Receipt status code: " 66 | + helloWorldLiquid.getDeployReceipt().getStatus()); 67 | } 68 | } catch (ContractException e) { 69 | System.out.println( 70 | "Deploy error, error code: {" 71 | + e.getErrorCode() 72 | + "}, error msg: {" 73 | + e.getMessage() 74 | + "}"); 75 | System.exit(0); 76 | } 77 | } else if (method.equals(HelloWorldLiquid.FUNC_SET) && args.length == 4) { 78 | HelloWorldLiquid helloWorldLiquid = 79 | HelloWorldLiquid.load(path, client, client.getCryptoSuite().getCryptoKeyPair()); 80 | String value = args[3]; 81 | TransactionReceipt receipt = helloWorldLiquid.set(value); 82 | if (receipt.getStatus() == 0) { 83 | System.out.println("Set success!"); 84 | } else { 85 | System.out.println("Set failed."); 86 | System.out.println("Receipt status code: " + receipt.getStatus()); 87 | } 88 | } else { 89 | Usage(); 90 | } 91 | System.exit(0); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/transaction/ISignTransaction.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.transaction; 2 | 3 | import org.fisco.bcos.sdk.jni.common.JniException; 4 | 5 | public interface ISignTransaction { 6 | /*同步的签名接口,不需要传入回调,直接返回签名结果 7 | * cryptoType: ECDSA=0,SM=1等,也可以约定其他,可修改类型以扩展更多参数 8 | * */ 9 | public String requestForSign(byte[] rawTxHash, int cryptoType); 10 | /*异步的签名接口,传入回调,当远程调用签名服务时,可以采用异步回调风格,避免堵塞 11 | * cryptoType: ECDSA=0,SM=1等,也可以约定其他,可修改类型以扩展更多参数 12 | * */ 13 | public void requestForSignAsync( 14 | byte[] dateToSign, int cryptoType, ISignedTransactionCallback callback) 15 | throws JniException; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/transaction/ISignedTransactionCallback.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.transaction; 2 | 3 | import org.fisco.bcos.sdk.jni.common.JniException; 4 | 5 | public interface ISignedTransactionCallback { 6 | /*当采用异步签名方式时,如调用网络上的加密机,KMS,异步不堵塞,然后签名完成后回调接口*/ 7 | public int handleSignedTransaction(String signatureStr) throws JniException; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/org/fisco/bcos/sdk/demo/transaction/KeyToolSignTransaction.java: -------------------------------------------------------------------------------- 1 | package org.fisco.bcos.sdk.demo.transaction; 2 | 3 | import org.fisco.bcos.sdk.jni.common.JniException; 4 | import org.fisco.bcos.sdk.v3.crypto.CryptoSuite; 5 | import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; 6 | import org.fisco.bcos.sdk.v3.crypto.signature.SignatureResult; 7 | 8 | public class KeyToolSignTransaction implements ISignTransaction { 9 | public KeyToolSignTransaction(CryptoSuite cryptoSuite) { 10 | setCryptoSuite(cryptoSuite); 11 | } 12 | 13 | public CryptoSuite getCryptoSuite() { 14 | return cryptoSuite; 15 | } 16 | 17 | public void setCryptoSuite(CryptoSuite cryptoSuite) { 18 | this.cryptoSuite = cryptoSuite; 19 | } 20 | 21 | CryptoSuite cryptoSuite; 22 | 23 | // ****纯外部实现,这里比如是个http,rpc接口什么的 24 | // 这里的实现是调用了java-sdk签名接口,可以一次对接成功 25 | public String signData(byte[] dataToSign, int crytoType) { 26 | 27 | CryptoKeyPair cryptoKeyPair = cryptoSuite.getCryptoKeyPair(); 28 | // 这里cryptoSuite的实现已经自动适配国密和ECDSA,不需要用crytoType了 29 | SignatureResult signatureResult = cryptoSuite.sign(dataToSign, cryptoKeyPair); 30 | System.out.println( 31 | "crypto type:" 32 | + crytoType 33 | + ",signData -> signature:" 34 | + signatureResult.convertToString()); 35 | return signatureResult.convertToString(); 36 | } 37 | 38 | public String requestForSign(byte[] rawTxHash, int crytoType) { 39 | 40 | String signedDataString = signData(rawTxHash, crytoType); 41 | return signedDataString; 42 | } 43 | 44 | /*模拟异步调用,demo代码比较简单,就本地直接同步回调了,可以改成启动一个签名线程*/ 45 | public void requestForSignAsync( 46 | byte[] dataToSign, int crytotype, ISignedTransactionCallback callback) 47 | throws JniException { 48 | 49 | String signatureStr = requestForSign(dataToSign, crytotype); 50 | if (callback != null) { 51 | callback.handleSignedTransaction(signatureStr); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/resources/amop/config-full.toml: -------------------------------------------------------------------------------- 1 | [cryptoMaterial] 2 | 3 | certPath = "conf" # The certification path 4 | 5 | # The following configurations take the certPath by default if commented 6 | # caCert = "conf/ca.crt" # CA cert file path 7 | # If connect to the GM node, default CA cert path is ${certPath}/gm/gmca.crt 8 | 9 | # sslCert = "conf/sdk.crt" # SSL cert file path 10 | # If connect to the GM node, the default SDK cert path is ${certPath}/gm/gmsdk.crt 11 | 12 | # sslKey = "conf/sdk.key" # SSL key file path 13 | # If connect to the GM node, the default SDK privateKey path is ${certPath}/gm/gmsdk.key 14 | 15 | # enSslCert = "conf/gm/gmensdk.crt" # GM encryption cert file path 16 | # default load the GM SSL encryption cert from ${certPath}/gm/gmensdk.crt 17 | 18 | # enSslKey = "conf/gm/gmensdk.key" # GM ssl cert file path 19 | # default load the GM SSL encryption privateKey from ${certPath}/gm/gmensdk.key 20 | 21 | [network] 22 | peers=["127.0.0.1:20200", "127.0.0.1:20201","127.0.0.1:20202","127.0.0.1:20203" ] # The peer list to connect 23 | 24 | # Configure a private topic as a topic message sender. 25 | # [[amop]] 26 | # topicName = "PrivateTopic1" 27 | # publicKeys = [ "conf/amop/consumer_public_key_1.pem" ] # Public keys of the nodes that you want to send AMOP message of this topic to. 28 | 29 | # Configure a private topic as a topic subscriber. 30 | # [[amop]] 31 | # topicName = "PrivateTopic2" 32 | # privateKey = "conf/amop/consumer_private_key.p12" # Your private key that used to subscriber verification. 33 | # password = "123456" 34 | 35 | [account] 36 | keyStoreDir = "account" # The directory to load/store the account file, default is "account" 37 | # accountFilePath = "" # The account file path (default load from the path specified by the keyStoreDir) 38 | accountFileFormat = "pem" # The storage format of account file (Default is "pem", "p12" as an option) 39 | 40 | # accountAddress = "" # The transactions sending account address 41 | # Default is a randomly generated account 42 | # The randomly generated account is stored in the path specified by the keyStoreDir 43 | 44 | # password = "" # The password used to load the account file 45 | 46 | [threadPool] 47 | # channelProcessorThreadSize = "16" # The size of the thread pool to process channel callback 48 | # Default is the number of cpu cores 49 | 50 | # receiptProcessorThreadSize = "16" # The size of the thread pool to process transaction receipt notification 51 | # Default is the number of cpu cores 52 | 53 | maxBlockingQueueSize = "102400" # The max blocking queue size of the thread pool 54 | 55 | -------------------------------------------------------------------------------- /src/test/resources/amop/config-publisher-for-test.toml: -------------------------------------------------------------------------------- 1 | # This is a config file for amop test 2 | 3 | [cryptoMaterial] 4 | 5 | certPath = "conf" 6 | # CA cert file path 7 | # caCert = "conf/ca.crt" 8 | # SSL cert file path 9 | # sslCert = "conf/sdk.crt" 10 | # SSL key file path 11 | # sslKey = "conf/sdk.key" 12 | # enSslCert = "conf/gm/gmensdk.crt" 13 | # enSslKey = "conf/gm/gmensdk.key" 14 | 15 | [network] 16 | # The peer list to connect 17 | peers=["127.0.0.1:20200", "127.0.0.1:20201"] 18 | 19 | # Configure a "need verify AMOP topic" as a topic message sender. 20 | [[amop]] 21 | topicName = "privTopic" 22 | # Public keys of the nodes that you want to send AMOP message of this topic to. 23 | publicKeys = [ "conf/amop/consumer_public_key_1.pem"] 24 | 25 | 26 | [account] 27 | # The directory where the account private key file is placed in 28 | keyStoreDir = "account" 29 | # The account file path(Default load account from keyStoreDir directory when accountFilePath is not configured) 30 | # accountFilePath = "" 31 | # The storage format of the account, support pem and p12, default is pem 32 | accountFileFormat = "pem" 33 | # The address of the account used to send transactions 34 | # When it's empty, use a randomly generated account to send transactions, 35 | # and the randomly generated account information is stored in tmp sub-directory of keyStoreDir 36 | # accountAddress = "" 37 | # The password used to load the account private key file 38 | # password = "" 39 | 40 | [threadPool] 41 | # The size of the thread pool used to process the callback of the channel 42 | channelProcessorThreadSize = "16" 43 | # The size of the thread pool used to process the transaction receipt notification 44 | receiptProcessorThreadSize = "16" 45 | 46 | -------------------------------------------------------------------------------- /src/test/resources/amop/config-subscriber-for-test.toml: -------------------------------------------------------------------------------- 1 | # This is a config file for amop test 2 | 3 | [cryptoMaterial] 4 | 5 | certPath = "conf" 6 | # CA cert file path 7 | # caCert = "conf/ca.crt" 8 | # SSL cert file path 9 | # sslCert = "conf/sdk.crt" 10 | # SSL key file path 11 | # sslKey = "conf/sdk.key" 12 | # enSslCert = "conf/gm/gmensdk.crt" 13 | # enSslKey = "conf/gm/gmensdk.key" 14 | 15 | [network] 16 | # The peer list to connect 17 | peers=["127.0.0.1:20202", "127.0.0.1:20203"] 18 | 19 | # Configure a private topic as a topic message sender. 20 | [[amop]] 21 | topicName = "privTopic" 22 | # Your private key that used to subscriber verification. 23 | privateKey = "conf/amop/consumer_private_key.p12" 24 | password = "123456" 25 | 26 | 27 | [account] 28 | # The directory where the account private key file is placed in 29 | keyStoreDir = "account" 30 | # The account file path(Default load account from keyStoreDir directory when accountFilePath is not configured) 31 | # accountFilePath = "" 32 | # The storage format of the account, support pem and p12, default is pem 33 | accountFileFormat = "pem" 34 | # The address of the account used to send transactions 35 | # When it's empty, use a randomly generated account to send transactions, 36 | # and the randomly generated account information is stored in tmp sub-directory of keyStoreDir 37 | # accountAddress = "" 38 | # The password used to load the account private key file 39 | # password = "" 40 | 41 | 42 | [threadPool] 43 | # The size of the thread pool used to process the callback of the channel 44 | channelProcessorThreadSize = "16" 45 | # The size of the thread pool used to process the transaction receipt notification 46 | receiptProcessorThreadSize = "16" 47 | 48 | -------------------------------------------------------------------------------- /src/test/resources/amop/consumer_private_key.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FISCO-BCOS/java-sdk-demo/aaad7a3d64fa7569a26ce5f78792e6344ce2ffaa/src/test/resources/amop/consumer_private_key.p12 -------------------------------------------------------------------------------- /src/test/resources/amop/consumer_public_key_1.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAE17ngD1bT95MFNZ+i19sWYCHnMIa9zS56 3 | KNbtJzReHy3ez4XbdDjoRX/UdO+cTOuJq7fV+mCiLykC7CbcpSrV5Q== 4 | -----END PUBLIC KEY----- 5 | -------------------------------------------------------------------------------- /src/test/resources/clog.ini: -------------------------------------------------------------------------------- 1 | [log] 2 | enable=false 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=info 8 | ; MB 9 | max_log_file_size=200 10 | -------------------------------------------------------------------------------- /src/test/resources/config-example.toml: -------------------------------------------------------------------------------- 1 | [cryptoMaterial] 2 | 3 | certPath = "conf" # The certification path 4 | disableSsl = "false" # Communication with nodes without SSL 5 | useSMCrypto = "false" 6 | 7 | # The following configurations take the certPath by default if commented 8 | # caCert = "conf/ca.crt" # CA cert file path 9 | # sslCert = "conf/sdk.crt" # SSL cert file path 10 | # sslKey = "conf/sdk.key" # SSL key file path 11 | 12 | # The following configurations take the sm certPath by default if commented 13 | # caCert = "conf/sm_ca.crt" # SM CA cert file path 14 | # sslCert = "conf/sm_sdk.crt" # SM SSL cert file path 15 | # sslKey = "conf/sm_sdk.key" # SM SSL key file path 16 | # enSslCert = "conf/sm_ensdk.crt" # SM encryption cert file path 17 | # enSslKey = "conf/sm_ensdk.key" # SM ssl cert file path 18 | 19 | [network] 20 | sendRpcRequestToHighestBlockNode="false" 21 | peers=["127.0.0.1:20200", "127.0.0.1:20201"] # The peer list to connect 22 | 23 | [account] 24 | keyStoreDir = "account" # The directory to load/store the account file, default is "account" 25 | # accountFilePath = "" # The account file path (default load from the path specified by the keyStoreDir) 26 | accountFileFormat = "pem" # The storage format of account file (Default is "pem", "p12" as an option) 27 | 28 | # accountAddress = "" # The transactions sending account address 29 | # Default is a randomly generated account 30 | # The randomly generated account is stored in the path specified by the keyStoreDir 31 | 32 | # password = "" # The password used to load the account file 33 | 34 | [threadPool] 35 | # threadPoolSize = "16" # The size of the thread pool to process message callback 36 | # Default is the number of cpu cores 37 | 38 | -------------------------------------------------------------------------------- /src/test/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ./log 5 | 6 | 7 | 8 | 11 | 12 | %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M -- %msg%xEx%n 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | --------------------------------------------------------------------------------