From 876226977ff5b6f927d5e6f6277536a959739c5b Mon Sep 17 00:00:00 2001 From: ywy2090 <912554887@qq.com> Date: Thu, 26 Dec 2019 10:39:46 +0800 Subject: [PATCH] sync master (#481) * Optimize the method to execute transaction (#418) * handle Rlp list (#419) * change func name (#420) * Add an asynchronous way to call contract and change the type of return value (#421) * change func name * add an asynchronous way to call contract and change the type of return value * Fix gm unusable bugs (#437) (#441) * fix bug in Jenkins (#440) * fix bug in Jenkins * format code * fix call error status not handle bug. (#442) * fix bug in test * add error message * add CallContract test * print test message * suitable for the 2.2.0 version (#447) * suitable for the 2.2.0 version * fix PerformanceDTTest bug. * fix bug in rlp * add decoder for return value * Release 2.2.0 fisco (#458) * fix thead safe bug. * update transaction receipt status. update channel version. * update jackson-databind version * update Credentials create in test. * update performance test. (#460) * update performance test. * remove one log print. * change input in merkel * catch getNodeVersion exception. (#463) * Release 2.2.0 fisco (#464) * check int/uint range before abi encode. * add gm support for parallel test. * update ci_check_commit.sh * update netty-tcnative-boringssl-static version. (#465) * optimize hexToString. (#466) * merge master and modify change log (#471) * sync 2.1.2 to master (#449) * Fix gm unusable bugs (#437) * update ChangeLog.md (#448) * fix sdk link error. (#454) * modify changelog Co-authored-by: ywy2090 <912554887@qq.com> * update message service init failed. (#472) * add generateGroup,startGroup rpc interface (#467) * Release 2.2.0 bsn (#468) * update testGenerateGroup testStartGroup * add status code for generateGroup, startGroup * update message service init failed. * Optimize the print (#474) Co-authored-by: Shareong <740310627@qq.com> Co-authored-by: chaychen2005 <35914409+chaychen2005@users.noreply.github.com> --- .ci/ci_check_commit.sh | 2 +- Changelog.md | 17 +- build.gradle | 173 +++--- lib/solcJ-all-0.4.25-gm.jar | Bin release_note.txt | 2 +- .../org/fisco/bcos/web3j/Web3jApITest.java | 158 +++--- .../bcos/channel/client/CallContract.java | 278 +++++++++ .../fisco/bcos/channel/client/CallResult.java | 75 +++ .../channel/client/ExecuteTransaction.java | 28 + .../org/fisco/bcos/channel/client/Merkle.java | 34 ++ .../bcos/channel/client/ReceiptEncoder.java | 62 ++ .../fisco/bcos/channel/client/Service.java | 74 ++- .../channel/client/TransactionResource.java | 140 +++++ .../channel/handler/ChannelConnections.java | 99 +++- .../bcos/channel/handler/ChannelHandler.java | 70 +-- .../handler/ChannelHandlerContextHelper.java | 13 +- .../protocol/EnumChannelProtocolVersion.java | 3 +- .../parser/BlockNotificationParser.java | 12 +- .../protocol/parser/HeartBeatParser.java | 24 +- .../bcos/channel/proxy/ConnectionPair.java | 181 ------ .../bcos/channel/proxy/ResponseCallback.java | 7 - .../org/fisco/bcos/channel/proxy/Server.java | 529 ------------------ .../org/fisco/bcos/fisco/EnumNodeVersion.java | 7 +- .../org/fisco/bcos/web3j/abi/Constant.java | 12 + .../fisco/bcos/web3j/abi/datatypes/Int.java | 17 + .../bcos/web3j/abi/datatypes/IntType.java | 2 +- .../fisco/bcos/web3j/abi/datatypes/Uint.java | 14 +- .../fisco/bcos/web3j/crypto/EncryptType.java | 9 +- .../bcos/web3j/crypto/gm/GenCredential.java | 4 +- .../precompile/common/PrecompiledCommon.java | 2 + .../web3j/precompile/crud/CRUDService.java | 32 +- .../channel/ChannelEthereumService.java | 5 + .../web3j/protocol/channel/StatusCode.java | 33 ++ .../bcos/web3j/protocol/core/Ethereum.java | 41 +- .../web3j/protocol/core/JsonRpc2_0Web3j.java | 72 ++- .../core/methods/response/GenerateGroup.java | 36 ++ .../methods/response/MerkleProofUnit.java | 59 ++ .../core/methods/response/StartGroup.java | 36 ++ .../response/TransactionReceiptWithProof.java | 78 +++ .../response/TransactionWithProof.java | 71 +++ .../methods/status/GenerateGroupStatus.java | 17 + .../core/methods/status/StartGroupStatus.java | 21 + .../org/fisco/bcos/web3j/tx/Contract.java | 21 +- .../bcos/web3j/tx/TransactionManager.java | 12 + .../org/fisco/bcos/web3j/utils/Numeric.java | 25 +- .../bcos/channel/client/CallContractTest.java | 303 ++++++++++ .../client/TransactionResourceTest.java | 149 +++++ .../bcos/channel/test/amop/ProxyServer.java | 26 - .../test/contract/PerfomanceCollector.java | 6 +- .../test/contract/PerformanceCollector.java | 4 +- .../test/parallel/parallelok/ParallelOk.java | 24 +- .../parallel/parallelok/ParallelRevert.java | 289 ---------- .../parallel/parallelok/PerformanceDT.java | 6 + .../parallelok/PerformanceDTCollector.java | 2 +- .../parallelok/PerformanceDTTest.java | 24 +- .../test/parallel/precompile/DagTransfer.java | 23 +- .../parallel/precompile/PerformanceDT.java | 6 + .../precompile/PerformanceDTCollector.java | 3 +- .../precompile/PerformanceDTTest.java | 147 +++-- .../bcos/channel/test/rpc/GenerateGroup.java | 64 +++ .../bcos/channel/test/rpc/StartGroup.java | 50 ++ .../fisco/bcos/web3j/abi/TypeEncoderTest.java | 77 +++ .../web3j/abi/datatypes/StaticArrayTest.java | 3 +- 63 files changed, 2379 insertions(+), 1434 deletions(-) mode change 100644 => 100755 lib/solcJ-all-0.4.25-gm.jar create mode 100644 src/main/java/org/fisco/bcos/channel/client/CallContract.java create mode 100644 src/main/java/org/fisco/bcos/channel/client/CallResult.java create mode 100644 src/main/java/org/fisco/bcos/channel/client/ExecuteTransaction.java create mode 100644 src/main/java/org/fisco/bcos/channel/client/Merkle.java create mode 100644 src/main/java/org/fisco/bcos/channel/client/ReceiptEncoder.java create mode 100644 src/main/java/org/fisco/bcos/channel/client/TransactionResource.java delete mode 100644 src/main/java/org/fisco/bcos/channel/proxy/ConnectionPair.java delete mode 100644 src/main/java/org/fisco/bcos/channel/proxy/ResponseCallback.java delete mode 100644 src/main/java/org/fisco/bcos/channel/proxy/Server.java create mode 100644 src/main/java/org/fisco/bcos/web3j/abi/Constant.java create mode 100644 src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/GenerateGroup.java create mode 100644 src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/MerkleProofUnit.java create mode 100644 src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/StartGroup.java create mode 100644 src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionReceiptWithProof.java create mode 100644 src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionWithProof.java create mode 100644 src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/GenerateGroupStatus.java create mode 100644 src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/StartGroupStatus.java create mode 100644 src/test/java/org/fisco/bcos/channel/client/CallContractTest.java create mode 100644 src/test/java/org/fisco/bcos/channel/client/TransactionResourceTest.java delete mode 100644 src/test/java/org/fisco/bcos/channel/test/amop/ProxyServer.java delete mode 100644 src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelRevert.java create mode 100644 src/test/java/org/fisco/bcos/channel/test/rpc/GenerateGroup.java create mode 100644 src/test/java/org/fisco/bcos/channel/test/rpc/StartGroup.java diff --git a/.ci/ci_check_commit.sh b/.ci/ci_check_commit.sh index 9685e0eb8..9d6867355 100755 --- a/.ci/ci_check_commit.sh +++ b/.ci/ci_check_commit.sh @@ -3,7 +3,7 @@ set -e scan_code_script="cobra/cobra.py -f json -o /tmp/report.json -t " -ignore_files=(PerformanceOkDSync.java SM2Algorithm.java SM2KeyGenerator.java test) +ignore_files=(Constant.java PerformanceOkDSync.java SM2Algorithm.java SM2KeyGenerator.java test) LOG_ERROR() { content=${1} diff --git a/Changelog.md b/Changelog.md index d7b6ec162..bd555dcab 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,18 @@ +### v2.2.0 + +(2019-12-24) + +* 增加 +1. 新增默克尔树的验证接口 +2. 压测程序支持国密版本 + +* 更新 +1. 优化toHexString函数为apache commons库的实现 +2. 升级netty-tcnative-boringssl-static版本为2.0.27.Final + +* 兼容 +1. 适配fisco-bcos 2.2.0版本,支持Channel Message v1/V2/V3协议 + ### v2.1.2 (2019-11-14) @@ -138,4 +153,4 @@ * Compatibility -1. 兼容rc1的节点 \ No newline at end of file +1. 兼容rc1的节点 diff --git a/build.gradle b/build.gradle index 81e6ab41e..aeb25b1d4 100644 --- a/build.gradle +++ b/build.gradle @@ -8,9 +8,9 @@ buildscript { } plugins { - id 'com.github.sherter.google-java-format' version '0.8' + id 'com.github.sherter.google-java-format' version '0.8' } - + apply plugin: 'maven' apply plugin: 'idea' apply plugin: 'java' @@ -28,35 +28,35 @@ targetCompatibility = 1.8 // In this section you declare where to find the dependencies of your project repositories { maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } - maven { url 'https://dl.bintray.com/ethereum/maven/' } + maven { url 'https://dl.bintray.com/ethereum/maven/' } mavenCentral() } googleJavaFormat { - options style: 'AOSP' - source = sourceSets*.allJava - include '**/*.java' - exclude '**/temp/*.java' + options style: 'AOSP' + source = sourceSets*.allJava + include '**/*.java' + exclude '**/temp/*.java' } verifyGoogleJavaFormat { - source = sourceSets*.allJava - include '**/*.java' - exclude '**/temp/*.java' + source = sourceSets*.allJava + include '**/*.java' + exclude '**/temp/*.java' } -def spring_version="4.3.25.RELEASE" +def spring_version = "4.3.25.RELEASE" List logger = [ - 'org.slf4j:slf4j-log4j12:1.7.25' - //'org.slf4j:slf4j-api:1.7.25' + 'org.slf4j:slf4j-log4j12:1.7.25' + //'org.slf4j:slf4j-api:1.7.25' ] -List spring =[ - "org.springframework:spring-core:$spring_version", - "org.springframework:spring-beans:$spring_version", - "org.springframework:spring-context:$spring_version", - "org.springframework:spring-tx:$spring_version", +List spring = [ + "org.springframework:spring-core:$spring_version", + "org.springframework:spring-beans:$spring_version", + "org.springframework:spring-context:$spring_version", + "org.springframework:spring-tx:$spring_version", ] List alibaba = [ @@ -66,19 +66,19 @@ List alibaba = [ // In this section you declare the dependencies for your production and test code dependencies { - // compile files('lib/solcJ-all-0.4.25-gm.jar') - // compile 'org.ethereum:solcJ-all:0.5.2' - compile 'org.ethereum:solcJ-all:0.4.25' - compile logger,spring,alibaba - compile 'org.apache.commons:commons-lang3:3.1' - compile 'com.fasterxml.jackson.core:jackson-databind:2.9.9.2' - compile 'io.netty:netty-all:4.1.32.Final' - compile 'io.netty:netty-tcnative:2.0.25.Final' - compile 'io.netty:netty-tcnative-boringssl-static:2.0.20.Final' - compile 'com.google.guava:guava:28.1-jre' - compile 'commons-configuration:commons-configuration:1.10' - // web3j - compile 'org.apache.httpcomponents:httpclient:4.5.5', + // compile files('lib/solcJ-all-0.4.25-gm.jar') + // compile 'org.ethereum:solcJ-all:0.5.2' + compile 'org.ethereum:solcJ-all:0.4.25' + compile logger, spring, alibaba + compile 'org.apache.commons:commons-lang3:3.1' + compile 'com.fasterxml.jackson.core:jackson-databind:2.10.0' + compile 'io.netty:netty-all:4.1.32.Final' + compile 'io.netty:netty-tcnative:2.0.25.Final' + compile 'io.netty:netty-tcnative-boringssl-static:2.0.27.Final' + compile 'com.google.guava:guava:28.1-jre' + compile 'commons-configuration:commons-configuration:1.10' + // web3j + compile 'org.apache.httpcomponents:httpclient:4.5.5', 'org.bouncycastle:bcprov-jdk15on:1.60', 'com.lambdaworks:scrypt:1.4.0', 'com.squareup:javapoet:1.7.0', @@ -92,8 +92,8 @@ dependencies { 'com.github.stefanbirkner:system-rules:1.18.0', 'junit:junit:4.12', 'org.mockito:mockito-core:2.23.0' - compile 'de.vandermeer:asciitable:0.3.2' - compile 'org.projectlombok:lombok:1.18.2' + compile 'de.vandermeer:asciitable:0.3.2' + compile 'org.projectlombok:lombok:1.18.2' } //archivesBaseName = 'web3sdk' @@ -104,19 +104,19 @@ configurations { integrationTestCompile.extendsFrom testCompile integrationTestRuntime.extendsFrom testRuntime } - + // for old sdk sourceSets { - main { - java { - srcDir 'src/main/java' - srcDir 'src/test/java' - } - resources { - srcDir 'src/test/resources' - } - } - integrationTest { + main { + java { + srcDir 'src/main/java' + srcDir 'src/test/java' + } + resources { + srcDir 'src/test/resources' + } + } + integrationTest { java { compileClasspath += main.output + test.output runtimeClasspath += main.output + test.output @@ -139,57 +139,58 @@ check.dependsOn.remove(test) check.dependsOn.remove(integrationTest) check.dependsOn.remove(verifyGoogleJavaFormat) -import org.ajoberstar.grgit.* + +import org.ajoberstar.grgit.Grgit def repo = null; -try { - repo = Grgit.open('.') -} catch(Exception e) { - println(" .git directory not exist."); +try { + repo = Grgit.open('.') +} catch (Exception e) { + println(" .git directory not exist."); } // 1 dist jar jar { - destinationDir file('dist/apps') - archiveName project.name + '.jar' - exclude '**/*.xml' - exclude '**/*.properties' - exclude '**/*.crt' - exclude '**/*.key' - - manifest { - if(repo != null) { - attributes(["Built-By": System.getProperty("user.name"), - "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), - "Git-Branch": repo.branch.getCurrent().getName(), - "Git-Commit": repo.head().getAbbreviatedId(40), - ]) - } - } from sourceSets.main.output + destinationDir file('dist/apps') + archiveName project.name + '.jar' + exclude '**/*.xml' + exclude '**/*.properties' + exclude '**/*.crt' + exclude '**/*.key' - doLast { - - copy { - from file('tools/sol2java.sh') - into 'dist/tools/' - } - copy { - from configurations.runtime - into 'dist/lib' - } - copy { - from file('src/test/resources/') - into 'dist/conf' - } - copy { - from file('src/test/resources/contract/Table.sol') - into 'dist/tools/contracts' - } - } + manifest { + if (repo != null) { + attributes(["Built-By" : System.getProperty("user.name"), + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), + "Git-Branch" : repo.branch.getCurrent().getName(), + "Git-Commit" : repo.head().getAbbreviatedId(40), + ]) + } + } from sourceSets.main.output + + doLast { + + copy { + from file('tools/sol2java.sh') + into 'dist/tools/' + } + copy { + from configurations.runtime + into 'dist/lib' + } + copy { + from file('src/test/resources/') + into 'dist/conf' + } + copy { + from file('src/test/resources/contract/Table.sol') + into 'dist/tools/contracts' + } + } } test { - testLogging.showStandardStreams = true + testLogging.showStandardStreams = true } // for upload to maven //task sourcesJar(type: Jar) { @@ -254,4 +255,4 @@ test { // } // } //} -mainClassName = System.getProperty("exec.mainClass") ?: "org.fisco.bcos.channel.test.amop.Channel2Client" \ No newline at end of file +mainClassName = System.getProperty("exec.mainClass") ?: "org.fisco.bcos.channel.test.amop.Channel2Client" diff --git a/lib/solcJ-all-0.4.25-gm.jar b/lib/solcJ-all-0.4.25-gm.jar old mode 100644 new mode 100755 diff --git a/release_note.txt b/release_note.txt index 59696826f..a4b6ac3de 100644 --- a/release_note.txt +++ b/release_note.txt @@ -1 +1 @@ -v2.1.2 +v2.2.0 diff --git a/src/integration-test/java/org/fisco/bcos/web3j/Web3jApITest.java b/src/integration-test/java/org/fisco/bcos/web3j/Web3jApITest.java index b18509e0d..9e9bcf9da 100644 --- a/src/integration-test/java/org/fisco/bcos/web3j/Web3jApITest.java +++ b/src/integration-test/java/org/fisco/bcos/web3j/Web3jApITest.java @@ -5,7 +5,6 @@ import java.io.IOException; import java.math.BigInteger; import java.util.concurrent.ExecutionException; - import org.fisco.bcos.TestBase; import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameter; import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameterName; @@ -32,31 +31,31 @@ import org.junit.Test; public class Web3jApITest extends TestBase { - + @Test public void getNodeVersion() throws IOException { - NodeVersion nodeVersion = web3j.getNodeVersion().send(); + NodeVersion nodeVersion = web3j.getNodeVersion().send(); assertNotNull(nodeVersion.getNodeVersion().getBuildTime()); assertNotNull(nodeVersion.getNodeVersion().getBuildType()); assertNotNull(nodeVersion.getNodeVersion().getGitBranch()); assertNotNull(nodeVersion.getNodeVersion().getGitCommit()); assertNotNull(nodeVersion.getNodeVersion().getVersion()); } - + @Test public void getBlockNumber() throws IOException, InterruptedException, ExecutionException { - BlockNumber blockNumber = web3j.getBlockNumber().send(); + BlockNumber blockNumber = web3j.getBlockNumber().send(); + assertNotNull(blockNumber.getBlockNumber()); + blockNumber = web3j.getBlockNumber().sendAsync().get(); assertNotNull(blockNumber.getBlockNumber()); - blockNumber = web3j.getBlockNumber().sendAsync().get(); - assertNotNull(blockNumber.getBlockNumber()); } - + @Test public void getBlockNumberCache() throws IOException { - BigInteger blockNumberCache = web3j.getBlockNumberCache(); - assertNotNull(blockNumberCache); + BigInteger blockNumberCache = web3j.getBlockNumberCache(); + assertNotNull(blockNumberCache); } - + @Test public void pbftView() throws Exception { PbftView pbftView = web3j.getPbftView().send(); @@ -65,13 +64,13 @@ public void pbftView() throws Exception { @Test public void getConsensusStatus() throws Exception { - String consensusStatus = web3j.getConsensusStatus().sendForReturnString(); + String consensusStatus = web3j.getConsensusStatus().sendForReturnString(); assertNotNull(consensusStatus); } @Test public void getSyncStatus() throws Exception { - String syncStatus = web3j.getSyncStatus().sendForReturnString(); + String syncStatus = web3j.getSyncStatus().sendForReturnString(); assertNotNull(syncStatus); } @@ -92,100 +91,129 @@ public void groupList() throws Exception { GroupList groupList = web3j.getGroupList().send(); assertNotNull(groupList.getGroupList()); } - + @Test public void getSealerList() throws Exception { - SealerList sealerList = web3j.getSealerList().send(); - assertNotNull(sealerList.getSealerList()); + SealerList sealerList = web3j.getSealerList().send(); + assertNotNull(sealerList.getSealerList()); } - + @Test public void getObserverList() throws Exception { - ObserverList observerList = web3j.getObserverList().send(); - assertNotNull(observerList.getObserverList()); + ObserverList observerList = web3j.getObserverList().send(); + assertNotNull(observerList.getObserverList()); } - + @Test public void getNodeIDList() throws Exception { - NodeIDList nodeIDList = web3j.getNodeIDList().send(); - assertNotNull(nodeIDList.getNodeIDList()); + NodeIDList nodeIDList = web3j.getNodeIDList().send(); + assertNotNull(nodeIDList.getNodeIDList()); } - + @Test public void getSystemConfigByKey() throws Exception { - SystemConfig txCountLimit = web3j.getSystemConfigByKey("tx_count_limit").send(); - SystemConfig txGasLimit = web3j.getSystemConfigByKey("tx_gas_limit").send(); - assertNotNull(txCountLimit.getSystemConfigByKey()); - assertNotNull(txGasLimit.getSystemConfigByKey()); + SystemConfig txCountLimit = web3j.getSystemConfigByKey("tx_count_limit").send(); + SystemConfig txGasLimit = web3j.getSystemConfigByKey("tx_gas_limit").send(); + assertNotNull(txCountLimit.getSystemConfigByKey()); + assertNotNull(txGasLimit.getSystemConfigByKey()); } - + @Test public void getCode() throws Exception { - Code code = web3j.getCode(address, DefaultBlockParameterName.LATEST).send(); - assertNotNull(code.getCode()); + Code code = web3j.getCode(address, DefaultBlockParameterName.LATEST).send(); + assertNotNull(code.getCode()); } - + @Test public void getTotalTransactionCount() throws Exception { - TotalTransactionCount count = web3j.getTotalTransactionCount().send(); - assertNotNull(count.getTotalTransactionCount()); + TotalTransactionCount count = web3j.getTotalTransactionCount().send(); + assertNotNull(count.getTotalTransactionCount()); } - + @Test public void getBlockByHash() throws Exception { - BcosBlock bcosBlock = web3j.getBlockByHash(blockHash, true).send(); - assertNotNull(bcosBlock.getBlock()); + BcosBlock bcosBlock = web3j.getBlockByHash(blockHash, true).send(); + assertNotNull(bcosBlock.getBlock()); } - + @Test public void getBlockByNumber() throws Exception { - BcosBlock bcosBlock = web3j.getBlockByNumber(DefaultBlockParameter.valueOf(blockNumber), true).send(); - assertNotNull(bcosBlock.getBlock()); + BcosBlock bcosBlock = + web3j.getBlockByNumber(DefaultBlockParameter.valueOf(blockNumber), true).send(); + assertNotNull(bcosBlock.getBlock()); } - + @Test public void getBlockHashByNumber() throws Exception { - BlockHash blockHash = web3j.getBlockHashByNumber(DefaultBlockParameter.valueOf(blockNumber)).send(); - assertNotNull(blockHash.getBlockHashByNumber()); + BlockHash blockHash = + web3j.getBlockHashByNumber(DefaultBlockParameter.valueOf(blockNumber)).send(); + assertNotNull(blockHash.getBlockHashByNumber()); } - + @Test public void getTransactionByHash() throws Exception { - BcosTransaction bcosTransaction = web3j.getTransactionByHash(blockHash).send(); - assertNotNull(bcosTransaction.getTransaction()); + BcosTransaction bcosTransaction = web3j.getTransactionByHash(blockHash).send(); + assertNotNull(bcosTransaction.getTransaction()); } + // @Test + // public void getTransactionByHashWithProof() throws IOException { + // TransactionWithProof transactionWithProof = + // web3j.getTransactionByHashWithProof(txHash).send(); + // Transaction transaction = transactionWithProof.getTransactionWithProof().getTransaction(); + // assertNotNull(transaction); + // List merkleProofUnits = + // transactionWithProof.getTransactionWithProof().getTxProof(); + // assertNotNull(merkleProofUnits); + // } + @Test - public void getTransactionByBlockNumberAndIndex() throws IOException { - BcosTransaction bcosTransaction = web3j.getTransactionByBlockNumberAndIndex(DefaultBlockParameter.valueOf(blockNumber), new BigInteger("0")).send(); - Transaction transaction = bcosTransaction.getTransaction().get(); - assertNotNull(transaction); - } - + public void getTransactionByBlockNumberAndIndex() throws IOException { + BcosTransaction bcosTransaction = + web3j + .getTransactionByBlockNumberAndIndex( + DefaultBlockParameter.valueOf(blockNumber), new BigInteger("0")) + .send(); + Transaction transaction = bcosTransaction.getTransaction().get(); + assertNotNull(transaction); + } + @Test public void getTransactionByBlockHashAndIndex() throws IOException { - BcosTransaction bcosTransaction = web3j.getTransactionByBlockHashAndIndex(blockHash, new BigInteger("0")).send(); - Transaction transaction = bcosTransaction.getTransaction().get(); - assertNotNull(transaction); + BcosTransaction bcosTransaction = + web3j.getTransactionByBlockHashAndIndex(blockHash, new BigInteger("0")).send(); + Transaction transaction = bcosTransaction.getTransaction().get(); + assertNotNull(transaction); } - + @Test public void getTransactionReceipt() throws IOException { - BcosTransactionReceipt bcosTransactionReceipt = web3j.getTransactionReceipt(txHash).send(); - TransactionReceipt transactionReceipt = bcosTransactionReceipt.getTransactionReceipt().get(); - assertNotNull(transactionReceipt); + BcosTransactionReceipt bcosTransactionReceipt = web3j.getTransactionReceipt(txHash).send(); + TransactionReceipt transactionReceipt = bcosTransactionReceipt.getTransactionReceipt().get(); + assertNotNull(transactionReceipt); } - + + // @Test + // public void getTransactionReceiptByHashWithProof() throws IOException { + // TransactionReceiptWithProof transactionReceiptWithProof = + // web3j.getTransactionReceiptByHashWithProof(txHash).send(); + // TransactionReceipt transactionReceipt = + // transactionReceiptWithProof.getTransactionReceiptWithProof().getTransactionReceipt(); + // assertNotNull(transactionReceipt); + // List merkleProofUnits = + // transactionReceiptWithProof.getTransactionReceiptWithProof().getReceiptProof(); + // assertNotNull(merkleProofUnits); + // } + @Test public void getPendingTransaction() throws IOException { - PendingTransactions pendingTransactions = web3j.getPendingTransaction().send(); - assertNotNull(pendingTransactions.getPendingTransactions()); + PendingTransactions pendingTransactions = web3j.getPendingTransaction().send(); + assertNotNull(pendingTransactions.getPendingTransactions()); } - + @Test public void getPendingTxSize() throws IOException { - PendingTxSize pendingTxSize = web3j.getPendingTxSize().send(); - assertNotNull(pendingTxSize.getPendingTxSize()); + PendingTxSize pendingTxSize = web3j.getPendingTxSize().send(); + assertNotNull(pendingTxSize.getPendingTxSize()); } - } diff --git a/src/main/java/org/fisco/bcos/channel/client/CallContract.java b/src/main/java/org/fisco/bcos/channel/client/CallContract.java new file mode 100644 index 000000000..99c038423 --- /dev/null +++ b/src/main/java/org/fisco/bcos/channel/client/CallContract.java @@ -0,0 +1,278 @@ +package org.fisco.bcos.channel.client; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import org.fisco.bcos.web3j.abi.FunctionEncoder; +import org.fisco.bcos.web3j.abi.FunctionReturnDecoder; +import org.fisco.bcos.web3j.abi.TypeReference; +import org.fisco.bcos.web3j.abi.Utils; +import org.fisco.bcos.web3j.abi.datatypes.DynamicArray; +import org.fisco.bcos.web3j.abi.datatypes.Function; +import org.fisco.bcos.web3j.abi.datatypes.StaticArray; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.Utf8String; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.StatusCode; +import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameterName; +import org.fisco.bcos.web3j.protocol.core.methods.request.Transaction; +import org.fisco.bcos.web3j.protocol.core.methods.response.Call; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; + +public class CallContract { + + private static final BigInteger gasPrice = new BigInteger("3000000000"); + private static final BigInteger gasLimit = new BigInteger("3000000000"); + + private Credentials credentials; + private Web3j web3j; + + public CallContract(Credentials credentials, Web3j web3j) { + this.credentials = credentials; + this.web3j = web3j; + } + + public CallResult call(String contractAddress, String funcName, Type... args) { + final Function function = + new Function( + funcName, + Arrays.asList(args), + Collections.>emptyList()); + String data = FunctionEncoder.encode(function); + Call ethCall; + try { + ethCall = + web3j.call( + Transaction.createEthCallTransaction( + credentials.getAddress(), contractAddress, data), + DefaultBlockParameterName.LATEST) + .send(); + } catch (Exception e) { + return new CallResult(StatusCode.ExceptionCatched, e.getMessage(), "0x"); + } + + Call.CallOutput callOutput = ethCall.getValue(); + if (callOutput != null) { + return new CallResult( + callOutput.getStatus(), + StatusCode.getStatusMessage(callOutput.getStatus()), + callOutput.getOutput()); + } else { + return new CallResult( + StatusCode.ErrorInRPC, + StatusCode.getStatusMessage(StatusCode.ErrorInRPC), + "0x"); + } + } + + public TransactionReceipt sendTransaction( + String contractAddress, String funcName, Type... args) { + final Function function = + new Function( + funcName, + Arrays.asList(args), + Collections.>emptyList()); + + TransactionReceipt transactionReceipt = new TransactionReceipt(); + try { + ExecuteTransaction executeTransaction = + new ExecuteTransaction(contractAddress, web3j, credentials, gasPrice, gasLimit); + + transactionReceipt = executeTransaction.send(function); + String status = transactionReceipt.getStatus(); + transactionReceipt.setMessage(StatusCode.getStatusMessage(status)); + + } catch (Exception e) { + transactionReceipt.setStatus(StatusCode.ExceptionCatched); + transactionReceipt.setMessage(e.getMessage()); + transactionReceipt.setOutput("0x"); + } + return transactionReceipt; + } + + public TransactionReceipt sendTransaction( + BigInteger gasPrice, + BigInteger gasLimit, + String contractAddress, + String funcName, + Type... args) { + final Function function = + new Function( + funcName, + Arrays.asList(args), + Collections.>emptyList()); + TransactionReceipt transactionReceipt = new TransactionReceipt(); + try { + ExecuteTransaction executeTransaction = + new ExecuteTransaction(contractAddress, web3j, credentials, gasPrice, gasLimit); + transactionReceipt = executeTransaction.send(function); + + String status = transactionReceipt.getStatus(); + transactionReceipt.setMessage(StatusCode.getStatusMessage(status)); + + } catch (Exception e) { + transactionReceipt.setStatus(StatusCode.ExceptionCatched); + transactionReceipt.setMessage(e.getMessage()); + transactionReceipt.setOutput("0x"); + } + return transactionReceipt; + } + + public void asyncSendTransaction( + TransactionSucCallback callback, + String contractAddress, + String funcName, + Type... args) { + final Function function = + new Function( + funcName, + Arrays.asList(args), + Collections.>emptyList()); + + ExecuteTransaction executeTransaction = + new ExecuteTransaction(contractAddress, web3j, credentials, gasPrice, gasLimit); + + executeTransaction.asyncSend(function, callback); + } + + public void asyncSendTransaction( + TransactionSucCallback callback, + BigInteger gasPrice, + BigInteger gasLimit, + String contractAddress, + String funcName, + Type... args) { + final Function function = + new Function( + funcName, + Arrays.asList(args), + Collections.>emptyList()); + + ExecuteTransaction executeTransaction = + new ExecuteTransaction(contractAddress, web3j, credentials, gasPrice, gasLimit); + + executeTransaction.asyncSend(function, callback); + } + + public List decode(String data, TypeReference... typeReferences) { + if (data.isEmpty() || data.equals("0x")) return null; + List> typeReferencesList = Arrays.>asList(typeReferences); + return FunctionReturnDecoder.decode(data, Utils.convert(typeReferencesList)); + } + + public List decode(String data, String retType) throws Exception { + List result = new ArrayList<>(); + if (!retType.equals("") && data != null) { + String types[] = retType.split(","); + List> references = getTypeReferenceList(types); + + List returns = FunctionReturnDecoder.decode(data, Utils.convert(references)); + + result = types2Objects(returns, types); + } + return result; + } + + private List> getTypeReferenceList(String types[]) throws Exception { + List> result = new ArrayList<>(); + for (String type : types) { + switch (type.trim()) { + case "Int": + { + result.add(new TypeReference() {}); + break; + } + case "String": + { + result.add(new TypeReference() {}); + break; + } + case "IntArray": + { + result.add(new TypeReference>() {}); + break; + } + case "StringArray": + { + result.add(new TypeReference>() {}); + break; + } + default: + { + throw new Exception("Unsupported type :" + type.trim()); + } + } + } + return result; + } + + public List types2Objects(List datas, String javaTypes[]) throws Exception { + if (datas.size() != javaTypes.length) { + throw new Exception("The number of data and types is different."); + } + + List result = new ArrayList<>(); + for (int i = 0; i < datas.size(); ++i) { + result.add(type2Object(datas.get(i), javaTypes[i])); + } + + return result; + } + + public Object type2Object(Type data, String javaType) throws Exception { + switch (javaType) { + case "Int": + { + return ((BigInteger) data.getValue()).intValue(); + } + case "String": + { + return (String) data.getValue(); + } + case "IntArray": + { + List bigIntegers = convertList((List) data.getValue()); + return bigIntegerstoIntegers(bigIntegers); + } + case "StringArray": + { + return convertList((List) data.getValue()); + } + default: + { + throw new Exception("Unsupported type :" + javaType); + } + } + } + + public List bigIntegerstoIntegers(List bigIntegers) { + List integers = new ArrayList<>(); + for (BigInteger bigInteger : bigIntegers) { + integers.add(bigInteger.intValue()); + } + return integers; + } + + @SuppressWarnings("unchecked") + public List convertList(List arr) { + List out = new ArrayList(); + for (Iterator it = arr.iterator(); it.hasNext(); ) { + out.add((T) it.next().getValue()); + } + return out; + } + + public List> convertListList(List> arrs) { + List> out = new ArrayList>(); + for (StaticArray arr : arrs) { + List temp = convertList(arr.getValue()); + out.add(temp); + } + return out; + } +} diff --git a/src/main/java/org/fisco/bcos/channel/client/CallResult.java b/src/main/java/org/fisco/bcos/channel/client/CallResult.java new file mode 100644 index 000000000..20b5d0e57 --- /dev/null +++ b/src/main/java/org/fisco/bcos/channel/client/CallResult.java @@ -0,0 +1,75 @@ +package org.fisco.bcos.channel.client; + +import java.util.Objects; + +public class CallResult { + private String status; + private String message; + private String output; + + public CallResult() {} + + public CallResult(String status, String message, String output) { + this.status = status; + this.message = message; + this.output = output; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getOutput() { + return output; + } + + public void setOutput(String output) { + this.output = output; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CallResult)) { + return false; + } + CallResult that = (CallResult) o; + return Objects.equals(getStatus(), that.getStatus()) + && Objects.equals(getMessage(), that.getMessage()) + && Objects.equals(getOutput(), that.getOutput()); + } + + @Override + public int hashCode() { + return Objects.hash(getStatus(), getMessage(), getOutput()); + } + + @Override + public String toString() { + return "CallResult{" + + "status='" + + status + + '\'' + + ", message='" + + message + + '\'' + + ", output='" + + output + + '\'' + + '}'; + } +} diff --git a/src/main/java/org/fisco/bcos/channel/client/ExecuteTransaction.java b/src/main/java/org/fisco/bcos/channel/client/ExecuteTransaction.java new file mode 100644 index 000000000..bf5653f57 --- /dev/null +++ b/src/main/java/org/fisco/bcos/channel/client/ExecuteTransaction.java @@ -0,0 +1,28 @@ +package org.fisco.bcos.channel.client; + +import java.math.BigInteger; +import org.fisco.bcos.web3j.abi.datatypes.Function; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tx.Contract; + +public class ExecuteTransaction extends Contract { + + public ExecuteTransaction( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super("", contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public TransactionReceipt send(Function function) throws Exception { + return executeTransaction(function); + } + + public void asyncSend(Function function, TransactionSucCallback callback) { + asyncExecuteTransaction(function, callback); + } +} diff --git a/src/main/java/org/fisco/bcos/channel/client/Merkle.java b/src/main/java/org/fisco/bcos/channel/client/Merkle.java new file mode 100644 index 000000000..0d9ab0db3 --- /dev/null +++ b/src/main/java/org/fisco/bcos/channel/client/Merkle.java @@ -0,0 +1,34 @@ +package org.fisco.bcos.channel.client; + +import java.util.Arrays; +import java.util.List; +import org.fisco.bcos.web3j.crypto.Hash; +import org.fisco.bcos.web3j.protocol.core.methods.response.MerkleProofUnit; + +public class Merkle { + public static String calculateMerkleRoot(List merkleProofUnits, String hash) { + if (merkleProofUnits == null) { + return hash; + } + String result = hash; + for (MerkleProofUnit merkleProofUnit : merkleProofUnits) { + String left = splicing(merkleProofUnit.getLeft()); + String right = splicing(merkleProofUnit.getRight()); + String input = splicing("0x", left, result.substring(2), right); + result = Hash.sha3(input); + } + return result; + } + + private static String splicing(List stringList) { + StringBuilder result = new StringBuilder(); + for (String eachString : stringList) { + result.append(eachString); + } + return result.toString(); + } + + private static String splicing(String... stringList) { + return splicing(Arrays.asList(stringList)); + } +} diff --git a/src/main/java/org/fisco/bcos/channel/client/ReceiptEncoder.java b/src/main/java/org/fisco/bcos/channel/client/ReceiptEncoder.java new file mode 100644 index 000000000..e589f2a94 --- /dev/null +++ b/src/main/java/org/fisco/bcos/channel/client/ReceiptEncoder.java @@ -0,0 +1,62 @@ +package org.fisco.bcos.channel.client; + +import java.util.ArrayList; +import java.util.List; +import org.fisco.bcos.web3j.protocol.core.methods.response.Log; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.rlp.RlpEncoder; +import org.fisco.bcos.web3j.rlp.RlpList; +import org.fisco.bcos.web3j.rlp.RlpString; +import org.fisco.bcos.web3j.rlp.RlpType; +import org.fisco.bcos.web3j.utils.Numeric; + +// encode transaction receipt by Rlp into hex string +public class ReceiptEncoder { + public static String encode(TransactionReceipt transactionReceipt) { + List values = asRlpValues(transactionReceipt); + RlpList rlpList = new RlpList(values); + byte[] rlpBytes = RlpEncoder.encode(rlpList); + return Numeric.toHexString(rlpBytes); + } + + private static List asRlpValues(TransactionReceipt transactionReceipt) { + List result = new ArrayList<>(); + // bytes + result.add(RlpString.create(Numeric.hexStringToByteArray(transactionReceipt.getRoot()))); + + // BigInteger + result.add(RlpString.create(Numeric.toBigInt(transactionReceipt.getGasUsedRaw()))); + + result.add( + RlpString.create( + Numeric.hexStringToByteArray(transactionReceipt.getContractAddress()))); + + result.add( + RlpString.create(Numeric.hexStringToByteArray(transactionReceipt.getLogsBloom()))); + + result.add(RlpString.create(Numeric.toBigInt(transactionReceipt.getStatus()))); + + result.add(RlpString.create(Numeric.hexStringToByteArray(transactionReceipt.getOutput()))); + + // List + List logs = transactionReceipt.getLogs(); + List logList = new ArrayList<>(); + for (Log log : logs) { + List logUnit = new ArrayList<>(); + logUnit.add(RlpString.create(Numeric.hexStringToByteArray(log.getAddress()))); + + List topics = log.getTopics(); + List topicList = new ArrayList<>(); + for (String topic : topics) { + topicList.add(RlpString.create(Numeric.hexStringToByteArray(topic))); + } + RlpList topicRlpList = new RlpList(topicList); + logUnit.add(topicRlpList); + logUnit.add(RlpString.create(Numeric.hexStringToByteArray(log.getData()))); + logList.add(new RlpList(logUnit)); + } + RlpList logRlpList = new RlpList(logList); + result.add(logRlpList); + return result; + } +} diff --git a/src/main/java/org/fisco/bcos/channel/client/Service.java b/src/main/java/org/fisco/bcos/channel/client/Service.java index 4a4e6ceb7..4f13e8958 100644 --- a/src/main/java/org/fisco/bcos/channel/client/Service.java +++ b/src/main/java/org/fisco/bcos/channel/client/Service.java @@ -85,8 +85,9 @@ public class Service { public static final String topicNeedVerifyPrefix = "#!$TopicNeedVerify_"; private Integer connectSeconds = 30; + private boolean setJavaOpt = true; - private Integer connectSleepPerMillis = 1; + private Integer connectSleepPerMillis = 30; private String orgID; private String agencyName; private GroupChannelConnectionsConfig allChannelConnections; @@ -287,8 +288,19 @@ private void parseFromTopic2KeyInfo() addTopics(set); } + public void initJavaOpt() { + System.setProperty("jdk.tls.namedGroups", "secp256k1"); + logger.info( + "set jdk.tls.namedGroups opt, value : {}", + System.getProperty("jdk.tls.namedGroups")); + } + public void run() throws Exception { logger.debug("init ChannelService"); + + if (setJavaOpt) { + initJavaOpt(); + } parseFromTopic2KeyInfo(); int flag = 0; @@ -316,13 +328,18 @@ public void run() throws Exception { while (true) { Map networkConnection = channelConnections.getNetworkConnections(); - for (String key : networkConnection.keySet()) { - if (networkConnection.get(key) != null - && ChannelHandlerContextHelper.isChannelAvailable( - networkConnection.get(key))) { - running = true; - break; + channelConnections.getReadWriteLock().readLock().lock(); + try { + for (String key : networkConnection.keySet()) { + if (networkConnection.get(key) != null + && ChannelHandlerContextHelper.isChannelAvailable( + networkConnection.get(key))) { + running = true; + break; + } } + } finally { + channelConnections.getReadWriteLock().readLock().unlock(); } if (running || sleepTime > connectSeconds * 1000) { @@ -335,12 +352,39 @@ public void run() throws Exception { if (!running) { logger.error("connectSeconds = {}", connectSeconds); - logger.error( - "can not connect to nodes success, please checkout the node status and the sdk config!"); - throw new Exception( - "Can not connect to nodes success, please checkout the node status and the sdk config!"); + + String errorMessage = + " Can not connect to nodes " + + channelConnections.getConnectionsStr() + + " ,groupId: " + + String.valueOf(groupId) + + " ,caCert: " + + channelConnections.getCaCert() + + " ,sslKey: " + + channelConnections.getSslKey() + + " ,sslCert: " + + channelConnections.getSslCert() + + " ,java version: " + + System.getProperty("java.version"); + + logger.error(errorMessage); + throw new Exception(errorMessage); } + logger.info( + " Connect to nodes [" + + channelConnections.getConnectionsStr() + + "], groupId: " + + String.valueOf(groupId) + + " ,caCert: " + + channelConnections.getCaCert() + + " ,sslKey: " + + channelConnections.getSslKey() + + " ,sslCert: " + + channelConnections.getSslCert() + + " ,java version: " + + System.getProperty("java.version")); + eventLogFilterManager.start(); } catch (InterruptedException e) { logger.error("system error ", e); @@ -1535,4 +1579,12 @@ public Timer getTimeoutHandler() { public void setTimeoutHandler(Timer timeoutHandler) { this.timeoutHandler = timeoutHandler; } + + public boolean isSetJavaOpt() { + return setJavaOpt; + } + + public void setSetJavaOpt(boolean setJavaOpt) { + this.setJavaOpt = setJavaOpt; + } } diff --git a/src/main/java/org/fisco/bcos/channel/client/TransactionResource.java b/src/main/java/org/fisco/bcos/channel/client/TransactionResource.java new file mode 100644 index 000000000..f924eb0ab --- /dev/null +++ b/src/main/java/org/fisco/bcos/channel/client/TransactionResource.java @@ -0,0 +1,140 @@ +package org.fisco.bcos.channel.client; + +import java.io.IOException; +import java.math.BigInteger; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.fisco.bcos.web3j.crypto.Hash; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.methods.response.Transaction; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceiptWithProof; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionWithProof; +import org.fisco.bcos.web3j.rlp.RlpEncoder; +import org.fisco.bcos.web3j.rlp.RlpString; +import org.fisco.bcos.web3j.utils.Numeric; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TransactionResource { + private static final Logger logger = LoggerFactory.getLogger(TransactionResource.class); + + private Web3j web3j; + + public TransactionResource(Web3j web3j) { + this.web3j = web3j; + } + + public TransactionWithProof getTransactionWithProof(String transactionHash, String rootHash) + throws IOException { + TransactionWithProof transactionWithProof = + web3j.getTransactionByHashWithProof(transactionHash).send(); + if (transactionWithProof.getTransactionWithProof() == null) { + return null; + } + + Transaction transaction = transactionWithProof.getTransactionWithProof().getTransaction(); + logger.debug("Transaction:{}", transaction); + + // transaction index + String index = transaction.getTransactionIndexRaw(); + BigInteger indexValue = Numeric.toBigInt(index); + byte[] byteIndex = RlpEncoder.encode(RlpString.create(indexValue)); + String input = Numeric.toHexString(byteIndex) + transactionHash.substring(2); + logger.info("TransWithIndex:{}", input); + + String proof = + Merkle.calculateMerkleRoot( + transactionWithProof.getTransactionWithProof().getTxProof(), input); + // System.out.println("MerkleRoot: " + proof); + + if (!proof.equals(rootHash)) { + logger.debug("MerkleRoot:{}", proof); + logger.debug("TransRoot :{}", rootHash); + return null; + } + return transactionWithProof; + } + + public TransactionReceiptWithProof getTransactionReceiptWithProof( + String transactionHash, String rootHash) throws IOException { + TransactionReceiptWithProof transactionReceiptWithProof = + web3j.getTransactionReceiptByHashWithProof(transactionHash).send(); + + if (transactionReceiptWithProof.getTransactionReceiptWithProof() == null) { + return null; + } + TransactionReceipt transactionReceipt = + transactionReceiptWithProof + .getTransactionReceiptWithProof() + .getTransactionReceipt(); + logger.debug("Receipt {}", transactionReceipt.toString()); + + // transaction index + String index = transactionReceipt.getTransactionIndexRaw(); + BigInteger indexValue = Numeric.toBigInt(index); + byte[] byteIndex = RlpEncoder.encode(RlpString.create(indexValue)); + + String receiptRlp = ReceiptEncoder.encode(transactionReceipt); + logger.debug("ReceiptRlp:{}", receiptRlp); + + String rlpHash = Hash.sha3(receiptRlp); + logger.debug("ReceiptRlpHash:{}", rlpHash); + + String input = Numeric.toHexString(byteIndex) + rlpHash.substring(2); + logger.info("ReceiptWithIndex:{}", input); + + String proof = + Merkle.calculateMerkleRoot( + transactionReceiptWithProof + .getTransactionReceiptWithProof() + .getReceiptProof(), + input); + + // System.out.println("MerkleRoot: " + proof); + if (!proof.equals(rootHash)) { + logger.debug("MerkleRoot:{}", proof); + logger.debug("TransRoot :{}", rootHash); + return null; + } + return transactionReceiptWithProof; + } + + public ImmutablePair + getTransactionAndReceiptWithProof( + String transactionHash, String transactionsRoot, String receiptsRoot) + throws IOException { + TransactionWithProof transactionWithProof = + getTransactionWithProof(transactionHash, transactionsRoot); + if (transactionWithProof == null) { + return null; + } + + TransactionReceiptWithProof transactionReceiptWithProof = + getTransactionReceiptWithProof(transactionHash, receiptsRoot); + if (transactionReceiptWithProof == null) { + return null; + } + + String indexFromTransaction = + transactionWithProof + .getTransactionWithProof() + .getTransaction() + .getTransactionIndexRaw(); + + String indexFromReceipt = + transactionReceiptWithProof + .getTransactionReceiptWithProof() + .getTransactionReceipt() + .getTransactionIndexRaw(); + + logger.debug( + "indexFromTransaction:{}, indexFromReceipt:{}", + indexFromTransaction, + indexFromReceipt); + if (!indexFromTransaction.equals(indexFromReceipt)) { + return null; + } + + return new ImmutablePair<>(transactionWithProof, transactionReceiptWithProof); + } +} diff --git a/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java b/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java index c74c8f2b4..49f0f7151 100644 --- a/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java +++ b/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java @@ -31,7 +31,10 @@ import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.net.ssl.SSLException; +import org.fisco.bcos.web3j.tuples.generated.Tuple2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; @@ -56,6 +59,8 @@ public class ChannelConnections { private ThreadPoolTaskExecutor threadPool; private long idleTimeout = (long) 10000; private long heartBeatDelay = (long) 2000; + + public ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public Map networkConnections = new HashMap(); private int groupId; @@ -201,12 +206,17 @@ public ChannelHandlerContext randomNetworkConnection( ConcurrentHashMap nodeToBlockNumberMap) throws Exception { List activeConnections = new ArrayList(); - for (String key : networkConnections.keySet()) { - if (networkConnections.get(key) != null - && ChannelHandlerContextHelper.isChannelAvailable( - networkConnections.get(key))) { - activeConnections.add(networkConnections.get(key)); + getReadWriteLock().readLock().lock(); + try { + for (String key : networkConnections.keySet()) { + if (networkConnections.get(key) != null + && ChannelHandlerContextHelper.isChannelAvailable( + networkConnections.get(key))) { + activeConnections.add(networkConnections.get(key)); + } } + } finally { + getReadWriteLock().readLock().unlock(); } if (activeConnections.isEmpty()) { @@ -276,20 +286,37 @@ public Map getNetworkConnections() { public ChannelHandlerContext getNetworkConnectionByHost(String host, Integer port) { String endpoint = host + ":" + port; + ChannelHandlerContext channelHandlerContext = null; + getReadWriteLock().readLock().lock(); + try { + channelHandlerContext = networkConnections.get(endpoint); + } finally { + getReadWriteLock().readLock().unlock(); + } - return networkConnections.get(endpoint); + return channelHandlerContext; } public void setNetworkConnectionByHost(String host, Integer port, ChannelHandlerContext ctx) { String endpoint = host + ":" + port; - networkConnections.put(endpoint, ctx); + getReadWriteLock().writeLock().lock(); + try { + networkConnections.put(endpoint, ctx); + } finally { + getReadWriteLock().writeLock().unlock(); + } } public void removeNetworkConnectionByHost(String host, Integer port) { String endpoint = host + ":" + port; - networkConnections.remove(endpoint); + getReadWriteLock().writeLock().lock(); + try { + networkConnections.remove(endpoint); + } finally { + getReadWriteLock().writeLock().unlock(); + } } public void startListen(Integer port) throws SSLException { @@ -323,7 +350,6 @@ public void initChannel(SocketChannel ch) throws Exception { */ ChannelHandler handler = new ChannelHandler(); handler.setConnections(selfService); - handler.setIsServer(true); handler.setThreadPool(selfThreadPool); ch.pipeline() @@ -404,7 +430,6 @@ public void initChannel(SocketChannel ch) throws Exception { */ ChannelHandler handler = new ChannelHandler(); handler.setConnections(selfService); - handler.setIsServer(false); handler.setThreadPool(selfThreadPool); ch.pipeline() @@ -494,31 +519,53 @@ private SslContext initSslContextForListening() throws SSLException { } public void reconnect() { - for (Entry ctx : networkConnections.entrySet()) { - if (ctx.getValue() == null || !ctx.getValue().channel().isActive()) { - String[] split = ctx.getKey().split(":"); - String host = split[0]; - Integer port = Integer.parseInt(split[1]); - logger.info("try connect to: {}:{}", host, port); + List shouldConnectNodes = new ArrayList<>(); + List> shouldHeatBeatNodes = new ArrayList<>(); - bootstrap.connect(host, port); - // logger.debug("connect to: {}:{} success", host, port); - } else { - if (ChannelHandlerContextHelper.isChannelAvailable(ctx.getValue())) { - logger.trace("send heart beat to {}", ctx.getKey()); - callback.sendHeartbeat(ctx.getValue()); + getReadWriteLock().readLock().lock(); + try { + for (Entry ctx : networkConnections.entrySet()) { + if (ctx.getValue() == null || !ctx.getValue().channel().isActive()) { + shouldConnectNodes.add(ctx.getKey()); } else { - logger.debug( - " socket channel active, channel protocol handshake not finished, host: {}, ctx: {}", - ctx.getKey(), - System.identityHashCode(ctx.getValue())); + if (ChannelHandlerContextHelper.isChannelAvailable(ctx.getValue())) { + shouldHeatBeatNodes.add( + new Tuple2( + ctx.getKey(), ctx.getValue())); + } } } + } finally { + getReadWriteLock().readLock().unlock(); + } + + for (int j = 0; j < shouldHeatBeatNodes.size(); ++j) { + logger.trace("send heart beat to {}", shouldHeatBeatNodes.get(j).getValue1()); + callback.sendHeartbeat(shouldHeatBeatNodes.get(j).getValue2()); + } + + for (int i = 0; i < shouldConnectNodes.size(); ++i) { + String[] split = shouldConnectNodes.get(i).split(":"); + + String host = split[0]; + Integer port = Integer.parseInt(split[1]); + logger.info("try connect to: {}:{}", host, port); + + bootstrap.connect(host, port); + // logger.debug("connect to: {}:{} success", host, port); } } public void onReceiveMessage(ChannelHandlerContext ctx, ByteBuf message) { callback.onMessage(ctx, message); } + + public ReadWriteLock getReadWriteLock() { + return readWriteLock; + } + + public void setReadWriteLock(ReadWriteLock readWriteLock) { + this.readWriteLock = readWriteLock; + } } diff --git a/src/main/java/org/fisco/bcos/channel/handler/ChannelHandler.java b/src/main/java/org/fisco/bcos/channel/handler/ChannelHandler.java index 2ffefe7f5..97798ef48 100644 --- a/src/main/java/org/fisco/bcos/channel/handler/ChannelHandler.java +++ b/src/main/java/org/fisco/bcos/channel/handler/ChannelHandler.java @@ -55,31 +55,19 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { + "]," + String.valueOf(ctx.channel().isActive())); - if (isServer) { - logger.debug("server accept new connect: {}:{}", host, port); - // add the connection to the connections - ConnectionInfo info = new ConnectionInfo(); - info.setHost(host); - info.setPort(port); - - connections.getConnections().add(info); - connections.setNetworkConnectionByHost(info.getHost(), info.getPort(), ctx); - connections.getCallback().onConnect(ctx); + // 更新ctx信息 + ChannelHandlerContext connection = connections.getNetworkConnectionByHost(host, port); + if (connection != null && connection.channel().isActive()) { + logger.debug("connect available, close reconnect: {}:{}", host, port); + + ctx.channel().disconnect(); + ctx.channel().close(); } else { - // 更新ctx信息 - ChannelHandlerContext connection = - connections.getNetworkConnectionByHost(host, port); - if (connection != null && connection.channel().isActive()) { - logger.debug("connect available, close reconnect: {}:{}", host, port); - - ctx.channel().disconnect(); - ctx.channel().close(); - } else { - logger.debug("client connect success {}:{}", host, port); - connections.setNetworkConnectionByHost(host, port, ctx); - connections.getCallback().onConnect(ctx); - } + logger.debug("client connect success {}:{}", host, port); + connections.setNetworkConnectionByHost(host, port, ctx); + connections.getCallback().onConnect(ctx); } + } catch (Exception e) { logger.error("error", e); } @@ -102,22 +90,8 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { + " ," + String.valueOf(ctx.channel().isActive())); - if (isServer) { - // server mode,remove the connection - for (Integer i = 0; i < connections.getConnections().size(); ++i) { - ConnectionInfo info = connections.getConnections().get(i); - - if (info.getHost().equals(host) && info.getPort().equals(port)) { - connections.getConnections().remove(i); - } - } - - // remove the networkConnection - connections.removeNetworkConnectionByHost(host, port); - } else { - // set the connection disabled - // connections.setNetworkConnection(host, port, null); - } + // set the connection disabled + // connections.setNetworkConnection(host, port, null) connections.getCallback().onDisconnect(ctx); } catch (Exception e) { @@ -163,13 +137,8 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + " ," + String.valueOf(ctx.channel().isActive())); - if (isServer) { - // server mode,remove the connection - connections.removeNetworkConnectionByHost(host, port); - } else { - // set the connection disabled - // connections.setNetworkConnection(host, port, null); - } + // set the connection disabled + // connections.setNetworkConnection(host, port, null); ctx.disconnect(); ctx.close(); @@ -190,14 +159,6 @@ public void setConnections(ChannelConnections connections) { this.connections = connections; } - public Boolean getIsServer() { - return isServer; - } - - public void setIsServer(Boolean isServer) { - this.isServer = isServer; - } - public ThreadPoolTaskExecutor getThreadPool() { return threadPool; } @@ -209,6 +170,5 @@ public void setThreadPool(ThreadPoolTaskExecutor threadPool) { } private ChannelConnections connections; - private Boolean isServer = false; private ThreadPoolTaskExecutor threadPool; } diff --git a/src/main/java/org/fisco/bcos/channel/handler/ChannelHandlerContextHelper.java b/src/main/java/org/fisco/bcos/channel/handler/ChannelHandlerContextHelper.java index c2e3658e3..a7eb8f2e1 100644 --- a/src/main/java/org/fisco/bcos/channel/handler/ChannelHandlerContextHelper.java +++ b/src/main/java/org/fisco/bcos/channel/handler/ChannelHandlerContextHelper.java @@ -45,13 +45,16 @@ public static EnumChannelProtocolVersion getProtocolVersion(ChannelHandlerContex if (ctx.channel().hasAttr(attributeKey)) { ChannelProtocol channelProtocol = ctx.channel().attr(attributeKey).get(); - logger.trace(" host: {}, channel protocol: {}", host, channelProtocol); + if (null != channelProtocol) { + // logger.trace(" host: {}, channel protocol: {}", host, channelProtocol); - return channelProtocol.getEnumProtocol(); - - } else { // default channel version - return null; + return channelProtocol.getEnumProtocol(); + } else { + logger.debug(" channel has attr but get null, host: {}", host); + } } + + return null; } public static String getPeerHost(ChannelHandlerContext ctx) { diff --git a/src/main/java/org/fisco/bcos/channel/protocol/EnumChannelProtocolVersion.java b/src/main/java/org/fisco/bcos/channel/protocol/EnumChannelProtocolVersion.java index ed081a99d..d0ea9a493 100644 --- a/src/main/java/org/fisco/bcos/channel/protocol/EnumChannelProtocolVersion.java +++ b/src/main/java/org/fisco/bcos/channel/protocol/EnumChannelProtocolVersion.java @@ -2,7 +2,8 @@ public enum EnumChannelProtocolVersion { VERSION_1(1), // default version - VERSION_2(2); + VERSION_2(2), + VERSION_3(3); private int versionNumber; diff --git a/src/main/java/org/fisco/bcos/channel/protocol/parser/BlockNotificationParser.java b/src/main/java/org/fisco/bcos/channel/protocol/parser/BlockNotificationParser.java index 657b30efe..de54d815a 100644 --- a/src/main/java/org/fisco/bcos/channel/protocol/parser/BlockNotificationParser.java +++ b/src/main/java/org/fisco/bcos/channel/protocol/parser/BlockNotificationParser.java @@ -29,13 +29,6 @@ public BcosBlockNotification decode(String data) BcosBlockNotification bcosBlkNotify = new BcosBlockNotification(); switch (getVersion()) { - case VERSION_2: - { - bcosBlkNotify = - ObjectMapperFactory.getObjectMapper() - .readValue(data, BcosBlockNotification.class); - } - break; case VERSION_1: { String[] split = data.split(","); @@ -49,6 +42,11 @@ public BcosBlockNotification decode(String data) } break; default: + { + bcosBlkNotify = + ObjectMapperFactory.getObjectMapper() + .readValue(data, BcosBlockNotification.class); + } break; } diff --git a/src/main/java/org/fisco/bcos/channel/protocol/parser/HeartBeatParser.java b/src/main/java/org/fisco/bcos/channel/protocol/parser/HeartBeatParser.java index 203a2efc6..41ce792f8 100644 --- a/src/main/java/org/fisco/bcos/channel/protocol/parser/HeartBeatParser.java +++ b/src/main/java/org/fisco/bcos/channel/protocol/parser/HeartBeatParser.java @@ -29,19 +29,17 @@ public byte[] encode(String value) throws JsonProcessingException { byte[] result = null; switch (getVersion()) { - case VERSION_2: - { - BcosHeartbeat bcosHeartbeat = new BcosHeartbeat(); - bcosHeartbeat.setHeartBeat(Integer.parseInt(value)); - result = ObjectMapperFactory.getObjectMapper().writeValueAsBytes(bcosHeartbeat); - } - break; case VERSION_1: { result = value.getBytes(); } break; default: + { + BcosHeartbeat bcosHeartbeat = new BcosHeartbeat(); + bcosHeartbeat.setHeartBeat(Integer.parseInt(value)); + result = ObjectMapperFactory.getObjectMapper().writeValueAsBytes(bcosHeartbeat); + } break; } @@ -53,19 +51,17 @@ public BcosHeartbeat decode(String data) BcosHeartbeat bcosHeartbeat = new BcosHeartbeat(); switch (getVersion()) { - case VERSION_2: - { - bcosHeartbeat = - ObjectMapperFactory.getObjectMapper() - .readValue(data, BcosHeartbeat.class); - } - break; case VERSION_1: { bcosHeartbeat.setHeartBeat(Integer.parseInt(data)); } break; default: + { + bcosHeartbeat = + ObjectMapperFactory.getObjectMapper() + .readValue(data, BcosHeartbeat.class); + } break; } diff --git a/src/main/java/org/fisco/bcos/channel/proxy/ConnectionPair.java b/src/main/java/org/fisco/bcos/channel/proxy/ConnectionPair.java deleted file mode 100644 index 8712f9693..000000000 --- a/src/main/java/org/fisco/bcos/channel/proxy/ConnectionPair.java +++ /dev/null @@ -1,181 +0,0 @@ -package org.fisco.bcos.channel.proxy; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.util.Timeout; -import io.netty.util.TimerTask; -import java.security.SecureRandom; -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import org.fisco.bcos.channel.dto.ChannelResponse; -import org.fisco.bcos.channel.handler.ChannelConnections; -import org.fisco.bcos.channel.handler.ConnectionInfo; -import org.fisco.bcos.channel.handler.Message; -import org.fisco.bcos.channel.protocol.ChannelMessageError; -import org.fisco.bcos.channel.protocol.ChannelMessageType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -class ConnectionPair { - private static Logger logger = LoggerFactory.getLogger(ConnectionPair.class); - - public ChannelHandlerContext localConnection; // SDK connect - public ChannelHandlerContext remoteConnection; // node connect - public Timeout timeout; - - private Message message; - private ConnectionInfo remoteConnectionInfo; - private List remoteConnectionInfos; - private ChannelConnections remoteChannelConnections; - private Server server; - - public Message getMessage() { - return message; - } - - public void setMessage(Message message) { - this.message = message; - } - - public ConnectionInfo getRemoteConnectionInfo() { - return remoteConnectionInfo; - } - - public void setRemoteConnectionInfo(ConnectionInfo remoteConnectionInfo) { - this.remoteConnectionInfo = remoteConnectionInfo; - } - - public List getRemoteConnectionInfos() { - return remoteConnectionInfos; - } - - public void setRemoteConnectionInfos(List remoteConnectionInfos) { - this.remoteConnectionInfos = remoteConnectionInfos; - } - - public ChannelConnections getRemoteChannelConnections() { - return remoteChannelConnections; - } - - public void setRemoteChannelConnections(ChannelConnections remoteChannelConnections) { - this.remoteChannelConnections = remoteChannelConnections; - } - - public Server getServer() { - return server; - } - - public void setServer(Server server) { - this.server = server; - } - - public void init() { - final ConnectionPair self = this; - final String seq = message.getSeq(); - - timeout = - server.getTimeoutHandler() - .newTimeout( - new TimerTask() { - private ConnectionPair selfServer = self; - private String selfSeq = seq; - - @Override - public void run(Timeout timeout) throws Exception { - // 处理超时逻辑 - logger.trace("clean timeout session:{}", selfSeq); - - selfServer.server.getSeq2Connections().remove(selfSeq); - } - }, - 30000, - TimeUnit.MILLISECONDS); - } - - public void retrySendRemoteMessage() { - Integer errorCode = 0; - try { - // 选取客户端节点 - logger.debug("remoteConnection size :{}", remoteConnectionInfos.size()); - - remoteConnectionInfo = null; - if (remoteConnectionInfos.size() > 0) { - Random random = new SecureRandom(); - Integer index = random.nextInt(remoteConnectionInfos.size()); - - logger.debug("selected:{}", index); - - remoteConnectionInfo = remoteConnectionInfos.get(index); - - remoteConnectionInfos.remove(remoteConnectionInfos.get(index)); - } - - if (remoteConnectionInfo == null) { - // 所有节点已尝试,无法再重试了 - logger.error("remoteConnectionInfo null"); - - errorCode = ChannelMessageError.NODES_UNREACHABLE.getError(); - throw new Exception("remoteConnectionInfo null"); - } - - ChannelHandlerContext ctx = - remoteChannelConnections.getNetworkConnectionByHost( - remoteConnectionInfo.getHost(), remoteConnectionInfo.getPort()); - remoteConnection = ctx; - - if (ctx != null && ctx.channel().isActive()) { - ByteBuf out = ctx.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - ctx.writeAndFlush(out); - - logger.debug( - "send message to " - + remoteConnectionInfo.getHost() - + ":" - + String.valueOf(remoteConnectionInfo.getPort()) - + " success"); - } else { - logger.error("local node inactive"); - retrySendRemoteMessage(); - } - } catch (Exception e) { - logger.error("send message error", e); - - ChannelResponse response = new ChannelResponse(); - response.setErrorCode(errorCode); - response.setErrorMessage(e.getMessage()); - - // 找不到连接,错误 - logger.error("connection error 99"); - - if (message.getType() == (short) ChannelMessageType.AMOP_REQUEST.getType() - || message.getType() == ChannelMessageType.AMOP_RESPONSE.getType()) { - message.setType((short) ChannelMessageType.AMOP_RESPONSE.getType()); - } else { - // ethereum消息,不用改类型 - } - - message.setResult(ChannelMessageError.NODES_UNREACHABLE.getError()); - - ByteBuf out = localConnection.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - localConnection.writeAndFlush(out); - - // 彻底失败后,删掉这个seq - if (message.getSeq() != null) { - server.getSeq2Connections().remove(message.getSeq()); - } - - if (timeout != null) { - timeout.cancel(); - } - - return; - } - } -} diff --git a/src/main/java/org/fisco/bcos/channel/proxy/ResponseCallback.java b/src/main/java/org/fisco/bcos/channel/proxy/ResponseCallback.java deleted file mode 100644 index 8fd4e774f..000000000 --- a/src/main/java/org/fisco/bcos/channel/proxy/ResponseCallback.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.fisco.bcos.channel.proxy; - -import org.fisco.bcos.channel.handler.Message; - -public interface ResponseCallback { - public void onResponse(Message response); -} diff --git a/src/main/java/org/fisco/bcos/channel/proxy/Server.java b/src/main/java/org/fisco/bcos/channel/proxy/Server.java deleted file mode 100644 index 750270495..000000000 --- a/src/main/java/org/fisco/bcos/channel/proxy/Server.java +++ /dev/null @@ -1,529 +0,0 @@ -package org.fisco.bcos.channel.proxy; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.socket.SocketChannel; -import io.netty.util.HashedWheelTimer; -import io.netty.util.Timer; -import java.io.UnsupportedEncodingException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import javax.net.ssl.SSLException; -import org.fisco.bcos.channel.handler.ChannelConnections; -import org.fisco.bcos.channel.handler.ConnectionInfo; -import org.fisco.bcos.channel.handler.Message; -import org.fisco.bcos.channel.protocol.ChannelMessageError; -import org.fisco.bcos.channel.protocol.ChannelMessageType; -import org.fisco.bcos.web3j.protocol.ObjectMapperFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; - -public class Server { - private static Logger logger = LoggerFactory.getLogger(Server.class); - - class ConnectionCallback implements ChannelConnections.Callback { - public Server getServer() { - return server; - } - - public void setServer(Server server) { - this.server = server; - } - - public Boolean getFromRemote() { - return fromRemote; - } - - public void setFromRemote(Boolean fromRemote) { - this.fromRemote = fromRemote; - } - - @Override - public void onMessage(ChannelHandlerContext ctx, ByteBuf message) { - try { - Message msg = new Message(); - msg.readHeader(message); - msg.readExtra(message); - - logger.debug("receive Message type: {}", msg.getType()); - - if (msg.getType() == ChannelMessageType.AMOP_REQUEST.getType() - || msg.getType() == ChannelMessageType.AMOP_RESPONSE.getType()) { - logger.debug("channel2"); - } else if (msg.getType() == ChannelMessageType.AMOP_CLIENT_TOPICS.getType()) { - logger.debug("topic"); - - onTopic(ctx, msg); - return; - } else if (msg.getType() == ChannelMessageType.CHANNEL_RPC_REQUEST.getType()) { - logger.debug("ethereum"); - } else if (msg.getType() == ChannelMessageType.CLIENT_HEARTBEAT.getType()) { - onHeartBeat(ctx, msg); - return; - } else if (msg.getType() == ChannelMessageType.TRANSACTION_NOTIFY.getType()) { - logger.debug("transaction message call back."); - } else { - logger.error("unknown message:{}", msg.getType()); - } - - if (fromRemote) { - logger.debug("remote message"); - server.onRemoteMessage(ctx, msg); - } else { - logger.debug("local message"); - server.onLocalMessage(ctx, msg); - } - } finally { - message.release(); - } - } - - @Override - public void onConnect(ChannelHandlerContext ctx) { - // 成功连接到新节点,发送topic - if (fromRemote) { - try { - logger.debug("endpoint connection established,send topic"); - broadcastTopic(ctx); - } catch (Exception e) { - logger.error("error ", e); - } - } - } - - @Override - public void onDisconnect(ChannelHandlerContext ctx) { - // 有sdk断开,需更新topic - if (!fromRemote) { - // 需要清除该连接的信息 - logger.debug("SDK disconnect,update and broadcast topic"); - - broadcastTopic(); - } - } - - private Server server; - private Boolean fromRemote = false; - - @Override - public void sendHeartbeat(ChannelHandlerContext ctx) { - SocketChannel socketChannel = (SocketChannel) ctx.channel(); - String hostAddress = socketChannel.remoteAddress().getAddress().getHostAddress(); - int port = socketChannel.remoteAddress().getPort(); - - String remoteEndPoint = hostAddress + ":" + port; - - logger.trace("proxy server send heart beat message, remote host is {}", remoteEndPoint); - } - } - - public ChannelConnections getLocalConnections() { - return localConnections; - } - - public void setLocalConnections(ChannelConnections localConnections) { - this.localConnections = localConnections; - } - - public ChannelConnections getRemoteConnections() { - return remoteConnections; - } - - public void setRemoteConnections(ChannelConnections connections) { - this.remoteConnections = connections; - } - - public Map getSeq2Connections() { - return seq2Connections; - } - - public void setSeq2Connections(Map seq2Connections) { - this.seq2Connections = seq2Connections; - } - - public Integer getBindPort() { - return bindPort; - } - - public void setBindPort(Integer bindPort) { - this.bindPort = bindPort; - } - - public Timer getTimeoutHandler() { - return timeoutHandler; - } - - public void setTimeoutHandler(Timer timeoutHandler) { - this.timeoutHandler = timeoutHandler; - } - - public void run() throws SSLException { - logger.debug("init ProxyServer"); - - try { - ConnectionCallback localConnectionCallback = new ConnectionCallback(); - localConnectionCallback.setServer(this); - localConnectionCallback.setFromRemote(false); - - ConnectionCallback remoteConnectionCallback = new ConnectionCallback(); - remoteConnectionCallback.setServer(this); - remoteConnectionCallback.setFromRemote(true); - - localConnections.setCallback(localConnectionCallback); - localConnections.init(); - localConnections.startListen(bindPort); - - remoteConnections.setCallback(remoteConnectionCallback); - remoteConnections.init(); - remoteConnections.setThreadPool(threadPool); - remoteConnections.startConnect(); - } catch (Exception e) { - logger.error("error ", e); - - throw e; - } - } - - public void broadcastTopic() { - broadcastTopic(null); - } - - public void broadcastTopic(ChannelHandlerContext ctx) { - try { - Message message = new Message(); - message.setResult(0); - message.setType((short) ChannelMessageType.AMOP_CLIENT_TOPICS.getType()); - message.setSeq(UUID.randomUUID().toString().replaceAll("-", "")); - - Set allTopics = new HashSet(); - for (ConnectionInfo connectionInfo : localConnections.getConnections()) { - // 有效的连接,才增加到全局topic - ChannelHandlerContext localCtx = - localConnections.getNetworkConnectionByHost( - connectionInfo.getHost(), connectionInfo.getPort()); - - if (localCtx != null && localCtx.channel().isActive()) { - logger.debug( - "node:{}:{} follow topics: {}", - connectionInfo.getHost(), - connectionInfo.getPort(), - connectionInfo.getTopics()); - allTopics.addAll(connectionInfo.getTopics()); - } - } - - message.setData( - ObjectMapperFactory.getObjectMapper().writeValueAsBytes(allTopics.toArray())); - - logger.debug("all topics: {}", new String(message.getData())); - - if (ctx == null) { - // 广播到所有远端节点 - for (String key : remoteConnections.getNetworkConnections().keySet()) { - ChannelHandlerContext remoteCtx = - remoteConnections.getNetworkConnections().get(key); - - if (remoteCtx != null && remoteCtx.channel().isActive()) { - ByteBuf out = remoteCtx.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - if (remoteCtx != null && remoteCtx.channel().isActive()) { - logger.debug( - "send topic {}:{}", - ((SocketChannel) remoteCtx.channel()) - .remoteAddress() - .getAddress() - .getHostAddress(), - ((SocketChannel) remoteCtx.channel()) - .remoteAddress() - .getPort()); - - remoteCtx.writeAndFlush(out); - } - } - } - } else { - // 发送到指定远端节点 - logger.debug( - "topic send to {}:{}", - ((SocketChannel) ctx.channel()) - .remoteAddress() - .getAddress() - .getHostAddress(), - ((SocketChannel) ctx.channel()).remoteAddress().getPort()); - - ByteBuf out = ctx.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - ctx.writeAndFlush(out); - } - } catch (Exception e) { - logger.error("error ", e); - } - } - - public void onLocalMessage(ChannelHandlerContext ctx, Message message) { - try { - logger.debug("sdk request: " + message.getSeq()); - - ChannelHandlerContext remoteCtx = null; - - ConnectionPair pair = seq2Connections.get(message.getSeq()); - - if (pair != null) { - // 已有这个seq,发往远端的响应 - logger.debug("seq existed"); - - // 发送到远端的响应 - remoteCtx = pair.remoteConnection; - - if (message.getType() != ChannelMessageType.AMOP_RESPONSE.getType()) { - pair.localConnection = ctx; - } - - ByteBuf out = remoteCtx.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - logger.debug( - "msg send to:{}:{}", - ((SocketChannel) remoteCtx.channel()) - .remoteAddress() - .getAddress() - .getHostAddress(), - ((SocketChannel) remoteCtx.channel()).remoteAddress().getPort()); - remoteCtx.writeAndFlush(out); - } else { - pair = new ConnectionPair(); - pair.localConnection = ctx; - pair.setServer(this); - pair.setMessage(message); - - // 没有这个seq,可能是新发请求或者新收到的push - // 本地发往远程的消息,如果是链上链下,需要按给定的nodeID发 - - logger.debug("other type message,ConnectionPair"); - - pair.setRemoteChannelConnections(remoteConnections); - - List remoteConnectionInfos = new ArrayList(); - remoteConnectionInfos.addAll(remoteConnections.getConnections()); - pair.setRemoteConnectionInfos(remoteConnectionInfos); - - seq2Connections.put(message.getSeq(), pair); - - pair.init(); - pair.retrySendRemoteMessage(); - } - } catch (Exception e) { - logger.error("error ", e); - } - } - - public void onRemoteMessage(ChannelHandlerContext ctx, Message message) { - try { - logger.debug("processing : " + message.getSeq()); - - ChannelHandlerContext localCtx = null; - - ConnectionPair pair = seq2Connections.get(message.getSeq()); - - if (message.getType() == (short) ChannelMessageType.AMOP_REQUEST.getType()) { - - Short length = (short) message.getData()[0]; - String topic = new String(message.getData(), 1, length - 1); - - Set topicCtxs = new HashSet(); - for (ConnectionInfo connectionInfo : localConnections.getConnections()) { - if (connectionInfo.getTopics().contains(topic)) { - ChannelHandlerContext topicCtx = - localConnections.getNetworkConnectionByHost( - connectionInfo.getHost(), connectionInfo.getPort()); - - if (topicCtx != null && topicCtx.channel().isActive()) { - topicCtxs.add(topicCtx); - } - } - } - - logger.debug("send topic:{} sum{} follow topic", topic, topicCtxs.size()); - - if (topicCtxs.isEmpty()) { - // 找不到连接,错误 - logger.error("connection not found,error 99"); - - message.setType((short) ChannelMessageType.AMOP_RESPONSE.getType()); - message.setResult(ChannelMessageError.NODES_UNREACHABLE.getError()); - - ByteBuf out = ctx.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - ctx.writeAndFlush(out); - - return; - } - - // 随机下发 - Random random = new SecureRandom(); - Integer index = random.nextInt(topicCtxs.size()); - ChannelHandlerContext target = (ChannelHandlerContext) topicCtxs.toArray()[index]; - - logger.debug( - "send to {}:{}", - ((SocketChannel) target.channel()) - .remoteAddress() - .getAddress() - .getHostAddress(), - ((SocketChannel) target.channel()).remoteAddress().getPort()); - - localCtx = target; - - if (pair == null) { - pair = new ConnectionPair(); - pair.localConnection = localCtx; - pair.remoteConnection = ctx; - pair.setServer(this); - pair.setMessage(message); - - seq2Connections.put(message.getSeq(), pair); - pair.init(); - } else { - pair.remoteConnection = ctx; - } - } else { - if (pair != null) { - // 已有这个seq,可能是发送响应或者收到回包消息 - logger.debug("seq existed"); - - // 收到来自远端的回包 - localCtx = pair.localConnection; - - if (message.getResult() != 0 - && message.getType() == ChannelMessageType.AMOP_RESPONSE.getType()) { - // 链上链下二期错误时,执行retry - logger.error("endpoint error:{},retry", message.getResult()); - - pair.retrySendRemoteMessage(); - return; - } - - pair.remoteConnection = ctx; - } else { - // 没有这个seq,可能是新发请求或者新收到的push - - // 其他消息(链上链下一期),随机发 - localCtx = localConnections.randomNetworkConnection(null); - } - } - - if (localCtx == null || !localCtx.channel().isActive()) { - // 找不到连接,错误 - logger.error("connect unavailable,error 99"); - - message.setType((short) ChannelMessageType.AMOP_RESPONSE.getType()); - - message.setResult(ChannelMessageError.NODES_UNREACHABLE.getError()); - - ByteBuf out = ctx.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - ctx.writeAndFlush(out); - - return; - } - - ByteBuf out = localCtx.alloc().buffer(); - message.writeHeader(out); - message.writeExtra(out); - - logger.debug( - "send to:{}:{}", - ((SocketChannel) localCtx.channel()) - .remoteAddress() - .getAddress() - .getHostAddress(), - ((SocketChannel) localCtx.channel()).remoteAddress().getPort()); - localCtx.writeAndFlush(out); - } catch (Exception e) { - logger.error("error ", e); - } - } - - public void onHeartBeat(ChannelHandlerContext ctx, Message message) { - String content = "1"; - try { - content = new String(message.getData(), "utf-8"); - } catch (UnsupportedEncodingException e) { - logger.error("unexpected heartbeat "); - } catch (Exception e) { - logger.error("heartbeat error"); - } - - if (content.equals("0")) { - Message response = new Message(); - - response.setSeq(message.getSeq()); - response.setResult(0); - response.setType((short) ChannelMessageType.CLIENT_HEARTBEAT.getType()); - response.setData("1".getBytes()); - - ByteBuf out = ctx.alloc().buffer(); - response.writeHeader(out); - response.writeExtra(out); - - ctx.writeAndFlush(out); - } - } - - public void onTopic(ChannelHandlerContext ctx, Message message) { - logger.debug("SDK topics message: {} {}", message.getSeq(), new String(message.getData())); - String host = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress(); - Integer port = ((SocketChannel) ctx.channel()).remoteAddress().getPort(); // - ConnectionInfo info = localConnections.getConnectionInfo(host, port); - - if (info != null) { - try { - List topics = - ObjectMapperFactory.getObjectMapper() - .readValue(message.getData(), List.class); - - info.setTopics(topics); - - broadcastTopic(); - } catch (Exception e) { - logger.error("parse topic error", e); - } - } - } - - public ThreadPoolTaskExecutor getThreadPool() { - return threadPool; - } - - public void setThreadPool(ThreadPoolTaskExecutor threadPool) { - this.threadPool = threadPool; - } - - // private String orgID; - private ChannelConnections localConnections = new ChannelConnections(); - private ChannelConnections remoteConnections; - private Map seq2Connections = - new ConcurrentHashMap(); - private Integer bindPort = 8830; - - private Timer timeoutHandler = new HashedWheelTimer(); - - private ThreadPoolTaskExecutor threadPool; -} diff --git a/src/main/java/org/fisco/bcos/fisco/EnumNodeVersion.java b/src/main/java/org/fisco/bcos/fisco/EnumNodeVersion.java index 0f098da88..9fd443b54 100644 --- a/src/main/java/org/fisco/bcos/fisco/EnumNodeVersion.java +++ b/src/main/java/org/fisco/bcos/fisco/EnumNodeVersion.java @@ -8,7 +8,8 @@ public enum EnumNodeVersion { BCOS_2_0_0_RC3("2.0.0-rc3"), BCOS_2_0_0("2.0.0"), BCOS_2_0_1("2.0.1"), - BCOS_2_1_0("2.1.0"); + BCOS_2_1_0("2.1.0"), + BCOS_2_2_0("2.2.0"); private String version; @@ -25,7 +26,7 @@ public void setVersion(String version) { } // the object of node version - class Version { + public class Version { private int major; private int minor; private int patch; @@ -77,7 +78,7 @@ public void setExt(String ext) { } } - private static Version getClassVersion(String version) throws ChannelPrococolExceiption { + public static Version getClassVersion(String version) throws ChannelPrococolExceiption { try { // node version str format : "a.b.c" or "a.b.c-rcx" String[] s0 = version.trim().split("-"); diff --git a/src/main/java/org/fisco/bcos/web3j/abi/Constant.java b/src/main/java/org/fisco/bcos/web3j/abi/Constant.java new file mode 100644 index 000000000..1149ea531 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/abi/Constant.java @@ -0,0 +1,12 @@ +package org.fisco.bcos.web3j.abi; + +import java.math.BigInteger; + +public class Constant { + public static final BigInteger MAX_UINT256 = + new BigInteger("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16); + public static final BigInteger MAX_INT256 = + new BigInteger("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16); + public static final BigInteger MIN_INT256 = + new BigInteger("-7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16); +} diff --git a/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Int.java b/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Int.java index adb4f484c..104e1ab83 100644 --- a/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Int.java +++ b/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Int.java @@ -1,6 +1,7 @@ package org.fisco.bcos.web3j.abi.datatypes; import java.math.BigInteger; +import org.fisco.bcos.web3j.abi.Constant; /** Integer type. */ public class Int extends IntType { @@ -13,6 +14,22 @@ public Int(BigInteger value) { this(MAX_BIT_LENGTH, value); } + /** + * check if value between MIN_INT256 ~ MIN_INT256 + * + * @param value + * @return + */ + public boolean validInt(BigInteger value) { + return value.compareTo(Constant.MIN_INT256) >= 0 + && value.compareTo(Constant.MAX_INT256) <= 0; + } + + @Override + boolean valid(int bitSize, BigInteger value) { + return super.valid(bitSize, value) && validInt(value); + } + protected Int(int bitSize, BigInteger value) { super(TYPE_NAME, bitSize, value); } diff --git a/src/main/java/org/fisco/bcos/web3j/abi/datatypes/IntType.java b/src/main/java/org/fisco/bcos/web3j/abi/datatypes/IntType.java index b46464d72..b9161fe40 100644 --- a/src/main/java/org/fisco/bcos/web3j/abi/datatypes/IntType.java +++ b/src/main/java/org/fisco/bcos/web3j/abi/datatypes/IntType.java @@ -9,7 +9,7 @@ public IntType(String typePrefix, int bitSize, BigInteger value) { super(typePrefix + bitSize, value); if (!valid(bitSize, value)) { throw new UnsupportedOperationException( - "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256"); + "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256, and in valid range."); } } diff --git a/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Uint.java b/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Uint.java index d3f9a4943..8fe2229e8 100644 --- a/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Uint.java +++ b/src/main/java/org/fisco/bcos/web3j/abi/datatypes/Uint.java @@ -1,13 +1,13 @@ package org.fisco.bcos.web3j.abi.datatypes; import java.math.BigInteger; +import org.fisco.bcos.web3j.abi.Constant; /** Unsigned integer type. */ public class Uint extends IntType { public static final String TYPE_NAME = "uint"; public static final Uint DEFAULT = new Uint(BigInteger.ZERO); - /** This constructor is required by the {@link Address} type. */ Uint(String typePrefix, int bitSize, BigInteger value) { super(typePrefix, bitSize, value); @@ -22,9 +22,19 @@ public Uint(BigInteger value) { this(MAX_BIT_LENGTH, value); } + /** + * check if value between 0 ~ MAX_UINT256 + * + * @param value + * @return + */ + public boolean validUint(BigInteger value) { + return value.compareTo(BigInteger.ZERO) >= 0 && value.compareTo(Constant.MAX_UINT256) <= 0; + } + @Override boolean valid(int bitSize, BigInteger value) { - return super.valid(bitSize, value) && value.signum() != -1; + return super.valid(bitSize, value) && value.signum() != -1 && validUint(value); } @Override diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/EncryptType.java b/src/main/java/org/fisco/bcos/web3j/crypto/EncryptType.java index 8ab9384e1..13f260213 100644 --- a/src/main/java/org/fisco/bcos/web3j/crypto/EncryptType.java +++ b/src/main/java/org/fisco/bcos/web3j/crypto/EncryptType.java @@ -3,15 +3,18 @@ import org.fisco.bcos.web3j.crypto.gm.sm2.SM2Sign; import org.fisco.bcos.web3j.crypto.gm.sm3.SM3Digest; -/** Created by websterchen on 2018/4/25. */ public class EncryptType { - public static int encryptType = 0; // 0:ECDSA 1:SM2 + + public static final int ECDSA_TYPE = 0; + public static final int SM2_TYPE = 1; + + public static int encryptType = ECDSA_TYPE; // 0:ECDSA 1:SM2 public EncryptType(int encryptType) { EncryptType.encryptType = encryptType; SignInterface signInterface; HashInterface hashInterface; - if (encryptType == 1) { + if (encryptType == SM2_TYPE) { signInterface = new SM2Sign(); hashInterface = new SM3Digest(); } else { diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/gm/GenCredential.java b/src/main/java/org/fisco/bcos/web3j/crypto/gm/GenCredential.java index f8164cb00..d6586850d 100644 --- a/src/main/java/org/fisco/bcos/web3j/crypto/gm/GenCredential.java +++ b/src/main/java/org/fisco/bcos/web3j/crypto/gm/GenCredential.java @@ -74,13 +74,13 @@ private static ECKeyPair createECDSAKeyPair() { } } - private static ECKeyPair createKeyPair() { + public static ECKeyPair createKeyPair() { // use guomi if (EncryptType.encryptType == 1) return createGuomiKeyPair(); return createECDSAKeyPair(); // default use ECDSA } - private static ECKeyPair createKeyPair(String privKey) { + public static ECKeyPair createKeyPair(String privKey) { if (EncryptType.encryptType == 1) return createGuomiKeyPair(privKey); return createECDSAKeyPair(privKey); } diff --git a/src/main/java/org/fisco/bcos/web3j/precompile/common/PrecompiledCommon.java b/src/main/java/org/fisco/bcos/web3j/precompile/common/PrecompiledCommon.java index 0c96a2240..a693cbbcd 100644 --- a/src/main/java/org/fisco/bcos/web3j/precompile/common/PrecompiledCommon.java +++ b/src/main/java/org/fisco/bcos/web3j/precompile/common/PrecompiledCommon.java @@ -19,6 +19,8 @@ public class PrecompiledCommon { // system table for authority control public static final String USER_TABLE_PREFIX = "_user_"; + public static final String USER_TABLE_PREFIX_2_2_0_VERSION = "u_"; + public static final String SYS_TABLE = "_sys_tables_"; public static final String SYS_TABLE_ACCESS = "_sys_table_access_"; public static final String SYS_CONSENSUS = "_sys_consensus_"; diff --git a/src/main/java/org/fisco/bcos/web3j/precompile/crud/CRUDService.java b/src/main/java/org/fisco/bcos/web3j/precompile/crud/CRUDService.java index 876485585..b45968a9a 100644 --- a/src/main/java/org/fisco/bcos/web3j/precompile/crud/CRUDService.java +++ b/src/main/java/org/fisco/bcos/web3j/precompile/crud/CRUDService.java @@ -4,6 +4,7 @@ import java.math.BigInteger; import java.util.List; import java.util.Map; +import org.fisco.bcos.fisco.EnumNodeVersion; import org.fisco.bcos.web3j.crypto.Credentials; import org.fisco.bcos.web3j.precompile.common.PrecompiledCommon; import org.fisco.bcos.web3j.precompile.exception.PrecompileMessageException; @@ -12,8 +13,13 @@ import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; import org.fisco.bcos.web3j.tx.gas.ContractGasProvider; import org.fisco.bcos.web3j.tx.gas.StaticGasProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class CRUDService { + + private static final Logger logger = LoggerFactory.getLogger(CRUDService.class); + private static BigInteger gasPrice = new BigInteger("300000000"); private static BigInteger gasLimit = new BigInteger("300000000"); private static final String TableFactoryPrecompileAddress = @@ -128,11 +134,33 @@ public List> select(Table table, Condition condition) throws public Table desc(String tableName) throws Exception { Table table = new Table(); table.setTableName(PrecompiledCommon.SYS_TABLE); - table.setKey(PrecompiledCommon.USER_TABLE_PREFIX + tableName); + + /** Compatible with node version 2.2.0 */ + try { + String supportedVersion = + crud.getTransactionManager().getNodeVersion().getSupportedVersion(); + EnumNodeVersion.Version version = EnumNodeVersion.getClassVersion(supportedVersion); + + logger.debug("desc, table: {}, node version: {}", tableName, version); + + // less than 2.2.0 + if ((version.getMajor() == 2) && (version.getMinor() < 2)) { + table.setKey(PrecompiledCommon.USER_TABLE_PREFIX + tableName); + } else { + table.setKey(PrecompiledCommon.USER_TABLE_PREFIX_2_2_0_VERSION + tableName); + } + } catch (Exception e) { + throw new PrecompileMessageException( + " Cannot query node version, maybe disconnect to all nodes."); + } + Condition condition = table.getCondition(); List> userTable = select(table, condition); Table tableInfo = new Table(); - if (userTable.size() != 0) { + if ((userTable != null) + && (userTable.size() != 0) + && (null != userTable.get(0)) + && !userTable.get(0).isEmpty()) { tableInfo.setTableName(tableName); tableInfo.setKey(userTable.get(0).get("key_field")); tableInfo.setValueFields(userTable.get(0).get("value_field")); diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/channel/ChannelEthereumService.java b/src/main/java/org/fisco/bcos/web3j/protocol/channel/ChannelEthereumService.java index 48a058e51..2ba9b2769 100644 --- a/src/main/java/org/fisco/bcos/web3j/protocol/channel/ChannelEthereumService.java +++ b/src/main/java/org/fisco/bcos/web3j/protocol/channel/ChannelEthereumService.java @@ -87,6 +87,11 @@ public T send(Request request, Class responseType) throw if (StatusCode.CallAddressError.equals(callResult.getStatus())) { throw new ContractCallException("The contract address is incorrect."); } + + if (!StatusCode.Success.equals(callResult.getStatus())) { + throw new ContractCallException( + StatusCode.getStatusMessage(callResult.getStatus())); + } } return t; } catch (ContractCallException e) { diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/channel/StatusCode.java b/src/main/java/org/fisco/bcos/web3j/protocol/channel/StatusCode.java index 69893f00f..887946b78 100644 --- a/src/main/java/org/fisco/bcos/web3j/protocol/channel/StatusCode.java +++ b/src/main/java/org/fisco/bcos/web3j/protocol/channel/StatusCode.java @@ -33,6 +33,18 @@ public class StatusCode { public static final String TxPoolIsFull = "0x1c"; public static final String TransactionRefused = "0x1d"; + // extension + public static final String ExceptionCatched = "0x30"; + public static final String ErrorInRPC = "0x31"; + + /// txPool related errors + public static final String AlreadyKnown = "0x2710"; + public static final String AlreadyInChain = "0x2711"; + public static final String InvalidTxChainId = "0x2712"; + public static final String InvalidTxGroupId = "0x2713"; + public static final String RequestNotBelongToTheGroup = "0x2714"; + public static final String MalformedTx = "0x2715"; + public static String getStatusMessage(String status) { return getStatusMessage(status, " Error code: " + status); } @@ -130,6 +142,27 @@ public static String getStatusMessage(String status, String errorMessage) { case TransactionRefused: message = "transaction refuesd"; break; + case ErrorInRPC: + message = "error in RPC"; + break; + case AlreadyKnown: + message = "transaction already known"; + break; + case AlreadyInChain: + message = "transaction already in chain"; + break; + case InvalidTxChainId: + message = "invalid chain id"; + break; + case InvalidTxGroupId: + message = "invalid group id"; + break; + case RequestNotBelongToTheGroup: + message = "request not belong to the group"; + break; + case MalformedTx: + message = "malformed transaction"; + break; default: message = errorMessage; break; diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/Ethereum.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/Ethereum.java index 48b0d3d33..85f12b0e1 100644 --- a/src/main/java/org/fisco/bcos/web3j/protocol/core/Ethereum.java +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/Ethereum.java @@ -1,7 +1,36 @@ package org.fisco.bcos.web3j.protocol.core; import java.math.BigInteger; -import org.fisco.bcos.web3j.protocol.core.methods.response.*; +import java.util.List; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosFilter; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosLog; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosTransaction; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosTransactionReceipt; +import org.fisco.bcos.web3j.protocol.core.methods.response.BlockHash; +import org.fisco.bcos.web3j.protocol.core.methods.response.BlockNumber; +import org.fisco.bcos.web3j.protocol.core.methods.response.Call; +import org.fisco.bcos.web3j.protocol.core.methods.response.Code; +import org.fisco.bcos.web3j.protocol.core.methods.response.ConsensusStatus; +import org.fisco.bcos.web3j.protocol.core.methods.response.GenerateGroup; +import org.fisco.bcos.web3j.protocol.core.methods.response.GroupList; +import org.fisco.bcos.web3j.protocol.core.methods.response.GroupPeers; +import org.fisco.bcos.web3j.protocol.core.methods.response.NodeIDList; +import org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion; +import org.fisco.bcos.web3j.protocol.core.methods.response.ObserverList; +import org.fisco.bcos.web3j.protocol.core.methods.response.PbftView; +import org.fisco.bcos.web3j.protocol.core.methods.response.Peers; +import org.fisco.bcos.web3j.protocol.core.methods.response.PendingTransactions; +import org.fisco.bcos.web3j.protocol.core.methods.response.PendingTxSize; +import org.fisco.bcos.web3j.protocol.core.methods.response.SealerList; +import org.fisco.bcos.web3j.protocol.core.methods.response.SendTransaction; +import org.fisco.bcos.web3j.protocol.core.methods.response.StartGroup; +import org.fisco.bcos.web3j.protocol.core.methods.response.SyncStatus; +import org.fisco.bcos.web3j.protocol.core.methods.response.SystemConfig; +import org.fisco.bcos.web3j.protocol.core.methods.response.TotalTransactionCount; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceiptWithProof; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionWithProof; +import org.fisco.bcos.web3j.protocol.core.methods.response.UninstallFilter; /** Core FISCO BCOS JSON-RPC API. */ public interface Ethereum { @@ -43,6 +72,8 @@ Request getBlockByNumber( Request getTransactionByHash(String transactionHash); + Request getTransactionByHashWithProof(String transactionHash); + Request getTransactionByBlockHashAndIndex( String blockHash, BigInteger transactionIndex); @@ -51,6 +82,9 @@ Request getTransactionByBlockNumberAndIndex( Request getTransactionReceipt(String transactionHash); + Request getTransactionReceiptByHashWithProof( + String transactionHash); + Request getPendingTransaction(); BigInteger getBlockNumberCache(); @@ -63,6 +97,11 @@ Request call( Request sendRawTransaction(String signedTransactionData); + // generateGroup + Request generateGroup(int groupId, int timestamp, List nodeList); + + Request startGroup(int groupId); + // TODO Request newPendingTransactionFilter(); diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java index 870155375..e9d609e5b 100644 --- a/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java @@ -3,12 +3,46 @@ import io.reactivex.Flowable; import java.io.IOException; import java.math.BigInteger; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.Web3jService; import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; -import org.fisco.bcos.web3j.protocol.core.methods.response.*; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosFilter; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosLog; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosSubscribe; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosTransaction; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosTransactionReceipt; +import org.fisco.bcos.web3j.protocol.core.methods.response.BlockHash; +import org.fisco.bcos.web3j.protocol.core.methods.response.BlockNumber; +import org.fisco.bcos.web3j.protocol.core.methods.response.Call; +import org.fisco.bcos.web3j.protocol.core.methods.response.Code; +import org.fisco.bcos.web3j.protocol.core.methods.response.ConsensusStatus; +import org.fisco.bcos.web3j.protocol.core.methods.response.GenerateGroup; +import org.fisco.bcos.web3j.protocol.core.methods.response.GroupList; +import org.fisco.bcos.web3j.protocol.core.methods.response.GroupPeers; +import org.fisco.bcos.web3j.protocol.core.methods.response.Log; +import org.fisco.bcos.web3j.protocol.core.methods.response.NodeIDList; +import org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion; +import org.fisco.bcos.web3j.protocol.core.methods.response.ObserverList; +import org.fisco.bcos.web3j.protocol.core.methods.response.PbftView; +import org.fisco.bcos.web3j.protocol.core.methods.response.Peers; +import org.fisco.bcos.web3j.protocol.core.methods.response.PendingTransactions; +import org.fisco.bcos.web3j.protocol.core.methods.response.PendingTxSize; +import org.fisco.bcos.web3j.protocol.core.methods.response.SealerList; +import org.fisco.bcos.web3j.protocol.core.methods.response.SendTransaction; +import org.fisco.bcos.web3j.protocol.core.methods.response.StartGroup; +import org.fisco.bcos.web3j.protocol.core.methods.response.SyncStatus; +import org.fisco.bcos.web3j.protocol.core.methods.response.SystemConfig; +import org.fisco.bcos.web3j.protocol.core.methods.response.TotalTransactionCount; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceiptWithProof; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionWithProof; +import org.fisco.bcos.web3j.protocol.core.methods.response.UninstallFilter; import org.fisco.bcos.web3j.protocol.rx.JsonRpc2_0Rx; import org.fisco.bcos.web3j.protocol.websocket.events.LogNotification; import org.fisco.bcos.web3j.protocol.websocket.events.NewHeadsNotification; @@ -209,6 +243,15 @@ public Request getTransactionByHash(String transactionHash) BcosTransaction.class); } + @Override + public Request getTransactionByHashWithProof(String transactionHash) { + return new Request<>( + "getTransactionByHashWithProof", + Arrays.asList(groupId, transactionHash), + web3jService, + TransactionWithProof.class); + } + @Override public Request getTransactionByBlockHashAndIndex( String blockHash, BigInteger transactionIndex) { @@ -241,6 +284,16 @@ public Request getTransactionReceipt(String transacti BcosTransactionReceipt.class); } + @Override + public Request getTransactionReceiptByHashWithProof( + String transactionHash) { + return new Request<>( + "getTransactionReceiptByHashWithProof", + Arrays.asList(groupId, transactionHash), + web3jService, + TransactionReceiptWithProof.class); + } + @Override public Request getPendingTransaction() { return new Request<>( @@ -271,6 +324,21 @@ public Request getGroupPeers() { "getGroupPeers", Arrays.asList(groupId), web3jService, GroupPeers.class); } + @Override + public Request generateGroup( + int groupID, int timestamp, List nodeList) { + return new Request<>( + "generateGroup", + Arrays.asList(groupID, timestamp, nodeList), + web3jService, + GenerateGroup.class); + } + + @Override + public Request startGroup(int groupID) { + return new Request<>("startGroup", Arrays.asList(groupID), web3jService, StartGroup.class); + } + @Override public Request newPendingTransactionFilter() { return new Request<>( diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/GenerateGroup.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/GenerateGroup.java new file mode 100644 index 000000000..239b9b919 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/GenerateGroup.java @@ -0,0 +1,36 @@ +package org.fisco.bcos.web3j.protocol.core.methods.response; + +import org.fisco.bcos.web3j.protocol.core.Response; + +public class GenerateGroup extends Response { + + public Status getStatus() { + return getResult(); + } + + public static class Status { + private String code; + private String message; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "Status{" + "code='" + code + '\'' + ", message='" + message + '\'' + '}'; + } + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/MerkleProofUnit.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/MerkleProofUnit.java new file mode 100644 index 000000000..e5fb8e9ab --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/MerkleProofUnit.java @@ -0,0 +1,59 @@ +package org.fisco.bcos.web3j.protocol.core.methods.response; + +import java.util.List; +import java.util.Objects; + +/** + * MerkleProofUnit object used by both {@link TransactionReceiptWithProof} and {@link + * TransactionWithProof}. + */ +public class MerkleProofUnit { + private List left; + private List right; + + public MerkleProofUnit() {} + + public MerkleProofUnit(List left, List right) { + this.left = left; + this.right = right; + } + + public List getLeft() { + return left; + } + + public void setLeft(List left) { + this.left = left; + } + + public List getRight() { + return right; + } + + public void setRight(List right) { + this.right = right; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof MerkleProofUnit)) { + return false; + } + MerkleProofUnit that = (MerkleProofUnit) o; + return Objects.equals(getLeft(), that.getLeft()) + && Objects.equals(getRight(), that.getRight()); + } + + @Override + public int hashCode() { + return Objects.hash(getLeft(), getRight()); + } + + @Override + public String toString() { + return "MerkleProofUnit{" + "left=" + left + ", right=" + right + '}'; + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/StartGroup.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/StartGroup.java new file mode 100644 index 000000000..a08b5bcde --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/StartGroup.java @@ -0,0 +1,36 @@ +package org.fisco.bcos.web3j.protocol.core.methods.response; + +import org.fisco.bcos.web3j.protocol.core.Response; + +public class StartGroup extends Response { + + public Status getStatus() { + return getResult(); + } + + public static class Status { + private String code; + private String message; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "Status{" + "code='" + code + '\'' + ", message='" + message + '\'' + '}'; + } + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionReceiptWithProof.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionReceiptWithProof.java new file mode 100644 index 000000000..d669faf65 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionReceiptWithProof.java @@ -0,0 +1,78 @@ +package org.fisco.bcos.web3j.protocol.core.methods.response; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Objects; +import org.fisco.bcos.web3j.protocol.core.Response; + +/** getTransactionReceiptWithProof. */ +public class TransactionReceiptWithProof + extends Response { + + public ReceiptAndProof getTransactionReceiptWithProof() { + return getResult(); + } + + public static class ReceiptAndProof { + @JsonProperty("transactionReceipt") + private TransactionReceipt transactionReceipt; + + @JsonProperty("receiptProof") + private List receiptProof; + + public ReceiptAndProof() { + super(); + } + + public ReceiptAndProof( + TransactionReceipt transactionReceipt, List receiptProof) { + super(); + this.transactionReceipt = transactionReceipt; + this.receiptProof = receiptProof; + } + + public TransactionReceipt getTransactionReceipt() { + return transactionReceipt; + } + + public void setTransactionReceipt(TransactionReceipt transactionReceipt) { + this.transactionReceipt = transactionReceipt; + } + + public List getReceiptProof() { + return receiptProof; + } + + public void setReceiptProof(List receiptProof) { + this.receiptProof = receiptProof; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof ReceiptAndProof)) { + return false; + } + ReceiptAndProof that = (ReceiptAndProof) o; + return getTransactionReceipt().equals(that.getTransactionReceipt()) + && getReceiptProof().equals(that.getReceiptProof()); + } + + @Override + public int hashCode() { + return Objects.hash(getTransactionReceipt(), getReceiptProof()); + } + + @Override + public String toString() { + return "ReceiptProof{" + + "transactionReceipt=" + + transactionReceipt + + ", receiptProof=" + + receiptProof + + '}'; + } + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionWithProof.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionWithProof.java new file mode 100644 index 000000000..bbb245cc5 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/response/TransactionWithProof.java @@ -0,0 +1,71 @@ +package org.fisco.bcos.web3j.protocol.core.methods.response; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Objects; +import org.fisco.bcos.web3j.protocol.core.Response; + +/** getTransactionWithProof. */ +public class TransactionWithProof extends Response { + + public TransAndProof getTransactionWithProof() { + return getResult(); + } + + public static class TransAndProof { + @JsonProperty("transaction") + private Transaction transaction; + + @JsonProperty("txProof") + private List txProof; + + public TransAndProof() { + super(); + } + + public TransAndProof(Transaction transaction, List txProof) { + super(); + this.transaction = transaction; + this.txProof = txProof; + } + + public Transaction getTransaction() { + return transaction; + } + + public void setTransaction(Transaction transaction) { + this.transaction = transaction; + } + + public List getTxProof() { + return txProof; + } + + public void setTxProof(List txProof) { + this.txProof = txProof; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof TransAndProof)) { + return false; + } + TransAndProof tranProof = (TransAndProof) o; + return Objects.equals(getTransaction(), tranProof.getTransaction()) + && Objects.equals(getTxProof(), tranProof.getTxProof()); + } + + @Override + public int hashCode() { + return Objects.hash(getTransaction(), getTxProof()); + } + + @Override + public String toString() { + return "TransAndProof{" + "transaction=" + transaction + ", txProof=" + txProof + '}'; + } + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/GenerateGroupStatus.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/GenerateGroupStatus.java new file mode 100644 index 000000000..72cd263f8 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/GenerateGroupStatus.java @@ -0,0 +1,17 @@ +package org.fisco.bcos.web3j.protocol.core.methods.status; + +/** return status for rpc interface: generateGroup */ +public class GenerateGroupStatus { + // success + public static final String SUCCESS = "0x0"; + // group already exist + public static final String GROUP_EXIST = "0x1"; + // group genesis file already exist + public static final String GROUP_GENESIS_FILE_EXIST = "0x2"; + // group config file already exist + public static final String GROUP_CONFIG_FILE_EXIST = "0x3"; + // invalid parameters + public static final String INVALID_PARAMS = "0x4"; + // node inner error + public static final String OTHER_ERROR = "0x5"; +} diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/StartGroupStatus.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/StartGroupStatus.java new file mode 100644 index 000000000..6ef87575b --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/methods/status/StartGroupStatus.java @@ -0,0 +1,21 @@ +package org.fisco.bcos.web3j.protocol.core.methods.status; + +/** return status for rpc interface: startGroup */ +public class StartGroupStatus { + // success + public static final String SUCCESS = "0x0"; + // group already running + public static final String GROUP_IS_RUNNING = "0x1"; + // group genesis file not exist + public static final String GROUP_GENESIS_FILE_NOT_EXIST = "0x2"; + // group config file not exist + public static final String GROUP_CONFIG_FILE_NOT_EXIST = "0x3"; + // group genesis file invalid + public static final String GROUP_GENESIS_INVALID = "0x4"; + // group config file invalid + public static final String GROUP_CONFIG_INVALID = "0x5"; + // invalid parameters + public static final String INVALID_PARAMS = "0x6"; + // node inner error + public static final String OTHER_ERROR = "0x7"; +} diff --git a/src/main/java/org/fisco/bcos/web3j/tx/Contract.java b/src/main/java/org/fisco/bcos/web3j/tx/Contract.java index 2153f948b..f01ea6ef2 100644 --- a/src/main/java/org/fisco/bcos/web3j/tx/Contract.java +++ b/src/main/java/org/fisco/bcos/web3j/tx/Contract.java @@ -99,8 +99,9 @@ public static TransactionManager getTheTransactionManager( String chainId = "1"; String version = ""; String supportedVersion = ""; + NodeVersion.Version nodeVersion = null; try { - NodeVersion.Version nodeVersion = web3j.getNodeVersion().send().getNodeVersion(); + nodeVersion = web3j.getNodeVersion().send().getNodeVersion(); version = nodeVersion.getVersion(); supportedVersion = nodeVersion.getSupportedVersion(); @@ -117,10 +118,18 @@ public static TransactionManager getTheTransactionManager( logger.error("Query fisco-bcos version failed", e); } - return EnumNodeVersion.BCOS_2_0_0_RC1.getVersion().equals(version) - ? new RawTransactionManager(web3j, credentials) - : new ExtendedRawTransactionManager( - web3j, credentials, BigInteger.valueOf(groupId), new BigInteger(chainId)); + TransactionManager transactionManager = + EnumNodeVersion.BCOS_2_0_0_RC1.getVersion().equals(version) + ? new RawTransactionManager(web3j, credentials) + : new ExtendedRawTransactionManager( + web3j, + credentials, + BigInteger.valueOf(groupId), + new BigInteger(chainId)); + + transactionManager.setNodeVersion(nodeVersion); + + return transactionManager; } @Deprecated @@ -911,7 +920,7 @@ public Log getLog() { } @SuppressWarnings("unchecked") - protected static List convertToNative(List arr) { + public static List convertToNative(List arr) { List out = new ArrayList(); for (Iterator it = arr.iterator(); it.hasNext(); ) { out.add((T) it.next().getValue()); diff --git a/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java b/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java index 9bca19b55..bd71c0781 100644 --- a/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java +++ b/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java @@ -6,6 +6,7 @@ import org.fisco.bcos.web3j.crypto.Credentials; import org.fisco.bcos.web3j.crypto.ExtendedRawTransaction; import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion; import org.fisco.bcos.web3j.protocol.core.methods.response.SendTransaction; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; import org.fisco.bcos.web3j.protocol.exceptions.TransactionException; @@ -25,8 +26,19 @@ public abstract class TransactionManager { public static final int DEFAULT_POLLING_FREQUENCY = AttemptsConf.attempts; // 15 * 100 private final TransactionReceiptProcessor transactionReceiptProcessor; + final Credentials credentials; + private NodeVersion.Version nodeVersion; + + public NodeVersion.Version getNodeVersion() { + return nodeVersion; + } + + public void setNodeVersion(NodeVersion.Version nodeVersion) { + this.nodeVersion = nodeVersion; + } + protected TransactionManager( TransactionReceiptProcessor transactionReceiptProcessor, Credentials credentials) { this.transactionReceiptProcessor = transactionReceiptProcessor; diff --git a/src/main/java/org/fisco/bcos/web3j/utils/Numeric.java b/src/main/java/org/fisco/bcos/web3j/utils/Numeric.java index f6efc3e1b..c7a26e78e 100644 --- a/src/main/java/org/fisco/bcos/web3j/utils/Numeric.java +++ b/src/main/java/org/fisco/bcos/web3j/utils/Numeric.java @@ -3,6 +3,7 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; +import org.apache.commons.codec.binary.Hex; import org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException; import org.fisco.bcos.web3j.protocol.exceptions.MessageEncodingException; @@ -108,12 +109,12 @@ public static String toHexStringWithPrefix(BigInteger value) { return HEX_PREFIX + value.toString(16); } - public static String toHexStringNoPrefix(BigInteger value) { - return value.toString(16); + public static String toHexStringNoPrefix(byte[] input) { + return Hex.encodeHexString(input); } - public static String toHexStringNoPrefix(byte[] input) { - return toHexString(input, 0, input.length, false); + public static String toHexStringNoPrefix(BigInteger value) { + return value.toString(16); } public static String toHexStringWithPrefixZeroPadded(BigInteger value, int size) { @@ -207,19 +208,15 @@ public static byte[] hexStringToByteArray(String input) { } public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) { - StringBuilder stringBuilder = new StringBuilder(); - if (withPrefix) { - stringBuilder.append("0x"); - } - for (int i = offset; i < offset + length; i++) { - stringBuilder.append(String.format("%02x", input[i] & 0xFF)); - } - - return stringBuilder.toString(); + return withPrefix + ? toHexString(Arrays.copyOfRange(input, offset, offset + length)) + : toHexStringNoPrefix(Arrays.copyOfRange(input, offset, offset + length)); } public static String toHexString(byte[] input) { - return toHexString(input, 0, input.length, true); + StringBuilder stringBuilder = new StringBuilder(2 + input.length * 2); + stringBuilder.append("0x").append(Hex.encodeHexString(input)); + return stringBuilder.toString(); } public static byte asByte(int m, int n) { diff --git a/src/test/java/org/fisco/bcos/channel/client/CallContractTest.java b/src/test/java/org/fisco/bcos/channel/client/CallContractTest.java new file mode 100644 index 000000000..d4abfdc07 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/client/CallContractTest.java @@ -0,0 +1,303 @@ +package org.fisco.bcos.channel.client; + +import static org.fisco.bcos.web3j.abi.Utils.typeMap; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Semaphore; +import org.fisco.bcos.web3j.abi.FunctionReturnDecoder; +import org.fisco.bcos.web3j.abi.TypeReference; +import org.fisco.bcos.web3j.abi.Utils; +import org.fisco.bcos.web3j.abi.datatypes.Bool; +import org.fisco.bcos.web3j.abi.datatypes.DynamicArray; +import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes; +import org.fisco.bcos.web3j.abi.datatypes.StaticArray; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.Utf8String; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int16; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.abi.datatypes.generated.StaticArray2; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint16; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.gm.GenCredential; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class CallContractTest { + static Logger logger = LoggerFactory.getLogger(CallContractTest.class); + public static Web3j web3j; + + public static ECKeyPair keyPair; + public static Credentials credentials; + public static BigInteger gasPrice = new BigInteger("3000000000"); + public static BigInteger gasLimit = new BigInteger("3000000000"); + + public static void main(String[] args) throws Exception { + + try { + // init the Service + ApplicationContext context = + new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(args[0])); + service.run(); // run the daemon service + // init the client keys + credentials = GenCredential.create(); + + logger.info("-----> start test in CallContractTest!"); + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setTimeout(10 * 1000); + channelEthereumService.setChannelService(service); + web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0])); + + if (args.length == 2) { + String address = args[1]; + CallContract callContract = new CallContract(credentials, web3j); + System.out.println( + "************************ Test call & sendTrandation ************************"); + testSyncCallContract(callContract, address); + testAsyncCallContract(callContract, address); + + System.out.println("************************ Test decode ************************"); + testDecode(callContract, address); + System.out.println("Test CallContract successfully."); + } else { + System.out.println("Please input group id and contract address."); + } + } catch (Exception e) { + System.out.println(e.getLocalizedMessage()); + System.exit(1); + } + + System.exit(0); + } + + private static void testSyncCallContract(CallContract callContract, String address) { + CallResult contractResult; + + contractResult = + callContract.call( + address, + "getStringOld", + new Utf8String("hello world"), + new Int256(10086), + new Bool(true)); + + List> referencesList = + Arrays.>asList(new TypeReference() {}); + List returnList1 = + FunctionReturnDecoder.decode( + contractResult.getOutput(), Utils.convert(referencesList)); + System.out.println("call getStringOld: " + (String) returnList1.get(0).getValue()); + + TransactionReceipt receipt; + receipt = + callContract.sendTransaction( + gasPrice, + gasLimit, + address, + "setAndget", + new Utf8String("hello world"), + new Int256(10086)); + referencesList = + Arrays.>asList( + new TypeReference() {}, new TypeReference() {}); + List returnList2 = + FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList)); + System.out.println( + "call setAndget: " + + (String) returnList2.get(0).getValue() + + ", " + + (BigInteger) returnList2.get(1).getValue()); + + receipt = + callContract.sendTransaction( + address, "setAndget", new Utf8String("hello world"), new Int256(10086)); + referencesList = + Arrays.>asList( + new TypeReference() {}, new TypeReference() {}); + List returnList3 = + FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList)); + System.out.println( + "default call setAndget: " + + (String) returnList3.get(0).getValue() + + ", " + + (BigInteger) returnList3.get(1).getValue()); + + contractResult = + callContract.call( + address, + "getArray", + new StaticArray2( + typeMap( + Arrays.asList( + BigInteger.valueOf(-1), BigInteger.valueOf(2)), + Int16.class)), + new DynamicArray( + typeMap( + Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(2)), + Uint16.class))); + List returnList4 = + callContract.decode( + contractResult.getOutput(), + new TypeReference>() {}, + new TypeReference>() {}); + System.out.println( + "call getArray: " + + callContract.convertList((List) returnList4.get(0).getValue()) + + ", " + + callContract.convertList((List) returnList4.get(1).getValue())); + + List> dyadicArray = new ArrayList>(); + dyadicArray.add(Arrays.asList(BigInteger.valueOf(-1), BigInteger.valueOf(2))); + dyadicArray.add(Arrays.asList(BigInteger.valueOf(-1), BigInteger.valueOf(992))); + byte[] bytes = new byte[] {'a', 'b'}; + contractResult = + callContract.call( + address, + "newTest", + new StaticArray2(typeMap(dyadicArray, StaticArray2.class, Int256.class)), + new DynamicBytes(bytes)); + List returnList5 = + callContract.decode( + contractResult.getOutput(), + new TypeReference>>() {}, + new TypeReference() {}); + System.out.println( + "call newTest: " + + callContract.convertListList( + (List>) returnList5.get(0).getValue()) + + ", " + + new String((byte[]) returnList5.get(1).getValue()) + + ", " + + dyadicArray); + } + + static class TransactionCallback extends TransactionSucCallback { + TransactionCallback() { + try { + semaphore.acquire(1); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @Override + public void onResponse(TransactionReceipt receipt) { + this.receipt = receipt; + semaphore.release(); + } + + public TransactionReceipt receipt; + public Semaphore semaphore = new Semaphore(1, true); + }; + + private static void testAsyncCallContract(CallContract callContract, String address) { + TransactionCallback callback = new TransactionCallback(); + TransactionReceipt receipt; + + callContract.asyncSendTransaction( + callback, + gasPrice, + gasLimit, + address, + "setAndget", + new Utf8String("hello world"), + new Int256(10086)); + try { + callback.semaphore.acquire(1); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + System.out.println(e.getLocalizedMessage()); + } + receipt = callback.receipt; + List> referencesList = + Arrays.>asList( + new TypeReference() {}, new TypeReference() {}); + List returnList1 = + FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList)); + System.out.println( + "async call setAndget: " + + (String) returnList1.get(0).getValue() + + ", " + + (BigInteger) returnList1.get(1).getValue()); + + callContract.asyncSendTransaction( + callback, address, "setAndget", new Utf8String("hello world"), new Int256(10086)); + try { + callback.semaphore.acquire(1); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + System.out.println(e.getLocalizedMessage()); + } + receipt = callback.receipt; + referencesList = + Arrays.>asList( + new TypeReference() {}, new TypeReference() {}); + List returnList2 = + FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList)); + System.out.println( + "default async call setAndget: " + + (String) returnList2.get(0).getValue() + + ", " + + (BigInteger) returnList2.get(1).getValue()); + } + + private static void testDecode(CallContract callContract, String address) throws Exception { + CallResult contractResult; + + contractResult = callContract.call(address, "getInt", new Int256(10086)); + System.out.println("Decode Int: " + callContract.decode(contractResult.getOutput(), "Int")); + + contractResult = callContract.call(address, "getString", new Utf8String("hello world")); + System.out.println( + "Decode String: " + callContract.decode(contractResult.getOutput(), "String")); + + contractResult = + callContract.call( + address, + "getIntArray", + new DynamicArray( + typeMap( + Arrays.asList( + BigInteger.valueOf(110), BigInteger.valueOf(120)), + Int256.class))); + System.out.println( + "Decode IntArray: " + callContract.decode(contractResult.getOutput(), "IntArray")); + + contractResult = + callContract.call( + address, + "getStringArray", + new DynamicArray(typeMap(Arrays.asList("hehe", "xixi"), Utf8String.class))); + System.out.println( + "Decode StringArray: " + + callContract.decode(contractResult.getOutput(), "StringArray")); + + contractResult = + callContract.call( + address, + "getAll", + new Int256(10086), + new DynamicArray( + typeMap( + Arrays.asList( + BigInteger.valueOf(110), BigInteger.valueOf(120)), + Int256.class)), + new Utf8String("hello world"), + new DynamicArray(typeMap(Arrays.asList("hehe", "xixi"), Utf8String.class))); + System.out.println( + "Decode All: " + + callContract.decode( + contractResult.getOutput(), "Int,IntArray,String,StringArray")); + } +} diff --git a/src/test/java/org/fisco/bcos/channel/client/TransactionResourceTest.java b/src/test/java/org/fisco/bcos/channel/client/TransactionResourceTest.java new file mode 100644 index 000000000..0b701d8e9 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/client/TransactionResourceTest.java @@ -0,0 +1,149 @@ +package org.fisco.bcos.channel.client; + +import java.math.BigInteger; +import java.util.List; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameter; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock; +import org.fisco.bcos.web3j.protocol.core.methods.response.BcosTransaction; +import org.fisco.bcos.web3j.protocol.core.methods.response.MerkleProofUnit; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceiptWithProof; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionWithProof; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class TransactionResourceTest { + static Logger logger = LoggerFactory.getLogger(TransactionResourceTest.class); + public static Web3j web3j; + + public static ECKeyPair keyPair; + public static Credentials credentials; + + public static void main(String[] args) throws Exception { + + // init the Service + ApplicationContext context = + new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(args[0])); + service.run(); // run the daemon service + // init the client keys + keyPair = Keys.createEcKeyPair(); + credentials = Credentials.create(keyPair); + + logger.info("-----> start TransactionResourceTest !"); + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + try { + web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0])); + } catch (Exception e) { + System.out.println("Please provide groupID in the first paramters"); + System.exit(1); + } + + try { + if (args.length == 4) { + BigInteger blockNumber = new BigInteger(args[2]); + BigInteger transactionIndex = new BigInteger(args[3]); + DefaultBlockParameter defaultBlockParameter = + DefaultBlockParameter.valueOf(blockNumber); + + BcosTransaction bcosTransaction = + web3j.getTransactionByBlockNumberAndIndex( + defaultBlockParameter, transactionIndex) + .send(); + String transactionHash = bcosTransaction.getTransaction().get().getHash(); + + BcosBlock block = web3j.getBlockByNumber(defaultBlockParameter, true).send(); + String transactionsRootHash = block.getBlock().getTransactionsRoot(); + System.out.println("transactionsRoot: " + transactionsRootHash); + String receiptRootHash = block.getBlock().getReceiptsRoot(); + System.out.println("receiptRootHash : " + receiptRootHash); + + TransactionResource transactionResource = new TransactionResource(web3j); + + if ("getTrans".equals(args[1])) { + TransactionWithProof transactionWithProof = + web3j.getTransactionByHashWithProof(transactionHash).send(); + if (transactionWithProof == null) { + System.out.println("transactionWithProof == null"); + System.exit(1); + } + + System.out.println("***********Test getTransactionByHashWithProof************"); + List transactionProof = + transactionWithProof.getTransactionWithProof().getTxProof(); + System.out.println("transactionProof:" + transactionProof); + + TransactionWithProof newTransactionWithProof = + transactionResource.getTransactionWithProof( + transactionHash, transactionsRootHash); + if (newTransactionWithProof == null) { + System.out.println("Test getTransactionByHashWithProof failed!"); + + } else { + System.out.println( + newTransactionWithProof.getTransactionWithProof().toString()); + System.out.println("Test getTransactionByHashWithProof successfully!"); + } + + } else if ("getReceipt".equals(args[1])) { + TransactionReceiptWithProof transactionReceiptWithProof = + web3j.getTransactionReceiptByHashWithProof(transactionHash).send(); + if (transactionReceiptWithProof == null) { + System.out.println("transactionReceiptWithProof == null"); + System.exit(1); + } + + List transactionReceiptProof = + transactionReceiptWithProof + .getTransactionReceiptWithProof() + .getReceiptProof(); + System.out.println("receiptProof:" + transactionReceiptProof); + + System.out.println("***********Test getReceiptByHashWithProof************"); + TransactionReceiptWithProof newTransactionReceiptWithProof = + transactionResource.getTransactionReceiptWithProof( + transactionHash, receiptRootHash); + if (newTransactionReceiptWithProof == null) { + System.out.println("Test getReceiptByHashWithProof failed!"); + + } else { + System.out.println( + newTransactionReceiptWithProof + .getTransactionReceiptWithProof() + .toString()); + System.out.println("Test getReceiptByHashWithProof successfully!"); + } + } else if ("getAll".equals(args[1])) { + System.out.println( + "***********Test getTransactionAndReceiptWithProof************"); + ImmutablePair pair = + transactionResource.getTransactionAndReceiptWithProof( + transactionHash, transactionsRootHash, receiptRootHash); + if (pair == null) { + System.out.println("Test getAll failed!"); + } else { + System.out.println("Test getAll successful!"); + } + } else { + System.out.println("Command not found!"); + } + } else { + System.out.println("Please choose follow commands:\n getTrans or getReceipt!"); + } + } catch (Exception e) { + System.out.println(e.getLocalizedMessage()); + System.exit(1); + } + + System.exit(0); + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/amop/ProxyServer.java b/src/test/java/org/fisco/bcos/channel/test/amop/ProxyServer.java deleted file mode 100644 index ff41f8d78..000000000 --- a/src/test/java/org/fisco/bcos/channel/test/amop/ProxyServer.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.fisco.bcos.channel.test.amop; - -import static java.lang.System.exit; - -import org.fisco.bcos.channel.proxy.Server; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class ProxyServer { - - public static void main(String[] args) throws Exception { - - ApplicationContext context = - new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); - Server server1 = (Server) context.getBean("proxyServer1"); - Server server2 = (Server) context.getBean("proxyServer2"); - System.out.println("start testing"); - System.out.println("==================================================================="); - - server1.run(); - server2.run(); - - Thread.sleep(500000); - exit(1); - } -} diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java index f2bea5d3f..5586609c2 100644 --- a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java @@ -20,11 +20,11 @@ public void setTotal(Integer total) { public void onMessage(TransactionReceipt receipt, Long cost) { try { if (!receipt.isStatusOK()) { - System.out.println("receipt error"); + // System.out.println("receipt error"); error.addAndGet(1); } else { if (receipt.getLogs().isEmpty()) { - System.out.println("receipt log error"); + // System.out.println("receipt log error"); error.addAndGet(1); } } @@ -135,7 +135,7 @@ public void onMessage(TransactionReceipt receipt, Long cost) { public void onSelectMessage(TransactionReceipt receipt, Long cost) { try { if (!receipt.isStatusOK()) { - System.out.println("receipt error"); + // System.out.println("receipt error"); error.addAndGet(1); } diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceCollector.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceCollector.java index edae4b8f4..7fb7c3a13 100644 --- a/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceCollector.java +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceCollector.java @@ -20,11 +20,11 @@ public void setTotal(Integer total) { public void onMessage(TransactionReceipt receipt, Long cost) { try { if (!receipt.isStatusOK()) { - System.out.println("receipt error"); + // System.out.println("receipt error"); error.addAndGet(1); } else { if (receipt.getLogs().isEmpty()) { - System.out.println("receipt log error"); + // System.out.println("receipt log error"); error.addAndGet(1); } } diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelOk.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelOk.java index 5b633466d..64824f39b 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelOk.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelOk.java @@ -9,6 +9,7 @@ import org.fisco.bcos.web3j.abi.datatypes.Type; import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.crypto.EncryptType; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.core.RemoteCall; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; @@ -32,6 +33,13 @@ public class ParallelOk extends Contract { private static final String BINARY = "60806040526110066000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561005257600080fd5b50610aeb806100626000396000f30060806040526004361061008e576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806334a18dda1461009357806335ee5f871461010657806379fa913f146101835780638a42ebe9146101ec5780639b80b0501461025f578063bca926af14610318578063d39f70bc1461032f578063fad42f8714610346575b600080fd5b34801561009f57600080fd5b50610104600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506103ff565b005b34801561011257600080fd5b5061016d600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610570565b6040518082815260200191505060405180910390f35b34801561018f57600080fd5b506101ea600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506105e5565b005b3480156101f857600080fd5b5061025d600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061074d565b005b34801561026b57600080fd5b50610316600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506107c1565b005b34801561032457600080fd5b5061032d6108b8565b005b34801561033b57600080fd5b5061034461093a565b005b34801561035257600080fd5b506103fd600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506109b8565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630553904e3084846040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b838110156104e25780820151818401526020810190506104c7565b50505050905090810190601f16801561050f5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561053057600080fd5b505af1158015610544573d6000803e3d6000fd5b505050506040513d602081101561055a57600080fd5b8101908080519060200190929190505050505050565b60006001826040518082805190602001908083835b6020831015156105aa5780518252602082019150602081019050602083039250610585565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020549050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166311e3f2af30836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b838110156106c15780820151818401526020810190506106a6565b50505050905090810190601f1680156106ee5780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561070e57600080fd5b505af1158015610722573d6000803e3d6000fd5b505050506040513d602081101561073857600080fd5b81019080805190602001909291905050505050565b806001836040518082805190602001908083835b6020831015156107865780518252602082019150602081019050602083039250610761565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020819055505050565b806001846040518082805190602001908083835b6020831015156107fa57805182526020820191506020810190506020830392506107d5565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b602083101515610873578051825260208201915060208101905060208303925061084e565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540192505081905550505050565b6108f86040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e74323536290081525060026103ff565b6109386040805190810160405280601381526020017f73657428737472696e672c75696e74323536290000000000000000000000000081525060016103ff565b565b6109786040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e7432353629008152506105e5565b6109b66040805190810160405280601381526020017f73657428737472696e672c75696e7432353629000000000000000000000000008152506105e5565b565b806001846040518082805190602001908083835b6020831015156109f157805182526020820191506020810190506020830392506109cc565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b602083101515610a6a5780518252602082019150602081019050602083039250610a45565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390206000828254019250508190555060648111151515610aba57600080fd5b5050505600a165627a7a72305820df737a0d19f72bf33d291d99c82bf0c9d46af962f3cfcdaeca3f04e82d20f01c0029"; + public static String BINARY_GM = + "60806040526110066000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561005257600080fd5b50610aea806100626000396000f30060806040526004361061008d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168062f0e13314610092578063612d2bff146100fb578063748e7a1b146101b457806394618e4c146101cb578063ab71bf09146101e2578063b4c653e01461029b578063cd93c25d1461030e578063f2f4ee6d1461038b575b600080fd5b34801561009e57600080fd5b506100f9600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506103fe565b005b34801561010757600080fd5b506101b2600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610566565b005b3480156101c057600080fd5b506101c961065d565b005b3480156101d757600080fd5b506101e06106db565b005b3480156101ee57600080fd5b50610299600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061075d565b005b3480156102a757600080fd5b5061030c600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610864565b005b34801561031a57600080fd5b50610375600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506109d5565b6040518082815260200191505060405180910390f35b34801561039757600080fd5b506103fc600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610a4a565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663714c65bd30836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b838110156104da5780820151818401526020810190506104bf565b50505050905090810190601f1680156105075780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561052757600080fd5b505af115801561053b573d6000803e3d6000fd5b505050506040513d602081101561055157600080fd5b81019080805190602001909291905050505050565b806001846040518082805190602001908083835b60208310151561059f578051825260208201915060208101905060208303925061057a565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b60208310151561061857805182526020820191506020810190506020830392506105f3565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540192505081905550505050565b61069b6040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e7432353629008152506103fe565b6106d96040805190810160405280601381526020017f73657428737472696e672c75696e7432353629000000000000000000000000008152506103fe565b565b61071b6040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e7432353629008152506002610864565b61075b6040805190810160405280601381526020017f73657428737472696e672c75696e7432353629000000000000000000000000008152506001610864565b565b806001846040518082805190602001908083835b6020831015156107965780518252602082019150602081019050602083039250610771565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b60208310151561080f57805182526020820191506020810190506020830392506107ea565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020600082825401925050819055506064811115151561085f57600080fd5b505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663dc536a623084846040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b8381101561094757808201518184015260208101905061092c565b50505050905090810190601f1680156109745780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561099557600080fd5b505af11580156109a9573d6000803e3d6000fd5b505050506040513d60208110156109bf57600080fd5b8101908080519060200190929190505050505050565b60006001826040518082805190602001908083835b602083101515610a0f57805182526020820191506020810190506020830392506109ea565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020549050919050565b806001836040518082805190602001908083835b602083101515610a835780518252602082019150602081019050602083039250610a5e565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208190555050505600a165627a7a72305820d09526462e3d2fbfc6d8b8f40394e6d1fb975f884bb084679f2332943f8971bf0029"; + + public static final String getBinary() { + return (EncryptType.encryptType == EncryptType.ECDSA_TYPE ? BINARY : BINARY_GM); + } + public static final String FUNC_REGISTERPARALLELFUNCTION = "registerParallelFunction"; public static final String FUNC_BALANCEOF = "balanceOf"; @@ -55,7 +63,7 @@ protected ParallelOk( Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + super(getBinary(), contractAddress, web3j, credentials, gasPrice, gasLimit); } protected ParallelOk( @@ -63,7 +71,7 @@ protected ParallelOk( Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + super(getBinary(), contractAddress, web3j, credentials, contractGasProvider); } @Deprecated @@ -73,7 +81,7 @@ protected ParallelOk( TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + super(getBinary(), contractAddress, web3j, transactionManager, gasPrice, gasLimit); } protected ParallelOk( @@ -81,7 +89,7 @@ protected ParallelOk( Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + super(getBinary(), contractAddress, web3j, transactionManager, contractGasProvider); } public RemoteCall registerParallelFunction( @@ -362,14 +370,14 @@ public static ParallelOk load( public static RemoteCall deploy( Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return deployRemoteCall( - ParallelOk.class, web3j, credentials, contractGasProvider, BINARY, ""); + ParallelOk.class, web3j, credentials, contractGasProvider, getBinary(), ""); } @Deprecated public static RemoteCall deploy( Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall( - ParallelOk.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + ParallelOk.class, web3j, credentials, gasPrice, gasLimit, getBinary(), ""); } public static RemoteCall deploy( @@ -377,7 +385,7 @@ public static RemoteCall deploy( TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return deployRemoteCall( - ParallelOk.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + ParallelOk.class, web3j, transactionManager, contractGasProvider, getBinary(), ""); } @Deprecated @@ -387,6 +395,6 @@ public static RemoteCall deploy( BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall( - ParallelOk.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + ParallelOk.class, web3j, transactionManager, gasPrice, gasLimit, getBinary(), ""); } } diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelRevert.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelRevert.java deleted file mode 100644 index 9d207ec57..000000000 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelRevert.java +++ /dev/null @@ -1,289 +0,0 @@ -package org.fisco.bcos.channel.test.parallel.parallelok; - -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; -import org.fisco.bcos.channel.client.TransactionSucCallback; -import org.fisco.bcos.web3j.abi.TypeReference; -import org.fisco.bcos.web3j.abi.datatypes.Function; -import org.fisco.bcos.web3j.abi.datatypes.Type; -import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; -import org.fisco.bcos.web3j.crypto.Credentials; -import org.fisco.bcos.web3j.protocol.Web3j; -import org.fisco.bcos.web3j.protocol.core.RemoteCall; -import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.fisco.bcos.web3j.tx.Contract; -import org.fisco.bcos.web3j.tx.TransactionManager; -import org.fisco.bcos.web3j.tx.gas.ContractGasProvider; - -/** - * Auto generated code. - * - *

Do not modify! - * - *

Please use the web3j command line tools, - * or the org.fisco.bcos.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. - * - *

Generated with web3j version none. - */ -@SuppressWarnings("unchecked") -public class ParallelRevert extends Contract { - private static final String BINARY = - "60806040526110076000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561005257600080fd5b50610930806100626000396000f300608060405260043610610083576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806334a18dda1461008857806335ee5f87146100fb57806379fa913f146101785780638a42ebe9146101e15780639b80b05014610254578063bca926af1461030d578063d39f70bc14610324575b600080fd5b34801561009457600080fd5b506100f9600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061033b565b005b34801561010757600080fd5b50610162600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506104ac565b6040518082815260200191505060405180910390f35b34801561018457600080fd5b506101df600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610521565b005b3480156101ed57600080fd5b50610252600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610689565b005b34801561026057600080fd5b5061030b600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506106fd565b005b34801561031957600080fd5b50610322610804565b005b34801561033057600080fd5b50610339610886565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630553904e3084846040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b8381101561041e578082015181840152602081019050610403565b50505050905090810190601f16801561044b5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561046c57600080fd5b505af1158015610480573d6000803e3d6000fd5b505050506040513d602081101561049657600080fd5b8101908080519060200190929190505050505050565b60006001826040518082805190602001908083835b6020831015156104e657805182526020820191506020810190506020830392506104c1565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020549050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166311e3f2af30836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b838110156105fd5780820151818401526020810190506105e2565b50505050905090810190601f16801561062a5780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561064a57600080fd5b505af115801561065e573d6000803e3d6000fd5b505050506040513d602081101561067457600080fd5b81019080805190602001909291905050505050565b806001836040518082805190602001908083835b6020831015156106c2578051825260208201915060208101905060208303925061069d565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020819055505050565b806001846040518082805190602001908083835b6020831015156107365780518252602082019150602081019050602083039250610711565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b6020831015156107af578051825260208201915060208101905060208303925061078a565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540192505081905550606481111515156107ff57600080fd5b505050565b6108446040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e743235362900815250600261033b565b6108846040805190810160405280601381526020017f73657428737472696e672c75696e743235362900000000000000000000000000815250600161033b565b565b6108c46040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e743235362900815250610521565b6109026040805190810160405280601381526020017f73657428737472696e672c75696e743235362900000000000000000000000000815250610521565b5600a165627a7a7230582098a8175f9228fd5e6de012a15166541c53bff8d97397ba470d9257fdbb5b3ca90029"; - - public static final String FUNC_REGISTERPARALLELFUNCTION = "registerParallelFunction"; - - public static final String FUNC_BALANCEOF = "balanceOf"; - - public static final String FUNC_UNREGISTERPARALLELFUNCTION = "unregisterParallelFunction"; - - public static final String FUNC_SET = "set"; - - public static final String FUNC_TRANSFER = "transfer"; - - public static final String FUNC_ENABLEPARALLEL = "enableParallel"; - - public static final String FUNC_DISABLEPARALLEL = "disableParallel"; - - @Deprecated - protected ParallelRevert( - String contractAddress, - Web3j web3j, - Credentials credentials, - BigInteger gasPrice, - BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected ParallelRevert( - String contractAddress, - Web3j web3j, - Credentials credentials, - ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected ParallelRevert( - String contractAddress, - Web3j web3j, - TransactionManager transactionManager, - BigInteger gasPrice, - BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected ParallelRevert( - String contractAddress, - Web3j web3j, - TransactionManager transactionManager, - ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteCall registerParallelFunction( - String functionName, BigInteger criticalSize) { - final Function function = - new Function( - FUNC_REGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName), - new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256( - criticalSize)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public void registerParallelFunction( - String functionName, BigInteger criticalSize, TransactionSucCallback callback) { - final Function function = - new Function( - FUNC_REGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName), - new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256( - criticalSize)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public RemoteCall balanceOf(String name) { - final Function function = - new Function( - FUNC_BALANCEOF, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteCall unregisterParallelFunction(String functionName) { - final Function function = - new Function( - FUNC_UNREGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public void unregisterParallelFunction(String functionName, TransactionSucCallback callback) { - final Function function = - new Function( - FUNC_UNREGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public RemoteCall set(String name, BigInteger num) { - final Function function = - new Function( - FUNC_SET, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), - new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public void set(String name, BigInteger num, TransactionSucCallback callback) { - final Function function = - new Function( - FUNC_SET, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), - new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public RemoteCall transfer(String from, String to, BigInteger num) { - final Function function = - new Function( - FUNC_TRANSFER, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), - new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public void transfer(String from, String to, BigInteger num, TransactionSucCallback callback) { - final Function function = - new Function( - FUNC_TRANSFER, - Arrays.asList( - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), - new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), - new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public RemoteCall enableParallel() { - final Function function = - new Function( - FUNC_ENABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public void enableParallel(TransactionSucCallback callback) { - final Function function = - new Function( - FUNC_ENABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public RemoteCall disableParallel() { - final Function function = - new Function( - FUNC_DISABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public void disableParallel(TransactionSucCallback callback) { - final Function function = - new Function( - FUNC_DISABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - @Deprecated - public static ParallelRevert load( - String contractAddress, - Web3j web3j, - Credentials credentials, - BigInteger gasPrice, - BigInteger gasLimit) { - return new ParallelRevert(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static ParallelRevert load( - String contractAddress, - Web3j web3j, - TransactionManager transactionManager, - BigInteger gasPrice, - BigInteger gasLimit) { - return new ParallelRevert(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static ParallelRevert load( - String contractAddress, - Web3j web3j, - Credentials credentials, - ContractGasProvider contractGasProvider) { - return new ParallelRevert(contractAddress, web3j, credentials, contractGasProvider); - } - - public static ParallelRevert load( - String contractAddress, - Web3j web3j, - TransactionManager transactionManager, - ContractGasProvider contractGasProvider) { - return new ParallelRevert(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy( - Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall( - ParallelRevert.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy( - Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall( - ParallelRevert.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy( - Web3j web3j, - TransactionManager transactionManager, - ContractGasProvider contractGasProvider) { - return deployRemoteCall( - ParallelRevert.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy( - Web3j web3j, - TransactionManager transactionManager, - BigInteger gasPrice, - BigInteger gasLimit) { - return deployRemoteCall( - ParallelRevert.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); - } -} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDT.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDT.java index 4f7cc8a50..ad8c10375 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDT.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDT.java @@ -1,6 +1,7 @@ package org.fisco.bcos.channel.test.parallel.parallelok; import java.math.BigInteger; +import org.fisco.bcos.web3j.crypto.EncryptType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,6 +62,11 @@ public static void main(String[] args) throws Exception { PerformanceDTTest.setDagUserMgr(d); collector.setPerformanceDTTest(PerformanceDTTest); + System.out.println( + (EncryptType.encryptType == EncryptType.ECDSA_TYPE) + ? " ===>> normal parallel " + : " ===>> gm parallel "); + switch (command) { case "add": d.setTestType("add"); diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCollector.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCollector.java index e6e7b6195..bce48bd0e 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCollector.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCollector.java @@ -79,7 +79,7 @@ public boolean isEnd() { public void onMessage(TransactionReceipt receipt, Long cost) { try { if (!receipt.isStatusOK()) { - System.out.println("receipt error! status: " + receipt.getStatus()); + // System.out.println("receipt error! status: " + receipt.getStatus()); error.addAndGet(1); } diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTTest.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTTest.java index 8575aeb86..b6b9d7365 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTTest.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTTest.java @@ -12,9 +12,11 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.crypto.gm.GenCredential; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; import org.fisco.bcos.web3j.tx.Contract; @@ -171,9 +173,7 @@ public void initialize(String groupId) throws Exception { 15 * 100, scheduledExecutorService, Integer.parseInt(groupId)); - credentials = - Credentials.create( - "b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + credentials = GenCredential.create(); transactionManager = Contract.getTheTransactionManager(web3, credentials); } @@ -191,9 +191,7 @@ public void userAddTest(BigInteger count, BigInteger qps) { System.out.println("Deploying contract "); System.out.println( "==================================================================="); - credentials = - Credentials.create( - "b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + parallelok = ParallelOk.deploy( web3, @@ -272,6 +270,10 @@ public void run() { // end or not while (!collector.isEnd()) { Thread.sleep(3000); + logger.info( + " received: {}, total: {}", + collector.getReceived().intValue(), + collector.getTotal()); } dagUserMgr.setContractAddr(parallelokAddr); @@ -384,6 +386,10 @@ public void run() { // end or not while (!collector.isEnd()) { Thread.sleep(3000); + logger.info( + " received: {}, total: {}", + collector.getReceived().intValue(), + collector.getTotal()); } veryTransferData(threadPool); @@ -578,6 +584,10 @@ public void run() { while (!collector.isEnd()) { Thread.sleep(3000); + logger.info( + " received: {}, total: {}", + collector.getReceived().intValue(), + collector.getTotal()); } veryTransferData(threadPool); diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransfer.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransfer.java index 50a0100ef..5643eb8f9 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransfer.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransfer.java @@ -11,6 +11,7 @@ import org.fisco.bcos.web3j.abi.datatypes.Type; import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.crypto.EncryptType; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.core.RemoteCall; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; @@ -34,6 +35,8 @@ public class DagTransfer extends Contract { private static final String BINARY = "608060405234801561001057600080fd5b506103c6806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630b37617b146100725780631536aedd1461013f5780633fe8e3f5146101c3578063e555f3d91461024a578063ff2b0127146102d1575b600080fd5b34801561007e57600080fd5b50610129600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610358565b6040518082815260200191505060405180910390f35b34801561014b57600080fd5b506101a6600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610364565b604051808381526020018281526020019250505060405180910390f35b3480156101cf57600080fd5b50610234600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610379565b6040518082815260200191505060405180910390f35b34801561025657600080fd5b506102bb600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610384565b6040518082815260200191505060405180910390f35b3480156102dd57600080fd5b50610342600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061038f565b6040518082815260200191505060405180910390f35b60008090509392505050565b60008060008081915080905091509150915091565b600080905092915050565b600080905092915050565b6000809050929150505600a165627a7a723058207ff2a508f6093d5b125faa8cb120d0157aa5384ad0b65abc9c8d9b9b7d1eaaca0029"; + private static final String BINARY_GM = + "608060405234801561001057600080fd5b506103c6806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806301d04396146100725780631626c092146100f65780632f327550146101c3578063622793a51461024a578063ebceb511146102d1575b600080fd5b34801561007e57600080fd5b506100d9600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610358565b604051808381526020018281526020019250505060405180910390f35b34801561010257600080fd5b506101ad600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061036d565b6040518082815260200191505060405180910390f35b3480156101cf57600080fd5b50610234600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610379565b6040518082815260200191505060405180910390f35b34801561025657600080fd5b506102bb600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610384565b6040518082815260200191505060405180910390f35b3480156102dd57600080fd5b50610342600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061038f565b6040518082815260200191505060405180910390f35b60008060008081915080905091509150915091565b60008090509392505050565b600080905092915050565b600080905092915050565b6000809050929150505600a165627a7a723058200d11c2df16dd0f16c96758ea0dc32a74ec0fe83a8b6f7d9871a807be5dd4a8580029"; public static final String FUNC_USERTRANSFER = "userTransfer"; @@ -45,6 +48,10 @@ public class DagTransfer extends Contract { public static final String FUNC_USERDRAW = "userDraw"; + public static final String getBinary() { + return (EncryptType.encryptType == EncryptType.ECDSA_TYPE ? BINARY : BINARY_GM); + } + @Deprecated protected DagTransfer( String contractAddress, @@ -52,7 +59,7 @@ protected DagTransfer( Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + super(getBinary(), contractAddress, web3j, credentials, gasPrice, gasLimit); } protected DagTransfer( @@ -60,7 +67,7 @@ protected DagTransfer( Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + super(getBinary(), contractAddress, web3j, credentials, contractGasProvider); } @Deprecated @@ -70,7 +77,7 @@ protected DagTransfer( TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + super(getBinary(), contractAddress, web3j, transactionManager, gasPrice, gasLimit); } protected DagTransfer( @@ -78,7 +85,7 @@ protected DagTransfer( Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + super(getBinary(), contractAddress, web3j, transactionManager, contractGasProvider); } public RemoteCall userTransfer( @@ -277,14 +284,14 @@ public static DagTransfer load( public static RemoteCall deploy( Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return deployRemoteCall( - DagTransfer.class, web3j, credentials, contractGasProvider, BINARY, ""); + DagTransfer.class, web3j, credentials, contractGasProvider, getBinary(), ""); } @Deprecated public static RemoteCall deploy( Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall( - DagTransfer.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + DagTransfer.class, web3j, credentials, gasPrice, gasLimit, getBinary(), ""); } public static RemoteCall deploy( @@ -292,7 +299,7 @@ public static RemoteCall deploy( TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return deployRemoteCall( - DagTransfer.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + DagTransfer.class, web3j, transactionManager, contractGasProvider, getBinary(), ""); } @Deprecated @@ -302,6 +309,6 @@ public static RemoteCall deploy( BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall( - DagTransfer.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + DagTransfer.class, web3j, transactionManager, gasPrice, gasLimit, getBinary(), ""); } } diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDT.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDT.java index a5dd84d4f..eb89abda1 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDT.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDT.java @@ -1,6 +1,7 @@ package org.fisco.bcos.channel.test.parallel.precompile; import java.math.BigInteger; +import org.fisco.bcos.web3j.crypto.EncryptType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,6 +60,11 @@ public static void main(String[] args) throws Exception { PerformanceDTTest.setDagUserMgr(d); collector.setPerformanceDTTest(PerformanceDTTest); + System.out.println( + (EncryptType.encryptType == EncryptType.ECDSA_TYPE) + ? " ===>> normal parallel " + : " ===>> gm parallel "); + switch (command) { case "add": d.setTestType("add"); diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCollector.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCollector.java index e02bcad19..9355a0764 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCollector.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCollector.java @@ -93,7 +93,8 @@ public void onMessage(TransactionReceipt receipt, Long cost) { error.addAndGet(1); } } else { - System.out.println("receipt error! status: " + errorInfos.get(receipt.getStatus())); + // System.out.println("receipt error! status: " + + // errorInfos.get(receipt.getStatus())); error.addAndGet(1); } diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTTest.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTTest.java index e7db1bc0d..1d5d94cb1 100644 --- a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTTest.java +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTTest.java @@ -17,9 +17,11 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.crypto.gm.GenCredential; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; @@ -189,9 +191,7 @@ public void initialize(String groupId) throws Exception { scheduledExecutorService, Integer.parseInt(groupId)); - Credentials credentials = - Credentials.create( - "b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + Credentials credentials = GenCredential.create(); dagTransfer = DagTransfer.load( @@ -270,7 +270,11 @@ public void run() { // end or not while (!collector.isEnd()) { - Thread.sleep(100); + Thread.sleep(2000); + logger.info( + " received: {}, total: {}", + collector.getReceived().intValue(), + collector.getTotal()); } dagUserMgr.writeDagTransferUser(); @@ -377,67 +381,79 @@ public void run() { Lock fileLock = new ReentrantLock(); BufferedWriter writer = null; - writer = new BufferedWriter(new FileWriter(fileName)); - - AtomicLong writed = new AtomicLong(0); - for (int j = start; j < end; ++j) { - final int index = j; - final int totalWrite = end - start; - final BufferedWriter finalWriter = writer; - threadPool.execute( - new Runnable() { - @Override - public void run() { - while (true) { - DagTransferUser from = dagUserMgr.getFrom(index); - DagTransferUser to = dagUserMgr.getTo(index); - if ((deci.intValue() > 0) - && (deci.intValue() >= (index % 10 + 1))) { - to = dagUserMgr.getNext(index); - } - - Random random = new Random(); - int r = random.nextInt(100) + 1; - BigInteger amount = BigInteger.valueOf(r); - - try { - String signedTransaction = - dagTransfer.userTransferSeq( - from.getUser(), to.getUser(), amount); - String content = - String.format( - "%s %d %d%n", - signedTransaction, index, r); - fileLock.lock(); - finalWriter.write(content); - - long totalSigned = signed.incrementAndGet(); - if (totalSigned % (count.longValue() / 10) == 0) { - System.out.println( - "Signed transaction: " - + String.valueOf( - totalSigned - * 100 - / count.longValue()) - + "%"); + try { + writer = new BufferedWriter(new FileWriter(fileName)); + AtomicLong writed = new AtomicLong(0); + for (int j = start; j < end; ++j) { + final int index = j; + final int totalWrite = end - start; + final BufferedWriter finalWriter = writer; + threadPool.execute( + new Runnable() { + @Override + public void run() { + while (true) { + DagTransferUser from = dagUserMgr.getFrom(index); + DagTransferUser to = dagUserMgr.getTo(index); + if ((deci.intValue() > 0) + && (deci.intValue() >= (index % 10 + 1))) { + to = dagUserMgr.getNext(index); } - long writedCount = writed.incrementAndGet(); - totalWrited.incrementAndGet(); - if (writedCount >= totalWrite) { - finalWriter.close(); - } + Random random = new Random(); + int r = random.nextInt(100) + 1; + BigInteger amount = BigInteger.valueOf(r); + + try { + String signedTransaction = + dagTransfer.userTransferSeq( + from.getUser(), + to.getUser(), + amount); + String content = + String.format( + "%s %d %d%n", + signedTransaction, index, r); + fileLock.lock(); + finalWriter.write(content); + + long totalSigned = signed.incrementAndGet(); + if (totalSigned % (count.longValue() / 10) == 0) { + System.out.println( + "Signed transaction: " + + String.valueOf( + totalSigned + * 100 + / count + .longValue()) + + "%"); + } + + long writedCount = writed.incrementAndGet(); + totalWrited.incrementAndGet(); + if (writedCount >= totalWrite) { + finalWriter.close(); + } - break; - } catch (Exception e) { - e.printStackTrace(); - continue; - } finally { - fileLock.unlock(); + break; + } catch (Exception e) { + e.printStackTrace(); + continue; + } finally { + fileLock.unlock(); + } } } - } - }); + }); + } + } catch (Exception e) { + + if (writer != null) { + writer.close(); + } + + e.printStackTrace(); + System.exit(0); } } @@ -530,6 +546,9 @@ public void run() { + " transactions" + ",QPS=" + sendSpeed); + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); } finally { if (reader != null) { reader.close(); @@ -538,7 +557,11 @@ public void run() { } while (!collector.isEnd()) { - Thread.sleep(1000); + Thread.sleep(2000); + logger.info( + " received: {}, total: {}", + collector.getReceived().intValue(), + collector.getTotal()); } logger.info("End to send"); diff --git a/src/test/java/org/fisco/bcos/channel/test/rpc/GenerateGroup.java b/src/test/java/org/fisco/bcos/channel/test/rpc/GenerateGroup.java new file mode 100644 index 000000000..a26549f3f --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/rpc/GenerateGroup.java @@ -0,0 +1,64 @@ +package org.fisco.bcos.channel.test.rpc; + +import java.util.ArrayList; +import java.util.List; +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class GenerateGroup { + + private static Logger logger = LoggerFactory.getLogger(GenerateGroup.class); + + public static void Usage() { + System.out.println(" Usage:"); + System.out.println( + " \t java -cp conf/:lib/*:apps/* org.fisco.bcos.channel.test.rpc.GenerateGroup groupID timestamp node0 node1...nodeN"); + System.exit(0); + } + + public static void main(String[] args) throws Exception { + if (args.length < 3) { + Usage(); + } + + int groupID = Integer.valueOf(args[0]); + int timestamp = Integer.valueOf(args[1]); + List nodes = new ArrayList<>(); + + for (int i = 2; i < args.length; ++i) { + nodes.add(args[i]); + } + + System.out.println( + " Generate Group operation, groupID: " + + groupID + + " ,timestamp: " + + timestamp + + " ,nodes: " + + nodes); + + ApplicationContext context = + new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(1); + service.run(); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + Web3j web3j = Web3j.build(channelEthereumService, 1); + + org.fisco.bcos.web3j.protocol.core.methods.response.GenerateGroup generateGroup = + web3j.generateGroup(groupID, timestamp, nodes).send(); + logger.info(" generateGroup result: {}", generateGroup); + + System.out.println(" generateGroup result: " + generateGroup.getStatus()); + + System.exit(0); + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/rpc/StartGroup.java b/src/test/java/org/fisco/bcos/channel/test/rpc/StartGroup.java new file mode 100644 index 000000000..c45729b2d --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/rpc/StartGroup.java @@ -0,0 +1,50 @@ +package org.fisco.bcos.channel.test.rpc; + +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class StartGroup { + + private static Logger logger = LoggerFactory.getLogger(GenerateGroup.class); + + public static void Usage() { + System.out.println(" Usage:"); + System.out.println( + " \t java -cp conf/:lib/*:apps/* org.fisco.bcos.channel.test.rpc.StartGroup groupID"); + System.exit(0); + } + + public static void main(String[] args) throws Exception { + if (args.length < 1) { + Usage(); + } + + int groupID = Integer.valueOf(args[0]); + + System.out.println(" Start Group operation, groupID: " + groupID); + + ApplicationContext context = + new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(1); + service.run(); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + Web3j web3j = Web3j.build(channelEthereumService, 1); + + org.fisco.bcos.web3j.protocol.core.methods.response.StartGroup startGroup = + web3j.startGroup(groupID).send(); + logger.info(" StartGroup result: {}", startGroup); + + System.out.println(" StartGroup result: " + startGroup.getStatus()); + + System.exit(0); + } +} diff --git a/src/test/java/org/fisco/bcos/web3j/abi/TypeEncoderTest.java b/src/test/java/org/fisco/bcos/web3j/abi/TypeEncoderTest.java index 1ed184e76..4491000d1 100644 --- a/src/test/java/org/fisco/bcos/web3j/abi/TypeEncoderTest.java +++ b/src/test/java/org/fisco/bcos/web3j/abi/TypeEncoderTest.java @@ -1,11 +1,13 @@ package org.fisco.bcos.web3j.abi; +import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.math.BigInteger; import org.fisco.bcos.web3j.abi.datatypes.*; import org.fisco.bcos.web3j.abi.datatypes.generated.*; +import org.hamcrest.MatcherAssert; import org.junit.Test; public class TypeEncoderTest { @@ -257,4 +259,79 @@ public void testEmptyArray() { TypeEncoder.encodeDynamicArray(array), is("0000000000000000000000000000000000000000000000000000000000000000")); } + + @Test + public void throwsIfMaxOfU256() { + try { + Uint value = new Uint256(BigInteger.valueOf(-1)); + TypeEncoder.encodeNumeric(value); + } catch (UnsupportedOperationException e) { + MatcherAssert.assertThat( + e.getMessage(), + equalTo( + "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256, and in valid range.")); + } + + try { + Uint value = + new Uint256( + new BigInteger( + "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + 16)); + TypeEncoder.encodeNumeric(value); + } catch (UnsupportedOperationException e) { + MatcherAssert.assertThat( + e.getMessage(), + equalTo( + "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256, and in valid range.")); + } + } + + @Test + public void throwsIfMinOfInt256() { + try { + Int value = + new Int( + new BigInteger( + "-ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + 16)); + TypeEncoder.encodeNumeric(value); + } catch (UnsupportedOperationException e) { + MatcherAssert.assertThat( + e.getMessage(), + equalTo( + "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256, and in valid range.")); + } + + try { + Uint value = + new Uint256( + new BigInteger( + "-77fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + 16)); + TypeEncoder.encodeNumeric(value); + } catch (UnsupportedOperationException e) { + MatcherAssert.assertThat( + e.getMessage(), + equalTo( + "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256, and in valid range.")); + } + } + + @Test + public void throwsIfMaxOfInt256() { + try { + Int value = + new Int( + new BigInteger( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + 16)); + TypeEncoder.encodeNumeric(value); + } catch (UnsupportedOperationException e) { + MatcherAssert.assertThat( + e.getMessage(), + equalTo( + "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256, and in valid range.")); + } + } } diff --git a/src/test/java/org/fisco/bcos/web3j/abi/datatypes/StaticArrayTest.java b/src/test/java/org/fisco/bcos/web3j/abi/datatypes/StaticArrayTest.java index 6fe0e50fa..84e110717 100644 --- a/src/test/java/org/fisco/bcos/web3j/abi/datatypes/StaticArrayTest.java +++ b/src/test/java/org/fisco/bcos/web3j/abi/datatypes/StaticArrayTest.java @@ -44,7 +44,8 @@ public void throwsIfSizeIsAboveMaxOf32() { } catch (UnsupportedOperationException e) { assertThat( e.getMessage(), - equalTo("Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256")); + equalTo( + "Bitsize must be 8 bit aligned, and in range 0 < bitSize <= 256, and in valid range.")); } }