diff --git a/.ci/ci_check.sh b/.ci/ci_check.sh index cbceecd89..0f3c2d2e4 100755 --- a/.ci/ci_check.sh +++ b/.ci/ci_check.sh @@ -113,8 +113,6 @@ check_sm_node() } LOG_INFO "------ download_tassl---------" download_tassl -LOG_INFO "------ check_basic---------" -./gradlew build -x test LOG_INFO "------ download_build_chain---------" download_build_chain LOG_INFO "------ check_standard_node---------" diff --git a/.ci/ci_check_commit.sh b/.ci/ci_check_commit.sh index 2d9579de4..07659d29d 100644 --- a/.ci/ci_check_commit.sh +++ b/.ci/ci_check_commit.sh @@ -4,7 +4,7 @@ set -e scan_code_script="cobra/cobra.py -f json -o /tmp/report.json -t " ignore_files=(sh crt key json toml SignatureTest.java Ok.java bin abi ChannelTest.java ParallelOkDemo.java PerformanceAmop.java DagPrecompiledDemo.java KeyToolTest.java CryptoSuite.java AmopMsgHandlerTest.java TopicManager.java PrivateTopicVerifyTest.java AmopMsgBuilder.java TopicManagerTest.java AmopSubscribe.java AmopPublisher.java AmopPublisherPrivate.java AmopSubscribePrivate.java AmopPublisherFile.java AmopPublisherPrivateFile.java DemoAmopCallback.java FileToByteArrayHelper.java OkD.java TableTest.java PerformanceTable.java HelloWorld.java PerformanceRPC.java CodecTest.java ResponseTest.java ConfigTest.java) -commit_limit=6 +commit_limit=100 LOG_ERROR() { content=${1} diff --git a/Changelog.md b/Changelog.md index 8ee29621e..eaece7d90 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,50 @@ +## v2.7.0 +(2020-11-20) +Please read documentation of Java SDK. + +* [English User Handbook](https://fisco-bcos-documentation.readthedocs.io/en/latest/docs/sdk/java_sdk/index.html) +* [Chinese User Handbook](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/sdk/java_sdk/index.html#) +* [Chinese WIKI](https://github.com/FISCO-BCOS/java-sdk/wiki) + +Added: + * Added `getBatchReceiptsByBlockNumberAndRange` and `getBatchReceiptsByBlockHashAndRange` interfaces to support batch pull block transaction receipts + * Added the `getNodeInfo` interface to obtain subscribed topics information + * Added `revokeManager` interface to revoke contract life cycle management authority + * `ChainGovernanceService` adds `queryVotesOfMember` and `queryVotesOfThreshold` interfaces to support query voting status + +Changed: + * Separate `sdk-demo` as a `java-sdk-demo` project + +Fixed: + * Fix the exception of contract receipt parsing null pointer exception when deploying constructor with event + +Compatibility + +* FISCO BCOS v2.0+ +* AMOP Not compatible with Web3SDK + +---- +请参考文档: +* [英文版用户手册](https://fisco-bcos-documentation.readthedocs.io/en/latest/docs/sdk/java_sdk/index.html) +* [中文版用户手册](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/sdk/java_sdk/index.html#) +* [中文版WIKI](https://github.com/FISCO-BCOS/java-sdk/wiki) + +添加: + * 添加`getBatchReceiptsByBlockNumberAndRange`和`getBatchReceiptsByBlockHashAndRange`接口,支持批量拉取区块交易回执 + * 添加`getNodeInfo`接口,获取订阅的topics信息 + * 添加`revokeManager`接口,撤销合约生命周期管理权限 + * `ChainGovernanceService`添加`queryVotesOfMember`和`queryVotesOfThreshold`接口,支持查询投票情况 + +修改: + * 将`sdk-demo`独立为`java-sdk-demo`项目 + +修复: + * 修复部署构造函数带有event的合约异常时,合约回执解析空指针异常 + +适配性: +* 适配FISCO BCOS v2.0+ +* AMOP功能不兼容Web3SDK + ## v2.6.1 (2020-10-29) Please read documentation of Java SDK. @@ -21,8 +68,8 @@ Fixed: Compatibility -* FISCO BCOS v2.0+. -* Not compatible with Web3SDK. When two users want to use AMOP functions to talk with each other, they should either both use Java SDK, or both use Web3SDK. +* FISCO BCOS v2.0+ +* AMOP Not compatible with Web3SDK ---- 请参考文档: diff --git a/build.gradle b/build.gradle index daabfcb4c..6b035b041 100644 --- a/build.gradle +++ b/build.gradle @@ -26,9 +26,6 @@ ext { bcprovJDK15onVersion = "1.60" keyMiniToolkit = "1.0.2" - solcJVersion = "0.4.25.1" - //solcJVersion = "0.5.2.0" - //solcJVersion = "0.6.10.0" slf4jVersion = "1.7.30" junitVersion = "4.12" commonsCollections4Version = "4.4" @@ -39,7 +36,7 @@ ext { // integrationTest.mustRunAfter test allprojects { group = 'org.fisco-bcos.java-sdk' - version = '2.6.1' + version = '2.7.0-SNAPSHOT' apply plugin: 'maven' apply plugin: 'maven-publish' apply plugin: 'idea' @@ -58,12 +55,14 @@ allprojects { html.enabled false } } - sourceCompatibility = '1.8' + sourceCompatibility = 1.8 + targetCompatibility = 1.8 // In this section you declare where to find the dependencies of your project repositories { mavenCentral() maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } + maven { url "https://oss.sonatype.org/service/local/staging/deploy/maven2"} maven { url "https://oss.sonatype.org/content/repositories/snapshots" } } @@ -156,7 +155,6 @@ sourceSets { compileClasspath += main.output + test.output runtimeClasspath += main.output + test.output srcDir file('src/integration-test/java') - srcDir file('sdk-demo/src/main') } resources.srcDir file('src/integration-test/resources') } @@ -191,7 +189,6 @@ dependencies { compile ("com.moandjiezana.toml:toml4j:${toml4jVersion}") testCompile ("org.apache.commons:commons-collections4:${commonsCollections4Version}") - testCompile ("org.fisco-bcos:solcJ:${solcJVersion}") testCompile ("com.google.guava:guava:${guavaVersion}") } diff --git a/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/AmopImp.java b/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/AmopImp.java index 74c7420ee..a3a8e3f3b 100644 --- a/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/AmopImp.java +++ b/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/AmopImp.java @@ -115,13 +115,18 @@ public void sendAmopMsg(AmopMsgOut content, AmopResponseCallback callback) { new ResponseCallback() { @Override public void onResponse(Response response) { + logger.trace( + "receive response from subscriber, seq:{}", + response.getMessageID()); AmopResponse amopResponse = new AmopResponse(response); callback.onResponse(amopResponse); } }; this.channel.asyncSendToRandom(msg, cb, ops); logger.info( - "send amop msg to a random peer, seq{} topic{}", msg.getSeq(), content.getTopic()); + "send amop msg to a random peer, seq: {} topic: {}", + msg.getSeq(), + content.getTopic()); } @Override diff --git a/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/topic/AmopMsgHandler.java b/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/topic/AmopMsgHandler.java index 1a1fe5606..5cace8170 100644 --- a/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/topic/AmopMsgHandler.java +++ b/sdk-amop/src/main/java/org/fisco/bcos/sdk/amop/topic/AmopMsgHandler.java @@ -90,8 +90,7 @@ public void onConnect(ChannelHandlerContext ctx) { @Override public void onMessage(ChannelHandlerContext ctx, Message msg) { - logger.trace( - "receive msg, msg type:{}, content:{}", msg.getType(), new String(msg.getData())); + logger.trace("receive msg, msg type:{}, seq:{}", msg.getType(), msg.getSeq()); if (!isRunning) { logger.warn("Amop on msg, amop is not running, exit."); } diff --git a/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelImp.java b/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelImp.java index b09e65161..580165c25 100644 --- a/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelImp.java +++ b/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelImp.java @@ -327,6 +327,11 @@ public void run(Timeout timeout) { @Override public void asyncSendToRandom(Message out, ResponseCallback callback, Options options) { List peerList = getAvailablePeer(); + if (peerList.size() == 0) { + logger.warn( + "no available peer to send to, seq: {}, type: {}", out.getSeq(), out.getType()); + return; + } int random = (int) (Math.random() * (peerList.size())); String peerIpPort = peerList.get(random); logger.trace("send message to random peer {} ", peerIpPort); diff --git a/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelMsgHandler.java b/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelMsgHandler.java index 14bc3b843..90d959cee 100644 --- a/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelMsgHandler.java +++ b/sdk-core/src/main/java/org/fisco/bcos/sdk/channel/ChannelMsgHandler.java @@ -120,7 +120,7 @@ public void onConnect(ChannelHandlerContext ctx) { @Override public void onMessage(ChannelHandlerContext ctx, Message msg) { - logger.trace( + logger.debug( "onMessage in ChannelMsgHandler called, host : {}, seq : {}, msgType : {}", ChannelVersionNegotiation.getPeerHost(ctx), msg.getSeq(), @@ -129,10 +129,10 @@ public void onMessage(ChannelHandlerContext ctx, Message msg) { if (callback != null) { callback.cancelTimeout(); logger.trace( - " receive response, seq: {}, result: {}, content: {}", + " call registered callback, seq: {}, type: {} ,result: {}", msg.getSeq(), - msg.getResult(), - new String(msg.getData())); + msg.getType(), + msg.getResult()); Response response = new Response(); if (msg.getResult() != 0) { @@ -144,15 +144,16 @@ public void onMessage(ChannelHandlerContext ctx, Message msg) { response.setCtx(ctx); callback.onResponse(response); } else { - logger.trace( - " receive response with invalid seq, type: {}, result: {}, content: {}", - (int) msg.getType(), - msg.getResult(), - new String(msg.getData())); MsgHandler msgHandler = msgHandlers.get(msg.getType().intValue()); if (msgHandler != null) { + logger.trace( + " receive message, no callback, call handler, seq:{} , type: {}, result: {}", + msg.getSeq(), + (int) msg.getType(), + msg.getResult()); msgHandler.onMessage(ctx, msg); } + logger.debug(" call "); } } diff --git a/sdk-core/src/main/java/org/fisco/bcos/sdk/model/DataCompress.java b/sdk-core/src/main/java/org/fisco/bcos/sdk/model/DataCompress.java new file mode 100644 index 000000000..a254a9b56 --- /dev/null +++ b/sdk-core/src/main/java/org/fisco/bcos/sdk/model/DataCompress.java @@ -0,0 +1,54 @@ +/* + * Copyright 2014-2020 [fisco-dev] + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + */ + +package org.fisco.bcos.sdk.model; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +public class DataCompress { + public static byte[] compress(String data) { + + Deflater compress = new Deflater(); + + compress.setInput(data.getBytes()); + + byte[] compressedData = new byte[data.length()]; + compress.finish(); + + int compressLength = compress.deflate(compressedData, 0, compressedData.length); + return Arrays.copyOfRange(compressedData, 0, compressLength); + } + + public static byte[] uncompress(byte[] compressedData) throws IOException, DataFormatException { + + Inflater decompressor = new Inflater(); + decompressor.setInput(compressedData); + + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length)) { + byte[] buf = new byte[1024]; + while (!decompressor.finished()) { + int count = decompressor.inflate(buf); + bos.write(buf, 0, count); + } + + return bos.toByteArray(); + } + } +} diff --git a/sdk-core/src/main/java/org/fisco/bcos/sdk/model/PrecompiledRetCode.java b/sdk-core/src/main/java/org/fisco/bcos/sdk/model/PrecompiledRetCode.java index 46a1af9fe..1caa4e9c6 100644 --- a/sdk-core/src/main/java/org/fisco/bcos/sdk/model/PrecompiledRetCode.java +++ b/sdk-core/src/main/java/org/fisco/bcos/sdk/model/PrecompiledRetCode.java @@ -46,6 +46,11 @@ public class PrecompiledRetCode { new RetCode(-52000, "The committee member already exist"); // ContractLifeCyclePrecompiled -51999 ~ -51900 + public static final RetCode CODE_INVALID_REVOKE_LAST_AUTHORIZATION = + new RetCode( + -51907, "The permission of the last contract status manager can't be revoked"); + public static final RetCode CODE_INVALID_NON_EXIST_AUTHORIZATION = + new RetCode(-51906, "The contract status manager doesn't exist"); public static final RetCode CODE_INVALID_NO_AUTHORIZED = new RetCode(-51905, "Have no permission to access the contract table"); public static final RetCode CODE_INVALID_TABLE_NOT_EXIST = @@ -72,6 +77,8 @@ public class PrecompiledRetCode { new RetCode(-51600, "Execute PaillierAdd failed"); // CRUDPrecompiled -51599 ~ -51500 + public static final RetCode CODE_INVALID_UPDATE_TABLE_KEY = + new RetCode(-51503, "Don't update the table key"); public static final RetCode CODE_CONDITION_OPERATION_UNDEFINED = new RetCode(-51502, "Undefined function of Condition Precompiled"); public static final RetCode CODE_PARSE_CONDITION_ERROR = @@ -100,7 +107,7 @@ public class PrecompiledRetCode { -51004, "The committee permission control by ChainGovernancePrecompiled are recommended"); public static final RetCode CODE_CONTRACT_NOT_EXIST = - new RetCode(-51003, "The contract is not exist"); + new RetCode(-51003, "The contract doesn't exist"); public static final RetCode CODE_TABLE_NAME_OVERFLOW = new RetCode(-51002, "The table name string length exceeds the maximum limit"); public static final RetCode CODE_TABLE_AND_ADDRESS_NOT_EXIST = diff --git a/sdk-core/src/main/java/org/fisco/bcos/sdk/model/TransactionReceipt.java b/sdk-core/src/main/java/org/fisco/bcos/sdk/model/TransactionReceipt.java index 25e4e69dd..51f74e5a9 100644 --- a/sdk-core/src/main/java/org/fisco/bcos/sdk/model/TransactionReceipt.java +++ b/sdk-core/src/main/java/org/fisco/bcos/sdk/model/TransactionReceipt.java @@ -30,6 +30,8 @@ public class TransactionReceipt { private List logs; private String logsBloom; private String status; + // the node returned status message corresponding to the status + private String statusMsg; private String input; private String output; private List txProof; @@ -268,6 +270,14 @@ public boolean equals(Object o) { && Objects.equals(receiptProof, that.receiptProof); } + public String getStatusMsg() { + return statusMsg; + } + + public void setStatusMsg(String statusMsg) { + this.statusMsg = statusMsg; + } + @Override public int hashCode() { return Objects.hash( @@ -327,6 +337,9 @@ public String toString() { + ", status='" + status + '\'' + + ", statusMsg='" + + statusMsg + + '\'' + ", input='" + input + '\'' diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Hash.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Hash.java index c8f6b6648..d88be09b0 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Hash.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Hash.java @@ -18,5 +18,7 @@ public interface Hash { String hash(final String inputData); + String hashBytes(byte[] inputBytes); + byte[] hash(final byte[] inputBytes); } diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Keccak256.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Keccak256.java index a5643120f..3fa2efcae 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Keccak256.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/Keccak256.java @@ -30,6 +30,11 @@ public byte[] hash(final byte[] inputBytes) { return Hex.decode(calculateHash(inputBytes)); } + @Override + public String hashBytes(byte[] inputBytes) { + return calculateHash(inputBytes); + } + private String calculateHash(final byte[] inputBytes) { // Note: the exceptions should be handled by the caller CryptoResult hashResult = NativeInterface.keccak256(Hex.toHexString(inputBytes)); diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/SM3Hash.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/SM3Hash.java index cbc596b40..3290c02d7 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/SM3Hash.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/hash/SM3Hash.java @@ -21,16 +21,21 @@ public class SM3Hash implements Hash { @Override public String hash(final String inputData) { - return calcualteHash(inputData.getBytes()); + return calculateHash(inputData.getBytes()); + } + + @Override + public String hashBytes(byte[] inputBytes) { + return calculateHash(inputBytes); } @Override public byte[] hash(final byte[] inputBytes) { // Considering inefficient string conversion, this interface is not recommended - return Hex.decode(calcualteHash(inputBytes)); + return Hex.decode(calculateHash(inputBytes)); } - private String calcualteHash(final byte[] inputBytes) { + private String calculateHash(final byte[] inputBytes) { CryptoResult hashResult = NativeInterface.sm3(Hex.toHexString(inputBytes)); // call sm3 failed if (hashResult.wedprErrorMessage != null && !hashResult.wedprErrorMessage.isEmpty()) { diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignature.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignature.java index 2560fed75..a21bb481d 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignature.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignature.java @@ -28,7 +28,7 @@ public SignatureResult sign(final String message, final CryptoKeyPair keyPair) { @Override public SignatureResult sign(final byte[] message, final CryptoKeyPair keyPair) { - return sign(new String(message), keyPair); + return sign(Hex.toHexString(message), keyPair); } @Override diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignatureResult.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignatureResult.java index adbf1a0fb..92f872d5a 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignatureResult.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/ECDSASignatureResult.java @@ -63,4 +63,12 @@ public List encode() { super.encodeCommonField(encodeResult); return encodeResult; } + + public byte getV() { + return v; + } + + public void setV(byte v) { + this.v = v; + } } diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2Signature.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2Signature.java index d413527de..46b9b1ae3 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2Signature.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2Signature.java @@ -28,7 +28,7 @@ public SignatureResult sign(final String message, final CryptoKeyPair keyPair) { @Override public SignatureResult sign(final byte[] message, final CryptoKeyPair keyPair) { - return sign(new String(message), keyPair); + return sign(Hex.toHexString(message), keyPair); } @Override diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2SignatureResult.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2SignatureResult.java index ddedba6b2..8447f8e4b 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2SignatureResult.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SM2SignatureResult.java @@ -20,7 +20,7 @@ import org.fisco.bcos.sdk.utils.Hex; public class SM2SignatureResult extends SignatureResult { - protected final byte[] pub; + protected byte[] pub; public SM2SignatureResult(final String hexPublicKey, final String signatureString) { super(signatureString); @@ -52,4 +52,12 @@ public List encode() { super.encodeCommonField(encodeResult); return encodeResult; } + + public byte[] getPub() { + return pub; + } + + public void setPub(byte[] pub) { + this.pub = pub; + } } diff --git a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SignatureResult.java b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SignatureResult.java index 74a65d2d9..3f6a1eb4d 100644 --- a/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SignatureResult.java +++ b/sdk-crypto/src/main/java/org/fisco/bcos/sdk/crypto/signature/SignatureResult.java @@ -21,8 +21,8 @@ import org.fisco.bcos.sdk.utils.Hex; public abstract class SignatureResult { - protected final byte[] r; - protected final byte[] s; + protected byte[] r; + protected byte[] s; protected byte[] signatureBytes; SignatureResult(final byte[] r, final byte[] s) { @@ -64,6 +64,22 @@ public byte[] getS() { return s; } + public byte[] getSignatureBytes() { + return signatureBytes; + } + + public void setR(byte[] r) { + this.r = r; + } + + public void setS(byte[] s) { + this.s = s; + } + + public void setSignatureBytes(byte[] signatureBytes) { + this.signatureBytes = signatureBytes; + } + protected void encodeCommonField(List encodeResult) { encodeResult.add(RlpString.create(ByteUtils.trimLeadingZeroes(this.getR()))); encodeResult.add(RlpString.create(ByteUtils.trimLeadingZeroes(this.getS()))); diff --git a/sdk-crypto/src/test/java/org/fisco/bcos/sdk/crypto/SignatureTest.java b/sdk-crypto/src/test/java/org/fisco/bcos/sdk/crypto/SignatureTest.java index 55ba16734..5314ef40c 100644 --- a/sdk-crypto/src/test/java/org/fisco/bcos/sdk/crypto/SignatureTest.java +++ b/sdk-crypto/src/test/java/org/fisco/bcos/sdk/crypto/SignatureTest.java @@ -15,6 +15,8 @@ import java.io.File; import java.math.BigInteger; + +import org.bouncycastle.util.encoders.Hex; import org.fisco.bcos.sdk.config.Config; import org.fisco.bcos.sdk.config.ConfigOption; import org.fisco.bcos.sdk.config.exceptions.ConfigException; @@ -33,7 +35,6 @@ import org.fisco.bcos.sdk.crypto.signature.Signature; import org.fisco.bcos.sdk.crypto.signature.SignatureResult; import org.fisco.bcos.sdk.model.CryptoType; -import org.fisco.bcos.sdk.utils.Hex; import org.junit.Assert; import org.junit.Test; @@ -216,17 +217,20 @@ private void testInvalidPublicKey(CryptoKeyPair keyPair) { public void testSignature(Hash hasher, Signature signature, CryptoKeyPair keyPair) { String message = "abcde"; - + byte[] messageBytes = message.getBytes(); // check valid case for (int i = 0; i < 10; i++) { - message = hasher.hash("abcd----" + Integer.toString(i)); + String plainText = "abcd----" + Integer.toString(i); + message = hasher.hash(plainText); + messageBytes = hasher.hash(plainText.getBytes()); + Assert.assertTrue(message.equals(Hex.toHexString(messageBytes))); // sign SignatureResult signResult = signature.sign(message, keyPair); // verify Assert.assertTrue( signature.verify( keyPair.getHexPublicKey(), message, signResult.convertToString())); - signResult = signature.sign(message.getBytes(), keyPair); + signResult = signature.sign(messageBytes, keyPair); Assert.assertTrue( signature.verify( keyPair.getHexPublicKey(), message, signResult.convertToString())); @@ -235,7 +239,10 @@ public void testSignature(Hash hasher, Signature signature, CryptoKeyPair keyPai // check invalid case for (int i = 0; i < 10; i++) { message = hasher.hash("abcd----" + Integer.toString(i)); - String invaidMessage = hasher.hash("abcd---" + Integer.toString(i + 1)); + String plainText = "abcd---" + Integer.toString(i + 1); + String invalidMessage = hasher.hash(plainText); + byte[] invalidBytes = hasher.hash(plainText.getBytes()); + Assert.assertTrue(invalidMessage.equals(Hex.toHexString(invalidBytes))); // sign SignatureResult signResult = signature.sign(message, keyPair); // verify @@ -243,31 +250,35 @@ public void testSignature(Hash hasher, Signature signature, CryptoKeyPair keyPai false, signature.verify( keyPair.getHexPublicKey(), - invaidMessage, + invalidMessage, signResult.convertToString())); - signResult = signature.sign(message.getBytes(), keyPair); + signResult = signature.sign(messageBytes, keyPair); Assert.assertEquals( false, signature.verify( keyPair.getHexPublicKey(), - invaidMessage, + invalidMessage, signResult.convertToString())); } } public void testSignature(CryptoSuite signature, CryptoKeyPair keyPair) { String message = "abcde"; + byte[] messageBytes = message.getBytes(); // check valid case for (int i = 0; i < 10; i++) { // Note: the message must be hash - message = signature.hash("abcd----" + Integer.toString(i)); + String plainText = "abcd----" + Integer.toString(i); + message = signature.hash(plainText); + messageBytes = signature.hash(plainText.getBytes()); + Assert.assertTrue(message.equals(Hex.toHexString(messageBytes))); // sign SignatureResult signResult = signature.sign(message, keyPair); // verify Assert.assertTrue( signature.verify( keyPair.getHexPublicKey(), message, signResult.convertToString())); - signResult = signature.sign(message.getBytes(), keyPair); + signResult = signature.sign(messageBytes, keyPair); Assert.assertTrue( signature.verify( keyPair.getHexPublicKey(), message, signResult.convertToString())); @@ -276,7 +287,10 @@ public void testSignature(CryptoSuite signature, CryptoKeyPair keyPair) { // check invalid case for (int i = 0; i < 10; i++) { message = signature.hash("abcd----" + Integer.toString(i)); - String invaidMessage = signature.hash("abcd---" + Integer.toString(i + 1)); + String plainText = "abcd---" + Integer.toString(i + 1); + String invalidMessage = signature.hash(plainText); + byte[] invalidMessageBytes = signature.hash(plainText.getBytes()); + Assert.assertTrue(invalidMessage.equals(Hex.toHexString(invalidMessageBytes))); // sign SignatureResult signResult = signature.sign(message, keyPair); // verify @@ -284,14 +298,14 @@ public void testSignature(CryptoSuite signature, CryptoKeyPair keyPair) { false, signature.verify( keyPair.getHexPublicKey(), - invaidMessage, + invalidMessage, signResult.convertToString())); - signResult = signature.sign(message.getBytes(), keyPair); + signResult = signature.sign(messageBytes, keyPair); Assert.assertEquals( false, signature.verify( keyPair.getHexPublicKey(), - invaidMessage, + invalidMessage, signResult.convertToString())); } } diff --git a/sdk-demo/build.gradle b/sdk-demo/build.gradle deleted file mode 100644 index 8a275aa79..000000000 --- a/sdk-demo/build.gradle +++ /dev/null @@ -1,10 +0,0 @@ -// Apply the java-library plugin to add support for Java Library -plugins { - id 'java' -} -dependencies { - compile project(':sdk-codegen') - compile ("org.fisco-bcos:solcJ:${solcJVersion}") - compile ("com.google.guava:guava:${guavaVersion}") - compile ("org.apache.commons:commons-collections4:${commonsCollections4Version}") -} \ No newline at end of file diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgBuilder.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgBuilder.java deleted file mode 100644 index c57c907d7..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgBuilder.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.perf; - -import java.util.Random; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.AmopMsgOut; -import org.fisco.bcos.sdk.amop.AmopResponse; -import org.fisco.bcos.sdk.amop.AmopResponseCallback; -import org.fisco.bcos.sdk.amop.topic.TopicType; - -public class AmopMsgBuilder { - - public void sendMsg( - AmopMsgCollector collector, Amop sender, String topic, TopicType type, int contentLen) { - AmopMsgOut out = new AmopMsgOut(); - out.setTopic(topic); - out.setType(type); - out.setTimeout(5000); - out.setContent(getRandomBytes(contentLen)); - - AmopResponseCallback callback = - new AmopResponseCallback() { - @Override - public void onResponse(AmopResponse response) { - collector.addResponse(); - if (response.getErrorCode() != 0) { - System.out.println( - "error, code:" - + response.getErrorCode() - + " msg:" - + response.getErrorMessage()); - collector.addError(); - } - } - }; - sender.sendAmopMsg(out, callback); - } - - public byte[] getRandomBytes(int len) { - Random random = new Random(); - byte[] b = new byte[len]; - for (int i = 0; i < len; i++) { - Integer is = random.nextInt(9); - b[i] = Byte.parseByte(is.toString()); - } - return b; - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgCallback.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgCallback.java deleted file mode 100644 index d70c20810..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgCallback.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.perf; - -import org.fisco.bcos.sdk.amop.AmopCallback; -import org.fisco.bcos.sdk.amop.topic.AmopMsgIn; - -public class AmopMsgCallback extends AmopCallback { - private Long startTime = System.currentTimeMillis(); - - private AmopMsgCollector collector = new AmopMsgCollector(); - - public AmopMsgCollector getCollector() { - return collector; - } - - @Override - public byte[] receiveAmopMsg(AmopMsgIn msg) { - Long cost = System.currentTimeMillis() - startTime; - collector.onSubscribedTopicMsg(msg, cost); - return "Yes, I received!".getBytes(); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgCollector.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgCollector.java deleted file mode 100644 index 53bc8b95f..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/AmopMsgCollector.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.perf; - -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import org.fisco.bcos.sdk.amop.topic.AmopMsgIn; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AmopMsgCollector { - private static Logger logger = LoggerFactory.getLogger(AmopMsgCollector.class); - private AtomicLong less500 = new AtomicLong(0); - private AtomicLong less1000 = new AtomicLong(0); - private AtomicLong less2000 = new AtomicLong(0); - private AtomicLong less4000 = new AtomicLong(0); - private AtomicLong less10000 = new AtomicLong(0); - private AtomicLong timeout10000 = new AtomicLong(0); - private AtomicLong totalCost = new AtomicLong(0); - - private Integer total = 0; - private AtomicInteger received = new AtomicInteger(0); - private AtomicInteger error = new AtomicInteger(0); - private AtomicInteger responsed = new AtomicInteger(0); - private Long startTimestamp = System.currentTimeMillis(); - - public Integer getTotal() { - return total; - } - - public void setTotal(Integer total) { - this.total = total; - } - - public void addResponse() { - responsed.incrementAndGet(); - if (responsed.get() >= total) { - printResult(); - } - } - - public void addError() { - error.incrementAndGet(); - } - - public void onSubscribedTopicMsg(AmopMsgIn msg, long cost) { - - // System.out.println("Subscriber receive msg :" + Hex.toHexString(msg.getContent())); - try { - if (cost < 500) { - less500.incrementAndGet(); - } else if (cost < 1000) { - less1000.incrementAndGet(); - } else if (cost < 2000) { - less2000.incrementAndGet(); - } else if (cost < 4000) { - less4000.incrementAndGet(); - } else if (cost < 10000) { - less10000.incrementAndGet(); - } else { - timeout10000.incrementAndGet(); - } - totalCost.addAndGet(cost); - received.incrementAndGet(); - } catch (Exception e) { - logger.error("error:", e); - } - } - - public void printResult() { - - System.out.println("total"); - - Long totalTime = System.currentTimeMillis() - startTimestamp; - - System.out.println("==================================================================="); - - System.out.println("Total amop msg: " + String.valueOf(total)); - System.out.println("Total time: " + String.valueOf(totalTime) + "ms"); - System.out.println("Success received: " + String.valueOf(received.get())); - System.out.println("Response error:" + String.valueOf(error.get())); - System.out.println( - "Msg per second(exclude error requests): " - + String.valueOf(received.get() / ((double) totalTime / 1000))); - System.out.println("Avg time cost: " + String.valueOf(totalCost.get() / total) + "ms"); - System.out.println("Time area:"); - System.out.println( - "0 < time < 0.5s : " - + String.valueOf(less500) - + " : " - + String.valueOf((double) less500.get() / total * 100) - + "%"); - System.out.println( - "0.5 < time < 1s : " - + String.valueOf(less1000) - + " : " - + String.valueOf((double) less1000.get() / total * 100) - + "%"); - System.out.println( - "1 < time < 2s : " - + String.valueOf(less2000) - + " : " - + String.valueOf((double) less2000.get() / total * 100) - + "%"); - System.out.println( - "2 < time < 4s : " - + String.valueOf(less4000) - + " : " - + String.valueOf((double) less4000.get() / total * 100) - + "%"); - System.out.println( - "4 < time < 10s : " - + String.valueOf(less10000) - + " : " - + String.valueOf((double) less10000.get() / total * 100) - + "%"); - System.out.println( - "10 < time : " - + String.valueOf(timeout10000) - + " : " - + String.valueOf((double) timeout10000.get() / total * 100) - + "%"); - - System.exit(0); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/PerformanceAmop.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/PerformanceAmop.java deleted file mode 100644 index 067d7128f..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/perf/PerformanceAmop.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.perf; - -import com.google.common.util.concurrent.RateLimiter; -import java.util.concurrent.atomic.AtomicInteger; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.topic.TopicType; -import org.fisco.bcos.sdk.utils.ThreadPoolService; - -public class PerformanceAmop { - private static final String senderConfig = - PerformanceAmop.class - .getClassLoader() - .getResource("amop/config-publisher-for-test.toml") - .getPath(); - private static final String subscriberConfig = - PerformanceAmop.class - .getClassLoader() - .getResource("amop/config-subscriber-for-test.toml") - .getPath(); - private static AtomicInteger sendedMsg = new AtomicInteger(0); - private static AmopMsgBuilder msgBuilder = new AmopMsgBuilder(); - - /** @param args count, qps, msgSize */ - public static void main(String[] args) { - try { - Integer count = Integer.valueOf(args[0]); - Integer qps = Integer.valueOf(args[1]); - Integer msgSize = Integer.valueOf(args[2]); - - // Init subscriber - String topic = "normalTopic"; - Amop subscriber = BcosSDK.build(subscriberConfig).getAmop(); - AmopMsgCallback cb = new AmopMsgCallback(); - AmopMsgCollector collector = cb.getCollector(); - collector.setTotal(count); - subscriber.subscribeTopic(topic, cb); - subscriber.setCallback(cb); - - // Init publisher - Amop sender = BcosSDK.build(senderConfig).getAmop(); - - System.out.println("Start test"); - Thread.sleep(2000); - System.out.println("3s ..."); - Thread.sleep(1000); - System.out.println("2s ..."); - Thread.sleep(1000); - System.out.println("1s ..."); - Thread.sleep(1000); - System.out.println( - "====== PerformanceAmop Amop public topic text message performance start ======"); - RateLimiter limiter = RateLimiter.create(qps); - Integer area = count / 10; - final Integer total = count; - ThreadPoolService threadPoolService = new ThreadPoolService("PerformanceAmop", 102400); - - for (Integer i = 0; i < count; i++) { - limiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - msgBuilder.sendMsg( - collector, - sender, - "normalTopic", - TopicType.NORMAL_TOPIC, - msgSize); - int current = sendedMsg.incrementAndGet(); - if (current >= area && ((current % area) == 0)) { - System.out.println( - "Already sended: " - + current - + "/" - + total - + " amop text message"); - } - } - }); - } - // wait to send all msg - while (sendedMsg.get() != count) { - Thread.sleep(1000); - } - threadPoolService.stop(); - } catch (Exception e) { - System.out.println( - "====== PerformanceAmop test failed, error message: " + e.getMessage()); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisher.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisher.java deleted file mode 100644 index 2809c0616..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisher.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.AmopMsgOut; -import org.fisco.bcos.sdk.amop.topic.TopicType; - -public class AmopPublisher { - private static final int parameterNum = 4; - private static String publisherFile = - AmopPublisher.class - .getClassLoader() - .getResource("amop/config-publisher-for-test.toml") - .getPath(); - - /** - * @param args topicName, isBroadcast, Content(Content you want to send out), Count(how many msg - * you want to send out) - * @throws Exception AMOP publish exceptioned - */ - public static void main(String[] args) throws Exception { - if (args.length < parameterNum) { - System.out.println("param: target topic total number of request"); - return; - } - String topicName = args[0]; - Boolean isBroadcast = Boolean.valueOf(args[1]); - String content = args[2]; - Integer count = Integer.parseInt(args[3]); - BcosSDK sdk = BcosSDK.build(publisherFile); - Amop amop = sdk.getAmop(); - - System.out.println("3s ..."); - Thread.sleep(1000); - System.out.println("2s ..."); - Thread.sleep(1000); - System.out.println("1s ..."); - Thread.sleep(1000); - - System.out.println("start test"); - System.out.println("==================================================================="); - - for (Integer i = 0; i < count; ++i) { - Thread.sleep(2000); - AmopMsgOut out = new AmopMsgOut(); - out.setType(TopicType.NORMAL_TOPIC); - out.setContent(content.getBytes()); - out.setTimeout(6000); - out.setTopic(topicName); - DemoAmopResponseCallback cb = new DemoAmopResponseCallback(); - if (isBroadcast) { - amop.broadcastAmopMsg(out); - System.out.println( - "Step 1: Send out msg by broadcast, topic:" - + out.getTopic() - + " content:" - + new String(out.getContent())); - } else { - amop.sendAmopMsg(out, cb); - System.out.println( - "Step 1: Send out msg, topic:" - + out.getTopic() - + " content:" - + new String(out.getContent())); - } - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherFile.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherFile.java deleted file mode 100644 index 5111efc1c..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherFile.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import static org.fisco.bcos.sdk.demo.amop.tool.FileToByteArrayHelper.byteCat; -import static org.fisco.bcos.sdk.demo.amop.tool.FileToByteArrayHelper.getFileByteArray; -import static org.fisco.bcos.sdk.demo.amop.tool.FileToByteArrayHelper.intToByteArray; - -import java.io.File; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.AmopMsgOut; -import org.fisco.bcos.sdk.amop.topic.TopicType; - -public class AmopPublisherFile { - private static final int parameterNum = 4; - private static String publisherFile = - AmopPublisherFile.class - .getClassLoader() - .getResource("amop/config-publisher-for-test.toml") - .getPath(); - - /** - * @param args topicName, isBroadcast: true/false, fileName, count - * @throws Exception AMOP publish exceptioned - */ - public static void main(String[] args) throws Exception { - if (args.length < parameterNum) { - System.out.println("param: target topic total number of request"); - return; - } - String topicName = args[0]; - Boolean isBroadcast = Boolean.valueOf(args[1]); - String fileName = args[2]; - Integer count = Integer.parseInt(args[3]); - BcosSDK sdk = BcosSDK.build(publisherFile); - Amop amop = sdk.getAmop(); - Integer timeout = 6000; - if (args.length > 4) { - timeout = Integer.parseInt(args[4]); - } - System.out.println("3s ..."); - Thread.sleep(1000); - System.out.println("2s ..."); - Thread.sleep(1000); - System.out.println("1s ..."); - Thread.sleep(1000); - - System.out.println("start test"); - System.out.println("==================================================================="); - - int flag = -128; - byte[] byteflag = intToByteArray(flag); - int filelength = fileName.length(); - byte[] bytelength = intToByteArray(filelength); - byte[] bytefilename = fileName.getBytes(); - byte[] contentfile = getFileByteArray(new File(fileName)); - byte[] content = byteCat(byteCat(byteCat(byteflag, bytelength), bytefilename), contentfile); - - for (Integer i = 0; i < count; ++i) { - Thread.sleep(2000); - AmopMsgOut out = new AmopMsgOut(); - out.setType(TopicType.NORMAL_TOPIC); - out.setContent(content); - out.setTimeout(timeout); - out.setTopic(topicName); - DemoAmopResponseCallback cb = new DemoAmopResponseCallback(); - if (isBroadcast) { - amop.broadcastAmopMsg(out); - } else { - amop.sendAmopMsg(out, cb); - } - System.out.println( - "Step 1: Send out msg, topic:" + out.getTopic() + " content: file " + fileName); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherPrivate.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherPrivate.java deleted file mode 100644 index 8a961e58d..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherPrivate.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import java.util.ArrayList; -import java.util.List; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.AmopMsgOut; -import org.fisco.bcos.sdk.amop.topic.TopicType; -import org.fisco.bcos.sdk.crypto.keystore.KeyTool; -import org.fisco.bcos.sdk.crypto.keystore.PEMKeyStore; - -public class AmopPublisherPrivate { - private static final int parameterNum = 6; - private static String publisherFile = - AmopPublisherPrivate.class - .getClassLoader() - .getResource("amop/config-publisher-for-test.toml") - .getPath(); - - /** - * @param args topicName, pubKey1, pubKey2, isBroadcast: true/false, content, count. if only one - * public key please fill pubKey2 with null - * @throws Exception AMOP exceptioned - */ - public static void main(String[] args) throws Exception { - if (args.length < parameterNum) { - System.out.println( - "param: opicName, pubKey1, pubKey2, isBroadcast: true/false, content, count"); - return; - } - String topicName = args[0]; - String pubkey1 = args[1]; - String pubkey2 = args[2]; - Boolean isBroadcast = Boolean.valueOf(args[3]); - String content = args[4]; - Integer count = Integer.parseInt(args[5]); - BcosSDK sdk = BcosSDK.build(publisherFile); - Amop amop = sdk.getAmop(); - - System.out.println("3s ..."); - Thread.sleep(1000); - System.out.println("2s ..."); - Thread.sleep(1000); - System.out.println("1s ..."); - Thread.sleep(1000); - - System.out.println("start test"); - System.out.println("==================================================================="); - System.out.println("set up private topic"); - List keyToolList = new ArrayList<>(); - KeyTool keyTool = new PEMKeyStore(pubkey1); - keyToolList.add(keyTool); - if (!pubkey2.equals("null")) { - KeyTool keyTool1 = new PEMKeyStore(pubkey2); - keyToolList.add(keyTool1); - } - amop.publishPrivateTopic(topicName, keyToolList); - System.out.println("wait until finish private topic verify"); - System.out.println("3s ..."); - Thread.sleep(1000); - System.out.println("2s ..."); - Thread.sleep(1000); - System.out.println("1s ..."); - Thread.sleep(1000); - - for (Integer i = 0; i < count; ++i) { - Thread.sleep(2000); - AmopMsgOut out = new AmopMsgOut(); - out.setType(TopicType.PRIVATE_TOPIC); - out.setContent(content.getBytes()); - out.setTimeout(6000); - out.setTopic(topicName); - DemoAmopResponseCallback cb = new DemoAmopResponseCallback(); - if (isBroadcast) { - amop.broadcastAmopMsg(out); - System.out.println( - "Step 1: Send out msg by broadcast, topic:" - + out.getTopic() - + " content:" - + new String(out.getContent())); - } else { - amop.sendAmopMsg(out, cb); - System.out.println( - "Step 1: Send out msg, topic:" - + out.getTopic() - + " content:" - + new String(out.getContent())); - } - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherPrivateFile.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherPrivateFile.java deleted file mode 100644 index 0bfb6e009..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopPublisherPrivateFile.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import static org.fisco.bcos.sdk.demo.amop.tool.FileToByteArrayHelper.byteCat; -import static org.fisco.bcos.sdk.demo.amop.tool.FileToByteArrayHelper.getFileByteArray; -import static org.fisco.bcos.sdk.demo.amop.tool.FileToByteArrayHelper.intToByteArray; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.AmopMsgOut; -import org.fisco.bcos.sdk.amop.topic.TopicType; -import org.fisco.bcos.sdk.crypto.keystore.KeyTool; -import org.fisco.bcos.sdk.crypto.keystore.PEMKeyStore; - -public class AmopPublisherPrivateFile { - private static final int parameterNum = 6; - private static String publisherFile = - AmopPublisherPrivateFile.class - .getClassLoader() - .getResource("amop/config-publisher-for-test.toml") - .getPath(); - - /** - * @param args topicName, pubKey1, pubKey2, isBroadcast: true/false, fileName, count, timeout. - * if only one public key please fill pubKey2 with null - * @throws Exception the exception - */ - public static void main(String[] args) throws Exception { - if (args.length < parameterNum) { - System.out.println("param: target topic total number of request"); - return; - } - String topicName = args[0]; - String pubkey1 = args[1]; - String pubkey2 = args[2]; - Boolean isBroadcast = Boolean.valueOf(args[3]); - String fileName = args[4]; - Integer count = Integer.parseInt(args[5]); - Integer timeout = 6000; - if (args.length > 6) { - timeout = Integer.parseInt(args[6]); - } - BcosSDK sdk = BcosSDK.build(publisherFile); - Amop amop = sdk.getAmop(); - // todo setup topic - - System.out.println("3s ..."); - Thread.sleep(1000); - System.out.println("2s ..."); - Thread.sleep(1000); - System.out.println("1s ..."); - Thread.sleep(1000); - - System.out.println("start test"); - System.out.println("==================================================================="); - System.out.println("set up private topic"); - List kml = new ArrayList<>(); - KeyTool km1 = new PEMKeyStore(pubkey1); - kml.add(km1); - if (!pubkey2.equals("null")) { - KeyTool km2 = new PEMKeyStore(pubkey2); - kml.add(km2); - } - amop.publishPrivateTopic(topicName, kml); - System.out.println("wait until finish private topic verify"); - System.out.println("3s ..."); - Thread.sleep(1000); - System.out.println("2s ..."); - Thread.sleep(1000); - System.out.println("1s ..."); - Thread.sleep(1000); - - int flag = -128; - byte[] byteflag = intToByteArray(flag); - int filelength = fileName.length(); - byte[] bytelength = intToByteArray(filelength); - byte[] bytefilename = fileName.getBytes(); - byte[] contentfile = getFileByteArray(new File(fileName)); - byte[] content = byteCat(byteCat(byteCat(byteflag, bytelength), bytefilename), contentfile); - - for (Integer i = 0; i < count; ++i) { - Thread.sleep(2000); - AmopMsgOut out = new AmopMsgOut(); - out.setType(TopicType.PRIVATE_TOPIC); - out.setContent(content); - out.setTimeout(timeout); - out.setTopic(topicName); - DemoAmopResponseCallback cb = new DemoAmopResponseCallback(); - if (isBroadcast) { - amop.broadcastAmopMsg(out); - } else { - amop.sendAmopMsg(out, cb); - } - System.out.println( - "Step 1: Send out msg, topic:" + out.getTopic() + " content: file " + fileName); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopSubscriber.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopSubscriber.java deleted file mode 100644 index 2410936de..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopSubscriber.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import java.net.URL; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.AmopCallback; - -public class AmopSubscriber { - - public static void main(String[] args) throws Exception { - URL configUrl = - AmopSubscriber.class - .getClassLoader() - .getResource("amop/config-subscriber-for-test.toml"); - if (args.length < 1) { - System.out.println("Param: topic"); - return; - } - String topic = args[0]; - BcosSDK sdk = BcosSDK.build(configUrl.getPath()); - Amop amop = sdk.getAmop(); - AmopCallback cb = new DemoAmopCallback(); - System.out.println("Start test"); - amop.subscribeTopic(topic, cb); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopSubscriberPrivate.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopSubscriberPrivate.java deleted file mode 100644 index 380c7b740..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/AmopSubscriberPrivate.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.amop.Amop; -import org.fisco.bcos.sdk.amop.AmopCallback; -import org.fisco.bcos.sdk.crypto.keystore.KeyTool; -import org.fisco.bcos.sdk.crypto.keystore.P12KeyStore; -import org.fisco.bcos.sdk.crypto.keystore.PEMKeyStore; - -public class AmopSubscriberPrivate { - private static String subscriberConfigFile = - AmopSubscriberPrivate.class - .getClassLoader() - .getResource("amop/config-subscriber-for-test.toml") - .getPath(); - - /** - * @param args topic, privateKeyFile, password(Option) - * @throws Exception AMOP exceptioned - */ - public static void main(String[] args) throws Exception { - if (args.length < 2) { - System.out.println("Param: topic, privateKeyFile, password"); - return; - } - String topic = args[0]; - String privateKeyFile = args[1]; - BcosSDK sdk = BcosSDK.build(subscriberConfigFile); - Amop amop = sdk.getAmop(); - AmopCallback cb = new DemoAmopCallback(); - - System.out.println("Start test"); - amop.setCallback(cb); - - KeyTool km; - if (privateKeyFile.endsWith("p12")) { - String password = args[2]; - km = new P12KeyStore(privateKeyFile, password); - } else { - km = new PEMKeyStore(privateKeyFile); - } - amop.subscribePrivateTopics(topic, km, cb); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/DemoAmopCallback.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/DemoAmopCallback.java deleted file mode 100644 index 2c98bf8ec..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/DemoAmopCallback.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import static org.fisco.bcos.sdk.utils.ByteUtils.byteArrayToInt; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; -import org.fisco.bcos.sdk.amop.AmopCallback; -import org.fisco.bcos.sdk.amop.topic.AmopMsgIn; -import org.fisco.bcos.sdk.model.MsgType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DemoAmopCallback extends AmopCallback { - private static Logger logger = LoggerFactory.getLogger(DemoAmopCallback.class); - - @Override - public byte[] receiveAmopMsg(AmopMsgIn msg) { - if (msg.getContent().length > 8) { - byte[] content = msg.getContent(); - byte[] byteflag = subbytes(content, 0, 4); - int flag = byteArrayToInt(byteflag); - if (flag == -128) { - byte[] bytelength = subbytes(content, 4, 4); - int length = byteArrayToInt(bytelength); - byte[] bytefilename = subbytes(content, 8, length); - String filename = new String(bytefilename); - System.out.println( - "Step 2:Receive file, filename length:" - + length - + " filename binary:" - + Arrays.toString(bytefilename) - + " filename:" - + filename); - - int contentlength = content.length - 8 - filename.length(); - byte[] fileContent = subbytes(content, 8 + filename.length(), contentlength); - getFileFromBytes(fileContent, filename); - System.out.println("|---save file:" + filename + " success"); - byte[] responseData = "Yes, I received!".getBytes(); - if (msg.getType() == (short) MsgType.AMOP_REQUEST.getType()) { - System.out.println("|---response:" + new String(responseData)); - } - return responseData; - } - } - - byte[] responseData = "Yes, I received!".getBytes(); - System.out.println( - "Step 2:Receive msg, topic:" - + msg.getTopic() - + " content:" - + new String(msg.getContent())); - if (msg.getType() == (short) MsgType.AMOP_REQUEST.getType()) { - System.out.println("|---response:" + new String(responseData)); - } - return responseData; - } - - public static byte[] subbytes(byte[] src, int begin, int count) { - byte[] bs = new byte[count]; - System.arraycopy(src, begin, bs, 0, count); - return bs; - } - - public static void getFileFromBytes(byte[] b, String outputFile) { - File ret = null; - BufferedOutputStream stream = null; - FileOutputStream fstream = null; - try { - ret = new File(outputFile); - fstream = new FileOutputStream(ret); - stream = new BufferedOutputStream(fstream); - stream.write(b); - } catch (Exception e) { - logger.error(" write exception, message: {}", e.getMessage()); - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - logger.error(" close exception, message: {}", e.getMessage()); - } - } - - if (fstream != null) { - try { - fstream.close(); - } catch (IOException e) { - logger.error(" close exception, message: {}", e.getMessage()); - } - } - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/DemoAmopResponseCallback.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/DemoAmopResponseCallback.java deleted file mode 100644 index c585bde28..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/DemoAmopResponseCallback.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import org.fisco.bcos.sdk.amop.AmopResponse; -import org.fisco.bcos.sdk.amop.AmopResponseCallback; - -public class DemoAmopResponseCallback extends AmopResponseCallback { - - @Override - public void onResponse(AmopResponse response) { - if (response.getErrorCode() == 102) { - System.out.println( - "Step 3: Timeout, maybe your file is too large or your gave a short timeout. Add a timeout arg, topicName, isBroadcast: true/false, fileName, count, timeout"); - } else { - if (response.getAmopMsgIn() != null) { - System.out.println( - "Step 3:Get response, { errorCode:" - + response.getErrorCode() - + " error:" - + response.getErrorMessage() - + " seq:" - + response.getMessageID() - + " content:" - + new String(response.getAmopMsgIn().getContent()) - + " }"); - } else { - System.out.println( - "Step 3:Get response, { errorCode:" - + response.getErrorCode() - + " error:" - + response.getErrorMessage() - + " seq:" - + response.getMessageID()); - } - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/FileToByteArrayHelper.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/FileToByteArrayHelper.java deleted file mode 100644 index 8398fdcb2..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/amop/tool/FileToByteArrayHelper.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.fisco.bcos.sdk.demo.amop.tool; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - -public class FileToByteArrayHelper { - public static byte[] getFileByteArray(File file) { - long fileSize = file.length(); - if (fileSize > Integer.MAX_VALUE) { - System.out.println("file too big..."); - return null; - } - byte[] buffer = null; - try (FileInputStream fi = new FileInputStream(file)) { - buffer = new byte[(int) fileSize]; - int offset = 0; - int numRead = 0; - while (offset < buffer.length - && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { - offset += numRead; - } - if (offset != buffer.length) { - throw new IOException("Could not completely read file " + file.getName()); - } - } catch (Exception e) { - e.printStackTrace(); - } - return buffer; - } - - public static byte[] byteCat(byte[] data1, byte[] data2) { - byte[] data3 = new byte[data1.length + data2.length]; - System.arraycopy(data1, 0, data3, 0, data1.length); - System.arraycopy(data2, 0, data3, data1.length, data2.length); - return data3; - } - - public static byte[] intToByteArray(int i) { - byte[] result = new byte[4]; - result[0] = (byte) ((i >> 24) & 0xFF); - result[1] = (byte) ((i >> 16) & 0xFF); - result[2] = (byte) ((i >> 8) & 0xFF); - result[3] = (byte) (i & 0xFF); - return result; - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/codegen/CompileSolidityException.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/codegen/CompileSolidityException.java deleted file mode 100644 index 02fc40c4e..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/codegen/CompileSolidityException.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.codegen; - -/** Exceptioned when calling hash. */ -public class CompileSolidityException extends RuntimeException { - public CompileSolidityException(String message) { - super(message); - } - - public CompileSolidityException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/codegen/DemoSolcToJava.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/codegen/DemoSolcToJava.java deleted file mode 100644 index c07c34c63..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/codegen/DemoSolcToJava.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.codegen; - -import static org.fisco.solc.compiler.SolidityCompiler.Options.ABI; -import static org.fisco.solc.compiler.SolidityCompiler.Options.BIN; -import static org.fisco.solc.compiler.SolidityCompiler.Options.INTERFACE; -import static org.fisco.solc.compiler.SolidityCompiler.Options.METADATA; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; -import org.fisco.bcos.sdk.codegen.CodeGenMain; -import org.fisco.solc.compiler.CompilationResult; -import org.fisco.solc.compiler.SolidityCompiler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DemoSolcToJava { - - private static final Logger logger = LoggerFactory.getLogger(DemoSolcToJava.class); - - public static final String SOLIDITY_PATH = "contracts/solidity/"; - public static final String JAVA_PATH = "contracts/sdk/java/"; - public static final String ABI_PATH = "contracts/sdk/abi/"; - public static final String BIN_PATH = "contracts/sdk/bin/"; - - public static void main(String[] args) { - if (args.length < 1) { - System.out.println("Please provide a package name."); - return; - } - - File solFileList = new File(SOLIDITY_PATH); - File javaPath = new File(JAVA_PATH); - if (!javaPath.exists()) { - javaPath.mkdirs(); - } - File abiPath = new File(ABI_PATH + File.separator + "sm"); - if (!abiPath.exists()) { - abiPath.mkdirs(); - } - File binPath = new File(BIN_PATH + File.separator + "sm"); - if (!binPath.exists()) { - binPath.mkdirs(); - } - String tempDirPath = javaPath.getAbsolutePath(); - try { - compileSolToJava("*", tempDirPath, args[0], solFileList, ABI_PATH, BIN_PATH); - System.out.println( - "\nCompile solidity contract files to java contract files successfully!"); - } catch (IOException | CompileSolidityException e) { - System.out.print(e.getMessage()); - logger.error(" message: {}, e: {}", e.getMessage(), e); - } - } - - private static void writeStringToFile(String destFile, String content) throws IOException { - FileOutputStream fos = new FileOutputStream(destFile); - fos.write(content.getBytes()); - fos.close(); - } - - public static void compileSolToJava( - String solName, - String tempDirPath, - String packageName, - File solFileList, - String abiDir, - String binDir) - throws IOException { - File[] solFiles = solFileList.listFiles(); - if (solFiles.length == 0) { - System.out.println("The contracts directory is empty."); - return; - } - for (File solFile : solFiles) { - if (!solFile.getName().endsWith(".sol")) { - continue; - } - if (!"*".equals(solName)) { - if (!solFile.getName().equals(solName)) { - continue; - } - if (solFile.getName().startsWith("Lib")) { - throw new IOException("Don't deploy the library: " + solFile.getName()); - } - } else { - if (solFile.getName().startsWith("Lib")) { - continue; - } - } - - String contractName = solFile.getName().split("\\.")[0]; - - /** ecdsa compile */ - SolidityCompiler.Result res = - SolidityCompiler.compile(solFile, false, true, ABI, BIN, INTERFACE, METADATA); - logger.debug( - " solidity compiler result, success: {}, output: {}", - !res.isFailed(), - res.getOutput()); - if (res.isFailed() || "".equals(res.getOutput())) { - throw new CompileSolidityException(" Compile error: " + res.getErrors()); - } - - /** sm compile */ - SolidityCompiler.Result smRes = - SolidityCompiler.compile(solFile, true, true, ABI, BIN, INTERFACE, METADATA); - logger.debug( - " sm solidity compiler result, success: {}, output: {}, error: {}", - !smRes.isFailed(), - smRes.getOutput(), - smRes.getErrors()); - if (smRes.isFailed() || "".equals(smRes.getOutput())) { - throw new CompileSolidityException(" Compile SM error: " + res.getErrors()); - } - - CompilationResult result = CompilationResult.parse(res.getOutput()); - CompilationResult smResult = CompilationResult.parse(smRes.getOutput()); - - CompilationResult.ContractMetadata meta = result.getContract(contractName); - CompilationResult.ContractMetadata smMeta = smResult.getContract(contractName); - - writeStringToFile(new File(abiDir + contractName + ".abi").getAbsolutePath(), meta.abi); - writeStringToFile(new File(binDir + contractName + ".bin").getAbsolutePath(), meta.bin); - - writeStringToFile( - new File(abiDir + "/sm/" + contractName + ".abi").getAbsolutePath(), - smMeta.abi); - writeStringToFile( - new File(binDir + "/sm/" + contractName + ".bin").getAbsolutePath(), - smMeta.bin); - - String binFile; - String abiFile; - String smBinFile; - String filename = contractName; - abiFile = abiDir + filename + ".abi"; - binFile = binDir + filename + ".bin"; - smBinFile = binDir + "/sm/" + filename + ".bin"; - CodeGenMain.main( - Arrays.asList( - "-a", abiFile, - "-b", binFile, - "-s", smBinFile, - "-p", packageName, - "-o", tempDirPath) - .toArray(new String[0])); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/DagTransfer.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/DagTransfer.java deleted file mode 100644 index fccf250b8..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/DagTransfer.java +++ /dev/null @@ -1,322 +0,0 @@ -package org.fisco.bcos.sdk.demo.contract; - -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.fisco.bcos.sdk.abi.FunctionReturnDecoder; -import org.fisco.bcos.sdk.abi.TypeReference; -import org.fisco.bcos.sdk.abi.datatypes.Function; -import org.fisco.bcos.sdk.abi.datatypes.Type; -import org.fisco.bcos.sdk.abi.datatypes.Utf8String; -import org.fisco.bcos.sdk.abi.datatypes.generated.Uint256; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple1; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple2; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple3; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.contract.Contract; -import org.fisco.bcos.sdk.crypto.CryptoSuite; -import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; -import org.fisco.bcos.sdk.model.CryptoType; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.model.callback.TransactionCallback; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; - -@SuppressWarnings("unchecked") -public class DagTransfer extends Contract { - public static final String[] BINARY_ARRAY = {}; - - public static final String BINARY = String.join("", BINARY_ARRAY); - - public static final String[] SM_BINARY_ARRAY = {}; - - public static final String SM_BINARY = String.join("", SM_BINARY_ARRAY); - - public static final String[] ABI_ARRAY = { - "[{\"constant\":false,\"inputs\":[{\"name\":\"user_a\",\"type\":\"string\"},{\"name\":\"user_b\",\"type\":\"string\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"userTransfer\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"user\",\"type\":\"string\"}],\"name\":\"userBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"string\"},{\"name\":\"balance\",\"type\":\"uint256\"}],\"name\":\"userAdd\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"string\"},{\"name\":\"balance\",\"type\":\"uint256\"}],\"name\":\"userSave\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"string\"},{\"name\":\"balance\",\"type\":\"uint256\"}],\"name\":\"userDraw\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - }; - - public static final String ABI = String.join("", ABI_ARRAY); - - public static final String FUNC_USERTRANSFER = "userTransfer"; - - public static final String FUNC_USERBALANCE = "userBalance"; - - public static final String FUNC_USERADD = "userAdd"; - - public static final String FUNC_USERSAVE = "userSave"; - - public static final String FUNC_USERDRAW = "userDraw"; - - protected DagTransfer(String contractAddress, Client client, CryptoKeyPair credential) { - super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); - } - - public static String getBinary(CryptoSuite cryptoSuite) { - return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); - } - - public TransactionReceipt userTransfer(String user_a, String user_b, BigInteger amount) { - final Function function = - new Function( - FUNC_USERTRANSFER, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user_a), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user_b), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void userTransfer( - String user_a, String user_b, BigInteger amount, TransactionCallback callback) { - final Function function = - new Function( - FUNC_USERTRANSFER, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user_a), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user_b), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForUserTransfer( - String user_a, String user_b, BigInteger amount) { - final Function function = - new Function( - FUNC_USERTRANSFER, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user_a), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user_b), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple3 getUserTransferInput( - TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_USERTRANSFER, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple3( - (String) results.get(0).getValue(), - (String) results.get(1).getValue(), - (BigInteger) results.get(2).getValue()); - } - - public Tuple1 getUserTransferOutput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getOutput(); - final Function function = - new Function( - FUNC_USERTRANSFER, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public Tuple2 userBalance(String user) throws ContractException { - final Function function = - new Function( - FUNC_USERBALANCE, - Arrays.asList(new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user)), - Arrays.>asList( - new TypeReference() {}, new TypeReference() {})); - List results = executeCallWithMultipleValueReturn(function); - return new Tuple2( - (BigInteger) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public TransactionReceipt userAdd(String user, BigInteger balance) { - final Function function = - new Function( - FUNC_USERADD, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void userAdd(String user, BigInteger balance, TransactionCallback callback) { - final Function function = - new Function( - FUNC_USERADD, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForUserAdd(String user, BigInteger balance) { - final Function function = - new Function( - FUNC_USERADD, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple2 getUserAddInput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_USERADD, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple2( - (String) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public Tuple1 getUserAddOutput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getOutput(); - final Function function = - new Function( - FUNC_USERADD, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public TransactionReceipt userSave(String user, BigInteger balance) { - final Function function = - new Function( - FUNC_USERSAVE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void userSave(String user, BigInteger balance, TransactionCallback callback) { - final Function function = - new Function( - FUNC_USERSAVE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForUserSave(String user, BigInteger balance) { - final Function function = - new Function( - FUNC_USERSAVE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple2 getUserSaveInput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_USERSAVE, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple2( - (String) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public Tuple1 getUserSaveOutput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getOutput(); - final Function function = - new Function( - FUNC_USERSAVE, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public TransactionReceipt userDraw(String user, BigInteger balance) { - final Function function = - new Function( - FUNC_USERDRAW, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void userDraw(String user, BigInteger balance, TransactionCallback callback) { - final Function function = - new Function( - FUNC_USERDRAW, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForUserDraw(String user, BigInteger balance) { - final Function function = - new Function( - FUNC_USERDRAW, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(user), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(balance)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple2 getUserDrawInput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_USERDRAW, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple2( - (String) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public Tuple1 getUserDrawOutput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getOutput(); - final Function function = - new Function( - FUNC_USERDRAW, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public static DagTransfer load( - String contractAddress, Client client, CryptoKeyPair credential) { - return new DagTransfer(contractAddress, client, credential); - } - - public static DagTransfer deploy(Client client, CryptoKeyPair credential) - throws ContractException { - return deploy( - DagTransfer.class, client, credential, getBinary(client.getCryptoSuite()), ""); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/Ok.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/Ok.java deleted file mode 100644 index c37257e4d..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/Ok.java +++ /dev/null @@ -1,151 +0,0 @@ -package org.fisco.bcos.sdk.demo.contract; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.fisco.bcos.sdk.abi.FunctionReturnDecoder; -import org.fisco.bcos.sdk.abi.TypeReference; -import org.fisco.bcos.sdk.abi.datatypes.Event; -import org.fisco.bcos.sdk.abi.datatypes.Function; -import org.fisco.bcos.sdk.abi.datatypes.Type; -import org.fisco.bcos.sdk.abi.datatypes.generated.Uint256; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple1; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.contract.Contract; -import org.fisco.bcos.sdk.crypto.CryptoSuite; -import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; -import org.fisco.bcos.sdk.eventsub.EventCallback; -import org.fisco.bcos.sdk.model.CryptoType; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.model.callback.TransactionCallback; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; - -@SuppressWarnings("unchecked") -public class Ok extends Contract { - public static final String[] BINARY_ARRAY = { - "608060405234801561001057600080fd5b5060016000800160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506402540be40060006001018190555060028060000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060006002600101819055506103bf806100c26000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806366c99139146100515780636d4ce63c1461007e575b600080fd5b34801561005d57600080fd5b5061007c600480360381019080803590602001909291905050506100a9565b005b34801561008a57600080fd5b506100936102e1565b6040518082815260200191505060405180910390f35b8060006001015410806100c757506002600101548160026001015401105b156100d1576102de565b8060006001015403600060010181905550806002600101600082825401925050819055507fc77b710b83d1dc3f3fafeccd08a6c469beb873b2f0975b50d1698e46b3ee5b4c816040518082815260200191505060405180910390a160046080604051908101604052806040805190810160405280600881526020017f323031373034313300000000000000000000000000000000000000000000000081525081526020016000800160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600260000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001838152509080600181540180825580915050906001820390600052602060002090600402016000909192909190915060008201518160000190805190602001906102419291906102ee565b5060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160020160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550606082015181600301555050505b50565b6000600260010154905090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061032f57805160ff191683800117855561035d565b8280016001018555821561035d579182015b8281111561035c578251825591602001919060010190610341565b5b50905061036a919061036e565b5090565b61039091905b8082111561038c576000816000905550600101610374565b5090565b905600a165627a7a723058208e45b63292be04a7dc7a9721084c85fff95b392534d9e9362cf84a1b75be8dc80029" - }; - - public static final String BINARY = String.join("", BINARY_ARRAY); - - public static final String[] SM_BINARY_ARRAY = { - "608060405234801561001057600080fd5b5060016000800160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506402540be40060006001018190555060028060000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060006002600101819055506103bf806100c26000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063299f7f9d146100515780638fff0fc41461007c575b600080fd5b34801561005d57600080fd5b506100666100a9565b6040518082815260200191505060405180910390f35b34801561008857600080fd5b506100a7600480360381019080803590602001909291905050506100b6565b005b6000600260010154905090565b8060006001015410806100d457506002600101548160026001015401105b156100de576102eb565b8060006001015403600060010181905550806002600101600082825401925050819055507fc345610041c3c141ff9e0fbc73b34bf13842fd02e0c3cfe6541eedd6adef4b2c816040518082815260200191505060405180910390a160046080604051908101604052806040805190810160405280600881526020017f323031373034313300000000000000000000000000000000000000000000000081525081526020016000800160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600260000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018381525090806001815401808255809150509060018203906000526020600020906004020160009091929091909150600082015181600001908051906020019061024e9291906102ee565b5060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160020160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550606082015181600301555050505b50565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061032f57805160ff191683800117855561035d565b8280016001018555821561035d579182015b8281111561035c578251825591602001919060010190610341565b5b50905061036a919061036e565b5090565b61039091905b8082111561038c576000816000905550600101610374565b5090565b905600a165627a7a72305820760c6c97c0ebf59ab2bb361d87b702ca01db177b03e7f76dc57ece4f04aa3e9d0029" - }; - - public static final String SM_BINARY = String.join("", SM_BINARY_ARRAY); - - public static final String[] ABI_ARRAY = { - "[{\"constant\":false,\"inputs\":[{\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"trans\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"TransEvent\",\"type\":\"event\"}]" - }; - - public static final String ABI = String.join("", ABI_ARRAY); - - public static final String FUNC_TRANS = "trans"; - - public static final String FUNC_GET = "get"; - - public static final Event TRANSEVENT_EVENT = - new Event( - "TransEvent", - Arrays.>asList(new TypeReference() {}));; - - protected Ok(String contractAddress, Client client, CryptoKeyPair credential) { - super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); - } - - public static String getBinary(CryptoSuite cryptoSuite) { - return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); - } - - public TransactionReceipt trans(BigInteger num) { - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void trans(BigInteger num, TransactionCallback callback) { - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForTrans(BigInteger num) { - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple1 getTransInput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public BigInteger get() throws ContractException { - final Function function = - new Function( - FUNC_GET, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeCallWithSingleValueReturn(function, BigInteger.class); - } - - public List getTransEventEvents( - TransactionReceipt transactionReceipt) { - List valueList = - extractEventParametersWithLog(TRANSEVENT_EVENT, transactionReceipt); - ArrayList responses = - new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - TransEventEventResponse typedResponse = new TransEventEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.num = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public void subscribeTransEventEvent( - String fromBlock, String toBlock, List otherTopics, EventCallback callback) { - String topic0 = eventEncoder.encode(TRANSEVENT_EVENT); - subscribeEvent(ABI, BINARY, topic0, fromBlock, toBlock, otherTopics, callback); - } - - public void subscribeTransEventEvent(EventCallback callback) { - String topic0 = eventEncoder.encode(TRANSEVENT_EVENT); - subscribeEvent(ABI, BINARY, topic0, callback); - } - - public static Ok load(String contractAddress, Client client, CryptoKeyPair credential) { - return new Ok(contractAddress, client, credential); - } - - public static Ok deploy(Client client, CryptoKeyPair credential) throws ContractException { - return deploy(Ok.class, client, credential, getBinary(client.getCryptoSuite()), ""); - } - - public static class TransEventEventResponse { - public TransactionReceipt.Logs log; - - public BigInteger num; - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/OkD.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/OkD.java deleted file mode 100644 index 864bb7aab..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/OkD.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.fisco.bcos.sdk.demo.contract; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.fisco.bcos.sdk.abi.FunctionReturnDecoder; -import org.fisco.bcos.sdk.abi.TypeReference; -import org.fisco.bcos.sdk.abi.datatypes.Event; -import org.fisco.bcos.sdk.abi.datatypes.Function; -import org.fisco.bcos.sdk.abi.datatypes.Type; -import org.fisco.bcos.sdk.abi.datatypes.Utf8String; -import org.fisco.bcos.sdk.abi.datatypes.generated.Int256; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple2; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.contract.Contract; -import org.fisco.bcos.sdk.crypto.CryptoSuite; -import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; -import org.fisco.bcos.sdk.eventsub.EventCallback; -import org.fisco.bcos.sdk.model.CryptoType; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.model.callback.TransactionCallback; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; - -@SuppressWarnings("unchecked") -public class OkD extends Contract { - public static final String[] BINARY_ARRAY = { - "608060405234801561001057600080fd5b50600080600060016000800160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506402540be40060006001018190555060028060000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600060026001018190555061100192508273ffffffffffffffffffffffffffffffffffffffff166356004b6a6040518163ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018060200180602001848103845260048152602001807f745f6f6b000000000000000000000000000000000000000000000000000000008152506020018481038352600b8152602001807f66726f6d5f6163636f7574000000000000000000000000000000000000000000815250602001848103825260218152602001807f66726f6d5f62616c616e63652c746f5f6163636f75742c746f5f62616c616e6381526020017f65000000000000000000000000000000000000000000000000000000000000008152506040019350505050602060405180830381600087803b1580156101f557600080fd5b505af1158015610209573d6000803e3d6000fd5b505050506040513d602081101561021f57600080fd5b81019080805190602001909291905050505061100192508273ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260048152602001807f745f6f6b00000000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156102d657600080fd5b505af11580156102ea573d6000803e3d6000fd5b505050506040513d602081101561030057600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff166313db93466040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561037757600080fd5b505af115801561038b573d6000803e3d6000fd5b505050506040513d60208110156103a157600080fd5b810190808051906020019092919050505090508073ffffffffffffffffffffffffffffffffffffffff1663e942b5166040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600b8152602001807f66726f6d5f6163636f7574000000000000000000000000000000000000000000815250602001838103825260038152602001807f307831000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561048d57600080fd5b505af11580156104a1573d6000803e3d6000fd5b505050508073ffffffffffffffffffffffffffffffffffffffff1663e942b5166040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600c8152602001807f66726f6d5f62616c616e636500000000000000000000000000000000000000008152506020018381038252600b8152602001807f313030303030303030303000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561057e57600080fd5b505af1158015610592573d6000803e3d6000fd5b505050508073ffffffffffffffffffffffffffffffffffffffff1663e942b5166040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f746f5f6163636f75740000000000000000000000000000000000000000000000815250602001838103825260038152602001807f307832000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561066f57600080fd5b505af1158015610683573d6000803e3d6000fd5b505050508073ffffffffffffffffffffffffffffffffffffffff1663e942b5166040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600a8152602001807f746f5f62616c616e636500000000000000000000000000000000000000000000815250602001838103825260018152602001807f300000000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561076057600080fd5b505af1158015610774573d6000803e3d6000fd5b505050505050506108228061078a6000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680636d4ce63c14610051578063abe181b51461007c575b600080fd5b34801561005d57600080fd5b506100666100ef565b6040518082815260200191505060405180910390f35b34801561008857600080fd5b506100ed600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506100fc565b005b6000600260010154905090565b60008060008084600060010154128061012057506002600101548560026001015401125b1561012a576107ee565b84600060010154036000600101819055508460026001016000828254019250508190555061100193508373ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260048152602001807f745f6f6b00000000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156101f357600080fd5b505af1158015610207573d6000803e3d6000fd5b505050506040513d602081101561021d57600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff166313db93466040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561029457600080fd5b505af11580156102a8573d6000803e3d6000fd5b505050506040513d60208110156102be57600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663e942b516876040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600b8152602001807f66726f6d5f6163636f7574000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610391578082015181840152602081019050610376565b50505050905090810190601f1680156103be5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b1580156103de57600080fd5b505af11580156103f2573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff16632ef8ba746000600101546040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018381526020018281038252600c8152602001807f66726f6d5f62616c616e6365000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b1580156104a357600080fd5b505af11580156104b7573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663e942b5166040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f746f5f6163636f75740000000000000000000000000000000000000000000000815250602001838103825260038152602001807f307832000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561059457600080fd5b505af11580156105a8573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff16632ef8ba746002600101546040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018381526020018281038252600a8152602001807f746f5f62616c616e63650000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561065957600080fd5b505af115801561066d573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff166331afac3687846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b8381101561072c578082015181840152602081019050610711565b50505050905090810190601f1680156107595780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561077957600080fd5b505af115801561078d573d6000803e3d6000fd5b505050506040513d60208110156107a357600080fd5b810190808051906020019092919050505090507f66f7705280112a4d1145399e0414adc43a2d6974b487710f417edcf7d4a39d71816040518082815260200191505060405180910390a15b5050505050505600a165627a7a72305820307df815a9c714eb36e529357cd78a05148a38f1832b64df2a805a405586ef3e0029" - }; - - public static final String BINARY = String.join("", BINARY_ARRAY); - - public static final String[] SM_BINARY_ARRAY = { - "608060405234801561001057600080fd5b50600080600060016000800160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506402540be40060006001018190555060028060000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600060026001018190555061100192508273ffffffffffffffffffffffffffffffffffffffff1663c92a78016040518163ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018060200180602001848103845260048152602001807f745f6f6b000000000000000000000000000000000000000000000000000000008152506020018481038352600b8152602001807f66726f6d5f6163636f7574000000000000000000000000000000000000000000815250602001848103825260218152602001807f66726f6d5f62616c616e63652c746f5f6163636f75742c746f5f62616c616e6381526020017f65000000000000000000000000000000000000000000000000000000000000008152506040019350505050602060405180830381600087803b1580156101f557600080fd5b505af1158015610209573d6000803e3d6000fd5b505050506040513d602081101561021f57600080fd5b81019080805190602001909291905050505061100192508273ffffffffffffffffffffffffffffffffffffffff166359a48b656040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260048152602001807f745f6f6b00000000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156102d657600080fd5b505af11580156102ea573d6000803e3d6000fd5b505050506040513d602081101561030057600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff16635887ab246040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561037757600080fd5b505af115801561038b573d6000803e3d6000fd5b505050506040513d60208110156103a157600080fd5b810190808051906020019092919050505090508073ffffffffffffffffffffffffffffffffffffffff16631a391cb46040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600b8152602001807f66726f6d5f6163636f7574000000000000000000000000000000000000000000815250602001838103825260038152602001807f307831000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561048d57600080fd5b505af11580156104a1573d6000803e3d6000fd5b505050508073ffffffffffffffffffffffffffffffffffffffff16631a391cb46040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600c8152602001807f66726f6d5f62616c616e636500000000000000000000000000000000000000008152506020018381038252600b8152602001807f313030303030303030303000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561057e57600080fd5b505af1158015610592573d6000803e3d6000fd5b505050508073ffffffffffffffffffffffffffffffffffffffff16631a391cb46040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f746f5f6163636f75740000000000000000000000000000000000000000000000815250602001838103825260038152602001807f307832000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561066f57600080fd5b505af1158015610683573d6000803e3d6000fd5b505050508073ffffffffffffffffffffffffffffffffffffffff16631a391cb46040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600a8152602001807f746f5f62616c616e636500000000000000000000000000000000000000000000815250602001838103825260018152602001807f300000000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561076057600080fd5b505af1158015610774573d6000803e3d6000fd5b505050505050506108228061078a6000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063299f7f9d1461005157806390749a5e1461007c575b600080fd5b34801561005d57600080fd5b506100666100ef565b6040518082815260200191505060405180910390f35b34801561008857600080fd5b506100ed600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506100fc565b005b6000600260010154905090565b60008060008084600060010154128061012057506002600101548560026001015401125b1561012a576107ee565b84600060010154036000600101819055508460026001016000828254019250508190555061100193508373ffffffffffffffffffffffffffffffffffffffff166359a48b656040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260048152602001807f745f6f6b00000000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156101f357600080fd5b505af1158015610207573d6000803e3d6000fd5b505050506040513d602081101561021d57600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff16635887ab246040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561029457600080fd5b505af11580156102a8573d6000803e3d6000fd5b505050506040513d60208110156102be57600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff16631a391cb4876040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001806020018381038352600b8152602001807f66726f6d5f6163636f7574000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610391578082015181840152602081019050610376565b50505050905090810190601f1680156103be5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b1580156103de57600080fd5b505af11580156103f2573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663def426986000600101546040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018381526020018281038252600c8152602001807f66726f6d5f62616c616e6365000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b1580156104a357600080fd5b505af11580156104b7573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff16631a391cb46040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f746f5f6163636f75740000000000000000000000000000000000000000000000815250602001838103825260038152602001807f307832000000000000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561059457600080fd5b505af11580156105a8573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663def426986002600101546040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018381526020018281038252600a8152602001807f746f5f62616c616e63650000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561065957600080fd5b505af115801561066d573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff16634c6f30c087846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b8381101561072c578082015181840152602081019050610711565b50505050905090810190601f1680156107595780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561077957600080fd5b505af115801561078d573d6000803e3d6000fd5b505050506040513d60208110156107a357600080fd5b810190808051906020019092919050505090507f11edf97b45aa6c006853fb598a4a9be2e678d9498feb5e6c1f389b491e12bc4a816040518082815260200191505060405180910390a15b5050505050505600a165627a7a72305820e07034d3e12dfdf1f20c39aa151a5623c7b2690d56eab36fedd1ca3fedce899d0029" - }; - - public static final String SM_BINARY = String.join("", SM_BINARY_ARRAY); - - public static final String[] ABI_ARRAY = { - "[{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from_accout\",\"type\":\"string\"},{\"name\":\"num\",\"type\":\"int256\"}],\"name\":\"trans\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"count\",\"type\":\"int256\"}],\"name\":\"insertResult\",\"type\":\"event\"}]" - }; - - public static final String ABI = String.join("", ABI_ARRAY); - - public static final String FUNC_GET = "get"; - - public static final String FUNC_TRANS = "trans"; - - public static final Event INSERTRESULT_EVENT = - new Event( - "insertResult", - Arrays.>asList(new TypeReference() {}));; - - protected OkD(String contractAddress, Client client, CryptoKeyPair credential) { - super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); - } - - public static String getBinary(CryptoSuite cryptoSuite) { - return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); - } - - public BigInteger get() throws ContractException { - final Function function = - new Function( - FUNC_GET, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeCallWithSingleValueReturn(function, BigInteger.class); - } - - public TransactionReceipt trans(String from_accout, BigInteger num) { - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from_accout), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(num)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void trans(String from_accout, BigInteger num, TransactionCallback callback) { - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from_accout), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(num)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForTrans(String from_accout, BigInteger num) { - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from_accout), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(num)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple2 getTransInput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_TRANS, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple2( - (String) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public List getInsertResultEvents( - TransactionReceipt transactionReceipt) { - List valueList = - extractEventParametersWithLog(INSERTRESULT_EVENT, transactionReceipt); - ArrayList responses = - new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - InsertResultEventResponse typedResponse = new InsertResultEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public void subscribeInsertResultEvent( - String fromBlock, String toBlock, List otherTopics, EventCallback callback) { - String topic0 = eventEncoder.encode(INSERTRESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, fromBlock, toBlock, otherTopics, callback); - } - - public void subscribeInsertResultEvent(EventCallback callback) { - String topic0 = eventEncoder.encode(INSERTRESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, callback); - } - - public static OkD load(String contractAddress, Client client, CryptoKeyPair credential) { - return new OkD(contractAddress, client, credential); - } - - public static OkD deploy(Client client, CryptoKeyPair credential) throws ContractException { - return deploy(OkD.class, client, credential, getBinary(client.getCryptoSuite()), ""); - } - - public static class InsertResultEventResponse { - public TransactionReceipt.Logs log; - - public BigInteger count; - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/ParallelOk.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/ParallelOk.java deleted file mode 100644 index cb0776c06..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/ParallelOk.java +++ /dev/null @@ -1,393 +0,0 @@ -package org.fisco.bcos.sdk.demo.contract; - -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.fisco.bcos.sdk.abi.FunctionReturnDecoder; -import org.fisco.bcos.sdk.abi.TypeReference; -import org.fisco.bcos.sdk.abi.datatypes.Function; -import org.fisco.bcos.sdk.abi.datatypes.Type; -import org.fisco.bcos.sdk.abi.datatypes.Utf8String; -import org.fisco.bcos.sdk.abi.datatypes.generated.Uint256; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple1; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple2; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple3; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.contract.Contract; -import org.fisco.bcos.sdk.crypto.CryptoSuite; -import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; -import org.fisco.bcos.sdk.model.CryptoType; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.model.callback.TransactionCallback; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; - -@SuppressWarnings("unchecked") -public class ParallelOk extends Contract { - public static final String[] BINARY_ARRAY = { - "60806040526110066000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561005257600080fd5b50610aeb806100626000396000f30060806040526004361061008e576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806334a18dda1461009357806335ee5f871461010657806379fa913f146101835780638a42ebe9146101ec5780639b80b0501461025f578063bca926af14610318578063d39f70bc1461032f578063fad42f8714610346575b600080fd5b34801561009f57600080fd5b50610104600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506103ff565b005b34801561011257600080fd5b5061016d600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610570565b6040518082815260200191505060405180910390f35b34801561018f57600080fd5b506101ea600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506105e5565b005b3480156101f857600080fd5b5061025d600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061074d565b005b34801561026b57600080fd5b50610316600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506107c1565b005b34801561032457600080fd5b5061032d6108b8565b005b34801561033b57600080fd5b5061034461093a565b005b34801561035257600080fd5b506103fd600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506109b8565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630553904e3084846040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b838110156104e25780820151818401526020810190506104c7565b50505050905090810190601f16801561050f5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561053057600080fd5b505af1158015610544573d6000803e3d6000fd5b505050506040513d602081101561055a57600080fd5b8101908080519060200190929190505050505050565b60006001826040518082805190602001908083835b6020831015156105aa5780518252602082019150602081019050602083039250610585565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020549050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166311e3f2af30836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b838110156106c15780820151818401526020810190506106a6565b50505050905090810190601f1680156106ee5780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561070e57600080fd5b505af1158015610722573d6000803e3d6000fd5b505050506040513d602081101561073857600080fd5b81019080805190602001909291905050505050565b806001836040518082805190602001908083835b6020831015156107865780518252602082019150602081019050602083039250610761565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020819055505050565b806001846040518082805190602001908083835b6020831015156107fa57805182526020820191506020810190506020830392506107d5565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b602083101515610873578051825260208201915060208101905060208303925061084e565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540192505081905550505050565b6108f86040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e74323536290081525060026103ff565b6109386040805190810160405280601381526020017f73657428737472696e672c75696e74323536290000000000000000000000000081525060016103ff565b565b6109786040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e7432353629008152506105e5565b6109b66040805190810160405280601381526020017f73657428737472696e672c75696e7432353629000000000000000000000000008152506105e5565b565b806001846040518082805190602001908083835b6020831015156109f157805182526020820191506020810190506020830392506109cc565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b602083101515610a6a5780518252602082019150602081019050602083039250610a45565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390206000828254019250508190555060648111151515610aba57600080fd5b5050505600a165627a7a723058203df637a9f27f60ded73c5d33efa5cfcb7b3a52fab87e18249ab9cdbf5566126d0029" - }; - - public static final String BINARY = String.join("", BINARY_ARRAY); - - public static final String[] SM_BINARY_ARRAY = { - "60806040526110066000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561005257600080fd5b50610aea806100626000396000f30060806040526004361061008d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168062f0e13314610092578063612d2bff146100fb578063748e7a1b146101b457806394618e4c146101cb578063ab71bf09146101e2578063b4c653e01461029b578063cd93c25d1461030e578063f2f4ee6d1461038b575b600080fd5b34801561009e57600080fd5b506100f9600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506103fe565b005b34801561010757600080fd5b506101b2600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610566565b005b3480156101c057600080fd5b506101c961065d565b005b3480156101d757600080fd5b506101e06106db565b005b3480156101ee57600080fd5b50610299600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061075d565b005b3480156102a757600080fd5b5061030c600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610864565b005b34801561031a57600080fd5b50610375600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506109d5565b6040518082815260200191505060405180910390f35b34801561039757600080fd5b506103fc600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610a4a565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663714c65bd30836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b838110156104da5780820151818401526020810190506104bf565b50505050905090810190601f1680156105075780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561052757600080fd5b505af115801561053b573d6000803e3d6000fd5b505050506040513d602081101561055157600080fd5b81019080805190602001909291905050505050565b806001846040518082805190602001908083835b60208310151561059f578051825260208201915060208101905060208303925061057a565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b60208310151561061857805182526020820191506020810190506020830392506105f3565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540192505081905550505050565b61069b6040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e7432353629008152506103fe565b6106d96040805190810160405280601381526020017f73657428737472696e672c75696e7432353629000000000000000000000000008152506103fe565b565b61071b6040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e7432353629008152506002610864565b61075b6040805190810160405280601381526020017f73657428737472696e672c75696e7432353629000000000000000000000000008152506001610864565b565b806001846040518082805190602001908083835b6020831015156107965780518252602082019150602081019050602083039250610771565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b60208310151561080f57805182526020820191506020810190506020830392506107ea565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020600082825401925050819055506064811115151561085f57600080fd5b505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663dc536a623084846040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b8381101561094757808201518184015260208101905061092c565b50505050905090810190601f1680156109745780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561099557600080fd5b505af11580156109a9573d6000803e3d6000fd5b505050506040513d60208110156109bf57600080fd5b8101908080519060200190929190505050505050565b60006001826040518082805190602001908083835b602083101515610a0f57805182526020820191506020810190506020830392506109ea565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020549050919050565b806001836040518082805190602001908083835b602083101515610a835780518252602082019150602081019050602083039250610a5e565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208190555050505600a165627a7a72305820bdd068ddd29d31c6bd5b2d5ba93d15eec371fccc5579888cf009ac61aa91a8190029" - }; - - public static final String SM_BINARY = String.join("", SM_BINARY_ARRAY); - - public static final String[] ABI_ARRAY = { - "[{\"constant\":false,\"inputs\":[{\"name\":\"functionName\",\"type\":\"string\"},{\"name\":\"criticalSize\",\"type\":\"uint256\"}],\"name\":\"registerParallelFunction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"functionName\",\"type\":\"string\"}],\"name\":\"unregisterParallelFunction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"string\"},{\"name\":\"to\",\"type\":\"string\"},{\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"enableParallel\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"disableParallel\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"string\"},{\"name\":\"to\",\"type\":\"string\"},{\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"transferWithRevert\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - }; - - public static final String ABI = String.join("", ABI_ARRAY); - - 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"; - - public static final String FUNC_TRANSFERWITHREVERT = "transferWithRevert"; - - protected ParallelOk(String contractAddress, Client client, CryptoKeyPair credential) { - super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); - } - - public static String getBinary(CryptoSuite cryptoSuite) { - return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); - } - - public TransactionReceipt registerParallelFunction( - String functionName, BigInteger criticalSize) { - final Function function = - new Function( - FUNC_REGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(functionName), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256( - criticalSize)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void registerParallelFunction( - String functionName, BigInteger criticalSize, TransactionCallback callback) { - final Function function = - new Function( - FUNC_REGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(functionName), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256( - criticalSize)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForRegisterParallelFunction( - String functionName, BigInteger criticalSize) { - final Function function = - new Function( - FUNC_REGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(functionName), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256( - criticalSize)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple2 getRegisterParallelFunctionInput( - TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_REGISTERPARALLELFUNCTION, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple2( - (String) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public BigInteger balanceOf(String name) throws ContractException { - final Function function = - new Function( - FUNC_BALANCEOF, - Arrays.asList(new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name)), - Arrays.>asList(new TypeReference() {})); - return executeCallWithSingleValueReturn(function, BigInteger.class); - } - - public TransactionReceipt unregisterParallelFunction(String functionName) { - final Function function = - new Function( - FUNC_UNREGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(functionName)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void unregisterParallelFunction(String functionName, TransactionCallback callback) { - final Function function = - new Function( - FUNC_UNREGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(functionName)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForUnregisterParallelFunction(String functionName) { - final Function function = - new Function( - FUNC_UNREGISTERPARALLELFUNCTION, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(functionName)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple1 getUnregisterParallelFunctionInput( - TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_UNREGISTERPARALLELFUNCTION, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((String) results.get(0).getValue()); - } - - public TransactionReceipt set(String name, BigInteger num) { - final Function function = - new Function( - FUNC_SET, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void set(String name, BigInteger num, TransactionCallback callback) { - final Function function = - new Function( - FUNC_SET, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForSet(String name, BigInteger num) { - final Function function = - new Function( - FUNC_SET, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple2 getSetInput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_SET, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple2( - (String) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public TransactionReceipt transfer(String from, String to, BigInteger num) { - final Function function = - new Function( - FUNC_TRANSFER, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(to), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void transfer(String from, String to, BigInteger num, TransactionCallback callback) { - final Function function = - new Function( - FUNC_TRANSFER, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(to), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForTransfer(String from, String to, BigInteger num) { - final Function function = - new Function( - FUNC_TRANSFER, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(to), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple3 getTransferInput( - TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_TRANSFER, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple3( - (String) results.get(0).getValue(), - (String) results.get(1).getValue(), - (BigInteger) results.get(2).getValue()); - } - - public TransactionReceipt enableParallel() { - final Function function = - new Function( - FUNC_ENABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void enableParallel(TransactionCallback callback) { - final Function function = - new Function( - FUNC_ENABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForEnableParallel() { - final Function function = - new Function( - FUNC_ENABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public TransactionReceipt disableParallel() { - final Function function = - new Function( - FUNC_DISABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void disableParallel(TransactionCallback callback) { - final Function function = - new Function( - FUNC_DISABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForDisableParallel() { - final Function function = - new Function( - FUNC_DISABLEPARALLEL, - Arrays.asList(), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public TransactionReceipt transferWithRevert(String from, String to, BigInteger num) { - final Function function = - new Function( - FUNC_TRANSFERWITHREVERT, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(to), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void transferWithRevert( - String from, String to, BigInteger num, TransactionCallback callback) { - final Function function = - new Function( - FUNC_TRANSFERWITHREVERT, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(to), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForTransferWithRevert( - String from, String to, BigInteger num) { - final Function function = - new Function( - FUNC_TRANSFERWITHREVERT, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(from), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(to), - new org.fisco.bcos.sdk.abi.datatypes.generated.Uint256(num)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple3 getTransferWithRevertInput( - TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_TRANSFERWITHREVERT, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple3( - (String) results.get(0).getValue(), - (String) results.get(1).getValue(), - (BigInteger) results.get(2).getValue()); - } - - public static ParallelOk load(String contractAddress, Client client, CryptoKeyPair credential) { - return new ParallelOk(contractAddress, client, credential); - } - - public static ParallelOk deploy(Client client, CryptoKeyPair credential) - throws ContractException { - return deploy(ParallelOk.class, client, credential, getBinary(client.getCryptoSuite()), ""); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/TableTest.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/TableTest.java deleted file mode 100644 index e9d418e6f..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/TableTest.java +++ /dev/null @@ -1,509 +0,0 @@ -package org.fisco.bcos.sdk.demo.contract; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.fisco.bcos.sdk.abi.FunctionReturnDecoder; -import org.fisco.bcos.sdk.abi.TypeReference; -import org.fisco.bcos.sdk.abi.datatypes.DynamicArray; -import org.fisco.bcos.sdk.abi.datatypes.Event; -import org.fisco.bcos.sdk.abi.datatypes.Function; -import org.fisco.bcos.sdk.abi.datatypes.Type; -import org.fisco.bcos.sdk.abi.datatypes.Utf8String; -import org.fisco.bcos.sdk.abi.datatypes.generated.Bytes32; -import org.fisco.bcos.sdk.abi.datatypes.generated.Int256; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple1; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple2; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple3; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.contract.Contract; -import org.fisco.bcos.sdk.crypto.CryptoSuite; -import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; -import org.fisco.bcos.sdk.eventsub.EventCallback; -import org.fisco.bcos.sdk.model.CryptoType; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.model.callback.TransactionCallback; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; - -@SuppressWarnings("unchecked") -public class TableTest extends Contract { - public static final String[] BINARY_ARRAY = { - "608060405234801561001057600080fd5b5061221f806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063487a5a1014610072578063c4f41ab31461013f578063ebf3b24f146101c6578063efc81a8c14610293578063fcd7e3c1146102aa575b600080fd5b34801561007e57600080fd5b50610129600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506103f8565b6040518082815260200191505060405180910390f35b34801561014b57600080fd5b506101b0600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610aee565b6040518082815260200191505060405180910390f35b3480156101d257600080fd5b5061027d600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610fe7565b6040518082815260200191505060405180910390f35b34801561029f57600080fd5b506102a8611606565b005b3480156102b657600080fd5b50610311600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050611798565b60405180806020018060200180602001848103845287818151815260200191508051906020019060200280838360005b8381101561035c578082015181840152602081019050610341565b50505050905001848103835286818151815260200191508051906020019060200280838360005b8381101561039e578082015181840152602081019050610383565b50505050905001848103825285818151815260200191508051906020019060200280838360005b838110156103e05780820151818401526020810190506103c5565b50505050905001965050505050505060405180910390f35b60008060008060008061100194508473ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156104a657600080fd5b505af11580156104ba573d6000803e3d6000fd5b505050506040513d60208110156104d057600080fd5b810190808051906020019092919050505093508373ffffffffffffffffffffffffffffffffffffffff166313db93466040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561054757600080fd5b505af115801561055b573d6000803e3d6000fd5b505050506040513d602081101561057157600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff1663e942b516886040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610644578082015181840152602081019050610629565b50505050905090810190601f1680156106715780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561069157600080fd5b505af11580156106a5573d6000803e3d6000fd5b505050508373ffffffffffffffffffffffffffffffffffffffff16637857d7c96040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561070d57600080fd5b505af1158015610721573d6000803e3d6000fd5b505050506040513d602081101561073757600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663cd30a1d18a6040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b8381101561080a5780820151818401526020810190506107ef565b50505050905090810190601f1680156108375780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561085757600080fd5b505af115801561086b573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663e44594b9896040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561091757600080fd5b505af115801561092b573d6000803e3d6000fd5b505050508373ffffffffffffffffffffffffffffffffffffffff1663bf2b70a18a85856040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825285818151815260200191508051906020019080838360005b83811015610a1d578082015181840152602081019050610a02565b50505050905090810190601f168015610a4a5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b158015610a6b57600080fd5b505af1158015610a7f573d6000803e3d6000fd5b505050506040513d6020811015610a9557600080fd5b810190808051906020019092919050505090507f0bdcb3b747cf033ae78b4b6e1576d2725709d03f68ad3d641b12cb72de614354816040518082815260200191505060405180910390a180955050505050509392505050565b600080600080600061100193508373ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015610b9b57600080fd5b505af1158015610baf573d6000803e3d6000fd5b505050506040513d6020811015610bc557600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff16637857d7c96040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015610c3c57600080fd5b505af1158015610c50573d6000803e3d6000fd5b505050506040513d6020811015610c6657600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663cd30a1d1886040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610d39578082015181840152602081019050610d1e565b50505050905090810190601f168015610d665780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015610d8657600080fd5b505af1158015610d9a573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663e44594b9876040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b158015610e4657600080fd5b505af1158015610e5a573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff166328bb211788846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b83811015610f19578082015181840152602081019050610efe565b50505050905090810190601f168015610f465780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b158015610f6657600080fd5b505af1158015610f7a573d6000803e3d6000fd5b505050506040513d6020811015610f9057600080fd5b810190808051906020019092919050505090507f896358cb98e9e8e891ae04efd1bc177efbe5cffd7eca2e784b16ed7468553e08816040518082815260200191505060405180910390a18094505050", - "505092915050565b600080600080600061100193508373ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b15801561109457600080fd5b505af11580156110a8573d6000803e3d6000fd5b505050506040513d60208110156110be57600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff166313db93466040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561113557600080fd5b505af1158015611149573d6000803e3d6000fd5b505050506040513d602081101561115f57600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663e942b516896040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015611232578082015181840152602081019050611217565b50505050905090810190601f16801561125f5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561127f57600080fd5b505af1158015611293573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff16632ef8ba74886040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561133f57600080fd5b505af1158015611353573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663e942b516876040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b838110156114175780820151818401526020810190506113fc565b50505050905090810190601f1680156114445780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561146457600080fd5b505af1158015611478573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff166331afac3689846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b8381101561153757808201518184015260208101905061151c565b50505050905090810190601f1680156115645780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561158457600080fd5b505af1158015611598573d6000803e3d6000fd5b505050506040513d60208110156115ae57600080fd5b810190808051906020019092919050505090507f66f7705280112a4d1145399e0414adc43a2d6974b487710f417edcf7d4a39d71816040518082815260200191505060405180910390a1809450505050509392505050565b60008061100191508173ffffffffffffffffffffffffffffffffffffffff166356004b6a6040518163ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018060200180602001848103845260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001848103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001848103825260118152602001807f6974656d5f69642c6974656d5f6e616d650000000000000000000000000000008152506020019350505050602060405180830381600087803b15801561172057600080fd5b505af1158015611734573d6000803e3d6000fd5b505050506040513d602081101561174a57600080fd5b810190808051906020019092919050505090507fcd4779437d9d027acc605a96427bfbd3787a1402cb53a5e64cd813d5391fbc2b816040518082815260200191505060405180910390a15050565b6060806060600080600080606080606060008061100198508873ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b15801561185057600080fd5b505af1158015611864573d6000803e3d6000fd5b505050506040513d602081101561187a57600080fd5b810190808051906020019092919050505097508773ffffffffffffffffffffffffffffffffffffffff16637857d7c96040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b1580156118f157600080fd5b505af1158015611905573d6000803e3d6000fd5b505050506040513d602081101561191b57600080fd5b810190808051906020019092919050505096508773ffffffffffffffffffffffffffffffffffffffff1663e8434e398e896040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b838110156119e95780820151818401526020810190506119ce565b50505050905090810190601f168015611a165780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b158015611a3657600080fd5b505af1158015611a4a573d6000803e3d6000fd5b505050506040513d6020811015611a6057600080fd5b810190808051906020019092919050505095508573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611ad757600080fd5b505af1158015611aeb573d6000803e3d6000fd5b505050506040513d6020811015611b0157600080fd5b8101908080519060200190929190505050604051908082528060200260200182016040528015611b405781602001602082028038833980820191505090505b5094508573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611ba757600080fd5b505af1158015611bbb573d6000803e3d6000fd5b505050506040513d6020811015611bd157600080fd5b8101908080519060200190929190505050604051908082528060200260200182016040528015611c105781602001602082028038833980820191505090505b5093508573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611c7757600080fd5b505af1158015611c8b573d6000803e3d6000fd5b505050506040513d6020811015611ca157600080fd5b8101908080519060200190929190505050604051908082528060200260200182016040528015611ce05781602001602082028038833980820191505090505b509250600091505b8573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611d4c57600080fd5b505af1158015611d60573d6000803e3d6000fd5b505050506040513d6020811015611d7657600080fd5b81019080805190602001909291905050508212156121da578573ffffffffffffffffffffffffffffffffffffffff1663846719e0836040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180828152602001915050602060405180830381600087803b158015611dfd57600080fd5b505af1158015611e11573d6000803e3d6000fd5b505050506040513d6020811015611e2757600080fd5b810190808051906020019092919050505090508073ffffffffffffffffffffffffffffffffffffffff166327314f796040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015611eda57600080fd5b505af1158015611eee573d6000803e3d6000fd5b505050506040513d6020811015611f0457600080fd5b81019080805190602001909291905050508583815181101515611f2357fe5b9060200190602002019060001916908160001916815250508073ffffffffffffffffffffffffffffffffffffffff1663fda69fae6040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260078152602001807f6974656d5f696400000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015611fdb57600080fd5b505af115", - "8015611fef573d6000803e3d6000fd5b505050506040513d602081101561200557600080fd5b8101908080519060200190929190505050848381518110151561202457fe5b90602001906020020181815250508073ffffffffffffffffffffffffffffffffffffffff166327314f796040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156120d257600080fd5b505af11580156120e6573d6000803e3d6000fd5b505050506040513d60208110156120fc57600080fd5b8101908080519060200190929190505050838381518110151561211b57fe5b9060200190602002019060001916908160001916815250507fc65cd2adf133adee2ddcfab8b165c2f1f7b185c4389b0789a11112483efb1c84858381518110151561216257fe5b90602001906020020151858481518110151561217a57fe5b90602001906020020151858581518110151561219257fe5b906020019060200201516040518084600019166000191681526020018381526020018260001916600019168152602001935050505060405180910390a1816001019150611ce8565b8484849b509b509b5050505050505050505091939092505600a165627a7a7230582032177e069ae4110c8c4a603273d4a04482e613644296721d9e07c5486cdf7dd50029" - }; - - public static final String BINARY = String.join("", BINARY_ARRAY); - - public static final String[] SM_BINARY_ARRAY = { - "608060405234801561001057600080fd5b5061221f806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630fe1160f1461007257806345710fa5146100f957806349cc36b5146101105780635b325d78146101dd578063e020d4641461032b575b600080fd5b34801561007e57600080fd5b506100e3600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506103f8565b6040518082815260200191505060405180910390f35b34801561010557600080fd5b5061010e6108f1565b005b34801561011c57600080fd5b506101c7600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610a83565b6040518082815260200191505060405180910390f35b3480156101e957600080fd5b50610244600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050611179565b60405180806020018060200180602001848103845287818151815260200191508051906020019060200280838360005b8381101561028f578082015181840152602081019050610274565b50505050905001848103835286818151815260200191508051906020019060200280838360005b838110156102d15780820151818401526020810190506102b6565b50505050905001848103825285818151815260200191508051906020019060200280838360005b838110156103135780820151818401526020810190506102f8565b50505050905001965050505050505060405180910390f35b34801561033757600080fd5b506103e2600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050611bd4565b6040518082815260200191505060405180910390f35b600080600080600061100193508373ffffffffffffffffffffffffffffffffffffffff166359a48b656040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156104a557600080fd5b505af11580156104b9573d6000803e3d6000fd5b505050506040513d60208110156104cf57600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff1663c74f8caf6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561054657600080fd5b505af115801561055a573d6000803e3d6000fd5b505050506040513d602081101561057057600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663ae763db5886040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610643578082015181840152602081019050610628565b50505050905090810190601f1680156106705780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561069057600080fd5b505af11580156106a4573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663d62b54b4876040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561075057600080fd5b505af1158015610764573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff166309ff42f088846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b83811015610823578082015181840152602081019050610808565b50505050905090810190601f1680156108505780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561087057600080fd5b505af1158015610884573d6000803e3d6000fd5b505050506040513d602081101561089a57600080fd5b810190808051906020019092919050505090507f809ffa7913d4c04a8785eea307a714cf83228bb7eded9cebd577c114e36c9967816040518082815260200191505060405180910390a18094505050505092915050565b60008061100191508173ffffffffffffffffffffffffffffffffffffffff1663c92a78016040518163ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018060200180602001848103845260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001848103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001848103825260118152602001807f6974656d5f69642c6974656d5f6e616d650000000000000000000000000000008152506020019350505050602060405180830381600087803b158015610a0b57600080fd5b505af1158015610a1f573d6000803e3d6000fd5b505050506040513d6020811015610a3557600080fd5b810190808051906020019092919050505090507f698cf490d4172e8c174ef6380602ab47c18d429938f9f778cc2c0f3b5498f2c6816040518082815260200191505060405180910390a15050565b60008060008060008061100194508473ffffffffffffffffffffffffffffffffffffffff166359a48b656040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015610b3157600080fd5b505af1158015610b45573d6000803e3d6000fd5b505050506040513d6020811015610b5b57600080fd5b810190808051906020019092919050505093508373ffffffffffffffffffffffffffffffffffffffff16635887ab246040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015610bd257600080fd5b505af1158015610be6573d6000803e3d6000fd5b505050506040513d6020811015610bfc57600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff16631a391cb4886040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610ccf578082015181840152602081019050610cb4565b50505050905090810190601f168015610cfc5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015610d1c57600080fd5b505af1158015610d30573d6000803e3d6000fd5b505050508373ffffffffffffffffffffffffffffffffffffffff1663c74f8caf6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015610d9857600080fd5b505af1158015610dac573d6000803e3d6000fd5b505050506040513d6020811015610dc257600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663ae763db58a6040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610e95578082015181840152602081019050610e7a565b50505050905090810190601f168015610ec25780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015610ee257600080fd5b505af1158015610ef6573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663d62b54b4896040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b158015610fa257600080fd5b505af1158015610fb6573d6000803e3d6000fd5b505050508373ffffffffffffffffffffffffffffffffffffffff1663664b37d68a85856040518463ff", - "ffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825285818151815260200191508051906020019080838360005b838110156110a857808201518184015260208101905061108d565b50505050905090810190601f1680156110d55780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b1580156110f657600080fd5b505af115801561110a573d6000803e3d6000fd5b505050506040513d602081101561112057600080fd5b810190808051906020019092919050505090507f21c0ede88315971cad0fa2aa5d177bf992894f6be25236454587141c48683046816040518082815260200191505060405180910390a180955050505050509392505050565b6060806060600080600080606080606060008061100198508873ffffffffffffffffffffffffffffffffffffffff166359a48b656040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b15801561123157600080fd5b505af1158015611245573d6000803e3d6000fd5b505050506040513d602081101561125b57600080fd5b810190808051906020019092919050505097508773ffffffffffffffffffffffffffffffffffffffff1663c74f8caf6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b1580156112d257600080fd5b505af11580156112e6573d6000803e3d6000fd5b505050506040513d60208110156112fc57600080fd5b810190808051906020019092919050505096508773ffffffffffffffffffffffffffffffffffffffff1663d8ac59578e896040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b838110156113ca5780820151818401526020810190506113af565b50505050905090810190601f1680156113f75780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561141757600080fd5b505af115801561142b573d6000803e3d6000fd5b505050506040513d602081101561144157600080fd5b810190808051906020019092919050505095508573ffffffffffffffffffffffffffffffffffffffff1663d3e9af5a6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b1580156114b857600080fd5b505af11580156114cc573d6000803e3d6000fd5b505050506040513d60208110156114e257600080fd5b81019080805190602001909291905050506040519080825280602002602001820160405280156115215781602001602082028038833980820191505090505b5094508573ffffffffffffffffffffffffffffffffffffffff1663d3e9af5a6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561158857600080fd5b505af115801561159c573d6000803e3d6000fd5b505050506040513d60208110156115b257600080fd5b81019080805190602001909291905050506040519080825280602002602001820160405280156115f15781602001602082028038833980820191505090505b5093508573ffffffffffffffffffffffffffffffffffffffff1663d3e9af5a6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561165857600080fd5b505af115801561166c573d6000803e3d6000fd5b505050506040513d602081101561168257600080fd5b81019080805190602001909291905050506040519080825280602002602001820160405280156116c15781602001602082028038833980820191505090505b509250600091505b8573ffffffffffffffffffffffffffffffffffffffff1663d3e9af5a6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561172d57600080fd5b505af1158015611741573d6000803e3d6000fd5b505050506040513d602081101561175757600080fd5b8101908080519060200190929190505050821215611bbb578573ffffffffffffffffffffffffffffffffffffffff16633dd2b614836040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180828152602001915050602060405180830381600087803b1580156117de57600080fd5b505af11580156117f2573d6000803e3d6000fd5b505050506040513d602081101561180857600080fd5b810190808051906020019092919050505090508073ffffffffffffffffffffffffffffffffffffffff1663fdebe4146040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156118bb57600080fd5b505af11580156118cf573d6000803e3d6000fd5b505050506040513d60208110156118e557600080fd5b8101908080519060200190929190505050858381518110151561190457fe5b9060200190602002019060001916908160001916815250508073ffffffffffffffffffffffffffffffffffffffff16634900862e6040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260078152602001807f6974656d5f696400000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156119bc57600080fd5b505af11580156119d0573d6000803e3d6000fd5b505050506040513d60208110156119e657600080fd5b81019080805190602001909291905050508483815181101515611a0557fe5b90602001906020020181815250508073ffffffffffffffffffffffffffffffffffffffff1663fdebe4146040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015611ab357600080fd5b505af1158015611ac7573d6000803e3d6000fd5b505050506040513d6020811015611add57600080fd5b81019080805190602001909291905050508383815181101515611afc57fe5b9060200190602002019060001916908160001916815250507fef677d3bedeedc56f98504970ca9c69a69871a4cf5d7abee1012f075f3d064888583815181101515611b4357fe5b906020019060200201518584815181101515611b5b57fe5b906020019060200201518585815181101515611b7357fe5b906020019060200201516040518084600019166000191681526020018381526020018260001916600019168152602001935050505060405180910390a18160010191506116c9565b8484849b509b509b505050505050505050509193909250565b600080600080600061100193508373ffffffffffffffffffffffffffffffffffffffff166359a48b656040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015611c8157600080fd5b505af1158015611c95573d6000803e3d6000fd5b505050506040513d6020811015611cab57600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff16635887ab246040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611d2257600080fd5b505af1158015611d36573d6000803e3d6000fd5b505050506040513d6020811015611d4c57600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff16631a391cb4896040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015611e1f578082015181840152602081019050611e04565b50505050905090810190601f168015611e4c5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015611e6c57600080fd5b505af1158015611e80573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663def42698886040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b158015611f2c57600080fd5b505af1158015611f40573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff16631a391cb4876040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f6974656d5f6e616d65000000000000000000000000000000000000000000000081525060200183810382528481815181526020019150805190", - "6020019080838360005b83811015612004578082015181840152602081019050611fe9565b50505050905090810190601f1680156120315780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561205157600080fd5b505af1158015612065573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff16634c6f30c089846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b83811015612124578082015181840152602081019050612109565b50505050905090810190601f1680156121515780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561217157600080fd5b505af1158015612185573d6000803e3d6000fd5b505050506040513d602081101561219b57600080fd5b810190808051906020019092919050505090507f11edf97b45aa6c006853fb598a4a9be2e678d9498feb5e6c1f389b491e12bc4a816040518082815260200191505060405180910390a18094505050505093925050505600a165627a7a72305820c9979fb6dfc3ec7ef02df3bde20e569eeef6226bd9006cdc269fd95900538a410029" - }; - - public static final String SM_BINARY = String.join("", SM_BINARY_ARRAY); - - public static final String[] ABI_ARRAY = { - "[{\"constant\":false,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"item_id\",\"type\":\"int256\"},{\"name\":\"item_name\",\"type\":\"string\"}],\"name\":\"update\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"item_id\",\"type\":\"int256\"}],\"name\":\"remove\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"item_id\",\"type\":\"int256\"},{\"name\":\"item_name\",\"type\":\"string\"}],\"name\":\"insert\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"create\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"}],\"name\":\"select\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32[]\"},{\"name\":\"\",\"type\":\"int256[]\"},{\"name\":\"\",\"type\":\"bytes32[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"count\",\"type\":\"int256\"}],\"name\":\"createResult\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"name\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"item_id\",\"type\":\"int256\"},{\"indexed\":false,\"name\":\"item_name\",\"type\":\"bytes32\"}],\"name\":\"selectResult\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"count\",\"type\":\"int256\"}],\"name\":\"insertResult\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"count\",\"type\":\"int256\"}],\"name\":\"updateResult\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"count\",\"type\":\"int256\"}],\"name\":\"removeResult\",\"type\":\"event\"}]" - }; - - public static final String ABI = String.join("", ABI_ARRAY); - - public static final String FUNC_UPDATE = "update"; - - public static final String FUNC_REMOVE = "remove"; - - public static final String FUNC_INSERT = "insert"; - - public static final String FUNC_CREATE = "create"; - - public static final String FUNC_SELECT = "select"; - - public static final Event CREATERESULT_EVENT = - new Event( - "createResult", - Arrays.>asList(new TypeReference() {}));; - - public static final Event SELECTRESULT_EVENT = - new Event( - "selectResult", - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {}, - new TypeReference() {}));; - - public static final Event INSERTRESULT_EVENT = - new Event( - "insertResult", - Arrays.>asList(new TypeReference() {}));; - - public static final Event UPDATERESULT_EVENT = - new Event( - "updateResult", - Arrays.>asList(new TypeReference() {}));; - - public static final Event REMOVERESULT_EVENT = - new Event( - "removeResult", - Arrays.>asList(new TypeReference() {}));; - - protected TableTest(String contractAddress, Client client, CryptoKeyPair credential) { - super(getBinary(client.getCryptoSuite()), contractAddress, client, credential); - } - - public static String getBinary(CryptoSuite cryptoSuite) { - return (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE ? BINARY : SM_BINARY); - } - - public TransactionReceipt update(String name, BigInteger item_id, String item_name) { - final Function function = - new Function( - FUNC_UPDATE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(item_name)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void update( - String name, BigInteger item_id, String item_name, TransactionCallback callback) { - final Function function = - new Function( - FUNC_UPDATE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(item_name)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForUpdate(String name, BigInteger item_id, String item_name) { - final Function function = - new Function( - FUNC_UPDATE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(item_name)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple3 getUpdateInput( - TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_UPDATE, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple3( - (String) results.get(0).getValue(), - (BigInteger) results.get(1).getValue(), - (String) results.get(2).getValue()); - } - - public Tuple1 getUpdateOutput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getOutput(); - final Function function = - new Function( - FUNC_UPDATE, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public TransactionReceipt remove(String name, BigInteger item_id) { - final Function function = - new Function( - FUNC_REMOVE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void remove(String name, BigInteger item_id, TransactionCallback callback) { - final Function function = - new Function( - FUNC_REMOVE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForRemove(String name, BigInteger item_id) { - final Function function = - new Function( - FUNC_REMOVE, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple2 getRemoveInput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_REMOVE, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple2( - (String) results.get(0).getValue(), (BigInteger) results.get(1).getValue()); - } - - public Tuple1 getRemoveOutput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getOutput(); - final Function function = - new Function( - FUNC_REMOVE, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public TransactionReceipt insert(String name, BigInteger item_id, String item_name) { - final Function function = - new Function( - FUNC_INSERT, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(item_name)), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void insert( - String name, BigInteger item_id, String item_name, TransactionCallback callback) { - final Function function = - new Function( - FUNC_INSERT, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(item_name)), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForInsert(String name, BigInteger item_id, String item_name) { - final Function function = - new Function( - FUNC_INSERT, - Arrays.asList( - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name), - new org.fisco.bcos.sdk.abi.datatypes.generated.Int256(item_id), - new org.fisco.bcos.sdk.abi.datatypes.Utf8String(item_name)), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple3 getInsertInput( - TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getInput().substring(10); - final Function function = - new Function( - FUNC_INSERT, - Arrays.asList(), - Arrays.>asList( - new TypeReference() {}, - new TypeReference() {}, - new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple3( - (String) results.get(0).getValue(), - (BigInteger) results.get(1).getValue(), - (String) results.get(2).getValue()); - } - - public Tuple1 getInsertOutput(TransactionReceipt transactionReceipt) { - String data = transactionReceipt.getOutput(); - final Function function = - new Function( - FUNC_INSERT, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); - return new Tuple1((BigInteger) results.get(0).getValue()); - } - - public TransactionReceipt create() { - final Function function = - new Function( - FUNC_CREATE, - Arrays.asList(), - Collections.>emptyList()); - return executeTransaction(function); - } - - public void create(TransactionCallback callback) { - final Function function = - new Function( - FUNC_CREATE, - Arrays.asList(), - Collections.>emptyList()); - asyncExecuteTransaction(function, callback); - } - - public String getSignedTransactionForCreate() { - final Function function = - new Function( - FUNC_CREATE, - Arrays.asList(), - Collections.>emptyList()); - return createSignedTransaction(function); - } - - public Tuple3, List, List> select(String name) - throws ContractException { - final Function function = - new Function( - FUNC_SELECT, - Arrays.asList(new org.fisco.bcos.sdk.abi.datatypes.Utf8String(name)), - Arrays.>asList( - new TypeReference>() {}, - new TypeReference>() {}, - new TypeReference>() {})); - List results = executeCallWithMultipleValueReturn(function); - return new Tuple3, List, List>( - convertToNative((List) results.get(0).getValue()), - convertToNative((List) results.get(1).getValue()), - convertToNative((List) results.get(2).getValue())); - } - - public List getCreateResultEvents( - TransactionReceipt transactionReceipt) { - List valueList = - extractEventParametersWithLog(CREATERESULT_EVENT, transactionReceipt); - ArrayList responses = - new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - CreateResultEventResponse typedResponse = new CreateResultEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public void subscribeCreateResultEvent( - String fromBlock, String toBlock, List otherTopics, EventCallback callback) { - String topic0 = eventEncoder.encode(CREATERESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, fromBlock, toBlock, otherTopics, callback); - } - - public void subscribeCreateResultEvent(EventCallback callback) { - String topic0 = eventEncoder.encode(CREATERESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, callback); - } - - public List getSelectResultEvents( - TransactionReceipt transactionReceipt) { - List valueList = - extractEventParametersWithLog(SELECTRESULT_EVENT, transactionReceipt); - ArrayList responses = - new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - SelectResultEventResponse typedResponse = new SelectResultEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.name = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); - typedResponse.item_id = - (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); - typedResponse.item_name = (byte[]) eventValues.getNonIndexedValues().get(2).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public void subscribeSelectResultEvent( - String fromBlock, String toBlock, List otherTopics, EventCallback callback) { - String topic0 = eventEncoder.encode(SELECTRESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, fromBlock, toBlock, otherTopics, callback); - } - - public void subscribeSelectResultEvent(EventCallback callback) { - String topic0 = eventEncoder.encode(SELECTRESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, callback); - } - - public List getInsertResultEvents( - TransactionReceipt transactionReceipt) { - List valueList = - extractEventParametersWithLog(INSERTRESULT_EVENT, transactionReceipt); - ArrayList responses = - new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - InsertResultEventResponse typedResponse = new InsertResultEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public void subscribeInsertResultEvent( - String fromBlock, String toBlock, List otherTopics, EventCallback callback) { - String topic0 = eventEncoder.encode(INSERTRESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, fromBlock, toBlock, otherTopics, callback); - } - - public void subscribeInsertResultEvent(EventCallback callback) { - String topic0 = eventEncoder.encode(INSERTRESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, callback); - } - - public List getUpdateResultEvents( - TransactionReceipt transactionReceipt) { - List valueList = - extractEventParametersWithLog(UPDATERESULT_EVENT, transactionReceipt); - ArrayList responses = - new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - UpdateResultEventResponse typedResponse = new UpdateResultEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public void subscribeUpdateResultEvent( - String fromBlock, String toBlock, List otherTopics, EventCallback callback) { - String topic0 = eventEncoder.encode(UPDATERESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, fromBlock, toBlock, otherTopics, callback); - } - - public void subscribeUpdateResultEvent(EventCallback callback) { - String topic0 = eventEncoder.encode(UPDATERESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, callback); - } - - public List getRemoveResultEvents( - TransactionReceipt transactionReceipt) { - List valueList = - extractEventParametersWithLog(REMOVERESULT_EVENT, transactionReceipt); - ArrayList responses = - new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - RemoveResultEventResponse typedResponse = new RemoveResultEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public void subscribeRemoveResultEvent( - String fromBlock, String toBlock, List otherTopics, EventCallback callback) { - String topic0 = eventEncoder.encode(REMOVERESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, fromBlock, toBlock, otherTopics, callback); - } - - public void subscribeRemoveResultEvent(EventCallback callback) { - String topic0 = eventEncoder.encode(REMOVERESULT_EVENT); - subscribeEvent(ABI, BINARY, topic0, callback); - } - - public static TableTest load(String contractAddress, Client client, CryptoKeyPair credential) { - return new TableTest(contractAddress, client, credential); - } - - public static TableTest deploy(Client client, CryptoKeyPair credential) - throws ContractException { - return deploy(TableTest.class, client, credential, getBinary(client.getCryptoSuite()), ""); - } - - public static class CreateResultEventResponse { - public TransactionReceipt.Logs log; - - public BigInteger count; - } - - public static class SelectResultEventResponse { - public TransactionReceipt.Logs log; - - public byte[] name; - - public BigInteger item_id; - - public byte[] item_name; - } - - public static class InsertResultEventResponse { - public TransactionReceipt.Logs log; - - public BigInteger count; - } - - public static class UpdateResultEventResponse { - public TransactionReceipt.Logs log; - - public BigInteger count; - } - - public static class RemoveResultEventResponse { - public TransactionReceipt.Logs log; - - public BigInteger count; - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/DagTransfer.sol b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/DagTransfer.sol deleted file mode 100644 index 53b40e8a1..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/DagTransfer.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma solidity ^0.4.25; -contract DagTransfer{ - function userAdd(string user, uint256 balance) public returns(uint256); - function userSave(string user, uint256 balance) public returns(uint256); - function userDraw(string user, uint256 balance) public returns(uint256); - function userBalance(string user) public constant returns(uint256,uint256); - function userTransfer(string user_a, string user_b, uint256 amount) public returns(uint256); -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Ok.sol b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Ok.sol deleted file mode 100644 index 6fc46f070..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/Ok.sol +++ /dev/null @@ -1,42 +0,0 @@ -pragma solidity ^0.4.24; -contract Ok{ - - struct Account{ - address account; - uint balance; - } - - struct Translog { - string time; - address from; - address to; - uint amount; - } - - Account from; - Account to; - event TransEvent(uint num); - Translog[] log; - - function Ok(){ - from.account=0x1; - from.balance=10000000000; - to.account=0x2; - to.balance=0; - - } - - function get()constant returns(uint){ - return to.balance; - } - - function trans(uint num){ - if (from.balance < num || to.balance + num < to.balance) - return; // Deny overflow - - from.balance=from.balance-num; - to.balance+=num; - TransEvent(num); - log.push(Translog("20170413",from.account,to.account,num)); - } -} \ No newline at end of file diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/OkD.sol b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/OkD.sol deleted file mode 100644 index ba7f16bce..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/OkD.sol +++ /dev/null @@ -1,57 +0,0 @@ -import "./Table.sol"; - -contract OkD{ - event insertResult(int count); - - struct Account{ - address account; - int balance; - } - - Account from; - Account to; - - function OkD(){ - - from.account=0x1; - from.balance=10000000000; - to.account=0x2; - to.balance=0; - - TableFactory tf = TableFactory(0x1001); - tf.createTable("t_ok", "from_accout", "from_balance,to_accout,to_balance"); - tf = TableFactory(0x1001); - Table table = tf.openTable("t_ok"); - Entry entry = table.newEntry(); - entry.set("from_accout", "0x1"); - entry.set("from_balance", "10000000000"); - entry.set("to_accout", "0x2"); - entry.set("to_balance", "0"); - - } - function get()constant returns(int){ - return to.balance; - } - function trans(string from_accout, int num){ - - if (from.balance < num || to.balance + num < to.balance) - return; // Deny overflow - - from.balance = from.balance - num; - to.balance += num; - - TableFactory tf = TableFactory(0x1001); - Table table = tf.openTable("t_ok"); - Entry entry = table.newEntry(); - entry.set("from_accout", from_accout); - entry.set("from_balance", from.balance); - entry.set("to_accout", "0x2"); - entry.set("to_balance", to.balance); - int count = table.insert(from_accout, entry); - insertResult(count); - - // log.push(Translog("20170413",from.account,to.account,num)); - - } - -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelContract.sol b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelContract.sol deleted file mode 100644 index 106403468..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelContract.sol +++ /dev/null @@ -1,25 +0,0 @@ -pragma solidity ^0.4.25; - -contract ParallelConfigPrecompiled -{ - function registerParallelFunctionInternal(address, string, uint256) public returns (int); - function unregisterParallelFunctionInternal(address, string) public returns (int); -} - -contract ParallelContract -{ - ParallelConfigPrecompiled precompiled = ParallelConfigPrecompiled(0x1006); - - function registerParallelFunction(string functionName, uint256 criticalSize) public - { - precompiled.registerParallelFunctionInternal(address(this), functionName, criticalSize); - } - - function unregisterParallelFunction(string functionName) public - { - precompiled.unregisterParallelFunctionInternal(address(this), functionName); - } - - function enableParallel() public; - function disableParallel() public; -} \ No newline at end of file diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelOk.sol b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelOk.sol deleted file mode 100644 index 99a868a31..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/ParallelOk.sol +++ /dev/null @@ -1,49 +0,0 @@ -pragma solidity ^0.4.25; - -import "./ParallelContract.sol"; - -// A parallel contract example -contract ParallelOk is ParallelContract -{ - mapping (string => uint256) _balance; - - // Just an example, overflow is ok, use 'SafeMath' if needed - function transfer(string from, string to, uint256 num) public - { - _balance[from] -= num; - _balance[to] += num; - } - - // Just for testing whether the parallel revert function is working well, no practical use - function transferWithRevert(string from, string to, uint256 num) public - { - _balance[from] -= num; - _balance[to] += num; - require(num <= 100); - } - - function set(string name, uint256 num) public - { - _balance[name] = num; - } - - function balanceOf(string name) public view returns (uint256) - { - return _balance[name]; - } - - // Register parallel function - function enableParallel() public - { - // critical number is to define how many critical params from start - registerParallelFunction("transfer(string,string,uint256)", 2); // critical: string string - registerParallelFunction("set(string,uint256)", 1); // critical: string - } - - // Disable register parallel function - function disableParallel() public - { - unregisterParallelFunction("transfer(string,string,uint256)"); - unregisterParallelFunction("set(string,uint256)"); - } -} \ No newline at end of file diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/TableTest.sol b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/TableTest.sol deleted file mode 100644 index 8d57ee2aa..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/sol/TableTest.sol +++ /dev/null @@ -1,87 +0,0 @@ -import "./Table.sol"; - -contract TableTest { - event createResult(int count); - event selectResult(bytes32 name, int item_id, bytes32 item_name); - event insertResult(int count); - event updateResult(int count); - event removeResult(int count); - - //create table - function create() public { - TableFactory tf = TableFactory(0x1001); //The fixed address is 0x1001 for TableFactory - int count = tf.createTable("t_test", "name", "item_id,item_name"); - emit createResult(count); - } - - //select records - function select(string name) public constant returns(bytes32[], int[], bytes32[]){ - TableFactory tf = TableFactory(0x1001); - Table table = tf.openTable("t_test"); - - Condition condition = table.newCondition(); - //condition.EQ("name", name); - - Entries entries = table.select(name, condition); - bytes32[] memory user_name_bytes_list = new bytes32[](uint256(entries.size())); - int[] memory item_id_list = new int[](uint256(entries.size())); - bytes32[] memory item_name_bytes_list = new bytes32[](uint256(entries.size())); - - for(int i=0; i()); - eventLogParams.setTopics(new ArrayList<>()); - - class SubscribeCallback implements EventCallback { - public transient Semaphore semaphore = new Semaphore(1, true); - - SubscribeCallback() { - try { - semaphore.acquire(1); - } catch (InterruptedException e) { - logger.error("error :", e); - Thread.currentThread().interrupt(); - } - } - - @Override - public void onReceiveLog(int status, List logs) { - String str = "status in onReceiveLog : " + status; - logger.debug(str); - semaphore.release(); - if (logs != null) { - for (EventLog log : logs) { - logger.debug( - " blockNumber:" - + log.getBlockNumber() - + ",txIndex:" - + log.getTransactionIndex() - + " data:" - + log.getData()); - } - } - } - } - - SubscribeCallback subscribeEventCallback = new SubscribeCallback(); - String registerId = eventSubscribe.subscribeEvent(eventLogParams, subscribeEventCallback); - System.out.print("subscribe event, registerId is " + registerId); - - while (true) {} - } - - public static void main(String[] args) { - allEventLog(); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/event/SendOk.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/event/SendOk.java deleted file mode 100644 index 44828e319..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/event/SendOk.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.event; - -import java.math.BigInteger; -import java.net.URL; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.demo.contract.Ok; -import org.fisco.bcos.sdk.model.ConstantConfig; - -public class SendOk { - - private static void usage() { - System.out.println(" Usage:"); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.event.SendOk [groupId] [count]."); - } - - public static void main(String[] args) { - try { - String configFileName = ConstantConfig.CONFIG_FILE_NAME; - URL configUrl = SendOk.class.getClassLoader().getResource(configFileName); - - if (configUrl == null) { - System.out.println("The configFile " + configFileName + " doesn't exist!"); - return; - } - if (args.length < 2) { - usage(); - return; - } - int groupId = Integer.valueOf(args[0]).intValue(); - Integer count = Integer.valueOf(args[1]); - - String configFile = configUrl.getPath(); - BcosSDK sdk = BcosSDK.build(configFile); - - // build the client - Client client = sdk.getClient(groupId); - - // deploy the HelloWorld - System.out.println("====== Deploy Ok ====== "); - Ok ok = Ok.deploy(client, client.getCryptoSuite().getCryptoKeyPair()); - System.out.println( - "====== Deploy Ok successfully, address: " - + ok.getContractAddress() - + " ====== "); - - System.out.println("====== Send Ok trans begin ======"); - for (int i = 0; i < count; i++) { - ok.trans(new BigInteger("4")); - System.out.println("transaction idx " + i + " sent"); - } - System.out.println("====== Send Ok trans end ======"); - } catch (Exception e) { - System.out.println("====== Send Ok failed, error message: " + e.getMessage()); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/ParallelOkPerf.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/ParallelOkPerf.java deleted file mode 100644 index abdedd6fd..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/ParallelOkPerf.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf; - -import java.io.IOException; -import java.math.BigInteger; -import java.net.URL; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.demo.contract.ParallelOk; -import org.fisco.bcos.sdk.demo.perf.model.DagUserInfo; -import org.fisco.bcos.sdk.demo.perf.parallel.DagPrecompiledDemo; -import org.fisco.bcos.sdk.demo.perf.parallel.ParallelOkDemo; -import org.fisco.bcos.sdk.model.ConstantConfig; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; -import org.fisco.bcos.sdk.utils.ThreadPoolService; - -public class ParallelOkPerf { - private static Client client; - private static DagUserInfo dagUserInfo = new DagUserInfo(); - - public static void Usage() { - System.out.println(" Usage:"); - System.out.println("===== ParallelOk test==========="); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [parallelok] [groupID] [add] [count] [tps] [file]."); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [parallelok] [groupID] [transfer] [count] [tps] [file]."); - System.out.println("===== DagTransafer test==========="); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [precompiled] [groupID] [add] [count] [tps] [file]."); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.ParallelOkPerf [precompiled] [groupID] [transfer] [count] [tps] [file]."); - } - - public static void main(String[] args) - throws ContractException, IOException, InterruptedException { - try { - String configFileName = ConstantConfig.CONFIG_FILE_NAME; - URL configUrl = ParallelOkPerf.class.getClassLoader().getResource(configFileName); - if (configUrl == null) { - System.out.println("The configFile " + configFileName + " doesn't exist!"); - return; - } - if (args.length < 6) { - Usage(); - return; - } - String perfType = args[0]; - Integer groupId = Integer.valueOf(args[1]); - String command = args[2]; - Integer count = Integer.valueOf(args[3]); - Integer qps = Integer.valueOf(args[4]); - String userFile = args[5]; - - String configFile = configUrl.getPath(); - BcosSDK sdk = BcosSDK.build(configFile); - client = sdk.getClient(Integer.valueOf(groupId)); - dagUserInfo.setFile(userFile); - ThreadPoolService threadPoolService = - new ThreadPoolService( - "ParallelOkPerf", - sdk.getConfig().getThreadPoolConfig().getMaxBlockingQueueSize()); - - if (perfType.compareToIgnoreCase("parallelok") == 0) { - parallelOkPerf(groupId, command, count, qps, threadPoolService); - } else if (perfType.compareToIgnoreCase("precompiled") == 0) { - dagTransferPerf(groupId, command, count, qps, threadPoolService); - } else { - System.out.println( - "invalid perf option: " - + perfType - + ", only support parallelok/precompiled now"); - Usage(); - } - } catch (Exception e) { - System.out.println("ParallelOkPerf test failed, error info: " + e.getMessage()); - System.exit(0); - } - } - - public static void parallelOkPerf( - Integer groupId, - String command, - Integer count, - Integer qps, - ThreadPoolService threadPoolService) - throws IOException, InterruptedException, ContractException { - System.out.println( - "====== ParallelOk trans, count: " - + count - + ", qps:" - + qps - + ", groupId: " - + groupId); - ParallelOk parallelOk; - ParallelOkDemo parallelOkDemo; - switch (command) { - case "add": - // deploy ParallelOk - parallelOk = ParallelOk.deploy(client, client.getCryptoSuite().getCryptoKeyPair()); - // enable parallel - parallelOk.enableParallel(); - System.out.println( - "====== ParallelOk userAdd, deploy success, address: " - + parallelOk.getContractAddress()); - parallelOkDemo = new ParallelOkDemo(parallelOk, dagUserInfo, threadPoolService); - parallelOkDemo.userAdd(BigInteger.valueOf(count), BigInteger.valueOf(qps)); - break; - case "transfer": - dagUserInfo.loadDagTransferUser(); - parallelOk = - ParallelOk.load( - dagUserInfo.getContractAddr(), - client, - client.getCryptoSuite().getCryptoKeyPair()); - System.out.println( - "====== ParallelOk trans, load success, address: " - + parallelOk.getContractAddress()); - parallelOkDemo = new ParallelOkDemo(parallelOk, dagUserInfo, threadPoolService); - parallelOkDemo.userTransfer(BigInteger.valueOf(count), BigInteger.valueOf(qps)); - break; - - default: - System.out.println("invalid command: " + command); - Usage(); - break; - } - } - - public static void dagTransferPerf( - Integer groupId, - String command, - Integer count, - Integer qps, - ThreadPoolService threadPoolService) - throws IOException, InterruptedException, ContractException { - System.out.println( - "====== DagTransfer trans, count: " - + count - + ", qps:" - + qps - + ", groupId: " - + groupId); - - DagPrecompiledDemo dagPrecompiledDemo; - switch (command) { - case "add": - dagPrecompiledDemo = new DagPrecompiledDemo(client, dagUserInfo, threadPoolService); - dagPrecompiledDemo.userAdd(BigInteger.valueOf(count), BigInteger.valueOf(qps)); - break; - case "transfer": - dagUserInfo.loadDagTransferUser(); - dagPrecompiledDemo = new DagPrecompiledDemo(client, dagUserInfo, threadPoolService); - dagPrecompiledDemo.userTransfer(BigInteger.valueOf(count), BigInteger.valueOf(qps)); - break; - default: - System.out.println("invalid command: " + command); - Usage(); - break; - } - } -}; diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceOk.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceOk.java deleted file mode 100644 index b728cefcd..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceOk.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf; - -import com.google.common.util.concurrent.RateLimiter; -import java.math.BigInteger; -import java.net.URL; -import java.util.concurrent.atomic.AtomicInteger; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.BcosSDKException; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.demo.contract.Ok; -import org.fisco.bcos.sdk.demo.perf.callback.PerformanceCallback; -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.model.ConstantConfig; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; -import org.fisco.bcos.sdk.utils.ThreadPoolService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PerformanceOk { - private static Logger logger = LoggerFactory.getLogger(PerformanceOk.class); - private static AtomicInteger sendedTransactions = new AtomicInteger(0); - - private static void Usage() { - System.out.println(" Usage:"); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceOk [count] [tps] [groupId]."); - } - - public static void main(String[] args) { - try { - String configFileName = ConstantConfig.CONFIG_FILE_NAME; - URL configUrl = PerformanceOk.class.getClassLoader().getResource(configFileName); - - if (configUrl == null) { - System.out.println("The configFile " + configFileName + " doesn't exist!"); - return; - } - if (args.length < 3) { - Usage(); - return; - } - Integer count = Integer.valueOf(args[0]); - Integer qps = Integer.valueOf(args[1]); - Integer groupId = Integer.valueOf(args[2]); - System.out.println( - "====== PerformanceOk trans, count: " - + count - + ", qps:" - + qps - + ", groupId: " - + groupId); - - String configFile = configUrl.getPath(); - BcosSDK sdk = BcosSDK.build(configFile); - - // build the client - Client client = sdk.getClient(groupId); - - // deploy the HelloWorld - System.out.println("====== Deploy Ok ====== "); - Ok ok = Ok.deploy(client, client.getCryptoSuite().getCryptoKeyPair()); - System.out.println( - "====== Deploy Ok succ, address: " + ok.getContractAddress() + " ====== "); - - PerformanceCollector collector = new PerformanceCollector(); - collector.setTotal(count); - RateLimiter limiter = RateLimiter.create(qps); - Integer area = count / 10; - final Integer total = count; - - System.out.println("====== PerformanceOk trans start ======"); - - ThreadPoolService threadPoolService = - new ThreadPoolService( - "PerformanceOk", - sdk.getConfig().getThreadPoolConfig().getMaxBlockingQueueSize()); - - for (Integer i = 0; i < count; ++i) { - limiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - PerformanceCallback callback = new PerformanceCallback(); - callback.setTimeout(0); - callback.setCollector(collector); - try { - ok.trans(new BigInteger("4"), callback); - } catch (Exception e) { - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - callback.onResponse(receipt); - logger.info(e.getMessage()); - } - int current = sendedTransactions.incrementAndGet(); - if (current >= area && ((current % area) == 0)) { - System.out.println( - "Already sended: " - + current - + "/" - + total - + " transactions"); - } - } - }); - } - // wait to collect all the receipts - while (!collector.getReceived().equals(count)) { - Thread.sleep(1000); - } - threadPoolService.stop(); - System.exit(0); - } catch (BcosSDKException | ContractException | InterruptedException e) { - System.out.println( - "====== PerformanceOk test failed, error message: " + e.getMessage()); - System.exit(0); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceOkD.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceOkD.java deleted file mode 100644 index cc50f5311..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceOkD.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf; - -import com.google.common.util.concurrent.RateLimiter; -import java.math.BigInteger; -import java.net.URL; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.BcosSDKException; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.demo.contract.OkD; -import org.fisco.bcos.sdk.demo.perf.callback.PerformanceCallback; -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.model.ConstantConfig; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; -import org.fisco.bcos.sdk.utils.ThreadPoolService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PerformanceOkD { - private static Logger logger = LoggerFactory.getLogger(PerformanceOkD.class); - private static AtomicInteger sendedTransactions = new AtomicInteger(0); - - private static void Usage() { - System.out.println(" Usage:"); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceOkD [count] [tps] [groupId]."); - } - - public static void main(String[] args) { - try { - String configFileName = ConstantConfig.CONFIG_FILE_NAME; - URL configUrl = PerformanceOkD.class.getClassLoader().getResource(configFileName); - if (configUrl == null) { - System.out.println("The configFile " + configFileName + " doesn't exist!"); - return; - } - if (args.length < 3) { - Usage(); - return; - } - Integer count = Integer.valueOf(args[0]); - Integer qps = Integer.valueOf(args[1]); - Integer groupId = Integer.valueOf(args[2]); - System.out.println( - "====== PerformanceOkD trans, count: " - + count - + ", qps:" - + qps - + ", groupId: " - + groupId); - - String configFile = configUrl.getPath(); - BcosSDK sdk = BcosSDK.build(configFile); - - // build the client - Client client = sdk.getClient(groupId); - - // deploy the HelloWorld - System.out.println("====== Deploy OkD ====== "); - OkD okd = OkD.deploy(client, client.getCryptoSuite().getCryptoKeyPair()); - System.out.println( - "====== Deploy OkD success, address: " + okd.getContractAddress() + " ====== "); - - PerformanceCollector collector = new PerformanceCollector(); - collector.setTotal(count); - RateLimiter limiter = RateLimiter.create(qps); - Integer area = count / 10; - final Integer total = count; - - System.out.println("====== PerformanceOkD trans start ======"); - - ThreadPoolService threadPoolService = - new ThreadPoolService( - "PerformanceOkD", - sdk.getConfig().getThreadPoolConfig().getMaxBlockingQueueSize()); - Random random = new Random(System.currentTimeMillis()); - for (Integer i = 0; i < count; ++i) { - limiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - PerformanceCallback callback = new PerformanceCallback(); - callback.setTimeout(0); - callback.setCollector(collector); - try { - okd.trans( - String.valueOf(random.nextLong()), - new BigInteger("1"), - callback); - } catch (Exception e) { - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - callback.onResponse(receipt); - logger.info(e.getMessage()); - } - int current = sendedTransactions.incrementAndGet(); - if (current >= area && ((current % area) == 0)) { - System.out.println( - "Already sended: " - + current - + "/" - + total - + " transactions"); - } - } - }); - } - // wait to collect all the receipts - while (!collector.getReceived().equals(count)) { - Thread.sleep(1000); - } - threadPoolService.stop(); - System.exit(0); - } catch (BcosSDKException | ContractException | InterruptedException e) { - System.out.println( - "====== PerformanceOkD test failed, error message: " + e.getMessage()); - System.exit(0); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceRPC.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceRPC.java deleted file mode 100644 index 3d17a5781..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceRPC.java +++ /dev/null @@ -1,168 +0,0 @@ -package org.fisco.bcos.sdk.demo.perf; - -import com.google.common.util.concurrent.RateLimiter; -import java.math.BigInteger; -import java.net.URL; -import java.security.SecureRandom; -import java.util.concurrent.atomic.AtomicInteger; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.model.ConstantConfig; -import org.fisco.bcos.sdk.model.JsonRpcResponse; -import org.fisco.bcos.sdk.utils.ThreadPoolService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PerformanceRPC { - private static Logger logger = LoggerFactory.getLogger(PerformanceRPC.class); - private static AtomicInteger sended = new AtomicInteger(0); - - public static void Usage() { - System.out.println(" Usage:"); - System.out.println( - " \t java -cp 'conf/:lib/*:apps/*' org.fisco.bcos.sdk.demo.perf.PerformanceRPC groupID totalCount qps"); - System.exit(0); - } - - public static void main(String[] args) throws Exception { - try { - String configFileName = ConstantConfig.CONFIG_FILE_NAME; - URL configUrl = PerformanceOk.class.getClassLoader().getResource(configFileName); - - if (configUrl == null) { - System.out.println("The configFile " + configFileName + " doesn't exist!"); - return; - } - - if (args.length < 3) { - Usage(); - } - - Integer count = Integer.parseInt(args[0]); - Integer qps = Integer.parseInt(args[1]); - int groupId = Integer.valueOf(args[2]); - String configFile = configUrl.getPath(); - BcosSDK sdk = BcosSDK.build(configFile); - Client client = sdk.getClient(groupId); - - System.out.println("Start test..."); - System.out.println( - "==================================================================="); - - PerformanceCollector collector = new PerformanceCollector(); - collector.setTotal(count); - - RateLimiter limiter = RateLimiter.create(qps); - Integer area = count / 10; - final Integer total = count; - ThreadPoolService threadPoolService = - new ThreadPoolService( - "PerformanceRPC", - sdk.getConfig().getThreadPoolConfig().getMaxBlockingQueueSize()); - - System.out.println("Start test, total: " + count); - for (Integer i = 0; i < count; ++i) { - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - limiter.acquire(); - JsonRpcResponse response = new JsonRpcResponse(); - try { - int random = new SecureRandom().nextInt(50000); - int methodNum = 10; - Long startTime = System.nanoTime(); - - switch (random % methodNum) { - // 1. call getPendingTxSize - case 0: - response = client.getPendingTxSize(); - break; - // 2. call getBlockNumber - case 1: - response = client.getBlockNumber(); - break; - // 3. call getSyncStatus - case 2: - response = client.getSyncStatus(); - break; - // 4. call getConsensusStatus - // case 3: - // response = - // web3j.getConsensusStatus().send(); - // break; - // 5. call getSealerList - case 4: - response = client.getSealerList(); - break; - // 6. call getTotalTransactionCount - case 5: - response = client.getTotalTransactionCount(); - break; - // 7. call getObserverList - case 6: - response = client.getObserverList(); - break; - // 8. call getBlockHashByNumber - case 7: - BigInteger blockNumber = - client.getBlockNumber() - .getBlockNumber(); - response = - client.getBlockHashByNumber( - blockNumber); - break; - // 9. call getSystemConfigByKey - case 8: - response = - client.getSystemConfigByKey( - "tx_count_limit"); - break; - // 10. call getPbftView - case 9: - response = client.getPbftView(); - break; - default: - // default call getPbftView - response = client.getPbftView(); - } - Long cost = System.nanoTime() - startTime; - collector.onRpcMessage(response, cost); - - } catch (Exception e) { - logger.error( - "test rpc interface failed, error info: {}", - e.getMessage()); - JsonRpcResponse.Error error = - new JsonRpcResponse.Error(); - error.setCode(1); - response.setError(error); - collector.onRpcMessage(response, 0L); - } - - int current = sended.incrementAndGet(); - - if (current >= area && ((current % area) == 0)) { - System.out.println( - "Already sended: " - + current - + "/" - + total - + " RPC Requests"); - } - } - }); - } - while (collector.getReceived().longValue() < collector.getTotal().longValue()) { - Thread.sleep(50); - } - System.exit(0); - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceTable.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceTable.java deleted file mode 100644 index 9ad858064..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/PerformanceTable.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf; - -import com.google.common.util.concurrent.RateLimiter; -import java.math.BigInteger; -import java.net.URL; -import java.util.Random; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import org.fisco.bcos.sdk.BcosSDK; -import org.fisco.bcos.sdk.BcosSDKException; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.demo.contract.TableTest; -import org.fisco.bcos.sdk.demo.perf.callback.PerformanceCallback; -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.model.ConstantConfig; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; -import org.fisco.bcos.sdk.utils.ThreadPoolService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PerformanceTable { - private static Logger logger = LoggerFactory.getLogger(PerformanceTable.class); - private static AtomicInteger sendedTransactions = new AtomicInteger(0); - private static AtomicLong uniqueID = new AtomicLong(0); - - private static void Usage() { - System.out.println(" Usage:"); - System.out.println("===== PerformanceTable test==========="); - System.out.println( - " \t java -cp \'conf/:lib/*:apps/*\' org.fisco.bcos.sdk.demo.perf.PerformanceTable [insert] [count] [tps] [groupId]."); - System.out.println( - " \t java -cp \'conf/:lib/*:apps/*\' org.fisco.bcos.sdk.demo.perf.PerformanceTable [update] [count] [tps] [groupId]."); - System.out.println( - " \t java -cp \'conf/:lib/*:apps/*\' org.fisco.bcos.sdk.demo.perf.PerformanceTable [remove] [count] [tps] [groupId]."); - System.out.println( - " \t java -cp \'conf/:lib/*:apps/*\' org.fisco.bcos.sdk.demo.perf.PerformanceTable [query] [count] [tps] [groupId]."); - } - - public static void main(String[] args) { - try { - String configFileName = ConstantConfig.CONFIG_FILE_NAME; - URL configUrl = PerformanceTable.class.getClassLoader().getResource(configFileName); - if (configUrl == null) { - System.out.println("The configFile " + configFileName + " doesn't exist!"); - return; - } - if (args.length < 4) { - Usage(); - return; - } - String command = args[0]; - Integer count = Integer.valueOf(args[1]); - Integer qps = Integer.valueOf(args[2]); - Integer groupId = Integer.valueOf(args[3]); - System.out.println( - "====== PerformanceTable " - + command - + ", count: " - + count - + ", qps:" - + qps - + ", groupId: " - + groupId); - - String configFile = configUrl.getPath(); - BcosSDK sdk = BcosSDK.build(configFile); - - // build the client - Client client = sdk.getClient(groupId); - - // deploy the HelloWorld - System.out.println("====== Deploy TableTest ====== "); - TableTest tableTest = - TableTest.deploy(client, client.getCryptoSuite().getCryptoKeyPair()); - // create table - tableTest.create(); - System.out.println( - "====== Deploy TableTest success, address: " - + tableTest.getContractAddress() - + " ====== "); - - PerformanceCollector collector = new PerformanceCollector(); - collector.setTotal(count); - RateLimiter limiter = RateLimiter.create(qps); - Integer area = count / 10; - final Integer total = count; - - System.out.println("====== PerformanceTable " + command + " start ======"); - ThreadPoolService threadPoolService = - new ThreadPoolService( - "PerformanceTable", - sdk.getConfig().getThreadPoolConfig().getMaxBlockingQueueSize()); - for (Integer i = 0; i < count; ++i) { - limiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - callTableOperation(command, tableTest, collector); - int current = sendedTransactions.incrementAndGet(); - if (current >= area && ((current % area) == 0)) { - System.out.println( - "Already sended: " - + current - + "/" - + total - + " transactions"); - } - } - }); - } - // wait to collect all the receipts - while (!collector.getReceived().equals(count)) { - Thread.sleep(1000); - } - threadPoolService.stop(); - System.exit(0); - } catch (BcosSDKException | ContractException | InterruptedException e) { - System.out.println( - "====== PerformanceTable test failed, error message: " + e.getMessage()); - System.exit(0); - } - } - - private static void callTableOperation( - String command, TableTest tableTest, PerformanceCollector collector) { - if (command.compareToIgnoreCase("insert") == 0) { - insert(tableTest, collector); - } - - if (command.compareToIgnoreCase("update") == 0) { - update(tableTest, collector); - } - if (command.compareToIgnoreCase("remove") == 0) { - remove(tableTest, collector); - } - if (command.compareToIgnoreCase("query") == 0) { - query(tableTest, collector); - } - } - - public static long getNextID() { - return uniqueID.getAndIncrement(); - } - - private static String getId() { - UUID uuid = UUID.randomUUID(); - return uuid.toString().replace("-", ""); - } - - private static PerformanceCallback createCallback(PerformanceCollector collector) { - PerformanceCallback callback = new PerformanceCallback(); - callback.setTimeout(0); - callback.setCollector(collector); - return callback; - } - - private static void sendTransactionException( - Exception e, String command, PerformanceCallback callback) { - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - callback.onResponse(receipt); - logger.info("call command {} failed, error info: {}", command, e.getMessage()); - } - - private static void insert(TableTest tableTest, PerformanceCollector collector) { - PerformanceCallback callback = createCallback(collector); - try { - long _id = getNextID(); - tableTest.insert( - "fruit" + _id % 100, BigInteger.valueOf(_id), "apple" + getId(), callback); - } catch (Exception e) { - sendTransactionException(e, "insert", callback); - } - } - - private static void update(TableTest tableTest, PerformanceCollector collector) { - PerformanceCallback callback = createCallback(collector); - try { - long _id = getNextID(); - Random r = new Random(); - long l1 = r.nextLong(); - tableTest.update( - "fruit" + l1 % 100, BigInteger.valueOf(_id), "apple" + getId(), callback); - } catch (Exception e) { - sendTransactionException(e, "update", callback); - } - } - - private static void remove(TableTest tableTest, PerformanceCollector collector) { - PerformanceCallback callback = createCallback(collector); - try { - long _id = getNextID(); - Random r = new Random(); - long l1 = r.nextLong(); - tableTest.remove("fruit" + l1 % 100, BigInteger.valueOf(_id), callback); - - } catch (Exception e) { - sendTransactionException(e, "remove", callback); - } - } - - private static void query(TableTest tableTest, PerformanceCollector collector) { - try { - Long time_before = System.currentTimeMillis(); - Random r = new Random(); - long l1 = r.nextLong(); - tableTest.select("fruit" + l1 % 100); - Long time_after = System.currentTimeMillis(); - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("0x0"); - collector.onMessage(receipt, time_after - time_before); - } catch (Exception e) { - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - collector.onMessage(receipt, (long) (0)); - logger.error("query error: {}", e); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/callback/ParallelOkCallback.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/callback/ParallelOkCallback.java deleted file mode 100644 index 88dccd746..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/callback/ParallelOkCallback.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf.callback; - -import java.math.BigInteger; -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.demo.perf.model.DagTransferUser; -import org.fisco.bcos.sdk.demo.perf.model.DagUserInfo; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.model.callback.TransactionCallback; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ParallelOkCallback extends TransactionCallback { - private static Logger logger = LoggerFactory.getLogger(ParallelOkCallback.class); - public static final String ADD_USER_CALLBACK = "add"; - public static final String TRANS_CALLBACK = "transfer"; - private Long startTime; - - private final PerformanceCollector collector; - private final DagUserInfo dagUserInfo; - private final String callbackType; - - private DagTransferUser user = null; - private DagTransferUser fromUser = null; - private DagTransferUser toUser = null; - private BigInteger amount = null; - - public ParallelOkCallback( - PerformanceCollector collector, DagUserInfo dagUserInfo, String callbackType) { - this.collector = collector; - this.dagUserInfo = dagUserInfo; - this.callbackType = callbackType; - } - - public void recordStartTime() { - this.startTime = System.currentTimeMillis(); - } - - @Override - public void onResponse(TransactionReceipt receipt) { - Long cost = System.currentTimeMillis() - startTime; - try { - if (receipt.isStatusOK()) { - if (callbackType.compareTo(ADD_USER_CALLBACK) == 0) { // add test - dagUserInfo.addUser(user); - } else if (callbackType.compareTo(TRANS_CALLBACK) == 0) { // transfer test - fromUser.decrease(amount); - toUser.increase(amount); - } - } - collector.onMessage(receipt, cost); - } catch (Exception e) { - logger.error("onMessage error: ", e); - } - } - - public DagTransferUser getFromUser() { - return fromUser; - } - - public void setFromUser(DagTransferUser fromUser) { - this.fromUser = fromUser; - } - - public DagTransferUser getToUser() { - return toUser; - } - - public void setToUser(DagTransferUser toUser) { - this.toUser = toUser; - } - - public BigInteger getAmount() { - return amount; - } - - public void setAmount(BigInteger amount) { - this.amount = amount; - } - - public DagTransferUser getUser() { - return user; - } - - public void setUser(DagTransferUser user) { - this.user = user; - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/callback/PerformanceCallback.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/callback/PerformanceCallback.java deleted file mode 100644 index 0631dcc01..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/callback/PerformanceCallback.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf.callback; - -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.model.callback.TransactionCallback; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PerformanceCallback extends TransactionCallback { - - private static Logger logger = LoggerFactory.getLogger(PerformanceCallback.class); - private Long startTime = System.currentTimeMillis(); - - private PerformanceCollector collector; - - public PerformanceCollector getCollector() { - return collector; - } - - public void setCollector(PerformanceCollector collector) { - this.collector = collector; - } - - public PerformanceCallback() {} - - @Override - public void onResponse(TransactionReceipt receipt) { - Long cost = System.currentTimeMillis() - startTime; - - try { - collector.onMessage(receipt, cost); - } catch (Exception e) { - logger.error("onMessage error: ", e); - } - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/collector/PerformanceCollector.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/collector/PerformanceCollector.java deleted file mode 100644 index d5505ebf6..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/collector/PerformanceCollector.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf.collector; - -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import org.fisco.bcos.sdk.model.JsonRpcResponse; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PerformanceCollector { - private static Logger logger = LoggerFactory.getLogger(PerformanceCollector.class); - private AtomicLong less50 = new AtomicLong(0); - private AtomicLong less100 = new AtomicLong(0); - private AtomicLong less200 = new AtomicLong(0); - private AtomicLong less400 = new AtomicLong(0); - private AtomicLong less1000 = new AtomicLong(0); - private AtomicLong less2000 = new AtomicLong(0); - private AtomicLong timeout2000 = new AtomicLong(0); - private AtomicLong totalCost = new AtomicLong(0); - - private Integer total = 0; - private AtomicInteger received = new AtomicInteger(0); - private AtomicInteger error = new AtomicInteger(0); - private Long startTimestamp = System.currentTimeMillis(); - - public Integer getTotal() { - return total; - } - - public void setTotal(Integer total) { - this.total = total; - } - - public Integer getReceived() { - return received.get(); - } - - public void setReceived(Integer received) { - this.received.getAndSet(received); - } - - public void onRpcMessage(JsonRpcResponse response, Long cost) { - try { - boolean errorMessage = false; - if (response.getError() != null && response.getError().getCode() != 0) { - logger.warn("receive error jsonRpcResponse: {}", response.toString()); - errorMessage = true; - } - stat(errorMessage, cost); - } catch (Exception e) { - logger.error("onRpcMessage exception: {}", e.getMessage()); - } - } - - public void onMessage(TransactionReceipt receipt, Long cost) { - try { - boolean errorMessage = false; - if (!receipt.isStatusOK()) { - logger.error( - "error receipt, status: {}, output: {}, message: {}", - receipt.getStatus(), - receipt.getOutput(), - receipt.getMessage()); - errorMessage = true; - } - stat(errorMessage, cost); - } catch (Exception e) { - logger.error("error:", e); - } - } - - public void stat(boolean errorMessage, Long cost) { - if (errorMessage) { - error.addAndGet(1); - } - - if ((received.get() + 1) % (total / 10) == 0) { - System.out.println( - " |received:" - + String.valueOf((received.get() + 1) * 100 / total) - + "%"); - } - - if (cost < 50) { - less50.incrementAndGet(); - } else if (cost < 100) { - less100.incrementAndGet(); - } else if (cost < 200) { - less200.incrementAndGet(); - } else if (cost < 400) { - less400.incrementAndGet(); - } else if (cost < 1000) { - less1000.incrementAndGet(); - } else if (cost < 2000) { - less2000.incrementAndGet(); - } else { - timeout2000.incrementAndGet(); - } - - totalCost.addAndGet(cost); - - if (received.incrementAndGet() >= total) { - System.out.println("total"); - - Long totalTime = System.currentTimeMillis() - startTimestamp; - - System.out.println( - "==================================================================="); - - System.out.println("Total transactions: " + String.valueOf(total)); - System.out.println("Total time: " + String.valueOf(totalTime) + "ms"); - System.out.println( - "TPS(include error requests): " - + String.valueOf(total / ((double) totalTime / 1000))); - System.out.println( - "TPS(exclude error requests): " - + String.valueOf( - (double) (total - error.get()) / ((double) totalTime / 1000))); - System.out.println("Avg time cost: " + String.valueOf(totalCost.get() / total) + "ms"); - System.out.println( - "Error rate: " - + String.valueOf((error.get() / (double) received.get()) * 100) - + "%"); - - System.out.println("Time area:"); - System.out.println( - "0 < time < 50ms : " - + String.valueOf(less50) - + " : " - + String.valueOf((double) less50.get() / total * 100) - + "%"); - System.out.println( - "50 < time < 100ms : " - + String.valueOf(less100) - + " : " - + String.valueOf((double) less100.get() / total * 100) - + "%"); - System.out.println( - "100 < time < 200ms : " - + String.valueOf(less200) - + " : " - + String.valueOf((double) less200.get() / total * 100) - + "%"); - System.out.println( - "200 < time < 400ms : " - + String.valueOf(less400) - + " : " - + String.valueOf((double) less400.get() / total * 100) - + "%"); - System.out.println( - "400 < time < 1000ms : " - + String.valueOf(less1000) - + " : " - + String.valueOf((double) less1000.get() / total * 100) - + "%"); - System.out.println( - "1000 < time < 2000ms : " - + String.valueOf(less2000) - + " : " - + String.valueOf((double) less2000.get() / total * 100) - + "%"); - System.out.println( - "2000 < time : " - + String.valueOf(timeout2000) - + " : " - + String.valueOf((double) timeout2000.get() / total * 100) - + "%"); - } - } - - public void setStartTimestamp(Long startTimestamp) { - this.startTimestamp = startTimestamp; - } - - public Long getStartTimestamp() { - return startTimestamp; - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagTransferUser.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagTransferUser.java deleted file mode 100644 index c0ac1f464..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagTransferUser.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf.model; - -import java.math.BigInteger; - -public class DagTransferUser { - private String user; - private BigInteger amount; - - public String getUser() { - return user; - } - - public synchronized void setUser(String user) { - this.user = user; - } - - public synchronized BigInteger getAmount() { - return amount; - } - - public synchronized void setAmount(BigInteger amount) { - this.amount = amount; - } - - public synchronized void increase(BigInteger amount) { - this.amount = this.amount.add(amount); - } - - public synchronized void decrease(BigInteger amount) { - this.amount = this.amount.subtract(amount); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagUserInfo.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagUserInfo.java deleted file mode 100644 index 9f6bbbc53..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/model/DagUserInfo.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf.model; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DagUserInfo { - private static Logger logger = LoggerFactory.getLogger(DagUserInfo.class); - - private List userList = new ArrayList(); - - private String file = null; - - private String parallelokAddr = ""; - - public void setContractAddr(String addr) { - this.parallelokAddr = addr; - } - - public String getContractAddr() { - return this.parallelokAddr; - } - - public List getUserList() { - return userList; - } - - public void setUserList(List userList) { - this.userList = userList; - } - - public String getFile() { - return file; - } - - public void setFile(String file) { - this.file = file; - } - - public synchronized void addUser(DagTransferUser user) { - userList.add(user); - } - - public boolean isEmpty() { - return userList.isEmpty(); - } - - public DagTransferUser getFrom(int idx) { - assert !isEmpty() : "Has no user."; - return userList.get(idx % userList.size()); - } - - public DagTransferUser getTo(int idx) { - assert !isEmpty() : "Has no user."; - int mid = userList.size() / 2; - return userList.get((idx + mid) % userList.size()); - } - - public DagTransferUser getNext(int idx) { - return userList.get((idx + 1) % userList.size()); - } - - public void writeDagTransferUser() throws IOException { - if (file == null) { - return; - } - logger.info("file {}, begin load.", file); - - BufferedWriter bw = null; - try { - bw = new BufferedWriter(new FileWriter(new File(file))); - - // Write contract address first - bw.write(parallelokAddr + "\n"); - - // And write user - for (int i = 0; i < userList.size(); i++) { - bw.write(userList.get(i).getUser() + "\n"); - logger.trace(" write user , user is {}", userList.get(i).getUser()); - } - - bw.flush(); - - } finally { - if (bw != null) { - bw.close(); - } - } - - logger.info("file {}, load end, count is {}.", file, userList.size()); - System.out.println(" Write DagTransferUser end, count is " + userList.size()); - } - - public void loadDagTransferUser() throws IOException { - if (file == null) { - return; - } - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(new File(file))); - - String line = null; - - // Get contract addr first - if ((line = br.readLine()) != null) { - parallelokAddr = line; - } - - // And get user - while ((line = br.readLine()) != null) { - line = line.trim(); - if (!line.isEmpty()) { - DagTransferUser user = new DagTransferUser(); - user.setUser(line); - addUser(user); - // System.out.println("load DagTransferUser ==>> " + line); - } - } - - } finally { - if (br != null) { - br.close(); - } - } - - logger.info("file {}, load end, count is {}.", file, userList.size()); - - System.out.println("Load DagTransferUser end, count is " + userList.size()); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/parallel/DagPrecompiledDemo.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/parallel/DagPrecompiledDemo.java deleted file mode 100644 index 01a3fa412..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/parallel/DagPrecompiledDemo.java +++ /dev/null @@ -1,321 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf.parallel; - -import com.google.common.util.concurrent.RateLimiter; -import java.io.IOException; -import java.math.BigInteger; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; -import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple2; -import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.demo.contract.DagTransfer; -import org.fisco.bcos.sdk.demo.perf.callback.ParallelOkCallback; -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.demo.perf.model.DagTransferUser; -import org.fisco.bcos.sdk.demo.perf.model.DagUserInfo; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.utils.ThreadPoolService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DagPrecompiledDemo { - private static final Logger logger = LoggerFactory.getLogger(DagPrecompiledDemo.class); - private final DagTransfer dagTransfer; - private final DagUserInfo dagUserInfo; - private final PerformanceCollector collector; - private final ThreadPoolService threadPoolService; - private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - private static final String DAG_TRANSFER_ADDR = "0x0000000000000000000000000000000000005002"; - - public DagPrecompiledDemo( - Client client, DagUserInfo dagUserInfo, ThreadPoolService threadPoolService) { - this.threadPoolService = threadPoolService; - this.dagTransfer = - DagTransfer.load( - DAG_TRANSFER_ADDR, client, client.getCryptoSuite().getCryptoKeyPair()); - this.dagUserInfo = dagUserInfo; - this.collector = new PerformanceCollector(); - } - - public void userAdd(BigInteger userCount, BigInteger qps) - throws InterruptedException, IOException { - System.out.println("Start userAdd test..."); - System.out.println("==================================================================="); - RateLimiter limiter = RateLimiter.create(qps.intValue()); - Integer area = userCount.intValue() / 10; - - long seconds = System.currentTimeMillis() / 1000L; - - this.collector.setStartTimestamp(System.currentTimeMillis()); - AtomicInteger sended = new AtomicInteger(0); - AtomicInteger sendFailed = new AtomicInteger(9); - collector.setTotal(userCount.intValue()); - - for (Integer i = 0; i < userCount.intValue(); i++) { - final Integer index = i; - limiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - String user = - Long.toHexString(seconds) + Integer.toHexString(index); - BigInteger amount = new BigInteger("1000000000"); - DagTransferUser dtu = new DagTransferUser(); - dtu.setUser(user); - dtu.setAmount(amount); - ParallelOkCallback callback = - new ParallelOkCallback( - collector, - dagUserInfo, - ParallelOkCallback.ADD_USER_CALLBACK); - callback.setUser(dtu); - try { - callback.recordStartTime(); - callback.setTimeout(0); - dagTransfer.userAdd(user, amount, callback); - int current = sended.incrementAndGet(); - if (current >= area && ((current % area) == 0)) { - System.out.println( - "Already sended: " - + current - + "/" - + userCount - + " transactions"); - } - } catch (Exception e) { - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - callback.onResponse(receipt); - logger.error( - "dagTransfer add failed, error info: " - + e.getMessage()); - sendFailed.incrementAndGet(); - logger.info(e.getMessage()); - } - } - }); - } - while (collector.getReceived().intValue() != collector.getTotal().intValue()) { - logger.info( - " received: {}, total: {}, sendFailed: {}, sended: {}", - collector.getReceived().intValue(), - collector.getTotal(), - sendFailed.get(), - sended.get()); - Thread.sleep(2000); - } - // save the user info - dagUserInfo.writeDagTransferUser(); - System.exit(0); - } - - public void queryAccountInfo(BigInteger qps) throws InterruptedException { - System.out.println("Start queryAccountInfo..."); - // get the user - List allUser = dagUserInfo.getUserList(); - RateLimiter rateLimiter = RateLimiter.create(qps.intValue()); - AtomicInteger getted = new AtomicInteger(0); - for (Integer i = 0; i < allUser.size(); i++) { - final Integer index = i; - rateLimiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - try { - Tuple2 result = - dagTransfer.userBalance( - allUser.get(index).getUser()); - - if (result.getValue1().compareTo(new BigInteger("0")) - == 0) { - allUser.get(index).setAmount(result.getValue2()); - } else { - System.out.println( - " Query failed, user is " - + allUser.get(index).getUser()); - System.exit(0); - } - int all = getted.incrementAndGet(); - if (all >= allUser.size()) { - System.out.println( - dateFormat.format(new Date()) - + " Query account finished"); - } - } catch (Exception e) { - System.out.println( - " Query failed, user is " - + allUser.get(index).getUser()); - System.exit(0); - } - } - }); - } - while (getted.get() < allUser.size()) { - Thread.sleep(50); - } - } - - public void userTransfer(BigInteger count, BigInteger qps) throws InterruptedException { - System.out.println("Start userTransfer test..."); - System.out.println("==================================================================="); - queryAccountInfo(qps); - long startTime = System.currentTimeMillis(); - AtomicInteger sended = new AtomicInteger(0); - AtomicInteger sendFailed = new AtomicInteger(0); - collector.setTotal(count.intValue()); - collector.setStartTimestamp(startTime); - Integer area = count.intValue() / 10; - RateLimiter rateLimiter = RateLimiter.create(qps.intValue()); - // transfer balance - for (Integer i = 0; i < count.intValue(); i++) { - final Integer index = i; - rateLimiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - ParallelOkCallback callback = - new ParallelOkCallback( - collector, - dagUserInfo, - ParallelOkCallback.TRANS_CALLBACK); - try { - DagTransferUser from = dagUserInfo.getFrom(index); - DagTransferUser to = dagUserInfo.getTo(index); - Random random = new Random(); - int r = random.nextInt(100) + 1; - BigInteger amount = BigInteger.valueOf(r); - callback.setFromUser(from); - callback.setToUser(to); - callback.setAmount(amount); - callback.setTimeout(0); - callback.recordStartTime(); - dagTransfer.userTransfer( - from.getUser(), to.getUser(), amount, callback); - long elapsed = System.currentTimeMillis() - startTime; - sended.incrementAndGet(); - double sendSpeed = sended.get() / ((double) elapsed / 1000); - if (sended.get() >= area && ((sended.get() % area) == 0)) { - System.out.println( - "Already sent: " - + sended.get() - + "/" - + count - + " transactions"); - } - } catch (Exception e) { - logger.warn( - "userTransfer failed, error info: {}", - e.getMessage()); - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - receipt.setMessage( - "userTransfer failed, error info: " - + e.getMessage()); - callback.onResponse(receipt); - sendFailed.incrementAndGet(); - } - } - }); - } - while (collector.getReceived().intValue() != count.intValue()) { - Thread.sleep(2000); - logger.info( - " received: {}, total: {}, sended: {}, sendFailed: {}", - collector.getReceived().intValue(), - collector.getTotal(), - sended.get(), - sendFailed.get()); - } - veryTransferData(qps); - System.exit(0); - } - - public void veryTransferData(BigInteger qps) throws InterruptedException { - System.out.println("Start veryTransferData..."); - RateLimiter rateLimiter = RateLimiter.create(qps.intValue()); - AtomicInteger verify_success = new AtomicInteger(0); - AtomicInteger verify_failed = new AtomicInteger(0); - - List allUser = dagUserInfo.getUserList(); - for (Integer i = 0; i < allUser.size(); i++) { - final Integer index = i; - rateLimiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - try { - Tuple2 result = - dagTransfer.userBalance( - allUser.get(index).getUser()); - - String user = allUser.get(index).getUser(); - BigInteger local = allUser.get(index).getAmount(); - BigInteger remote = result.getValue2(); - - if (result.getValue1().compareTo(new BigInteger("0")) - != 0) { - logger.error( - " query failed, user " - + user - + " ret code " - + result.getValue1()); - verify_failed.incrementAndGet(); - return; - } - if (local.compareTo(remote) != 0) { - verify_failed.incrementAndGet(); - logger.error( - " local amount is not same as remote, user " - + user - + " local " - + local - + " remote " - + remote); - } else { - verify_success.incrementAndGet(); - } - } catch (Exception e) { - logger.error( - "get amount failed, error info: {}", - e.getMessage()); - verify_failed.incrementAndGet(); - } - } - }); - } - while (verify_success.get() + verify_failed.get() < allUser.size()) { - Thread.sleep(40); - } - System.out.println("validation:"); - System.out.println(" \tuser count is " + allUser.size()); - System.out.println(" \tverify_success count is " + verify_success); - System.out.println(" \tverify_failed count is " + verify_failed); - } -} diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/parallel/ParallelOkDemo.java b/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/parallel/ParallelOkDemo.java deleted file mode 100644 index 04eb87787..000000000 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/perf/parallel/ParallelOkDemo.java +++ /dev/null @@ -1,303 +0,0 @@ -/** - * Copyright 2014-2020 [fisco-dev] - * - *

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

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

Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.fisco.bcos.sdk.demo.perf.parallel; - -import com.google.common.util.concurrent.RateLimiter; -import java.io.IOException; -import java.math.BigInteger; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; -import org.fisco.bcos.sdk.demo.contract.ParallelOk; -import org.fisco.bcos.sdk.demo.perf.callback.ParallelOkCallback; -import org.fisco.bcos.sdk.demo.perf.collector.PerformanceCollector; -import org.fisco.bcos.sdk.demo.perf.model.DagTransferUser; -import org.fisco.bcos.sdk.demo.perf.model.DagUserInfo; -import org.fisco.bcos.sdk.model.TransactionReceipt; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; -import org.fisco.bcos.sdk.utils.ThreadPoolService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ParallelOkDemo { - private static final Logger logger = LoggerFactory.getLogger(ParallelOkDemo.class); - private static AtomicInteger sended = new AtomicInteger(0); - private AtomicInteger getted = new AtomicInteger(0); - - private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - private final ParallelOk parallelOk; - private final ThreadPoolService threadPoolService; - private final PerformanceCollector collector; - private final DagUserInfo dagUserInfo; - - public ParallelOkDemo( - ParallelOk parallelOk, DagUserInfo dagUserInfo, ThreadPoolService threadPoolService) { - this.threadPoolService = threadPoolService; - this.parallelOk = parallelOk; - this.dagUserInfo = dagUserInfo; - this.collector = new PerformanceCollector(); - } - - public void veryTransferData(BigInteger qps) throws InterruptedException { - RateLimiter rateLimiter = RateLimiter.create(qps.intValue()); - System.out.println("==================================================================="); - AtomicInteger verifyFailed = new AtomicInteger(0); - AtomicInteger verifySuccess = new AtomicInteger(0); - - final List userInfo = dagUserInfo.getUserList(); - int userSize = userInfo.size(); - for (int i = 0; i < userSize; i++) { - rateLimiter.acquire(); - final int userIndex = i; - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - try { - String user = userInfo.get(userIndex).getUser(); - BigInteger balance = parallelOk.balanceOf(user); - BigInteger localAmount = - userInfo.get(userIndex).getAmount(); - if (localAmount.compareTo(balance) != 0) { - logger.error( - "local balance is not the same as the remote, user: {}, local balance: {}, remote balance: {}", - user, - localAmount, - balance); - verifyFailed.incrementAndGet(); - } else { - verifySuccess.incrementAndGet(); - } - } catch (ContractException exception) { - verifyFailed.incrementAndGet(); - logger.error( - "get remote balance failed, error info: " - + exception.getMessage()); - } - } - }); - } - while (verifySuccess.get() + verifyFailed.get() < userSize) { - Thread.sleep(40); - } - - System.out.println("validation:"); - System.out.println(" \tuser count is " + userSize); - System.out.println(" \tverify_success count is " + verifySuccess); - System.out.println(" \tverify_failed count is " + verifyFailed); - } - - public void userAdd(BigInteger userCount, BigInteger qps) - throws InterruptedException, IOException { - System.out.println("==================================================================="); - System.out.println("Start UserAdd test, count " + userCount); - RateLimiter limiter = RateLimiter.create(qps.intValue()); - - long currentSeconds = System.currentTimeMillis() / 1000L; - Integer area = userCount.intValue() / 10; - long startTime = System.currentTimeMillis(); - collector.setTotal(userCount.intValue()); - collector.setStartTimestamp(startTime); - AtomicInteger sendFailed = new AtomicInteger(0); - for (Integer i = 0; i < userCount.intValue(); i++) { - final Integer index = i; - limiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - // generate the user according to currentSeconds - String user = - Long.toHexString(currentSeconds) - + Integer.toHexString(index); - BigInteger amount = new BigInteger("1000000000"); - DagTransferUser dtu = new DagTransferUser(); - dtu.setUser(user); - dtu.setAmount(amount); - ParallelOkCallback callback = - new ParallelOkCallback( - collector, - dagUserInfo, - ParallelOkCallback.ADD_USER_CALLBACK); - callback.setTimeout(0); - callback.setUser(dtu); - try { - callback.recordStartTime(); - parallelOk.set(user, amount, callback); - int current = sended.incrementAndGet(); - - if (current >= area && ((current % area) == 0)) { - long elapsed = System.currentTimeMillis() - startTime; - double sendSpeed = current / ((double) elapsed / 1000); - System.out.println( - "Already sended: " - + current - + "/" - + userCount - + " transactions" - + ",QPS=" - + sendSpeed); - } - - } catch (Exception e) { - logger.warn( - "addUser failed, error info: {}", e.getMessage()); - sendFailed.incrementAndGet(); - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - receipt.setMessage( - "userAdd failed, error info: " + e.getMessage()); - callback.onResponse(receipt); - } - } - }); - } - while (collector.getReceived().intValue() != userCount.intValue()) { - logger.info( - " sendFailed: {}, received: {}, total: {}", - sendFailed.get(), - collector.getReceived().intValue(), - collector.getTotal()); - Thread.sleep(100); - } - dagUserInfo.setContractAddr(parallelOk.getContractAddress()); - dagUserInfo.writeDagTransferUser(); - System.exit(0); - } - - public void queryAccount(BigInteger qps) throws InterruptedException { - final List allUsers = dagUserInfo.getUserList(); - RateLimiter rateLimiter = RateLimiter.create(qps.intValue()); - AtomicInteger sent = new AtomicInteger(0); - for (Integer i = 0; i < allUsers.size(); i++) { - final Integer index = i; - rateLimiter.acquire(); - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - try { - BigInteger result = - parallelOk.balanceOf(allUsers.get(index).getUser()); - allUsers.get(index).setAmount(result); - int all = sent.incrementAndGet(); - if (all >= allUsers.size()) { - System.out.println( - dateFormat.format(new Date()) - + " Query account finished"); - } - } catch (ContractException exception) { - logger.warn( - "queryAccount for {} failed, error info: {}", - allUsers.get(index).getUser(), - exception.getMessage()); - System.exit(0); - } - } - }); - } - while (sent.get() < allUsers.size()) { - Thread.sleep(50); - } - } - - public void userTransfer(BigInteger count, BigInteger qps) - throws InterruptedException, IOException { - System.out.println("Querying account info..."); - queryAccount(qps); - System.out.println("Sending transfer transactions..."); - RateLimiter limiter = RateLimiter.create(qps.intValue()); - int division = count.intValue() / 10; - long startTime = System.currentTimeMillis(); - collector.setStartTimestamp(startTime); - collector.setTotal(count.intValue()); - AtomicInteger sendFailed = new AtomicInteger(0); - for (Integer i = 0; i < count.intValue(); i++) { - limiter.acquire(); - final int index = i; - threadPoolService - .getThreadPool() - .execute( - new Runnable() { - @Override - public void run() { - try { - Random random = new Random(); - int r = random.nextInt(100); - BigInteger amount = BigInteger.valueOf(r); - - ParallelOkCallback callback = - new ParallelOkCallback( - collector, - dagUserInfo, - ParallelOkCallback.TRANS_CALLBACK); - callback.setTimeout(0); - DagTransferUser from = dagUserInfo.getFrom(index); - DagTransferUser to = dagUserInfo.getTo(index); - - callback.setFromUser(from); - callback.setToUser(to); - callback.setAmount(amount); - callback.recordStartTime(); - parallelOk.transfer( - from.getUser(), to.getUser(), amount, callback); - int current = sended.incrementAndGet(); - if (current >= division && ((current % division) == 0)) { - long elapsed = System.currentTimeMillis() - startTime; - double sendSpeed = current / ((double) elapsed / 1000); - System.out.println( - "Already sent: " - + current - + "/" - + count - + " transactions" - + ",QPS=" - + sendSpeed); - } - } catch (Exception e) { - logger.error( - "call transfer failed, error info: {}", - e.getMessage()); - TransactionReceipt receipt = new TransactionReceipt(); - receipt.setStatus("-1"); - receipt.setMessage( - "call transfer failed, error info: " - + e.getMessage()); - collector.onMessage(receipt, Long.valueOf(0)); - sendFailed.incrementAndGet(); - } - } - }); - } - - while (collector.getReceived().intValue() != count.intValue()) { - Thread.sleep(3000); - logger.info( - "userTransfer: sendFailed: {}, received: {}, total: {}", - sendFailed.get(), - collector.getReceived().intValue(), - collector.getTotal()); - } - veryTransferData(qps); - System.exit(0); - } -} diff --git a/sdk-demo/src/test/resources/amop/config-publisher-for-test.toml b/sdk-demo/src/test/resources/amop/config-publisher-for-test.toml deleted file mode 100644 index ceb34741a..000000000 --- a/sdk-demo/src/test/resources/amop/config-publisher-for-test.toml +++ /dev/null @@ -1,44 +0,0 @@ -# This is a config file for amop test - -[cryptoMaterial] -certPath = "conf" -# CA cert file path -# caCert = "conf/ca.crt" -# SSL cert file path -# sslCert = "conf/sdk.crt" -# SSL key file path -# sslKey = "conf/sdk.key" -# enSslCert = "conf/gm/gmensdk.crt" -# enSslKey = "conf/gm/gmensdk.key" - -[network] -# The peer list to connect -peers=["127.0.0.1:20200", "127.0.0.1:20201"] - -# Configure a "need verify AMOP topic" as a topic message sender. -[[amop]] -topicName = "privTopic" -# Public keys of the nodes that you want to send AMOP message of this topic to. -publicKeys = [ "conf/amop/consumer_public_key_1.pem"] - - -[account] -# The directory where the account private key file is placed in -keyStoreDir = "account" -# The account file path(Default load account from keyStoreDir directory when accountFilePath is not configured) -# accountFilePath = "" -# The storage format of the account, support pem and p12, default is pem -accountFileFormat = "pem" -# The address of the account used to send transactions -# When it's empty, use a randomly generated account to send transactions, -# and the randomly generated account information is stored in tmp sub-directory of keyStoreDir -# accountAddress = "" -# The password used to load the account private key file -# password = "" - -[threadPool] -# The size of the thread pool used to process the callback of the channel -channelProcessorThreadSize = "16" -# The size of the thread pool used to process the transaction receipt notification -receiptProcessorThreadSize = "16" - diff --git a/sdk-demo/src/test/resources/amop/config-subscriber-for-test.toml b/sdk-demo/src/test/resources/amop/config-subscriber-for-test.toml deleted file mode 100644 index 1ffd63fdd..000000000 --- a/sdk-demo/src/test/resources/amop/config-subscriber-for-test.toml +++ /dev/null @@ -1,46 +0,0 @@ -# This is a config file for amop test - -[cryptoMaterial] -certPath = "conf" -# CA cert file path -# caCert = "conf/ca.crt" -# SSL cert file path -# sslCert = "conf/sdk.crt" -# SSL key file path -# sslKey = "conf/sdk.key" -# enSslCert = "conf/gm/gmensdk.crt" -# enSslKey = "conf/gm/gmensdk.key" - -[network] -# The peer list to connect -peers=["127.0.0.1:20202", "127.0.0.1:20203"] - -# Configure a private topic as a topic message sender. -[[amop]] -topicName = "privTopic" -# Your private key that used to subscriber verification. -privateKey = "conf/amop/consumer_private_key.p12" -password = "123456" - - -[account] -# The directory where the account private key file is placed in -keyStoreDir = "account" -# The account file path(Default load account from keyStoreDir directory when accountFilePath is not configured) -# accountFilePath = "" -# The storage format of the account, support pem and p12, default is pem -accountFileFormat = "pem" -# The address of the account used to send transactions -# When it's empty, use a randomly generated account to send transactions, -# and the randomly generated account information is stored in tmp sub-directory of keyStoreDir -# accountAddress = "" -# The password used to load the account private key file -# password = "" - - -[threadPool] -# The size of the thread pool used to process the callback of the channel -channelProcessorThreadSize = "16" -# The size of the thread pool used to process the transaction receipt notification -receiptProcessorThreadSize = "16" - diff --git a/sdk-demo/src/test/resources/amop/consumer_private_key.p12 b/sdk-demo/src/test/resources/amop/consumer_private_key.p12 deleted file mode 100644 index 09388e9a7..000000000 Binary files a/sdk-demo/src/test/resources/amop/consumer_private_key.p12 and /dev/null differ diff --git a/sdk-demo/src/test/resources/amop/consumer_public_key_1.pem b/sdk-demo/src/test/resources/amop/consumer_public_key_1.pem deleted file mode 100644 index 0b6ef051e..000000000 --- a/sdk-demo/src/test/resources/amop/consumer_public_key_1.pem +++ /dev/null @@ -1,4 +0,0 @@ ------BEGIN PUBLIC KEY----- -MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAE17ngD1bT95MFNZ+i19sWYCHnMIa9zS56 -KNbtJzReHy3ez4XbdDjoRX/UdO+cTOuJq7fV+mCiLykC7CbcpSrV5Q== ------END PUBLIC KEY----- diff --git a/sdk-demo/src/test/resources/applicationContext-sample.xml b/sdk-demo/src/test/resources/applicationContext-sample.xml deleted file mode 100644 index a4684aec2..000000000 --- a/sdk-demo/src/test/resources/applicationContext-sample.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - 127.0.0.1:20200 - 127.0.0.1:20201 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sdk-demo/src/test/resources/config-example.toml b/sdk-demo/src/test/resources/config-example.toml deleted file mode 100644 index 037bceb5f..000000000 --- a/sdk-demo/src/test/resources/config-example.toml +++ /dev/null @@ -1,54 +0,0 @@ -[cryptoMaterial] - -certPath = "conf" # The certification path - -# The following configurations take the certPath by default if commented -# caCert = "conf/ca.crt" # CA cert file path - # If connect to the GM node, default CA cert path is ${certPath}/gm/gmca.crt - -# sslCert = "conf/sdk.crt" # SSL cert file path - # If connect to the GM node, the default SDK cert path is ${certPath}/gm/gmsdk.crt - -# sslKey = "conf/sdk.key" # SSL key file path - # If connect to the GM node, the default SDK privateKey path is ${certPath}/gm/gmsdk.key - -# enSslCert = "conf/gm/gmensdk.crt" # GM encryption cert file path - # default load the GM SSL encryption cert from ${certPath}/gm/gmensdk.crt - -# enSslKey = "conf/gm/gmensdk.key" # GM ssl cert file path - # default load the GM SSL encryption privateKey from ${certPath}/gm/gmensdk.key - -[network] -peers=["127.0.0.1:20200", "127.0.0.1:20201"] # The peer list to connect - -# Configure a private topic as a topic message sender. -# [[amop]] -# topicName = "PrivateTopic1" -# publicKeys = [ "conf/amop/consumer_public_key_1.pem" ] # Public keys of the nodes that you want to send AMOP message of this topic to. - -# Configure a private topic as a topic subscriber. -# [[amop]] -# topicName = "PrivateTopic2" -# privateKey = "conf/amop/consumer_private_key.p12" # Your private key that used to subscriber verification. -# password = "123456" - -[account] -keyStoreDir = "account" # The directory to load/store the account file, default is "account" -# accountFilePath = "" # The account file path (default load from the path specified by the keyStoreDir) -accountFileFormat = "pem" # The storage format of account file (Default is "pem", "p12" as an option) - -# accountAddress = "" # The transactions sending account address - # Default is a randomly generated account - # The randomly generated account is stored in the path specified by the keyStoreDir - -# password = "" # The password used to load the account file - -[threadPool] -# channelProcessorThreadSize = "16" # The size of the thread pool to process channel callback - # Default is the number of cpu cores - -# receiptProcessorThreadSize = "16" # The size of the thread pool to process transaction receipt notification - # Default is the number of cpu cores - -maxBlockingQueueSize = "102400" # The max blocking queue size of the thread pool - diff --git a/sdk-demo/src/test/resources/log4j.properties b/sdk-demo/src/test/resources/log4j.properties deleted file mode 100644 index 55785c234..000000000 --- a/sdk-demo/src/test/resources/log4j.properties +++ /dev/null @@ -1,32 +0,0 @@ -# -# Copyright 2014-2020 [fisco-dev] -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software distributed under the License -# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express -# or implied. See the License for the specific language governing permissions and limitations under -# the License. -# -# - -### set log levels ### -log4j.rootLogger=DEBUG, file - -### output the log information to the file ### -log4j.appender.file=org.apache.log4j.DailyRollingFileAppender -log4j.appender.file.DatePattern='_'yyyyMMddHH'.log' -log4j.appender.file.File=./log/sdk.log -log4j.appender.file.Append=true -log4j.appender.file.filter.traceFilter=org.apache.log4j.varia.LevelRangeFilter -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=[%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C{1}.%M(%L) | %m%n - -###output the log information to the console ### -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=[%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C{1}.%M(%L) | %m%n diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/Client.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/Client.java index 9ec40c6f6..4f6bd62e9 100644 --- a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/Client.java +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/Client.java @@ -24,6 +24,7 @@ import org.fisco.bcos.sdk.client.protocol.response.BcosBlockHeader; import org.fisco.bcos.sdk.client.protocol.response.BcosTransaction; import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceipt; +import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceiptsDecoder; import org.fisco.bcos.sdk.client.protocol.response.BlockHash; import org.fisco.bcos.sdk.client.protocol.response.BlockNumber; import org.fisco.bcos.sdk.client.protocol.response.Call; @@ -33,6 +34,7 @@ import org.fisco.bcos.sdk.client.protocol.response.GroupList; import org.fisco.bcos.sdk.client.protocol.response.GroupPeers; import org.fisco.bcos.sdk.client.protocol.response.NodeIDList; +import org.fisco.bcos.sdk.client.protocol.response.NodeInfo; import org.fisco.bcos.sdk.client.protocol.response.ObserverList; import org.fisco.bcos.sdk.client.protocol.response.PbftView; import org.fisco.bcos.sdk.client.protocol.response.Peers; @@ -707,6 +709,22 @@ void queryGroupStatusAsync( */ void getPeersAsync(RespCallback callback); + /** + * Peer operation: get node information + * + * @param endpoint the target node that receive the request + * @return node information + */ + NodeInfo getNodeInfo(String endpoint); + + /** + * Peer operation: get node information + * + * @param endpoint the target node that receive the request + * @param callback callback the call back instance + */ + void getNodeInfoAsync(String endpoint, RespCallback callback); + /** * Peer operation: get node ids * @@ -781,6 +799,28 @@ void queryGroupStatusAsync( */ void getNodeVersion(RespCallback callback); + /** + * get receipt list according to the block number and the given range + * + * @param blockNumber the block number of the receipts + * @param from the start index of the receipt list required + * @param count the end index of the receipt list required + * @return the receipt list + */ + BcosTransactionReceiptsDecoder getBatchReceiptsByBlockNumberAndRange( + BigInteger blockNumber, String from, String count); + + /** + * get receipt list according to the block hash and the given range + * + * @param blockHash the block hash of the receipts + * @param from the start index of the receipt list required + * @param count the end index of the receipt list required + * @return the receipt list + */ + BcosTransactionReceiptsDecoder getBatchReceiptsByBlockHashAndRange( + String blockHash, String from, String count); + /** * Peer operation: get consensus status * diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/ClientImpl.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/ClientImpl.java index c2cbc3caa..1f4112e39 100644 --- a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/ClientImpl.java +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/ClientImpl.java @@ -26,6 +26,7 @@ import org.fisco.bcos.sdk.client.protocol.response.BcosBlockHeader; import org.fisco.bcos.sdk.client.protocol.response.BcosTransaction; import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceipt; +import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceiptsDecoder; import org.fisco.bcos.sdk.client.protocol.response.BlockHash; import org.fisco.bcos.sdk.client.protocol.response.BlockNumber; import org.fisco.bcos.sdk.client.protocol.response.Call; @@ -35,6 +36,7 @@ import org.fisco.bcos.sdk.client.protocol.response.GroupList; import org.fisco.bcos.sdk.client.protocol.response.GroupPeers; import org.fisco.bcos.sdk.client.protocol.response.NodeIDList; +import org.fisco.bcos.sdk.client.protocol.response.NodeInfo; import org.fisco.bcos.sdk.client.protocol.response.ObserverList; import org.fisco.bcos.sdk.client.protocol.response.PbftView; import org.fisco.bcos.sdk.client.protocol.response.Peers; @@ -743,6 +745,23 @@ public void getPeersAsync(RespCallback callback) { callback); } + @Override + public NodeInfo getNodeInfo(String endpoint) { + return this.jsonRpcService.sendRequestToPeer( + new JsonRpcRequest(JsonRpcMethods.GET_NODE_INFO, Arrays.asList()), + endpoint, + NodeInfo.class); + } + + @Override + public void getNodeInfoAsync(String endpoint, RespCallback callback) { + this.jsonRpcService.asyncSendRequestToPeer( + new JsonRpcRequest(JsonRpcMethods.GET_NODE_INFO, Arrays.asList()), + endpoint, + NodeInfo.class, + callback); + } + @Override public NodeIDList getNodeIDList() { return this.jsonRpcService.sendRequestToGroup( @@ -976,6 +995,27 @@ public TransactionReceipt sendRawTransactionAndGetReceiptWithProof( return callback.receipt; } + @Override + public BcosTransactionReceiptsDecoder getBatchReceiptsByBlockNumberAndRange( + BigInteger blockNumber, String from, String count) { + return this.jsonRpcService.sendRequestToGroup( + new JsonRpcRequest( + JsonRpcMethods.GET_BATCH_RECEIPT_BY_BLOCK_NUMBER_AND_RANGE, + Arrays.asList( + this.groupId, String.valueOf(blockNumber), from, count, true)), + BcosTransactionReceiptsDecoder.class); + } + + @Override + public BcosTransactionReceiptsDecoder getBatchReceiptsByBlockHashAndRange( + String blockHash, String from, String count) { + return this.jsonRpcService.sendRequestToGroup( + new JsonRpcRequest( + JsonRpcMethods.GET_BATCH_RECEIPT_BY_BLOCK_HASH_AND_RANGE, + Arrays.asList(this.groupId, blockHash, from, count, true)), + BcosTransactionReceiptsDecoder.class); + } + @Override public EventResource getEventResource() { return eventResource; diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/model/JsonTransactionResponse.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/model/JsonTransactionResponse.java index 02f4a3155..c0e52ee98 100644 --- a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/model/JsonTransactionResponse.java +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/model/JsonTransactionResponse.java @@ -15,10 +15,27 @@ package org.fisco.bcos.sdk.client.protocol.model; import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; +import org.fisco.bcos.sdk.client.exceptions.ClientException; +import org.fisco.bcos.sdk.crypto.CryptoSuite; +import org.fisco.bcos.sdk.crypto.signature.ECDSASignatureResult; +import org.fisco.bcos.sdk.crypto.signature.SM2SignatureResult; +import org.fisco.bcos.sdk.crypto.signature.SignatureResult; +import org.fisco.bcos.sdk.model.CryptoType; +import org.fisco.bcos.sdk.rlp.RlpEncoder; +import org.fisco.bcos.sdk.rlp.RlpList; +import org.fisco.bcos.sdk.rlp.RlpString; +import org.fisco.bcos.sdk.rlp.RlpType; +import org.fisco.bcos.sdk.utils.Hex; import org.fisco.bcos.sdk.utils.Numeric; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class JsonTransactionResponse { + private static Logger logger = LoggerFactory.getLogger(JsonTransactionResponse.class); + // the fields related to get-transaction private String blockHash; private String blockNumber; @@ -30,9 +47,89 @@ public class JsonTransactionResponse { private String to; private String transactionIndex; private String value; - - // the fields related to get-block private String gasPrice; + private String blockLimit; + private String chainId; + private String groupId; + private String extraData; + private SignatureResponse signature; + + public JsonTransactionResponse() {} + + public static class SignatureResponse { + private String r; + private String s; + private String v; + private String signature; + + public SignatureResponse() {} + + public String getR() { + return r; + } + + public void setR(String r) { + this.r = r; + } + + public String getS() { + return s; + } + + public void setS(String s) { + this.s = s; + } + + public String getV() { + return v; + } + + public void setV(String v) { + this.v = v; + } + + public String getSignature() { + return signature; + } + + public void setSignature(String signature) { + this.signature = signature; + } + + @Override + public String toString() { + return "{" + + "r='" + + r + + '\'' + + ", s='" + + s + + '\'' + + ", v='" + + v + + '\'' + + ", signature='" + + signature + + '\'' + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SignatureResponse that = (SignatureResponse) o; + return Objects.equals(r, that.r) + && Objects.equals(s, that.s) + && Objects.equals(v, that.v) + && Objects.equals(signature, that.signature); + } + + @Override + public int hashCode() { + return Objects.hash(r, s, v, signature); + } + } public String getBlockHash() { return blockHash; @@ -122,6 +219,117 @@ public void setGasPrice(String gasPrice) { this.gasPrice = gasPrice; } + public String getBlockLimit() { + return blockLimit; + } + + public void setBlockLimit(String blockLimit) { + this.blockLimit = blockLimit; + } + + public String getChainId() { + return chainId; + } + + public void setChainId(String chainId) { + this.chainId = chainId; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public String getExtraData() { + return extraData; + } + + public void setExtraData(String extraData) { + this.extraData = extraData; + } + + public SignatureResponse getSignature() { + return signature; + } + + public void setSignature(SignatureResponse signature) { + this.signature = signature; + } + + private List encodeTransactionResponse(CryptoSuite cryptoSuite) + throws ClientException { + if (blockLimit == null + || chainId == null + || groupId == null + || extraData == null + || signature == null) { + throw new ClientException( + "calculate hash for the transaction failed for missing fields! Please make sure FISCO BCOS version >= v2.7.0"); + } + List result = new ArrayList<>(); + // nonce + result.add(RlpString.create(Numeric.decodeQuantity(nonce))); + // gasPrice + result.add(RlpString.create(Numeric.decodeQuantity(gasPrice))); + // gas + result.add(RlpString.create(Numeric.decodeQuantity(gas))); + // blockLimit + result.add(RlpString.create(Numeric.decodeQuantity(blockLimit))); + // to + result.add(RlpString.create(Numeric.hexStringToByteArray(to))); + // value + result.add(RlpString.create(Numeric.decodeQuantity(value))); + // input + result.add(RlpString.create(Numeric.hexStringToByteArray(input))); + // chainId + result.add(RlpString.create(Numeric.decodeQuantity(chainId))); + // groupId + result.add(RlpString.create(Numeric.decodeQuantity(groupId))); + // extraData + if (extraData.equals("0x")) { + result.add(RlpString.create("")); + } else { + result.add(RlpString.create(Numeric.hexStringToByteArray(extraData))); + } + int startIndex = 0; + if (signature.getSignature().startsWith("0x")) { + startIndex = 2; + } + // signature + SignatureResult signatureResult; + if (cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE) { + signatureResult = + new ECDSASignatureResult(signature.getSignature().substring(startIndex)); + } else { + signatureResult = + new SM2SignatureResult( + signature.getV(), signature.getSignature().substring(startIndex)); + } + result.addAll(signatureResult.encode()); + return result; + } + + // calculate the hash for the transaction + public String calculateHash(CryptoSuite cryptoSuite) throws ClientException { + try { + List encodedTransaction = encodeTransactionResponse(cryptoSuite); + RlpList rlpList = new RlpList(encodedTransaction); + return "0x" + Hex.toHexString(cryptoSuite.hash(RlpEncoder.encode(rlpList))); + } catch (Exception e) { + logger.warn( + "calculate hash for the transaction failed, blockHash: {}, blockNumber: {}, transactionHash: {}, error info: {}", + blockHash, + blockNumber, + hash, + e); + throw new ClientException( + "calculate hash for transaction " + hash + " failed for " + e.getMessage(), e); + } + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -139,7 +347,12 @@ public boolean equals(Object o) { && Objects.equals(to, that.to) && Objects.equals(transactionIndex, that.transactionIndex) && Objects.equals(value, that.value) - && Objects.equals(gasPrice, that.gasPrice); + && Objects.equals(gasPrice, that.gasPrice) + && Objects.equals(blockLimit, that.blockLimit) + && Objects.equals(chainId, that.chainId) + && Objects.equals(groupId, that.groupId) + && Objects.equals(extraData, that.extraData) + && Objects.equals(signature, that.signature); } @Override @@ -155,12 +368,17 @@ public int hashCode() { to, transactionIndex, value, - gasPrice); + gasPrice, + blockLimit, + chainId, + groupId, + extraData, + signature); } @Override public String toString() { - return "Transaction {" + return "{" + "blockHash='" + blockHash + '\'' @@ -194,6 +412,20 @@ public String toString() { + ", gasPrice='" + gasPrice + '\'' + + ", blockLimit='" + + blockLimit + + '\'' + + ", chainId='" + + chainId + + '\'' + + ", groupId='" + + groupId + + '\'' + + ", extraData='" + + extraData + + '\'' + + ", signature=" + + signature + '}'; } } diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/request/JsonRpcMethods.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/request/JsonRpcMethods.java index 999e74f60..1a2796298 100644 --- a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/request/JsonRpcMethods.java +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/request/JsonRpcMethods.java @@ -50,6 +50,7 @@ public class JsonRpcMethods { // the interface related to the node public static final String GET_CLIENT_VERSION = "getClientVersion"; + public static final String GET_NODE_INFO = "getNodeInfo"; public static final String GET_PEERS = "getPeers"; public static final String GET_GROUP_LIST = "getGroupList"; public static final String GET_NODEIDLIST = "getNodeIDList"; @@ -62,5 +63,10 @@ public class JsonRpcMethods { public static final String RECOVER_GROUP = "recoverGroup"; public static final String QUERY_GROUP_STATUS = "queryGroupStatus"; + public static final String GET_BATCH_RECEIPT_BY_BLOCK_NUMBER_AND_RANGE = + "getBatchReceiptsByBlockNumberAndRange"; + public static final String GET_BATCH_RECEIPT_BY_BLOCK_HASH_AND_RANGE = + "getBatchReceiptsByBlockHashAndRange"; + private JsonRpcMethods() {} } diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlock.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlock.java index db8bd9a5c..c617c7989 100644 --- a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlock.java +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlock.java @@ -118,7 +118,7 @@ public int hashCode() { @Override public String toString() { - return "Block{" + return "{" + "transactions=" + transactions + ", number='" diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlockHeader.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlockHeader.java index 7cecba883..0e9564f52 100644 --- a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlockHeader.java +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosBlockHeader.java @@ -16,12 +16,23 @@ package org.fisco.bcos.sdk.client.protocol.response; import java.math.BigInteger; +import java.util.ArrayList; import java.util.List; import java.util.Objects; +import org.fisco.bcos.sdk.client.exceptions.ClientException; +import org.fisco.bcos.sdk.crypto.CryptoSuite; import org.fisco.bcos.sdk.model.JsonRpcResponse; +import org.fisco.bcos.sdk.rlp.RlpEncoder; +import org.fisco.bcos.sdk.rlp.RlpList; +import org.fisco.bcos.sdk.rlp.RlpString; +import org.fisco.bcos.sdk.rlp.RlpType; +import org.fisco.bcos.sdk.utils.Hex; import org.fisco.bcos.sdk.utils.Numeric; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class BcosBlockHeader extends JsonRpcResponse { + private static Logger logger = LoggerFactory.getLogger(BcosBlockHeader.class); @Override public void setResult(BlockHeader result) { @@ -70,14 +81,7 @@ public int hashCode() { @Override public String toString() { - return "Signature{" - + "index='" - + index - + '\'' - + ", signature='" - + signature - + '\'' - + '}'; + return "{" + "index='" + index + '\'' + ", signature='" + signature + '\'' + '}'; } } @@ -218,6 +222,54 @@ public String getTimestamp() { return timestamp; } + private byte[] encodeBlockHeader() { + List encodedRlp = new ArrayList<>(); + encodedRlp.add(RlpString.create(Numeric.hexStringToByteArray(parentHash))); + encodedRlp.add(RlpString.create(Numeric.hexStringToByteArray(stateRoot))); + encodedRlp.add(RlpString.create(Numeric.hexStringToByteArray(transactionsRoot))); + encodedRlp.add(RlpString.create(Numeric.hexStringToByteArray(receiptsRoot))); + encodedRlp.add(RlpString.create(Numeric.hexStringToByteArray(dbHash))); + encodedRlp.add(RlpString.create(Numeric.hexStringToByteArray(logsBloom))); + encodedRlp.add(RlpString.create(Numeric.decodeQuantity(number))); + encodedRlp.add(RlpString.create(Numeric.decodeQuantity(gasLimit))); + encodedRlp.add(RlpString.create(Numeric.decodeQuantity(gasUsed))); + encodedRlp.add(RlpString.create(Numeric.decodeQuantity(timestamp))); + + List extraDataRlp = new ArrayList<>(); + for (String data : extraData) { + extraDataRlp.add(RlpString.create(Numeric.hexStringToByteArray(data))); + } + encodedRlp.add(new RlpList(extraDataRlp)); + encodedRlp.add(RlpString.create(Numeric.decodeQuantity(sealer))); + List sealerListRlp = new ArrayList<>(); + for (String sealerString : sealerList) { + sealerListRlp.add(RlpString.create(Numeric.hexStringToByteArray(sealerString))); + } + encodedRlp.add(new RlpList(sealerListRlp)); + RlpList rlpList = new RlpList(encodedRlp); + return RlpEncoder.encode(rlpList); + } + + // calculate hash for the block or the block header + public String calculateHash(CryptoSuite cryptoSuite) { + try { + byte[] hash = cryptoSuite.hash(encodeBlockHeader()); + return "0x" + Hex.toHexString(hash); + } catch (Exception e) { + logger.warn( + "calculateHash for the block failed, blockNumber: {}, blockHash: {}, error info: {}", + hash, + number, + e.getMessage()); + throw new ClientException( + "calculateHash for block " + + hash + + " failed, error info: " + + e.getMessage(), + e); + } + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosTransactionReceiptsDecoder.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosTransactionReceiptsDecoder.java new file mode 100644 index 000000000..025edc37c --- /dev/null +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosTransactionReceiptsDecoder.java @@ -0,0 +1,45 @@ +/* + * Copyright 2014-2020 [fisco-dev] + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + */ + +package org.fisco.bcos.sdk.client.protocol.response; + +import java.io.IOException; +import java.util.Base64; +import java.util.zip.DataFormatException; +import org.fisco.bcos.sdk.client.exceptions.ClientException; +import org.fisco.bcos.sdk.model.DataCompress; +import org.fisco.bcos.sdk.model.JsonRpcResponse; +import org.fisco.bcos.sdk.utils.ObjectMapperFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BcosTransactionReceiptsDecoder extends JsonRpcResponse { + private static Logger logger = LoggerFactory.getLogger(BcosTransactionReceiptsDecoder.class); + + public BcosTransactionReceiptsInfo.TransactionReceiptsInfo decodeTransactionReceiptsInfo() + throws ClientException { + try { + String encodedData = getResult(); + // decode the data with base64 + byte[] compressedData = Base64.getDecoder().decode(encodedData); + // uncompress the compressed data + byte[] jsonData = DataCompress.uncompress(compressedData); + return ObjectMapperFactory.getObjectMapper() + .readValue(jsonData, BcosTransactionReceiptsInfo.TransactionReceiptsInfo.class); + } catch (IOException | DataFormatException e) { + throw new ClientException("decode receipts failed, error info:" + e.getMessage(), e); + } + } +} diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosTransactionReceiptsInfo.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosTransactionReceiptsInfo.java new file mode 100644 index 000000000..3ac4525c3 --- /dev/null +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/BcosTransactionReceiptsInfo.java @@ -0,0 +1,115 @@ +/* + * Copyright 2014-2020 [fisco-dev] + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + */ + +package org.fisco.bcos.sdk.client.protocol.response; + +import java.util.List; +import org.fisco.bcos.sdk.model.JsonRpcResponse; +import org.fisco.bcos.sdk.model.TransactionReceipt; + +public class BcosTransactionReceiptsInfo + extends JsonRpcResponse { + public TransactionReceiptsInfo getTransactionReceiptsInfo() { + return getResult(); + } + + public static class BlockInfo { + private String receiptRoot; + private String blockNumber; + private String blockHash; + private String receiptsCount; + + public String getReceiptRoot() { + return receiptRoot; + } + + public void setReceiptRoot(String receiptRoot) { + this.receiptRoot = receiptRoot; + } + + public String getBlockNumber() { + return blockNumber; + } + + public void setBlockNumber(String blockNumber) { + this.blockNumber = blockNumber; + } + + public String getBlockHash() { + return blockHash; + } + + public void setBlockHash(String blockHash) { + this.blockHash = blockHash; + } + + public String getReceiptsCount() { + return receiptsCount; + } + + public void setReceiptsCount(String receiptsCount) { + this.receiptsCount = receiptsCount; + } + + @Override + public String toString() { + return "BlockInfo{" + + "receiptRoot='" + + receiptRoot + + '\'' + + ", blockNumber='" + + blockNumber + + '\'' + + ", blockHash='" + + blockHash + + '\'' + + ", receiptsCount='" + + receiptsCount + + '\'' + + '}'; + } + } + + public static class TransactionReceiptsInfo { + private BlockInfo blockInfo; + private List transactionReceipts; + + public BlockInfo getBlockInfo() { + return blockInfo; + } + + public void setBlockInfo(BlockInfo blockInfo) { + this.blockInfo = blockInfo; + } + + public List getTransactionReceipts() { + return transactionReceipts; + } + + public void setTransactionReceipts(List transactionReceipts) { + this.transactionReceipts = transactionReceipts; + } + + @Override + public String toString() { + return "TransactionReceiptsInfo{" + + "blockInfo=" + + blockInfo + + ", transactionReceipts=" + + transactionReceipts + + '}'; + } + } +} diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/NodeInfo.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/NodeInfo.java new file mode 100644 index 000000000..46401e194 --- /dev/null +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/NodeInfo.java @@ -0,0 +1,107 @@ +package org.fisco.bcos.sdk.client.protocol.response; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Objects; +import org.fisco.bcos.sdk.model.JsonRpcResponse; + +public class NodeInfo extends JsonRpcResponse { + public NodeInfo.NodeInformation getNodeInfo() { + return getResult(); + } + + public static class NodeInformation { + @JsonProperty("NodeID") + private String nodeID; + + @JsonProperty("IPAndPort") + private String ipAndPort; + + @JsonProperty("Agency") + private String agency; + + @JsonProperty("Node") + private String node; + + @JsonProperty("Topic") + private List topic; + + public String getNodeID() { + return nodeID; + } + + public void setNodeID(String nodeID) { + this.nodeID = nodeID; + } + + public String getIpAndPort() { + return ipAndPort; + } + + public void setIpAndPort(String ipAndPort) { + this.ipAndPort = ipAndPort; + } + + public String getAgency() { + return agency; + } + + public void setAgency(String agency) { + this.agency = agency; + } + + public String getNode() { + return node; + } + + public void setNode(String node) { + this.node = node; + } + + public List getTopic() { + return topic; + } + + public void setTopic(List topic) { + this.topic = topic; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NodeInformation that = (NodeInformation) o; + return Objects.equals(nodeID, that.nodeID) + && Objects.equals(node, that.node) + && Objects.equals(agency, that.agency) + && Objects.equals(ipAndPort, that.ipAndPort) + && Objects.equals(topic, that.topic); + } + + @Override + public int hashCode() { + return Objects.hash(node, nodeID, agency, ipAndPort, topic); + } + + @Override + public String toString() { + return "NodeInfo{" + + "nodeId='" + + nodeID + + '\'' + + ", iPAndPort='" + + ipAndPort + + '\'' + + ", node='" + + node + + '\'' + + ", agency='" + + agency + + '\'' + + ", topic='" + + topic + + '\'' + + '}'; + } + } +} diff --git a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/Peers.java b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/Peers.java index a342f7fe9..130c77678 100644 --- a/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/Peers.java +++ b/sdk-service/src/main/java/org/fisco/bcos/sdk/client/protocol/response/Peers.java @@ -105,16 +105,17 @@ public String toString() { + "nodeID='" + nodeID + '\'' - + ", ipAndPort='" + + ", iPAndPort='" + ipAndPort + '\'' + + ", node='" + + node + + '\'' + ", agency='" + agency + '\'' - + ", topic=" + + ", topic='" + topic - + ", node='" - + node + '\'' + '}'; } diff --git a/sdk-service/src/test/java/org/fisco/bcos/sdk/client/ResponseTest.java b/sdk-service/src/test/java/org/fisco/bcos/sdk/client/ResponseTest.java index d631989a7..390dcf7c0 100644 --- a/sdk-service/src/test/java/org/fisco/bcos/sdk/client/ResponseTest.java +++ b/sdk-service/src/test/java/org/fisco/bcos/sdk/client/ResponseTest.java @@ -13,6 +13,7 @@ */ package org.fisco.bcos.sdk.test.client; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; @@ -27,6 +28,8 @@ import org.fisco.bcos.sdk.client.protocol.response.BcosBlockHeader; import org.fisco.bcos.sdk.client.protocol.response.BcosTransaction; import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceipt; +import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceiptsDecoder; +import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceiptsInfo; import org.fisco.bcos.sdk.client.protocol.response.BlockHash; import org.fisco.bcos.sdk.client.protocol.response.BlockNumber; import org.fisco.bcos.sdk.client.protocol.response.Call; @@ -51,7 +54,10 @@ import org.fisco.bcos.sdk.client.protocol.response.TotalTransactionCount; import org.fisco.bcos.sdk.client.protocol.response.TransactionReceiptWithProof; import org.fisco.bcos.sdk.client.protocol.response.TransactionWithProof; +import org.fisco.bcos.sdk.crypto.CryptoSuite; +import org.fisco.bcos.sdk.model.CryptoType; import org.fisco.bcos.sdk.model.NodeVersion; +import org.fisco.bcos.sdk.model.TransactionReceipt; import org.fisco.bcos.sdk.utils.ObjectMapperFactory; import org.junit.Assert; import org.junit.Test; @@ -1412,5 +1418,239 @@ public void testTransactionWithProof() throws IOException { .getTransactionIndex()); Assert.assertEquals( "0x0", transactionWithProof.getTransactionWithProof().getTransaction().getValue()); + + } + + @Test + public void testSMGetTransactionAndCalculateHash() throws IOException { + String transactionString = "{\n" + + " \"id\": 1,\n" + + " \"jsonrpc\": \"2.0\",\n" + + " \"result\": {\n" + + " \"blockHash\": \"0x2ff860cf49b95f721398b78a128617bf62ab03e09002895c4926f7be990615f1\",\n" + + " \"blockLimit\": \"0x38e\",\n" + + " \"blockNumber\": \"0x19b\",\n" + + " \"chainId\": \"0x1\",\n" + + " \"extraData\": \"0x\",\n" + + " \"from\": \"0x37e6cd2081a11c345fac93eaff0ca9ef66f27451\",\n" + + " \"gas\": \"0x419ce0\",\n" + + " \"gasPrice\": \"0x51f4d5c00\",\n" + + " \"groupId\": \"0x1\",\n" + + " \"hash\": \"0x880ee49599e731086d44d268239bce2e36a1b1032329bcd3f194b2e86297caf4\",\n" + + " \"input\": \"0x3590b49f0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c48656c6c6f2c20464953434f0000000000000000000000000000000000000000\",\n" + + " \"nonce\": \"0x22cbceaa80e80cf1aa6c719b659601f2ae6ed68d549c537be57b44bc7668405\",\n" + + " \"signature\": {\n" + + " \"r\": \"0xcc108436f41e5ee91491f5e91bd72f1bdc43f6169d2b72bf96c7cf6f32702540\",\n" + + " \"s\": \"0x94eec76fe9d7902a9d328ec169329820914b7720d675c657356fd68f4758108f\",\n" + + " \"signature\": \"0xcc108436f41e5ee91491f5e91bd72f1bdc43f6169d2b72bf96c7cf6f3270254094eec76fe9d7902a9d328ec169329820914b7720d675c657356fd68f4758108f6feaf705e8b16de494b4fec3ec3176e38b1eaa416605f4bb5c141c2a22434580f03b8257b29213bdc059c9b3673a7c3868df55eb1b85c2abc22aae64e4d9cac6\",\n" + + " \"v\": \"0x6feaf705e8b16de494b4fec3ec3176e38b1eaa416605f4bb5c141c2a22434580f03b8257b29213bdc059c9b3673a7c3868df55eb1b85c2abc22aae64e4d9cac6\"\n" + + " },\n" + + " \"to\": \"0x0000000000000000000000000000000000000000\",\n" + + " \"transactionIndex\": \"0x0\",\n" + + " \"value\": \"0x0\"\n" + + " }\n" + + "}"; + + BcosTransaction bcosTransaction = objectMapper.readValue(transactionString.getBytes(), BcosTransaction.class); + CryptoSuite cryptoSuite = new CryptoSuite(CryptoType.SM_TYPE); + Assert.assertEquals( + bcosTransaction.getTransaction().get().calculateHash(cryptoSuite), + bcosTransaction.getTransaction().get().getHash()); + } + @Test + public void testSMGetBlockAndCalculateHash() throws IOException { + String blockHeaderStr = "{\n" + + " \"id\": 1,\n" + + " \"jsonrpc\": \"2.0\",\n" + + " \"result\": {\n" + + " \"dbHash\": \"0x68a77b2364be2f3197bce9ca265a5405ed77904237d8e31dbacfe9e1d3119f77\",\n" + + " \"extraData\": [],\n" + + " \"gasLimit\": \"0x0\",\n" + + " \"gasUsed\": \"0x0\",\n" + + " \"hash\": \"0xc5360efd06024b02340eb2afa283fe022f57791e888f22366b77d6218a247a13\",\n" + + " \"logsBloom\": \"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\n" + + " \"number\": 1,\n" + + " \"parentHash\": \"0x7e1b0fc3efa8026f282bfa994d3a79305542d5ad3ea65b84a8d72b152f15dfb1\",\n" + + " \"receiptsRoot\": \"0xd748b478e6b8f90e049f7a4a9d2b9acf76624baed8c2abe0e868b33cd5e989e5\",\n" + + " \"sealer\": \"0x3\",\n" + + " \"sealerList\": [\n" + + " \"1daca8140ba483b560d1b3b8905ca07f447b305875a4f9c6cb2a826c9315ef10bc87a7e135d0a34f605f3a95ff5d9a8c83f2ac5f070c6fe740400910813110a2\",\n" + + " \"2e6ddeb52fcdb0f0287c8b6bbe407f4a3a52bc1b04ea5b978ab698ac1802eb5db482ec1681b1d1d8d1a5e99143a7cde2b85fe29bbe6538066507a91fc8e5ecc6\",\n" + + " \"4905b78b643c19c03e7b8e6779fca2a3e917baa317e8d2abde6daec543d375ac5052aeda22fda7e174c780e04afd215f965237a809e814369a05bb90b965a6ed\",\n" + + " \"86f731c15ca2f44925fea7f379ca32a55245fb988228305c7625d4a174a186fc4472d4668053c7fe4c8608562cf2fb8fea1ab5ea4c96b9be01949b565ec36c9e\"\n" + + " ],\n" + + " \"signatureList\": [\n" + + " {\n" + + " \"index\": \"0x0\",\n" + + " \"signature\": \"0xa99fcb5298a5dd39644af81b2c3ebd9839ffa9f2cb65c6c8b9f2b84b8804c93cf836cb45059cdefe8767ea922e0141318da7ffcc6d0d9db2b0cfa23638bc86591daca8140ba483b560d1b3b8905ca07f447b305875a4f9c6cb2a826c9315ef10bc87a7e135d0a34f605f3a95ff5d9a8c83f2ac5f070c6fe740400910813110a2\"\n" + + " },\n" + + " {\n" + + " \"index\": \"0x3\",\n" + + " \"signature\": \"0x1addc8032fbca41e31afb429dd2f749653492684fcc7845acb4558d5b09095a311a2d965c2a59133b497cb2553c23f29c6613ca0d312acb4f9fd93df602936f686f731c15ca2f44925fea7f379ca32a55245fb988228305c7625d4a174a186fc4472d4668053c7fe4c8608562cf2fb8fea1ab5ea4c96b9be01949b565ec36c9e\"\n" + + " },\n" + + " {\n" + + " \"index\": \"0x1\",\n" + + " \"signature\": \"0xd2831bc1b60ce6a0bf71bd89d312b57ef9ad211b4efea3f8bfd38387998d547f5db59ce870a65d16d98a344c85ce0f2e22d371ce455eef0a8c9566f5fa7f71ec2e6ddeb52fcdb0f0287c8b6bbe407f4a3a52bc1b04ea5b978ab698ac1802eb5db482ec1681b1d1d8d1a5e99143a7cde2b85fe29bbe6538066507a91fc8e5ecc6\"\n" + + " }\n" + + " ],\n" + + " \"stateRoot\": \"0x68a77b2364be2f3197bce9ca265a5405ed77904237d8e31dbacfe9e1d3119f77\",\n" + + " \"timestamp\": \"0x174ce4a8931\",\n" + + " \"transactionsRoot\": \"0x60368d2fde59f678e096418d521b53fce8355fb8bca1448d4bb6f5209376e7fc\"\n" + + " }\n" + + "}"; + + BcosBlockHeader bcosBlockHeader = objectMapper.readValue(blockHeaderStr.getBytes(), BcosBlockHeader.class); + CryptoSuite cryptoSuite = new CryptoSuite(CryptoType.SM_TYPE); + Assert.assertEquals( + bcosBlockHeader.getBlockHeader().calculateHash(cryptoSuite), + bcosBlockHeader.getBlockHeader().getHash()); + } + + @Test + public void testECDSAGetTransactionAndCalculateHash() throws IOException { + String transactionStr = "{\n" + + " \"id\": 1,\n" + + " \"jsonrpc\": \"2.0\",\n" + + " \"result\": {\n" + + " \"blockHash\": \"0xed79502afaf87734f5bc75c2b50d340adc83128afed9dc626a4f5a3cfed837a7\",\n" + + " \"blockLimit\": \"0x100\",\n" + + " \"blockNumber\": \"0x1\",\n" + + " \"chainId\": \"0x1\",\n" + + " \"extraData\": \"0x\",\n" + + " \"from\": \"0xfb257558db8f24ee1c2799df7cc68051fc8d27f7\",\n" + + " \"gas\": \"0x2faf080\",\n" + + " \"gasPrice\": \"0xa\",\n" + + " \"groupId\": \"0x1\",\n" + + " \"hash\": \"0xd8a34a32b86e049fb5e1c0ce89a2a96c34f0c54e622e10abf20d0a0f15bb98cf\",\n" + + " \"input\": \"0x4ed3885e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000a464953434f2042434f5300000000000000000000000000000000000000000000\",\n" + + " \"nonce\": \"0x3eb675ec791c2d19858c91d0046821c27d815e2e9c151601203592000016309\",\n" + + " \"signature\": {\n" + + " \"r\": \"0x9edf7c0cb63645442aff11323916d51ec5440de979950747c0189f338afdcefd\",\n" + + " \"s\": \"0x2f3473184513c6a3516e066ea98b7cfb55a79481c9db98e658dd016c37f03dcf\",\n" + + " \"signature\": \"0x9edf7c0cb63645442aff11323916d51ec5440de979950747c0189f338afdcefd2f3473184513c6a3516e066ea98b7cfb55a79481c9db98e658dd016c37f03dcf00\",\n" + + " \"v\": \"0x0\"\n" + + " },\n" + + " \"to\": \"0x8c17cf316c1063ab6c89df875e96c9f0f5b2f744\",\n" + + " \"transactionIndex\": \"0x0\",\n" + + " \"value\": \"0x0\"\n" + + " }\n" + + "}"; + BcosTransaction bcosTransaction = objectMapper.readValue(transactionStr.getBytes(), BcosTransaction.class); + CryptoSuite cryptoSuite = new CryptoSuite(CryptoType.ECDSA_TYPE); + Assert.assertEquals( + bcosTransaction.getTransaction().get().calculateHash(cryptoSuite), + "0xd8a34a32b86e049fb5e1c0ce89a2a96c34f0c54e622e10abf20d0a0f15bb98cf"); + } + + @Test + public void testECDSAGetBlockAndCalculateHash() throws IOException { + String blockHeaderStr = "{\n" + + " \"id\": 1,\n" + + " \"jsonrpc\": \"2.0\",\n" + + " \"result\": {\n" + + " \"dbHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n" + + " \"extraData\": [],\n" + + " \"gasLimit\": \"0x0\",\n" + + " \"gasUsed\": \"0x0\",\n" + + " \"hash\": \"0xed79502afaf87734f5bc75c2b50d340adc83128afed9dc626a4f5a3cfed837a7\",\n" + + " \"logsBloom\": \"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\n" + + " \"number\": 1,\n" + + " \"parentHash\": \"0x4f6394763c33c1709e5a72b202ad4d7a3b8152de3dc698cef6f675ecdaf20a3b\",\n" + + " \"receiptsRoot\": \"0x69a04fa6073e4fc0947bac7ee6990e788d1e2c5ec0fe6c2436d0892e7f3c09d2\",\n" + + " \"sealer\": \"0x3\",\n" + + " \"sealerList\": [\n" + + " \"11e1be251ca08bb44f36fdeedfaeca40894ff80dfd80084607a75509edeaf2a9c6fee914f1e9efda571611cf4575a1577957edfd2baa9386bd63eb034868625f\",\n" + + " \"78a313b426c3de3267d72b53c044fa9fe70c2a27a00af7fea4a549a7d65210ed90512fc92b6194c14766366d434235c794289d66deff0796f15228e0e14a9191\",\n" + + " \"95b7ff064f91de76598f90bc059bec1834f0d9eeb0d05e1086d49af1f9c2f321062d011ee8b0df7644bd54c4f9ca3d8515a3129bbb9d0df8287c9fa69552887e\",\n" + + " \"b8acb51b9fe84f88d670646be36f31c52e67544ce56faf3dc8ea4cf1b0ebff0864c6b218fdcd9cf9891ebd414a995847911bd26a770f429300085f37e1131f36\"\n" + + " ],\n" + + " \"signatureList\": [\n" + + " {\n" + + " \"index\": \"0x0\",\n" + + " \"signature\": \"0x8c274e08c1b86b363634266a9c474a261313ec19ad28bd029465143e9708ef4e74844b6d3e4b1192e290548efe27639398917dfc42195fc81509aa995179895501\"\n" + + " },\n" + + " {\n" + + " \"index\": \"0x1\",\n" + + " \"signature\": \"0x2f25b3cae930b15963745b75bcd12f25837bca336e63f9039e531a505dd85f212b74da6a6530c87052bc8a54d49ee1baae480d32b8b2283cc0b5474f8dd1835400\"\n" + + " },\n" + + " {\n" + + " \"index\": \"0x3\",\n" + + " \"signature\": \"0x97bc872a3beb48d0c373a6a3368ce23086c1c070f29137978f5ac3803b5ef5dc7f9d0d2a377be5995b89a37bc0ccb6cced8a1fcf29b808d7073c2afe819b3be101\"\n" + + " }\n" + + " ],\n" + + " \"stateRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n" + + " \"timestamp\": \"0x174cf2bdede\",\n" + + " \"transactionsRoot\": \"0xab7114f4e2930d02852e1578c0a845328e8b69fa8413000d8570483d272937a8\"\n" + + " }\n" + + "}"; + BcosBlockHeader bcosBlockHeader = objectMapper.readValue(blockHeaderStr.getBytes(), BcosBlockHeader.class); + CryptoSuite cryptoSuite = new CryptoSuite(CryptoType.ECDSA_TYPE); + Assert.assertEquals( + bcosBlockHeader.getBlockHeader().calculateHash(cryptoSuite), + "0xed79502afaf87734f5bc75c2b50d340adc83128afed9dc626a4f5a3cfed837a7"); + } + + @Test + public void testCompressedBatchReceipts() throws IOException { + String receiptListStr = "{\n" + + " \"id\": 1,\n" + + " \"jsonrpc\": \"2.0\",\n" + + " \"result\": {\n" + + " \"blockInfo\": {\n" + + " \"blockHash\": \"0x9a3c01559f63f17739db7159ebe945da0105f15144c97cc0a18e5389f07a9fdb\",\n" + + " \"blockNumber\": \"0x1\",\n" + + " \"receiptRoot\": \"0x1e9ee115d0a0ed6a248f5a711e5e8a2f93c82b8d70922254efcec2b4bbd9d174\",\n" + + " \"receiptsCount\": \"0x1\"\n" + + " },\n" + + " \"transactionReceipts\": [\n" + + " {\n" + + " \"contractAddress\": \"0x7c6dc94e4e146cb13eb03dc98d2b96ac79ef5e67\",\n" + + " \"from\": \"0x6fad87071f790c3234108f41b76bb99874a6d813\",\n" + + " \"gasUsed\": \"0x44ab3\",\n" + + " \"logs\": [],\n" + + " \"output\": \"0x\",\n" + + " \"status\": \"0x0\",\n" + + " \"to\": \"0x0000000000000000000000000000000000000000\",\n" + + " \"transactionHash\": \"0x066dce3c06b9d74881e0996172717cfcba4330206243a9f964eb3097f3696e27\",\n" + + " \"transactionIndex\": \"0x0\"\n" + + " }\n" + + " ]\n" + + " }\n" + + "}"; + + BcosTransactionReceiptsInfo bcosTransactionReceiptsInfo = objectMapper.readValue(receiptListStr.getBytes(), BcosTransactionReceiptsInfo.class); + checkReceipts(bcosTransactionReceiptsInfo.getTransactionReceiptsInfo()); + + String compressedReceiptStr = "{\n" + + " \"id\": 1,\n" + + " \"jsonrpc\": \"2.0\",\n" + + " \"result\": \"eJyNUT1PZDEM7O9npN4iTpw43u5EA80VSFedKOLE4RDwgt6HhLTa/35h3wpEd67iiWc81pyMvPTyfDe1bo6nvbnNy19zNPadsy8WQuAWfQMiz1UIAqsoY6jZgg0NAiAWplJshqTBJ26WMrcq5rAL/tpeReeLJAxs1qJPb+t97+uOKasChGqz1Rqzw9RCJgANmrJr7EtykipZds4F1Fa0OEGRyhUIvySXm75NV1FzPph1ztOSy/rUp/vrhDn+OZnSp/FV1p+1zrosFwKVWAujogLGIuBVrB9Iqk445kKsLWiksa3N/fXCiS3XRJagEdvinUewqSEIRRHmRJhjTeAH5zEvvxetFxpilg/spT9++Hk4mL6tb9tufODLmtdtd2VHu/b9+Z9lvt39GaaN4z4dgUbhSpgSqGWOQI6ASiuS0XvrbHToR3ocUcVbpuYjR3X0XfZuqvp+dXh+OP/4B2fCqOE=\"\n" + + "}"; + BcosTransactionReceiptsDecoder bcosTransactionReceiptsDecoder= objectMapper.readValue(compressedReceiptStr.getBytes(), BcosTransactionReceiptsDecoder.class); + checkReceipts(bcosTransactionReceiptsDecoder.decodeTransactionReceiptsInfo()); + } + + private void checkReceipts(BcosTransactionReceiptsInfo.TransactionReceiptsInfo receiptsInfo) + { + BcosTransactionReceiptsInfo.BlockInfo blockInfo = receiptsInfo.getBlockInfo(); + // check block info + Assert.assertEquals("0x9a3c01559f63f17739db7159ebe945da0105f15144c97cc0a18e5389f07a9fdb", blockInfo.getBlockHash() + ); + Assert.assertEquals("0x1", blockInfo.getBlockNumber()); + Assert.assertEquals("0x1e9ee115d0a0ed6a248f5a711e5e8a2f93c82b8d70922254efcec2b4bbd9d174", blockInfo.getReceiptRoot()); + Assert.assertEquals("0x1", blockInfo.getReceiptsCount()); + + // check receipts + List receipts = receiptsInfo.getTransactionReceipts(); + Assert.assertTrue(receipts.size() == 1); + Assert.assertEquals("0x7c6dc94e4e146cb13eb03dc98d2b96ac79ef5e67", receipts.get(0).getContractAddress()); + Assert.assertEquals("0x6fad87071f790c3234108f41b76bb99874a6d813", receipts.get(0).getFrom()); + Assert.assertEquals("0x44ab3", receipts.get(0).getGasUsed()); + Assert.assertEquals("0x", receipts.get(0).getOutput()); + Assert.assertEquals("0x0", receipts.get(0).getStatus()); + Assert.assertEquals("0x0000000000000000000000000000000000000000", receipts.get(0).getTo()); + Assert.assertEquals("0x066dce3c06b9d74881e0996172717cfcba4330206243a9f964eb3097f3696e27", receipts.get(0).getTransactionHash()); + Assert.assertEquals("0x0", receipts.get(0).getTransactionIndex()); + Assert.assertTrue( receipts.get(0).getLogs().size() == 0); } } diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCyclePrecompiled.java b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCyclePrecompiled.java index 570ec707a..66151c283 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCyclePrecompiled.java +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCyclePrecompiled.java @@ -34,13 +34,15 @@ public class ContractLifeCyclePrecompiled extends Contract { public static final String SM_BINARY = String.join("", SM_BINARY_ARRAY); public static final String[] ABI_ARRAY = { - "[{\"constant\":true,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"getStatus\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"unfreeze\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"freeze\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"contractAddr\",\"type\":\"address\"},{\"name\":\"userAddr\",\"type\":\"address\"}],\"name\":\"grantManager\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"listManager\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" + "[{\"constant\":true,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"getStatus\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"contractAddr\",\"type\":\"address\"},{\"name\":\"userAddr\",\"type\":\"address\"}],\"name\":\"revokeManager\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"unfreeze\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"freeze\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"contractAddr\",\"type\":\"address\"},{\"name\":\"userAddr\",\"type\":\"address\"}],\"name\":\"grantManager\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"listManager\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" }; public static final String ABI = String.join("", ABI_ARRAY); public static final String FUNC_GETSTATUS = "getStatus"; + public static final String FUNC_REVOKEMANAGER = "revokeManager"; + public static final String FUNC_UNFREEZE = "unfreeze"; public static final String FUNC_FREEZE = "freeze"; @@ -71,6 +73,63 @@ public Tuple2 getStatus(String addr) throws ContractExceptio (BigInteger) results.get(0).getValue(), (String) results.get(1).getValue()); } + public TransactionReceipt revokeManager(String contractAddr, String userAddr) { + final Function function = + new Function( + FUNC_REVOKEMANAGER, + Arrays.asList( + new org.fisco.bcos.sdk.abi.datatypes.Address(contractAddr), + new org.fisco.bcos.sdk.abi.datatypes.Address(userAddr)), + Collections.>emptyList()); + return executeTransaction(function); + } + + public void revokeManager(String contractAddr, String userAddr, TransactionCallback callback) { + final Function function = + new Function( + FUNC_REVOKEMANAGER, + Arrays.asList( + new org.fisco.bcos.sdk.abi.datatypes.Address(contractAddr), + new org.fisco.bcos.sdk.abi.datatypes.Address(userAddr)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public String getSignedTransactionForRevokeManager(String contractAddr, String userAddr) { + final Function function = + new Function( + FUNC_REVOKEMANAGER, + Arrays.asList( + new org.fisco.bcos.sdk.abi.datatypes.Address(contractAddr), + new org.fisco.bcos.sdk.abi.datatypes.Address(userAddr)), + Collections.>emptyList()); + return createSignedTransaction(function); + } + + public Tuple2 getRevokeManagerInput(TransactionReceipt transactionReceipt) { + String data = transactionReceipt.getInput().substring(10); + final Function function = + new Function( + FUNC_REVOKEMANAGER, + Arrays.asList(), + Arrays.>asList( + new TypeReference

() {}, new TypeReference
() {})); + List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); + return new Tuple2( + (String) results.get(0).getValue(), (String) results.get(1).getValue()); + } + + public Tuple1 getRevokeManagerOutput(TransactionReceipt transactionReceipt) { + String data = transactionReceipt.getOutput(); + final Function function = + new Function( + FUNC_REVOKEMANAGER, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + List results = FunctionReturnDecoder.decode(data, function.getOutputParameters()); + return new Tuple1((BigInteger) results.get(0).getValue()); + } + public TransactionReceipt unfreeze(String addr) { final Function function = new Function( diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCycleService.java b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCycleService.java index 5e889eac8..ec929a783 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCycleService.java +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/contractmgr/ContractLifeCycleService.java @@ -61,6 +61,15 @@ public RetCode grantManager(String contractAddress, String userAddress) this.contractLifeCyclePrecompiled.grantManager(contractAddress, userAddress)); } + public RetCode revokeManager(String contractAddress, String userAddress) + throws ContractException { + // only supported after v2.7.0 + PrecompiledVersionCheck.CONTRACT_LIFE_CYCLE_REVOKE_MANAGER_VERSION.checkVersion( + currentVersion); + return ReceiptParser.parseTransactionReceipt( + this.contractLifeCyclePrecompiled.revokeManager(contractAddress, userAddress)); + } + public String getContractStatus(String contractAddress) throws ContractException { PrecompiledVersionCheck.CONTRACT_LIFE_CYCLE_PRECOMPILED_VERSION.checkVersion( currentVersion); diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/model/PrecompiledVersionCheck.java b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/model/PrecompiledVersionCheck.java index 40627507b..5b89708ce 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/model/PrecompiledVersionCheck.java +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/model/PrecompiledVersionCheck.java @@ -19,9 +19,13 @@ public class PrecompiledVersionCheck { new Version("getContractAddress", "2.3.0"); public static final Version CONTRACT_LIFE_CYCLE_PRECOMPILED_VERSION = new Version("ContractLifeCycle", "2.3.0"); + public static final Version CONTRACT_LIFE_CYCLE_REVOKE_MANAGER_VERSION = + new Version("ContractLifeCyclePrecompiled.revokeManager", "2.7.0"); public static final Version TABLE_CRUD_PRECOMPILED_VERSION = new Version("CRUD", "2.0.0-rc3"); public static final Version CHAIN_GOVERNANCE_PRECOMPILED_VERSION = new Version("ChainGovernance", "2.5.0"); + public static final Version CHAIN_GOVERNANCE_PRECOMPILED_QUERY_VERSION = + new Version("queryVotesOfMember and queryVotesOfThreshold ", "2.7.0"); public static final Version TABLE_PERMISSION_PRECOMPILED_VERSION = new Version("Permission", "2.0.0-rc3"); public static final Version GRANT_WRITE_PERMISSION_PRECOMPILED_VERSION = diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernancePrecompiled.java b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernancePrecompiled.java index a264eb696..6a61d7661 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernancePrecompiled.java +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernancePrecompiled.java @@ -34,7 +34,7 @@ public class ChainGovernancePrecompiled extends Contract { public static final String SM_BINARY = String.join("", SM_BINARY_ARRAY); public static final String[] ABI_ARRAY = { - "[{\"constant\":true,\"inputs\":[],\"name\":\"listOperators\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"},{\"name\":\"weight\",\"type\":\"int256\"}],\"name\":\"updateCommitteeMemberWeight\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"queryThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"queryCommitteeMemberWeight\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"},{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"grantCommitteeMember\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"unfreezeAccount\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"listCommitteeMembers\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"threshold\",\"type\":\"int256\"}],\"name\":\"updateThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"revokeCommitteeMember\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"grantOperator\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"freezeAccount\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"revokeOperator\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"getAccountStatus\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" + "[{\"constant\":true,\"inputs\":[],\"name\":\"listOperators\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"},{\"name\":\"weight\",\"type\":\"int256\"}],\"name\":\"updateCommitteeMemberWeight\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"queryThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"queryVotesOfMember\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"queryCommitteeMemberWeight\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"},{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"grantCommitteeMember\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"unfreezeAccount\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"queryVotesOfThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"listCommitteeMembers\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"threshold\",\"type\":\"int256\"}],\"name\":\"updateThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"revokeCommitteeMember\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"grantOperator\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"freezeAccount\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"user\",\"type\":\"address\"}],\"name\":\"revokeOperator\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"getAccountStatus\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" }; public static final String ABI = String.join("", ABI_ARRAY); @@ -45,12 +45,16 @@ public class ChainGovernancePrecompiled extends Contract { public static final String FUNC_QUERYTHRESHOLD = "queryThreshold"; + public static final String FUNC_QUERYVOTESOFMEMBER = "queryVotesOfMember"; + public static final String FUNC_QUERYCOMMITTEEMEMBERWEIGHT = "queryCommitteeMemberWeight"; public static final String FUNC_GRANTCOMMITTEEMEMBER = "grantCommitteeMember"; public static final String FUNC_UNFREEZEACCOUNT = "unfreezeAccount"; + public static final String FUNC_QUERYVOTESOFTHRESHOLD = "queryVotesOfThreshold"; + public static final String FUNC_LISTCOMMITTEEMEMBERS = "listCommitteeMembers"; public static final String FUNC_UPDATETHRESHOLD = "updateThreshold"; @@ -153,6 +157,15 @@ public BigInteger queryThreshold() throws ContractException { return executeCallWithSingleValueReturn(function, BigInteger.class); } + public String queryVotesOfMember(String account) throws ContractException { + final Function function = + new Function( + FUNC_QUERYVOTESOFMEMBER, + Arrays.asList(new org.fisco.bcos.sdk.abi.datatypes.Address(account)), + Arrays.>asList(new TypeReference() {})); + return executeCallWithSingleValueReturn(function, String.class); + } + public Tuple2 queryCommitteeMemberWeight(String user) throws ContractException { final Function function = @@ -264,6 +277,15 @@ public Tuple1 getUnfreezeAccountOutput(TransactionReceipt transactio return new Tuple1((BigInteger) results.get(0).getValue()); } + public String queryVotesOfThreshold() throws ContractException { + final Function function = + new Function( + FUNC_QUERYVOTESOFTHRESHOLD, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeCallWithSingleValueReturn(function, String.class); + } + public String listCommitteeMembers() throws ContractException { final Function function = new Function( diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernanceService.java b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernanceService.java index d8affe513..df8dc6aa6 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernanceService.java +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/permission/ChainGovernanceService.java @@ -150,4 +150,24 @@ public String getAccountStatus(String userAddress) throws ContractException { throw ReceiptParser.parseExceptionCall(e); } } + + public String queryVotesOfMember(String account) throws ContractException { + PrecompiledVersionCheck.CHAIN_GOVERNANCE_PRECOMPILED_QUERY_VERSION.checkVersion( + currentVersion); + try { + return this.chainGovernancePrecompiled.queryVotesOfMember(account); + } catch (ContractException e) { + throw ReceiptParser.parseExceptionCall(e); + } + } + + public String queryVotesOfThreshold() throws ContractException { + PrecompiledVersionCheck.CHAIN_GOVERNANCE_PRECOMPILED_QUERY_VERSION.checkVersion( + currentVersion); + try { + return this.chainGovernancePrecompiled.queryVotesOfThreshold(); + } catch (ContractException e) { + throw ReceiptParser.parseExceptionCall(e); + } + } } diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ChainGovernancePrecompiled.sol b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ChainGovernancePrecompiled.sol index 1ae3e33de..a573b8b64 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ChainGovernancePrecompiled.sol +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ChainGovernancePrecompiled.sol @@ -34,4 +34,6 @@ contract ChainGovernancePrecompiled { function unfreezeAccount(address account) public returns (int256); function getAccountStatus(address account) public view returns (string); + function queryVotesOfMember(address account) public view returns (string); + function queryVotesOfThreshold() public view returns (string); } diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ContractLifeCyclePrecompiled.sol b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ContractLifeCyclePrecompiled.sol index a445be9fb..a1394200d 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ContractLifeCyclePrecompiled.sol +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/contract/precompiled/sol/ContractLifeCyclePrecompiled.sol @@ -4,6 +4,7 @@ contract ContractLifeCyclePrecompiled { function freeze(address addr) public returns(int); function unfreeze(address addr) public returns(int); function grantManager(address contractAddr, address userAddr) public returns(int); + function revokeManager(address contractAddr, address userAddr) public returns(int); function getStatus(address addr) public constant returns(int,string); function listManager(address addr) public constant returns(int,address[]); } diff --git a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/transaction/codec/decode/TransactionDecoderService.java b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/transaction/codec/decode/TransactionDecoderService.java index c7a54aa81..357d1b0bf 100644 --- a/sdk-transaction/src/main/java/org/fisco/bcos/sdk/transaction/codec/decode/TransactionDecoderService.java +++ b/sdk-transaction/src/main/java/org/fisco/bcos/sdk/transaction/codec/decode/TransactionDecoderService.java @@ -87,10 +87,14 @@ public TransactionResponse decodeReceiptWithoutValues( String abi, TransactionReceipt transactionReceipt) throws TransactionException, IOException, ABICodecException { TransactionResponse response = decodeReceiptStatus(transactionReceipt); - String events = JsonUtils.toJson(decodeEvents(abi, transactionReceipt.getLogs())); response.setTransactionReceipt(transactionReceipt); - response.setEvents(events); response.setContractAddress(transactionReceipt.getContractAddress()); + // the exception transaction + if (!transactionReceipt.getStatus().equals("0x0")) { + return response; + } + String events = JsonUtils.toJson(decodeEvents(abi, transactionReceipt.getLogs())); + response.setEvents(events); return response; } diff --git a/settings.gradle b/settings.gradle index 4c604b73c..1fdb91b2b 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,11 +1,10 @@ -rootProject.name = "java-sdk" +rootProject.name = "java-sdk" -// submodules -include "sdk-core" -include "sdk-abi" -include "sdk-crypto" -include "sdk-amop" -include "sdk-service" -include "sdk-transaction" -include "sdk-codegen" -include "sdk-demo" +// submodules +include "sdk-core" +include "sdk-crypto" +include "sdk-abi" +include "sdk-amop" +include "sdk-service" +include "sdk-transaction" +include "sdk-codegen" diff --git a/src/integration-test/java/org/fisco/bcos/sdk/BcosSDKTest.java b/src/integration-test/java/org/fisco/bcos/sdk/BcosSDKTest.java index 0bf8df802..adbdf8e91 100644 --- a/src/integration-test/java/org/fisco/bcos/sdk/BcosSDKTest.java +++ b/src/integration-test/java/org/fisco/bcos/sdk/BcosSDKTest.java @@ -1,14 +1,16 @@ /* * Copyright 2014-2020 [fisco-dev] * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under * the License. * */ @@ -16,11 +18,12 @@ package org.fisco.bcos.sdk; import java.math.BigInteger; -import java.util.List; import org.fisco.bcos.sdk.client.Client; import org.fisco.bcos.sdk.client.exceptions.ClientException; import org.fisco.bcos.sdk.client.protocol.response.BcosBlock; import org.fisco.bcos.sdk.client.protocol.response.BcosBlockHeader; +import org.fisco.bcos.sdk.client.protocol.response.BcosTransaction; +import org.fisco.bcos.sdk.client.protocol.response.BcosTransactionReceiptsDecoder; import org.fisco.bcos.sdk.client.protocol.response.BlockHash; import org.fisco.bcos.sdk.client.protocol.response.BlockNumber; import org.fisco.bcos.sdk.client.protocol.response.ConsensusStatus; @@ -31,7 +34,7 @@ import org.fisco.bcos.sdk.client.protocol.response.SealerList; import org.fisco.bcos.sdk.client.protocol.response.SyncStatus; import org.fisco.bcos.sdk.config.exceptions.ConfigException; -import org.fisco.bcos.sdk.demo.contract.HelloWorld; +import org.fisco.bcos.sdk.contract.HelloWorld; import org.fisco.bcos.sdk.model.ConstantConfig; import org.fisco.bcos.sdk.model.NodeVersion; import org.fisco.bcos.sdk.model.TransactionReceipt; @@ -53,13 +56,6 @@ public void testClient() throws ConfigException { BcosSDK sdk = BcosSDK.build(configFile); // check groupList Assert.assertTrue(sdk.getChannel().getAvailablePeer().size() >= 1); - for (String endPoint : sdk.getChannel().getAvailablePeer()) { - List groupInfo = sdk.getGroupManagerService().getGroupInfoByNodeInfo(endPoint); - if (groupInfo.size() > 0) { - Assert.assertEquals(1, groupInfo.size()); - Assert.assertEquals("1", groupInfo.get(0)); - } - } // get the client Client client = sdk.getClient(Integer.valueOf(1)); @@ -164,9 +160,7 @@ public void testClient() throws ConfigException { // test getGroupList GroupList groupList = client.getGroupList(); - Assert.assertEquals(1, groupList.getGroupList().size()); - Assert.assertEquals("1", groupList.getGroupList().get(0)); - + Assert.assertTrue(groupList.getGroupList().size() >= 1); // test getConsensusStatus ConsensusStatus consensusStatus = client.getConsensusStatus(); Assert.assertTrue(consensusStatus.getConsensusStatus().getViewInfos().size() > 0); @@ -191,6 +185,43 @@ public void testClient() throws ConfigException { Assert.assertEquals( latestHash.getBlockHashByNumber(), consensusStatus.getConsensusStatus().getBaseConsensusInfo().getHighestblockHash()); + + try { + // test calculateHash interface for the transaction response + BcosTransaction transaction = + client.getTransactionByBlockNumberAndIndex( + blockNumber.getBlockNumber(), BigInteger.ZERO); + if (transaction.getTransaction().get() != null) { + System.out.println( + "### transactionHash:" + transaction.getTransaction().get().getHash()); + System.out.println( + "### calculated transactionHash:" + + transaction + .getTransaction() + .get() + .calculateHash(client.getCryptoSuite())); + Assert.assertEquals( + transaction.getTransaction().get().calculateHash(client.getCryptoSuite()), + transaction.getTransaction().get().getHash()); + } + + // test calculateHash interface for the getBlockHeader response + BcosBlockHeader blockHeader = + client.getBlockHeaderByNumber(blockNumber.getBlockNumber(), true); + String calculatedHash = + blockHeader.getBlockHeader().calculateHash(client.getCryptoSuite()); + System.out.println("### blockHeader calculatedHash : " + calculatedHash); + System.out.println( + "### blockHeader expectedHash: " + blockHeader.getBlockHeader().getHash()); + Assert.assertEquals(blockHeader.getBlockHeader().getHash(), calculatedHash); + + // test calculateHash interface for the block response + block = client.getBlockByNumber(blockNumber.getBlockNumber(), false); + calculatedHash = block.getBlock().calculateHash(client.getCryptoSuite()); + Assert.assertEquals(block.getBlock().getHash(), calculatedHash); + } catch (ClientException e) { + System.out.println("testClient exception, error info: " + e.getMessage()); + } } private void checkReceipt( @@ -283,6 +314,29 @@ public void testSendTransactions() throws ConfigException, ContractException { helloWorld2, client, blockNumber.add(BigInteger.valueOf(3)), receipt2, true); Assert.assertTrue(helloWorld.get().equals(settedString)); Assert.assertTrue(helloWorld2.get().equals(settedString)); + + // test getBatchReceiptsByBlockHashAndRange(added after v2.7.0) + BcosTransactionReceiptsDecoder bcosTransactionReceiptsDecoder = + client.getBatchReceiptsByBlockHashAndRange( + client.getBlockHashByNumber(client.getBlockNumber().getBlockNumber()) + .getBlockHashByNumber(), + "0", + "-1"); + System.out.println( + "### bcosTransactionReceiptsDecoder1: " + + bcosTransactionReceiptsDecoder + .decodeTransactionReceiptsInfo() + .toString()); + // test getBatchReceiptsByBlockNumberAndRange + bcosTransactionReceiptsDecoder = + client.getBatchReceiptsByBlockNumberAndRange( + client.getBlockNumber().getBlockNumber(), "0", "-1"); + System.out.println( + "### bcosTransactionReceiptsDecoder2: " + + bcosTransactionReceiptsDecoder + .decodeTransactionReceiptsInfo() + .toString()); + } catch (ContractException | ClientException | InterruptedException e) { System.out.println("testSendTransactions exceptioned, error info:" + e.getMessage()); } diff --git a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/HelloWorld.java b/src/integration-test/java/org/fisco/bcos/sdk/contract/HelloWorld.java similarity index 99% rename from sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/HelloWorld.java rename to src/integration-test/java/org/fisco/bcos/sdk/contract/HelloWorld.java index 8dce787d4..75ee65d97 100644 --- a/sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/HelloWorld.java +++ b/src/integration-test/java/org/fisco/bcos/sdk/contract/HelloWorld.java @@ -1,4 +1,4 @@ -package org.fisco.bcos.sdk.demo.contract; +package org.fisco.bcos.sdk.contract; import java.util.Arrays; import java.util.Collections; @@ -10,7 +10,6 @@ import org.fisco.bcos.sdk.abi.datatypes.Utf8String; import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple1; import org.fisco.bcos.sdk.client.Client; -import org.fisco.bcos.sdk.contract.Contract; import org.fisco.bcos.sdk.crypto.CryptoSuite; import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; import org.fisco.bcos.sdk.model.CryptoType; diff --git a/src/integration-test/java/org/fisco/bcos/sdk/precompiled/PrecompiledTest.java b/src/integration-test/java/org/fisco/bcos/sdk/precompiled/PrecompiledTest.java index 9cc155261..45d635915 100644 --- a/src/integration-test/java/org/fisco/bcos/sdk/precompiled/PrecompiledTest.java +++ b/src/integration-test/java/org/fisco/bcos/sdk/precompiled/PrecompiledTest.java @@ -28,6 +28,7 @@ import org.fisco.bcos.sdk.client.Client; import org.fisco.bcos.sdk.client.exceptions.ClientException; import org.fisco.bcos.sdk.config.exceptions.ConfigException; +import org.fisco.bcos.sdk.contract.HelloWorld; import org.fisco.bcos.sdk.contract.precompiled.callback.PrecompiledCallback; import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; import org.fisco.bcos.sdk.contract.precompiled.cns.CnsService; @@ -41,7 +42,6 @@ import org.fisco.bcos.sdk.contract.precompiled.sysconfig.SystemConfigService; import org.fisco.bcos.sdk.crypto.CryptoSuite; import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; -import org.fisco.bcos.sdk.demo.contract.HelloWorld; import org.fisco.bcos.sdk.model.ConstantConfig; import org.fisco.bcos.sdk.model.PrecompiledRetCode; import org.fisco.bcos.sdk.model.RetCode; diff --git a/src/test/resources/config-example.toml b/src/test/resources/config-example.toml index 037bceb5f..dc38a0dee 100644 --- a/src/test/resources/config-example.toml +++ b/src/test/resources/config-example.toml @@ -21,17 +21,25 @@ certPath = "conf" # The certification path [network] peers=["127.0.0.1:20200", "127.0.0.1:20201"] # The peer list to connect + +# AMOP configuration +# You can use following two methods to configure as a private topic message sender or subscriber. +# Usually, the public key and private key is generated by subscriber. +# Message sender receive public key from topic subscriber then make configuration. +# But, please do not config as both the message sender and the subscriber of one private topic, or you may send the message to yourself. + # Configure a private topic as a topic message sender. # [[amop]] -# topicName = "PrivateTopic1" +# topicName = "PrivateTopic" # publicKeys = [ "conf/amop/consumer_public_key_1.pem" ] # Public keys of the nodes that you want to send AMOP message of this topic to. # Configure a private topic as a topic subscriber. # [[amop]] -# topicName = "PrivateTopic2" +# topicName = "PrivateTopic" # privateKey = "conf/amop/consumer_private_key.p12" # Your private key that used to subscriber verification. # password = "123456" + [account] keyStoreDir = "account" # The directory to load/store the account file, default is "account" # accountFilePath = "" # The account file path (default load from the path specified by the keyStoreDir)