diff --git a/Changelog.md b/Changelog.md index 680012184..ebd674941 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,24 @@ +### v2.0.0-rc2 + +(2019-04-25) + +* Add + +1. 可并行合约开发框架ParallelContract.sol +2. 并行预编译转账合约DagTransferPrecompiled的压测程序 +3. 并行solidity转账合约parallelOk的压测程序 +4. CRUD合约的压测程序 +5. 回滚合约的压测程序 + +* Update + +1. 在交易编码中加入chainID和groupID,以支持rc2节点的交易格式 +2. sol转java,在java文件中增加了abi字段。 + +* Compatibility + +1. 兼容rc1,rc2的节点 + ### v2.0.0-rc1 (2019-03-18) diff --git a/build.gradle b/build.gradle index 968ac103e..e25f65362 100644 --- a/build.gradle +++ b/build.gradle @@ -27,7 +27,7 @@ def spring_version="4.3.18.RELEASE" List logger = [ 'org.slf4j:slf4j-log4j12:1.7.25' - // 'org.slf4j:slf4j-api:1.7.25' + //'org.slf4j:slf4j-api:1.7.25' ] List spring =[ @@ -35,8 +35,6 @@ List spring =[ "org.springframework:spring-beans:$spring_version", "org.springframework:spring-context:$spring_version", "org.springframework:spring-tx:$spring_version", - "org.springframework:spring-jdbc:$spring_version", - "org.springframework:spring-test:$spring_version" ] List alibaba = [ @@ -56,7 +54,6 @@ dependencies { compile 'io.netty:netty-tcnative:2.0.20.Final' compile 'io.netty:netty-tcnative-boringssl-static:2.0.20.Final' compile 'com.google.guava:guava:19.0' - compile 'org.jline:jline:3.9.0' compile 'commons-configuration:commons-configuration:1.10' // web3j @@ -72,7 +69,6 @@ dependencies { "org.apache.commons:commons-collections4:4.0", "commons-io:commons-io:2.4", 'com.github.stefanbirkner:system-rules:1.18.0', - 'io.bretty:console-table-builder:1.2', 'junit:junit:4.12', 'org.mockito:mockito-core:2.23.0' } diff --git a/release_note.txt b/release_note.txt index 1ee76d11b..a4b58387a 100644 --- a/release_note.txt +++ b/release_note.txt @@ -1 +1 @@ -v2.0.0-rc1 +v2.0.0-rc2 diff --git a/src/main/java/org/fisco/bcos/channel/client/Service.java b/src/main/java/org/fisco/bcos/channel/client/Service.java index 95361be3a..31fa326d2 100644 --- a/src/main/java/org/fisco/bcos/channel/client/Service.java +++ b/src/main/java/org/fisco/bcos/channel/client/Service.java @@ -36,7 +36,7 @@ public class Service { private GroupChannelConnectionsConfig allChannelConnections; private ChannelPushCallback pushCallback; private Map seq2Callback = new ConcurrentHashMap(); - private static int groupId; + private int groupId; private static ObjectMapper objectMapper = new ObjectMapper(); private BigInteger number = BigInteger.valueOf(0); diff --git a/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java b/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java index 33ffd69d4..32aad6898 100644 --- a/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java +++ b/src/main/java/org/fisco/bcos/channel/handler/ChannelConnections.java @@ -227,7 +227,7 @@ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast( sslCtx.newHandler(ch.alloc()), - new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), + new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, -4, 0), new IdleStateHandler( idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler); @@ -298,7 +298,7 @@ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast( sslCtx.newHandler(ch.alloc()), - new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), + new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, -4, 0), new IdleStateHandler( idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler); diff --git a/src/main/java/org/fisco/bcos/web3j/codegen/SolidityFunctionWrapper.java b/src/main/java/org/fisco/bcos/web3j/codegen/SolidityFunctionWrapper.java index 892b87b0a..b1e1f4827 100644 --- a/src/main/java/org/fisco/bcos/web3j/codegen/SolidityFunctionWrapper.java +++ b/src/main/java/org/fisco/bcos/web3j/codegen/SolidityFunctionWrapper.java @@ -680,19 +680,19 @@ static TypeName getNativeType(TypeName typeName) { String simpleName = ((ClassName) typeName).simpleName(); - if (simpleName.equals(Address.class.getSimpleName())) { + if (simpleName.startsWith(Address.class.getSimpleName())) { return TypeName.get(String.class); } else if (simpleName.startsWith("Uint")) { return TypeName.get(BigInteger.class); } else if (simpleName.startsWith("Int")) { return TypeName.get(BigInteger.class); - } else if (simpleName.equals(Utf8String.class.getSimpleName())) { + } else if (simpleName.startsWith(Utf8String.class.getSimpleName())) { return TypeName.get(String.class); } else if (simpleName.startsWith("Bytes")) { return TypeName.get(byte[].class); - } else if (simpleName.equals(DynamicBytes.class.getSimpleName())) { + } else if (simpleName.startsWith(DynamicBytes.class.getSimpleName())) { return TypeName.get(byte[].class); - } else if (simpleName.equals(Bool.class.getSimpleName())) { + } else if (simpleName.startsWith(Bool.class.getSimpleName())) { return TypeName.get(Boolean.class); // boolean cannot be a parameterized type } else { throw new UnsupportedOperationException( diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedRawTransaction.java b/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedRawTransaction.java new file mode 100644 index 000000000..43c4e2b65 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedRawTransaction.java @@ -0,0 +1,152 @@ +package org.fisco.bcos.web3j.crypto; + +import org.fisco.bcos.web3j.tx.TransactionConstant; +import org.fisco.bcos.web3j.utils.Numeric; + +import java.io.Serializable; +import java.math.BigInteger; + +/** + * Transaction class used for signing transactions locally.
+ * For the specification, refer to p4 of the yellow + * paper. + */ +public class ExtendedRawTransaction implements Serializable { + + private static final long serialVersionUID = -5580814755985097996L; + private BigInteger randomid; + private BigInteger gasPrice; + private BigInteger gasLimit; + private BigInteger blockLimit; + private String to; + private BigInteger value; + private String data; + private BigInteger fiscoChainId; + private BigInteger groupId; + private String extraData; + private BigInteger version = TransactionConstant.version; + + protected ExtendedRawTransaction( + BigInteger randomid, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger blockLimit, + String to, + BigInteger value, + String data, + BigInteger fiscoChainId, + BigInteger groupId, + String extraData) { + this.randomid = randomid; + this.gasPrice = gasPrice; + this.gasLimit = gasLimit; + this.blockLimit = blockLimit; + this.fiscoChainId = fiscoChainId; + this.groupId = groupId; + this.extraData = extraData; + this.to = to; + + this.value = value; + + if (data != null) { + this.data = Numeric.cleanHexPrefix(data); + } + } + + public static ExtendedRawTransaction createContractTransaction( + BigInteger randomid, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger blockLimit, + BigInteger value, + String init, + BigInteger chainId, + BigInteger groupId, + String extraData) { + + return new ExtendedRawTransaction(randomid, gasPrice, gasLimit, blockLimit, "", value, init,chainId,groupId,extraData); + } +// +// +// public static ExtendedRawTransaction createTransaction( +// BigInteger randomid, +// BigInteger gasPrice, +// BigInteger gasLimit, +// BigInteger blockLimit, +// String to, +// String data) { +// return createTransaction(randomid, gasPrice, gasLimit, blockLimit, to, BigInteger.ZERO, data); +// } + + public static ExtendedRawTransaction createTransaction( + BigInteger randomid, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger blockLimit, + String to, + BigInteger value, + String data, + BigInteger chainId, + BigInteger groupId, + String extraData) { + + return new ExtendedRawTransaction(randomid, gasPrice, gasLimit, blockLimit, to, value, data,chainId, groupId, extraData); + } + + public BigInteger getRandomid() { + return randomid; + } + + public BigInteger getGasPrice() { + return gasPrice; + } + + public BigInteger getGasLimit() { + return gasLimit; + } + + public BigInteger getBlockLimit() { + return blockLimit; + } + + public String getTo() { + return to; + } + + public BigInteger getValue() { + return value; + } + + public String getData() { + return data; + } + + public BigInteger getVersion() { + return version; + } + public BigInteger getGroupId() { + return groupId; + } + + public void setGroupId(BigInteger groupId) { + this.groupId = groupId; + } + + + public String getExtraData() { + return extraData; + } + + public void setExtraData(String extraData) { + this.extraData = extraData; + } + + public BigInteger getFiscoChainId() { + return fiscoChainId; + } + + public void setFiscoChainId(BigInteger fiscoChainId) { + this.fiscoChainId = fiscoChainId; + } + +} diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedTransactionDecoder.java b/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedTransactionDecoder.java new file mode 100644 index 000000000..121026bc1 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedTransactionDecoder.java @@ -0,0 +1,44 @@ +package org.fisco.bcos.web3j.crypto; + +import org.fisco.bcos.web3j.rlp.RlpDecoder; +import org.fisco.bcos.web3j.rlp.RlpList; +import org.fisco.bcos.web3j.rlp.RlpString; +import org.fisco.bcos.web3j.utils.Numeric; + +import java.math.BigInteger; + +public class ExtendedTransactionDecoder { + + public static ExtendedRawTransaction decode(String hexTransaction) { + byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); + RlpList rlpList = RlpDecoder.decode(transaction); + RlpList values = (RlpList) rlpList.getValues().get(0); + BigInteger randomid = ((RlpString) values.getValues().get(0)).asPositiveBigInteger(); + BigInteger gasPrice = ((RlpString) values.getValues().get(1)).asPositiveBigInteger(); + BigInteger gasLimit = ((RlpString) values.getValues().get(2)).asPositiveBigInteger(); + BigInteger blockLimit = ((RlpString) values.getValues().get(3)).asPositiveBigInteger(); + String to = ((RlpString) values.getValues().get(4)).asString(); + BigInteger value = ((RlpString) values.getValues().get(5)).asPositiveBigInteger(); + String data = ((RlpString) values.getValues().get(6)).asString(); + + //add extra data + BigInteger chainId = ((RlpString) values.getValues().get(7)).asPositiveBigInteger(); + BigInteger groupId = ((RlpString) values.getValues().get(8)).asPositiveBigInteger(); + String extraData = ((RlpString) values.getValues().get(9)).asString(); + if (values.getValues().size() > 9) { + byte v = ((RlpString) values.getValues().get(10)).getBytes()[0]; + byte[] r = + Numeric.toBytesPadded( + Numeric.toBigInt(((RlpString) values.getValues().get(11)).getBytes()), 32); + byte[] s = + Numeric.toBytesPadded( + Numeric.toBigInt(((RlpString) values.getValues().get(12)).getBytes()), 32); + Sign.SignatureData signatureData = new Sign.SignatureData(v, r, s); + return new SignedExtendedRawTransaction( + randomid, gasPrice, gasLimit, blockLimit, to, value, data,chainId, groupId, extraData, signatureData); + } else { + return ExtendedRawTransaction.createTransaction( + randomid, gasPrice, gasLimit, blockLimit, to, value, data,chainId, groupId, extraData); + } + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedTransactionEncoder.java b/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedTransactionEncoder.java new file mode 100644 index 000000000..17b57dbb3 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/crypto/ExtendedTransactionEncoder.java @@ -0,0 +1,108 @@ +package org.fisco.bcos.web3j.crypto; + +import org.fisco.bcos.web3j.rlp.RlpEncoder; +import org.fisco.bcos.web3j.rlp.RlpList; +import org.fisco.bcos.web3j.rlp.RlpString; +import org.fisco.bcos.web3j.rlp.RlpType; +import org.fisco.bcos.web3j.utils.Bytes; +import org.fisco.bcos.web3j.utils.Numeric; + +import java.util.ArrayList; +import java.util.List; + +/** + * Create RLP encoded transaction, implementation as per p4 of the yellow paper. + */ +public class ExtendedTransactionEncoder { + + public static byte[] signMessage(ExtendedRawTransaction rawTransaction, Credentials credentials) { + byte[] encodedTransaction = encode(rawTransaction); + Sign.SignatureData signatureData = + Sign.getSignInterface().signMessage(encodedTransaction, credentials.getEcKeyPair()); + + return encode(rawTransaction, signatureData); + } + + public static byte[] signMessage( + ExtendedRawTransaction rawTransaction, byte chainId, Credentials credentials) { + byte[] encodedTransaction = encode(rawTransaction, chainId); + Sign.SignatureData signatureData = + Sign.getSignInterface().signMessage(encodedTransaction, credentials.getEcKeyPair()); + + Sign.SignatureData eip155SignatureData = createEip155SignatureData(signatureData, chainId); + return encode(rawTransaction, eip155SignatureData); + } + + public static Sign.SignatureData createEip155SignatureData( + Sign.SignatureData signatureData, byte chainId) { + byte v = (byte) (signatureData.getV() + (chainId << 1) + 8); + + return new Sign.SignatureData(v, signatureData.getR(), signatureData.getS()); + } + + public static byte[] encode(ExtendedRawTransaction rawTransaction) { + return encode(rawTransaction, null); + } + + public static byte[] encode(ExtendedRawTransaction rawTransaction, byte chainId) { + Sign.SignatureData signatureData = + new Sign.SignatureData(chainId, new byte[] {}, new byte[] {}); + return encode(rawTransaction, signatureData); + } + + public static byte[] encode(ExtendedRawTransaction rawTransaction, Sign.SignatureData signatureData) { + List values = asRlpValues(rawTransaction, signatureData); + RlpList rlpList = new RlpList(values); + return RlpEncoder.encode(rlpList); + } + + static List asRlpValues( + ExtendedRawTransaction rawTransaction, Sign.SignatureData signatureData) { + List result = new ArrayList<>(); + result.add(RlpString.create(rawTransaction.getRandomid())); + result.add(RlpString.create(rawTransaction.getGasPrice())); + result.add(RlpString.create(rawTransaction.getGasLimit())); + result.add(RlpString.create(rawTransaction.getBlockLimit())); + // an empty to address (contract creation) should not be encoded as a numeric 0 value + String to = rawTransaction.getTo(); + if (to != null && to.length() > 0) { + // addresses that start with zeros should be encoded with the zeros included, not + // as numeric values + result.add(RlpString.create(Numeric.hexStringToByteArray(to))); + } else { + result.add(RlpString.create("")); + } + + result.add(RlpString.create(rawTransaction.getValue())); + + // value field will already be hex encoded, so we need to convert into binary first + byte[] data = Numeric.hexStringToByteArray(rawTransaction.getData()); + result.add(RlpString.create(data)); + + // add extra data!!! + + result.add(RlpString.create(rawTransaction.getFiscoChainId())); + result.add(RlpString.create(rawTransaction.getGroupId())); + if(rawTransaction.getExtraData()==null){ + result.add(RlpString.create("")); + } else { + result.add(RlpString.create(Numeric.hexStringToByteArray(rawTransaction.getExtraData()))); + } + if (signatureData != null) { + if (EncryptType.encryptType == 1) { + result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getPub()))); + // logger.debug("RLP-Pub:{},RLP-PubLen:{}",Hex.toHexString(signatureData.getPub()),signatureData.getPub().length); + result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR()))); + // logger.debug("RLP-R:{},RLP-RLen:{}",Hex.toHexString(signatureData.getR()),signatureData.getR().length); + result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS()))); + // logger.debug("RLP-S:{},RLP-SLen:{}",Hex.toHexString(signatureData.getS()),signatureData.getS().length); + } else { + result.add(RlpString.create(signatureData.getV())); + result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR()))); + result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS()))); + } + } + return result; + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/RawTransaction.java b/src/main/java/org/fisco/bcos/web3j/crypto/RawTransaction.java index 030802569..b6048c82f 100644 --- a/src/main/java/org/fisco/bcos/web3j/crypto/RawTransaction.java +++ b/src/main/java/org/fisco/bcos/web3j/crypto/RawTransaction.java @@ -1,5 +1,6 @@ package org.fisco.bcos.web3j.crypto; +import java.io.Serializable; import java.math.BigInteger; import org.fisco.bcos.web3j.tx.TransactionConstant; import org.fisco.bcos.web3j.utils.Numeric; @@ -9,8 +10,9 @@ * For the specification, refer to p4 of the yellow * paper. */ -public class RawTransaction { +public class RawTransaction implements Serializable { + private static final long serialVersionUID = -5580814755985097996L; private BigInteger randomid; private BigInteger gasPrice; private BigInteger gasLimit; diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/SignedExtendedRawTransaction.java b/src/main/java/org/fisco/bcos/web3j/crypto/SignedExtendedRawTransaction.java new file mode 100644 index 000000000..9c31b012d --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/crypto/SignedExtendedRawTransaction.java @@ -0,0 +1,76 @@ +package org.fisco.bcos.web3j.crypto; + +import java.math.BigInteger; +import java.security.SignatureException; + +public class SignedExtendedRawTransaction extends ExtendedRawTransaction { + + private static final int CHAIN_ID_INC = 35; + private static final int LOWER_REAL_V = 27; + + private Sign.SignatureData signatureData; + + public SignedExtendedRawTransaction( + BigInteger randomid, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger blockLimit, + String to, + BigInteger value, + String data, + BigInteger chainId, + BigInteger groupId, + String extraData, + Sign.SignatureData signatureData) { + super(randomid, gasPrice, gasLimit, blockLimit, to, value, data,chainId, groupId, extraData); + this.signatureData = signatureData; + } + + public Sign.SignatureData getSignatureData() { + return signatureData; + } + + public String getFrom() throws SignatureException { + Integer chainId = getChainId(); + byte[] encodedTransaction; + if (null == chainId) { + encodedTransaction = ExtendedTransactionEncoder.encode(this); + } else { + encodedTransaction = ExtendedTransactionEncoder.encode(this, chainId.byteValue()); + } + byte v = signatureData.getV(); + byte[] r = signatureData.getR(); + byte[] s = signatureData.getS(); + Sign.SignatureData signatureDataV = new Sign.SignatureData(getRealV(v), r, s); + BigInteger key = Sign.signedMessageToKey(encodedTransaction, signatureDataV); + return "0x" + Keys.getAddress(key); + } + + public void verify(String from) throws SignatureException { + String actualFrom = getFrom(); + if (!actualFrom.equals(from)) { + throw new SignatureException("from mismatch"); + } + } + + private byte getRealV(byte v) { + if (v == LOWER_REAL_V || v == (LOWER_REAL_V + 1)) { + return v; + } + byte realV = LOWER_REAL_V; + int inc = 0; + if ((int) v % 2 == 0) { + inc = 1; + } + return (byte) (realV + inc); + } + + public Integer getChainId() { + byte v = signatureData.getV(); + if (v == LOWER_REAL_V || v == (LOWER_REAL_V + 1)) { + return null; + } + Integer chainId = (v - CHAIN_ID_INC) / 2; + return chainId; + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/crypto/TransactionEncoder.java b/src/main/java/org/fisco/bcos/web3j/crypto/TransactionEncoder.java index 497cdc707..ec6bfe3b2 100644 --- a/src/main/java/org/fisco/bcos/web3j/crypto/TransactionEncoder.java +++ b/src/main/java/org/fisco/bcos/web3j/crypto/TransactionEncoder.java @@ -50,7 +50,7 @@ public static byte[] encode(RawTransaction rawTransaction, byte chainId) { return encode(rawTransaction, signatureData); } - private static byte[] encode(RawTransaction rawTransaction, Sign.SignatureData signatureData) { + public static byte[] encode(RawTransaction rawTransaction, Sign.SignatureData signatureData) { List values = asRlpValues(rawTransaction, signatureData); RlpList rlpList = new RlpList(values); return RlpEncoder.encode(rlpList); diff --git a/src/main/java/org/fisco/bcos/web3j/precompile/cns/CnsService.java b/src/main/java/org/fisco/bcos/web3j/precompile/cns/CnsService.java index 4926749f4..fe6cd58f9 100644 --- a/src/main/java/org/fisco/bcos/web3j/precompile/cns/CnsService.java +++ b/src/main/java/org/fisco/bcos/web3j/precompile/cns/CnsService.java @@ -12,6 +12,7 @@ import org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock; import org.fisco.bcos.web3j.protocol.core.methods.response.SyncStatus; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tx.Contract; import org.fisco.bcos.web3j.tx.RawTransactionManager; import org.fisco.bcos.web3j.tx.TransactionManager; import org.fisco.bcos.web3j.tx.gas.DefaultGasProvider; @@ -36,7 +37,7 @@ public class CnsService { public CnsService(Web3j web3j, long syncThreshold, Credentials credentials) { this.web3j = web3j; - transactionManager = new RawTransactionManager(web3j, credentials); + transactionManager = Contract.getTheTransactionManager(web3j,credentials); this.syncThreshold = syncThreshold; } diff --git a/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java b/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java index 65394188d..7e506d4bf 100644 --- a/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java +++ b/src/main/java/org/fisco/bcos/web3j/protocol/core/JsonRpc2_0Web3j.java @@ -1,10 +1,6 @@ package org.fisco.bcos.web3j.protocol.core; import io.reactivex.Flowable; -import java.io.IOException; -import java.math.BigInteger; -import java.util.*; -import java.util.concurrent.ScheduledExecutorService; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.Web3jService; import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; @@ -18,6 +14,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.math.BigInteger; +import java.util.*; +import java.util.concurrent.ScheduledExecutorService; + /** JSON-RPC 2.0 factory implementation. */ public class JsonRpc2_0Web3j implements Web3j { static Logger logger = LoggerFactory.getLogger(JsonRpc2_0Web3j.class); @@ -28,6 +29,8 @@ public class JsonRpc2_0Web3j implements Web3j { private final JsonRpc2_0Rx web3jRx; private final long blockTime; private final ScheduledExecutorService scheduledExecutorService; + + private int groupId = 1; public Web3jService web3jService() { @@ -413,6 +416,14 @@ public Flowable replayPastAndFutureBlocksFlowable( return web3jRx.replayPastAndFutureTransactionsFlowable(startBlock, blockTime); } + public int getGroupId() { + return groupId; + } + + public void setGroupId(int groupId) { + this.groupId = groupId; + } + public void shutdown() { scheduledExecutorService.shutdown(); try { diff --git a/src/main/java/org/fisco/bcos/web3j/tx/ClientTransactionManager.java b/src/main/java/org/fisco/bcos/web3j/tx/ClientTransactionManager.java index 65a734e9c..05beaa560 100644 --- a/src/main/java/org/fisco/bcos/web3j/tx/ClientTransactionManager.java +++ b/src/main/java/org/fisco/bcos/web3j/tx/ClientTransactionManager.java @@ -48,7 +48,7 @@ public ClientTransactionManager( @Override public SendTransaction sendTransaction( - BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value) + BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value, String extraData) throws IOException { Random r = new SecureRandom(); diff --git a/src/main/java/org/fisco/bcos/web3j/tx/Contract.java b/src/main/java/org/fisco/bcos/web3j/tx/Contract.java index 3be0b7c33..965656d09 100644 --- a/src/main/java/org/fisco/bcos/web3j/tx/Contract.java +++ b/src/main/java/org/fisco/bcos/web3j/tx/Contract.java @@ -6,6 +6,10 @@ import java.util.*; import java.util.concurrent.Semaphore; import java.util.stream.Collectors; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.channel.client.TransactionSucCallback; import org.fisco.bcos.web3j.abi.EventEncoder; import org.fisco.bcos.web3j.abi.EventValues; @@ -20,6 +24,7 @@ import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameter; import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameterName; +import org.fisco.bcos.web3j.protocol.core.JsonRpc2_0Web3j; import org.fisco.bcos.web3j.protocol.core.RemoteCall; import org.fisco.bcos.web3j.protocol.core.methods.request.Transaction; import org.fisco.bcos.web3j.protocol.core.methods.response.Call; @@ -32,6 +37,8 @@ import org.fisco.bcos.web3j.tx.gas.DefaultGasProvider; import org.fisco.bcos.web3j.tx.gas.StaticGasProvider; import org.fisco.bcos.web3j.utils.Numeric; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Solidity contract type abstraction for interacting with smart contracts via native Java types. @@ -39,9 +46,10 @@ public abstract class Contract extends ManagedTransaction { /** - * @deprecated ... * @see DefaultGasProvider + * @deprecated ... */ + static Logger logger = LoggerFactory.getLogger(Contract.class); public static final BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000); public static final String BIN_NOT_PROVIDED = "Bin file was not provided"; @@ -55,32 +63,61 @@ public abstract class Contract extends ManagedTransaction { protected DefaultBlockParameter defaultBlockParameter = DefaultBlockParameterName.LATEST; protected Contract( - String contractBinary, - String contractAddress, - Web3j web3j, - TransactionManager transactionManager, - ContractGasProvider gasProvider) { + String contractBinary, + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider gasProvider) { super(web3j, transactionManager); this.contractAddress = cnsService.getAddressByContractNameAndVersion(contractAddress); this.contractBinary = contractBinary; this.gasProvider = gasProvider; } + //************ protected Contract( - String contractBinary, - String contractAddress, - Web3j web3j, - Credentials credentials, - ContractGasProvider gasProvider) { - + String contractBinary, + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider gasProvider) { this( - contractBinary, - contractAddress, - web3j, - new RawTransactionManager(web3j, credentials), - gasProvider); + contractBinary, + contractAddress, + web3j, + getTheTransactionManager(web3j, credentials), + gasProvider); +// if (!Service.clientVersion.equals("2.0.0-rc1")) { +// this.extendedTransactionManager = new ExtendedRawTransactionManager(web3j, credentials, new BigInteger("1"), Service.chainId); +// } + } + + public static TransactionManager getTheTransactionManager( Web3j web3j, Credentials credentials) { + JsonRpc2_0Web3j jsonRpc2_0Web3j = (JsonRpc2_0Web3j) web3j; + int groupId = jsonRpc2_0Web3j.getGroupId(); + String clientVersion =null; + String chainId= "1"; + String versionContent; + if (clientVersion == null) { + try { + versionContent= web3j.getNodeVersion().sendForReturnString(); + logger.info("***version***"); + if (versionContent.contains("2.0.0-rc1")) { + clientVersion = "2.0.0-rc1"; + } + JSONObject jsonObject = JSONObject.parseObject(versionContent); + chainId = (String)jsonObject.get("Chain Id"); + } catch (IOException e) { + + logger.info("can not get node version "); + } + } ; + + return "2.0.0-rc1".equals(clientVersion) ? new RawTransactionManager(web3j, credentials) : new ExtendedRawTransactionManager(web3j, credentials, BigInteger.valueOf(groupId), new BigInteger(chainId)); + } + @Deprecated protected Contract( String contractBinary, @@ -109,7 +146,7 @@ protected Contract( contractBinary, contractAddress, web3j, - new RawTransactionManager(web3j, credentials), + getTheTransactionManager(web3j,credentials), gasPrice, gasLimit); } @@ -135,7 +172,7 @@ protected Contract( "", contractAddress, web3j, - new RawTransactionManager(web3j, credentials), + getTheTransactionManager(web3j,credentials), gasPrice, gasLimit); } @@ -754,4 +791,13 @@ protected static List convertToNative(List arr) { } return out; } + + public TransactionManager getTransactionManager() { + return transactionManager; + } + + public void setTransactionManager(TransactionManager transactionManager) { + this.transactionManager = transactionManager; + } + } diff --git a/src/main/java/org/fisco/bcos/web3j/tx/ExtendedRawTransactionManager.java b/src/main/java/org/fisco/bcos/web3j/tx/ExtendedRawTransactionManager.java new file mode 100644 index 000000000..a421e1655 --- /dev/null +++ b/src/main/java/org/fisco/bcos/web3j/tx/ExtendedRawTransactionManager.java @@ -0,0 +1,157 @@ +package org.fisco.bcos.web3j.tx; + +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.crypto.*; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.Request; +import org.fisco.bcos.web3j.protocol.core.methods.response.SendTransaction; +import org.fisco.bcos.web3j.tx.exceptions.TxHashMismatchException; +import org.fisco.bcos.web3j.utils.Numeric; +import org.fisco.bcos.web3j.utils.TxHashVerifier; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Random; + +/** + * TransactionManager implementation using Ethereum wallet file to create and sign transactions + * locally. + * + *

This transaction manager provides support for specifying the chain id for transactions as per + * EIP155. + */ +public class ExtendedRawTransactionManager extends TransactionManager { + private final Web3j web3j; + final Credentials credentials; + + private final byte chainId; + + private final BigInteger groupId; + private final BigInteger fiscoChainId; + + protected TxHashVerifier txHashVerifier = new TxHashVerifier(); + + + public ExtendedRawTransactionManager(Web3j web3j, Credentials credentials, byte chainId, BigInteger groupId, BigInteger fiscoChainId) { + super(web3j, credentials); + this.web3j = web3j; + this.credentials = credentials; + this.chainId = chainId; + this.groupId = groupId; + this.fiscoChainId = fiscoChainId; + } + + public ExtendedRawTransactionManager(Web3j web3j, Credentials credentials, byte chainId, int attempts, int sleepDuration,BigInteger groupId, BigInteger fiscoChainId) { + super(web3j, attempts, sleepDuration, credentials); + this.web3j = web3j; + this.credentials = credentials; + this.chainId = chainId; + this.groupId = groupId; + this.fiscoChainId = fiscoChainId; + } + + public ExtendedRawTransactionManager(Web3j web3j, Credentials credentials,BigInteger groupId, BigInteger fiscoChainId) { + this(web3j, credentials, ChainId.NONE, groupId , fiscoChainId); + } + + public ExtendedRawTransactionManager( + Web3j web3j, Credentials credentials, int attempts, int sleepDuration ,BigInteger groupId, BigInteger fiscoChainId) { + this(web3j, credentials, ChainId.NONE, attempts, sleepDuration, groupId, fiscoChainId); + } + + BigInteger getBlockLimit() throws IOException { + return web3j.getBlockNumberCache(); + } + + public TxHashVerifier getTxHashVerifier() { + return txHashVerifier; + } + + public void setTxHashVerifier(TxHashVerifier txHashVerifier) { + this.txHashVerifier = txHashVerifier; + } + + @Override + public SendTransaction sendTransaction( + BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value, String extraData) + throws IOException { + + Random r = new SecureRandom(); + BigInteger randomid = new BigInteger(250, r); + BigInteger blockLimit = getBlockLimit(); + ExtendedRawTransaction rawTransaction = + ExtendedRawTransaction.createTransaction(randomid, gasPrice, gasLimit, blockLimit, to, value, data, fiscoChainId, groupId, extraData); + + return signAndSend(rawTransaction); + } + + @Override + public SendTransaction sendTransaction( + BigInteger gasPrice, + BigInteger gasLimit, + String to, + String data, + BigInteger value, + String extraData, + TransactionSucCallback callback) + throws IOException { + Random r = new SecureRandom(); + BigInteger randomid = new BigInteger(250, r); + BigInteger blockLimit = getBlockLimit(); + ExtendedRawTransaction extendedRawTransaction = + ExtendedRawTransaction.createTransaction(randomid, gasPrice, gasLimit, blockLimit, to, value, data, fiscoChainId, groupId, extraData); + + return signAndSend(extendedRawTransaction, callback); + } + + public SendTransaction signAndSend(ExtendedRawTransaction rawTransaction) throws IOException { + + byte[] signedMessage; + + if (chainId > ChainId.NONE) { + signedMessage = ExtendedTransactionEncoder.signMessage(rawTransaction, chainId, credentials); + } else { + signedMessage = ExtendedTransactionEncoder.signMessage(rawTransaction, credentials); + } + + String hexValue = Numeric.toHexString(signedMessage); + SendTransaction sendTransaction = web3j.sendRawTransaction(hexValue).send(); + if (sendTransaction != null && !sendTransaction.hasError()) { + String txHashLocal = Hash.sha3(hexValue); + String txHashRemote = sendTransaction.getTransactionHash(); + if (!txHashVerifier.verify(txHashLocal, txHashRemote)) { + throw new TxHashMismatchException(txHashLocal, txHashRemote); + } + } + return sendTransaction; + } + + public SendTransaction signAndSend(ExtendedRawTransaction rawTransaction, TransactionSucCallback callback) + throws IOException { + + byte[] signedMessage; + + if (chainId > ChainId.NONE) { + signedMessage = ExtendedTransactionEncoder.signMessage(rawTransaction, chainId, credentials); + } else { + signedMessage = ExtendedTransactionEncoder.signMessage(rawTransaction, credentials); + } + + String hexValue = Numeric.toHexString(signedMessage); + Request request = web3j.sendRawTransaction(hexValue); + request.setNeedTransCallback(true); + request.setTransactionSucCallback(callback); + SendTransaction ethSendTransaction = request.send(); + + if (ethSendTransaction != null && !ethSendTransaction.hasError()) { + String txHashLocal = Hash.sha3(hexValue); + String txHashRemote = ethSendTransaction.getTransactionHash(); + if (!txHashVerifier.verify(txHashLocal, txHashRemote)) { + throw new TxHashMismatchException(txHashLocal, txHashRemote); + } + } + + return ethSendTransaction; + } +} diff --git a/src/main/java/org/fisco/bcos/web3j/tx/ManagedTransaction.java b/src/main/java/org/fisco/bcos/web3j/tx/ManagedTransaction.java index 1ee9ed16d..8ba498768 100644 --- a/src/main/java/org/fisco/bcos/web3j/tx/ManagedTransaction.java +++ b/src/main/java/org/fisco/bcos/web3j/tx/ManagedTransaction.java @@ -15,7 +15,7 @@ public abstract class ManagedTransaction { protected Web3j web3j; - protected TransactionManager transactionManager; + protected TransactionManager transactionManager ; protected CnsService cnsService; @@ -37,7 +37,7 @@ protected TransactionReceipt send( String to, String data, BigInteger value, BigInteger gasPrice, BigInteger gasLimit) throws IOException, TransactionException { - return transactionManager.executeTransaction(gasPrice, gasLimit, to, data, value); + return transactionManager.executeTransaction(gasPrice, gasLimit, to, data, value,null); } protected void sendOnly( @@ -48,6 +48,6 @@ protected void sendOnly( BigInteger gasLimit, TransactionSucCallback callback) throws IOException, TransactionException { - transactionManager.sendTransaction(gasPrice, gasLimit, to, data, value, callback); + transactionManager.sendTransaction(gasPrice, gasLimit, to, data, value, null, callback); } } diff --git a/src/main/java/org/fisco/bcos/web3j/tx/RawTransactionManager.java b/src/main/java/org/fisco/bcos/web3j/tx/RawTransactionManager.java index 1593ee547..2137f0f07 100644 --- a/src/main/java/org/fisco/bcos/web3j/tx/RawTransactionManager.java +++ b/src/main/java/org/fisco/bcos/web3j/tx/RawTransactionManager.java @@ -26,7 +26,6 @@ * EIP155. */ public class RawTransactionManager extends TransactionManager { - static Logger logger = LoggerFactory.getLogger(RawTransactionManager.class); private final Web3j web3j; final Credentials credentials; @@ -74,7 +73,7 @@ public void setTxHashVerifier(TxHashVerifier txHashVerifier) { @Override public SendTransaction sendTransaction( - BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value) + BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value, String extraData) throws IOException { Random r = new SecureRandom(); @@ -93,6 +92,7 @@ public SendTransaction sendTransaction( String to, String data, BigInteger value, + String extraData, TransactionSucCallback callback) throws IOException { Random r = new SecureRandom(); diff --git a/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java b/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java index 474e3d6aa..62ea22ed7 100644 --- a/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java +++ b/src/main/java/org/fisco/bcos/web3j/tx/TransactionManager.java @@ -44,15 +44,15 @@ protected TransactionManager( } protected TransactionReceipt executeTransaction( - BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value) + BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value, String extraData) throws IOException, TransactionException { - SendTransaction sendTransaction = sendTransaction(gasPrice, gasLimit, to, data, value); + SendTransaction sendTransaction = sendTransaction(gasPrice, gasLimit, to, data, value, extraData); return processResponse(sendTransaction); } public abstract SendTransaction sendTransaction( - BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value) + BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value, String extraData) throws IOException; public SendTransaction sendTransaction( @@ -61,6 +61,7 @@ public SendTransaction sendTransaction( String to, String data, BigInteger value, + String extraData, TransactionSucCallback callback) throws IOException { return null; diff --git a/src/test/java/org/fisco/bcos/channel/test/BasicTest.java b/src/test/java/org/fisco/bcos/channel/test/BasicTest.java index 8a797e110..f3c3cf606 100644 --- a/src/test/java/org/fisco/bcos/channel/test/BasicTest.java +++ b/src/test/java/org/fisco/bcos/channel/test/BasicTest.java @@ -11,6 +11,8 @@ import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameter; import org.fisco.bcos.web3j.protocol.core.methods.response.*; +import org.fisco.bcos.web3j.tx.Contract; +import org.fisco.bcos.web3j.tx.ExtendedRawTransactionManager; import org.junit.Ignore; import org.junit.Test; @@ -91,6 +93,16 @@ public void basicTest() throws Exception { } } + @Test + public void basicExtendedTransactionTest() throws Exception { + try { + testExtendedTransactionDeployContract(web3j, credentials); + } catch (Exception e) { + e.printStackTrace(); + throw new Exception("Execute basic test failed"); + } + } + private void testDeployContract(Web3j web3j, Credentials credentials) throws Exception { Ok okDemo = Ok.deploy(web3j, credentials, gasPrice, gasLimit).send(); if (okDemo != null) { @@ -112,7 +124,54 @@ private void testDeployContract(Web3j web3j, Credentials credentials) throws Exc System.out.println("####contract address is: " + okDemo.getContractAddress()); // TransactionReceipt receipt = okDemo.trans(new // BigInteger("4")).sendAsync().get(60000, TimeUnit.MILLISECONDS); + Ok okDemo1= Ok.load(okDemo.getContractAddress(),web3j,credentials,gasPrice,gasLimit); + okDemo1.trans(new BigInteger("4")).send(); + TransactionReceipt receipt = okDemo.trans(new BigInteger("4")).send(); + List events = okDemo.getTransEventEvents(receipt); + events.stream().forEach(System.out::println); + + System.out.println("###callback trans success"); + + System.out.println( + "####get block number from TransactionReceipt: " + receipt.getBlockNumber()); + System.out.println( + "####get transaction index from TransactionReceipt: " + receipt.getTransactionIndex()); + System.out.println("####get gas used from TransactionReceipt: " + receipt.getGasUsed()); + // System.out.println("####get cumulative gas used from TransactionReceipt: " + + // receipt.getCumulativeGasUsed()); + + BigInteger toBalance = okDemo.get().send(); + System.out.println("============to balance:" + toBalance.intValue()); + } + } + + private void testExtendedTransactionDeployContract(Web3j web3j, Credentials credentials) throws Exception { + + Ok okDemo = Ok.deploy(web3j, credentials, gasPrice, gasLimit).send(); + + + if (okDemo != null) { + System.out.println( + "####get nonce from Block: " + + web3j + .getBlockByNumber(DefaultBlockParameter.valueOf(new BigInteger("0")), true) + .send() + .getBlock() + .getNonce()); + System.out.println( + "####get block number by index from Block: " + + web3j + .getBlockByNumber(DefaultBlockParameter.valueOf(new BigInteger("1")), true) + .send() + .getBlock() + .getNumber()); + + System.out.println("####contract address is: " + okDemo.getContractAddress()); + // TransactionReceipt receipt = okDemo.trans(new + // BigInteger("4")).sendAsync().get(60000, TimeUnit.MILLISECONDS); + Ok okDemo1= Ok.load(okDemo.getContractAddress(),web3j,credentials,gasPrice,gasLimit); TransactionReceipt receipt = okDemo.trans(new BigInteger("4")).send(); + okDemo1.trans(new BigInteger("4")).send(); List events = okDemo.getTransEventEvents(receipt); events.stream().forEach(System.out::println); diff --git a/src/test/java/org/fisco/bcos/channel/test/TestBase.java b/src/test/java/org/fisco/bcos/channel/test/TestBase.java index e76a2b7ee..397da0701 100644 --- a/src/test/java/org/fisco/bcos/channel/test/TestBase.java +++ b/src/test/java/org/fisco/bcos/channel/test/TestBase.java @@ -23,7 +23,7 @@ public static void setUpBeforeClass() throws Exception { // ((ClassPathXmlApplicationContext) context).start(); Service service = context.getBean(Service.class); - service.run(); + service.run(); System.out.println("start..."); System.out.println("==================================================================="); diff --git a/src/test/java/org/fisco/bcos/channel/test/amop/Perfomance.java b/src/test/java/org/fisco/bcos/channel/test/amop/Performance.java similarity index 100% rename from src/test/java/org/fisco/bcos/channel/test/amop/Perfomance.java rename to src/test/java/org/fisco/bcos/channel/test/amop/Performance.java diff --git a/src/test/java/org/fisco/bcos/channel/test/amop/PerfomanceCallback.java b/src/test/java/org/fisco/bcos/channel/test/amop/PerformanceCallback.java similarity index 71% rename from src/test/java/org/fisco/bcos/channel/test/amop/PerfomanceCallback.java rename to src/test/java/org/fisco/bcos/channel/test/amop/PerformanceCallback.java index a43030260..99ed671c9 100644 --- a/src/test/java/org/fisco/bcos/channel/test/amop/PerfomanceCallback.java +++ b/src/test/java/org/fisco/bcos/channel/test/amop/PerformanceCallback.java @@ -3,11 +3,11 @@ import org.fisco.bcos.channel.client.ChannelResponseCallback; import org.fisco.bcos.channel.dto.ChannelResponse; -public class PerfomanceCallback extends ChannelResponseCallback { +public class PerformanceCallback extends ChannelResponseCallback { @Override public void onResponseMessage(ChannelResponse response) { collector.onMessage(response); } - public PerfomanceCollector collector; + public PerformanceCollector collector; } diff --git a/src/test/java/org/fisco/bcos/channel/test/amop/PerfomanceCollector.java b/src/test/java/org/fisco/bcos/channel/test/amop/PerformanceCollector.java similarity index 51% rename from src/test/java/org/fisco/bcos/channel/test/amop/PerfomanceCollector.java rename to src/test/java/org/fisco/bcos/channel/test/amop/PerformanceCollector.java index 198a527fd..c6468e34f 100644 --- a/src/test/java/org/fisco/bcos/channel/test/amop/PerfomanceCollector.java +++ b/src/test/java/org/fisco/bcos/channel/test/amop/PerformanceCollector.java @@ -6,8 +6,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class PerfomanceCollector { - static Logger logger = LoggerFactory.getLogger(PerfomanceCollector.class); +public class PerformanceCollector { + static Logger logger = LoggerFactory.getLogger(PerformanceCollector.class); public Map resultMap; public Integer total; public AtomicInteger received = new AtomicInteger(0); @@ -21,11 +21,8 @@ public void onMessage(ChannelResponse response) { Integer currentError = 0; if (response.getErrorCode() != 0) { - System.out.println( - "response error:" - + String.valueOf(response.getErrorCode()) - + ", " - + response.getErrorMessage()); + System.out + .println("response error:" + String.valueOf(response.getErrorCode()) + ", " + response.getErrorMessage()); currentError = 1; } @@ -34,8 +31,7 @@ public void onMessage(ChannelResponse response) { if (response.getMessageID() != null) { timer = resultMap.get(response.getMessageID()); if (timer == null) { - System.out.println( - "response error,seq:" + String.valueOf(response.getMessageID()) + " not found"); + System.out.println("response error,seq:" + String.valueOf(response.getMessageID()) + " not found"); currentError = 1; } } else { @@ -50,19 +46,12 @@ public void onMessage(ChannelResponse response) { received.incrementAndGet(); - logger.debug( - "response: {} {} {}, total:{}/{}", - response.getErrorCode(), - response.getMessageID(), - response.getContent(), - received, - total); + logger.debug("response: {} {} {}, total:{}/{}", response.getErrorCode(), response.getMessageID(), + response.getContent(), received, total); if ((received.get() + 1) % (total / 10) == 0) { - System.out.println( - " |received:" - + String.valueOf((received.get() + 1) * 100 / total) - + "%"); + System.out.println(" |received:" + + String.valueOf((received.get() + 1) * 100 / total) + "%"); } if (received.intValue() >= total) { @@ -113,55 +102,25 @@ public void onMessage(ChannelResponse response) { System.out.println("total: " + String.valueOf(total)); System.out.println("packageSize: " + String.valueOf(packageSize) + " byte"); System.out.println("tps: " + String.valueOf(tps)); - System.out.println( - "total/totalTime: " + String.valueOf(total / ((double) totalTime / 1000))); + System.out.println("total/totalTime: " + String.valueOf(total / ((double) totalTime / 1000))); System.out.println("totalCost/total:" + String.valueOf(totalCost / total) + "ms"); - System.out.println( - "error/received: " + String.valueOf((error.get() / received.get()) * 100) + "%"); + System.out.println("error/received: " + String.valueOf((error.get() / received.get()) * 100) + "%"); System.out.println("time:"); - System.out.println( - "0 < time < 50ms : " - + String.valueOf(less50) - + " : " - + String.valueOf((double) less50 / total * 100) - + "%"); - System.out.println( - "50 < time < 100ms : " - + String.valueOf(less100) - + " : " - + String.valueOf((double) less100 / total * 100) - + "%"); - System.out.println( - "100 < time < 200ms : " - + String.valueOf(less200) - + " : " - + String.valueOf((double) less200 / total * 100) - + "%"); - System.out.println( - "200 < time < 400ms : " - + String.valueOf(less400) - + " : " - + String.valueOf((double) less400 / total * 100) - + "%"); - System.out.println( - "400 < time < 1000ms : " - + String.valueOf(less1000) - + " : " - + String.valueOf((double) less1000 / total * 100) - + "%"); - System.out.println( - "1000 < time < 2000ms : " - + String.valueOf(less2000) - + " : " - + String.valueOf((double) less2000 / total * 100) - + "%"); - System.out.println( - "2000 < time : " - + String.valueOf(timeout2000) - + " : " - + String.valueOf((double) timeout2000 / total * 100) - + "%"); + System.out.println("0 < time < 50ms : " + String.valueOf(less50) + " : " + + String.valueOf((double) less50 / total * 100) + "%"); + System.out.println("50 < time < 100ms : " + String.valueOf(less100) + " : " + + String.valueOf((double) less100 / total * 100) + "%"); + System.out.println("100 < time < 200ms : " + String.valueOf(less200) + " : " + + String.valueOf((double) less200 / total * 100) + "%"); + System.out.println("200 < time < 400ms : " + String.valueOf(less400) + " : " + + String.valueOf((double) less400 / total * 100) + "%"); + System.out.println("400 < time < 1000ms : " + String.valueOf(less1000) + " : " + + String.valueOf((double) less1000 / total * 100) + "%"); + System.out.println("1000 < time < 2000ms : " + String.valueOf(less2000) + " : " + + String.valueOf((double) less2000 / total * 100) + "%"); + System.out.println("2000 < time : " + String.valueOf(timeout2000) + " : " + + String.valueOf((double) timeout2000 / total * 100) + "%"); } } catch (Exception e) { logger.error("error:", e); diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java index bcea4ea58..d46bc37f2 100644 --- a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceCollector.java @@ -127,7 +127,116 @@ public void onMessage(TransactionReceipt receipt, Long cost) { logger.error("error:", e); } } - + + + public void onSelectMessage(TransactionReceipt receipt, Long cost) { + try { + if (!receipt.isStatusOK()) { + System.out.println("receipt error"); + error.addAndGet(1); + } + + received.incrementAndGet(); + + 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.intValue() >= 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: " + String.valueOf(total / ((double) totalTime / 1000))); + System.out.println("Avg time cost: " + String.valueOf(totalCost.get() / total) + "ms"); + System.out.println( + "Error rate: " + String.valueOf((error.get() / 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) + + "%"); + + System.exit(0); + } + } catch (Exception e) { + logger.error("error:", e); + } + } + + + private AtomicLong less50 = new AtomicLong(0); private AtomicLong less100 = new AtomicLong(0); private AtomicLong less200 = new AtomicLong(0); diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOkD.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableInsert.java similarity index 82% rename from src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOkD.java rename to src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableInsert.java index 9a9100aa9..ac806c5e4 100644 --- a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOkD.java +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableInsert.java @@ -2,10 +2,15 @@ import com.google.common.util.concurrent.RateLimiter; import java.math.BigInteger; +import java.text.SimpleDateFormat; +import java.util.Date; import java.util.Random; +import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.web3j.crypto.Credentials; import org.fisco.bcos.web3j.protocol.Web3j; @@ -17,9 +22,23 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -public class PerfomanceOkD { - private static Logger logger = LoggerFactory.getLogger(PerfomanceOkD.class); +public class PerfomanceTableInsert { + private static Logger logger = LoggerFactory.getLogger(PerfomanceTableInsert.class); private static AtomicInteger sended = new AtomicInteger(0); + + + private static String getId(){ + UUID uuid = UUID.randomUUID(); + return uuid.toString().replace("-", ""); + } + + + private static AtomicLong uniqeid = new AtomicLong(0); + + public static long getNextID() { + return uniqeid.getAndIncrement(); + } + public static void main(String[] args) throws Exception { try { @@ -71,7 +90,7 @@ public static void main(String[] args) throws Exception { threadPool.initialize(); System.out.println("Deploying contract..."); - OkD ok = OkD.deploy(web3, credentials, gasPrice, gasLimit).send(); + TableTest tabletest = TableTest.deploy(web3, credentials, gasPrice, gasLimit).send(); PerfomanceCollector collector = new PerfomanceCollector(); collector.setTotal(count); @@ -89,10 +108,13 @@ public static void main(String[] args) throws Exception { @Override public void run() { limiter.acquire(); - PerfomanceOkCallback callback = new PerfomanceOkCallback(); + PerfomanceTableTestCallback callback = new PerfomanceTableTestCallback(); callback.setCollector(collector); try { - ok.trans(String.valueOf(random.nextLong()), new BigInteger("1"), callback); + long _id = getNextID(); + tabletest.insert("fruit"+_id%TableTestClient.modevalue, + BigInteger.valueOf(_id), + "apple"+getId(),callback); } catch (Exception e) { TransactionReceipt receipt = new TransactionReceipt(); receipt.setStatus("-1"); diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOk.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableModify.java similarity index 78% rename from src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOk.java rename to src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableModify.java index 9ab8cdd51..d5fb8cbe4 100644 --- a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOk.java +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableModify.java @@ -2,24 +2,43 @@ import com.google.common.util.concurrent.RateLimiter; import java.math.BigInteger; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Random; +import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.web3j.crypto.Credentials; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.fisco.bcos.web3j.utils.Web3AsyncThreadPoolSize; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -public class PerfomanceOk { - private static Logger logger = LoggerFactory.getLogger(PerfomanceOk.class); +public class PerfomanceTableModify { + private static Logger logger = LoggerFactory.getLogger(PerfomanceTableModify.class); private static AtomicInteger sended = new AtomicInteger(0); + + + private static String getId(){ + UUID uuid = UUID.randomUUID(); + return uuid.toString().replace("-", ""); + } + + + private static AtomicLong uniqeid = new AtomicLong(0); + + public static long getNextID() { + return uniqeid.getAndIncrement(); + } + public static void main(String[] args) throws Exception { try { @@ -36,9 +55,6 @@ public static void main(String[] args) throws Exception { ChannelEthereumService channelEthereumService = new ChannelEthereumService(); channelEthereumService.setChannelService(service); - Web3AsyncThreadPoolSize.web3AsyncCorePoolSize = 3000; - Web3AsyncThreadPoolSize.web3AsyncPoolSize = 2000; - ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500); Web3j web3 = Web3j.build( @@ -74,7 +90,7 @@ public static void main(String[] args) throws Exception { threadPool.initialize(); System.out.println("Deploying contract..."); - Ok ok = Ok.deploy(web3, credentials, gasPrice, gasLimit).send(); + TableTest tabletest = TableTest.deploy(web3, credentials, gasPrice, gasLimit).send(); PerfomanceCollector collector = new PerfomanceCollector(); collector.setTotal(count); @@ -83,6 +99,8 @@ public static void main(String[] args) throws Exception { Integer area = count / 10; final Integer total = count; + Random random = new Random(System.currentTimeMillis()); + System.out.println("Start test,total:" + count); for (Integer i = 0; i < count; ++i) { threadPool.execute( @@ -90,16 +108,22 @@ public static void main(String[] args) throws Exception { @Override public void run() { limiter.acquire(); - PerfomanceOkCallback callback = new PerfomanceOkCallback(); + PerfomanceTableTestCallback callback = new PerfomanceTableTestCallback(); callback.setCollector(collector); try { - ok.trans(new BigInteger("4"), callback); + long _id = getNextID(); + Random r=new Random(); + long l1=r.nextLong(); + tabletest.update("fruit"+l1%TableTestClient.modevalue, + BigInteger.valueOf(_id), + "apple"+getId(), + callback); } catch (Exception e) { TransactionReceipt receipt = new TransactionReceipt(); receipt.setStatus("-1"); callback.onResponse(receipt); - logger.info(e.getMessage()); + logger.error("Error sending:", e); } int current = sended.incrementAndGet(); @@ -113,7 +137,6 @@ public void run() { } catch (Exception e) { e.printStackTrace(); System.exit(-1); - ; } } } diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableQuery.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableQuery.java new file mode 100644 index 000000000..6098537cf --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableQuery.java @@ -0,0 +1,170 @@ +package org.fisco.bcos.channel.test.contract; + +import com.google.common.util.concurrent.RateLimiter; +import java.math.BigInteger; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tuples.generated.Tuple3; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +public class PerfomanceTableQuery { + private static Logger logger = LoggerFactory.getLogger(PerfomanceTableQuery.class); + private static AtomicInteger sended = new AtomicInteger(0); + + + private static String getId(){ + UUID uuid = UUID.randomUUID(); + return uuid.toString().replace("-", ""); + } + + + private static AtomicLong uniqeid = new AtomicLong(0); + + public static long getNextID() { + return uniqeid.getAndIncrement(); + } + + + public static void main(String[] args) throws Exception { + try { + String groupId = args[3]; + ApplicationContext context = + new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(groupId)); + service.run(); + + System.out.println("Start test..."); + System.out.println("==================================================================="); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500); + Web3j web3 = + Web3j.build( + channelEthereumService, + 15 * 100, + scheduledExecutorService, + Integer.parseInt(groupId)); + + Credentials credentials = + Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + + BigInteger gasPrice = new BigInteger("30000000"); + BigInteger gasLimit = new BigInteger("30000000"); + + String command = args[0]; + Integer count = 0; + Integer qps = 0; + + switch (command) { + case "trans": + count = Integer.parseInt(args[1]); + qps = Integer.parseInt(args[2]); + break; + default: + System.out.println("Args: "); + } + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count); + + threadPool.initialize(); + + System.out.println("Deploying contract..."); + TableTest tabletest = TableTest.deploy(web3, credentials, gasPrice, gasLimit).send(); + + PerfomanceCollector collector = new PerfomanceCollector(); + collector.setTotal(count); + + RateLimiter limiter = RateLimiter.create(qps); + Integer area = count / 10; + final Integer total = count; + + Random random = new Random(System.currentTimeMillis()); + + System.out.println("Start test,total:" + count); + for (Integer i = 0; i < count; ++i) { + threadPool.execute( + new Runnable() { + @Override + public void run() { + limiter.acquire(); + PerfomanceTableTestCallback callback = new PerfomanceTableTestCallback(); + callback.setCollector(collector); + try { + + Long time_before = System.currentTimeMillis(); + long _id = getNextID(); + Random r=new Random(); + long l1=r.nextLong(); + Tuple3, List, List> lists = + tabletest.select("fruit"+l1%TableTestClient.modevalue).send(); + Long time_after = System.currentTimeMillis(); + + TransactionReceipt receipt = new TransactionReceipt(); + receipt.setStatus("0"); + collector.onSelectMessage(receipt, time_after-time_before); + + /* + List value1 = lists.getValue1(); + List value2 = lists.getValue2(); + List value3 = lists.getValue3(); + logger.info("record numbers = " + value1.size()); + System.out.println("record numbers = " + value1.size()); + for (int i = 0; i < value1.size(); i++) { + String name = new String(value1.get(i)); + logger.info("name = " + name); + System.out.println("name = " + name); + int item_id = value2.get(i).intValue(); + logger.info("item_id = " + item_id); + System.out.println("item_id = " + item_id); + String item_name = new String(value3.get(i)); + logger.info("item_name = " + item_name); + System.out.println("item_name = " + item_name); + } + + */ + + } catch (Exception e) { + TransactionReceipt receipt = new TransactionReceipt(); + receipt.setStatus("-1"); + + callback.onResponse(receipt); + logger.error("Error sending:", e); + } + + int current = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + total + " transactions"); + } + } + }); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableRemove.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableRemove.java new file mode 100644 index 000000000..88fe4b067 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableRemove.java @@ -0,0 +1,141 @@ +package org.fisco.bcos.channel.test.contract; + +import com.google.common.util.concurrent.RateLimiter; +import java.math.BigInteger; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +public class PerfomanceTableRemove { + private static Logger logger = LoggerFactory.getLogger(PerfomanceTableRemove.class); + private static AtomicInteger sended = new AtomicInteger(0); + + + private static String getId(){ + UUID uuid = UUID.randomUUID(); + return uuid.toString().replace("-", ""); + } + + + private static AtomicLong uniqeid = new AtomicLong(0); + + public static long getNextID() { + return uniqeid.getAndIncrement(); + } + + + public static void main(String[] args) throws Exception { + try { + String groupId = args[3]; + ApplicationContext context = + new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(groupId)); + service.run(); + + System.out.println("Start test..."); + System.out.println("==================================================================="); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500); + Web3j web3 = + Web3j.build( + channelEthereumService, + 15 * 100, + scheduledExecutorService, + Integer.parseInt(groupId)); + + Credentials credentials = + Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + + BigInteger gasPrice = new BigInteger("30000000"); + BigInteger gasLimit = new BigInteger("30000000"); + + String command = args[0]; + Integer count = 0; + Integer qps = 0; + + switch (command) { + case "trans": + count = Integer.parseInt(args[1]); + qps = Integer.parseInt(args[2]); + break; + default: + System.out.println("Args: "); + } + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count); + + threadPool.initialize(); + + System.out.println("Deploying contract..."); + TableTest tabletest = TableTest.deploy(web3, credentials, gasPrice, gasLimit).send(); + + PerfomanceCollector collector = new PerfomanceCollector(); + collector.setTotal(count); + + RateLimiter limiter = RateLimiter.create(qps); + Integer area = count / 10; + final Integer total = count; + + Random random = new Random(System.currentTimeMillis()); + + System.out.println("Start test,total:" + count); + for (Integer i = 0; i < count; ++i) { + threadPool.execute( + new Runnable() { + @Override + public void run() { + limiter.acquire(); + PerfomanceTableTestCallback callback = new PerfomanceTableTestCallback(); + callback.setCollector(collector); + try { + long _id = getNextID(); + Random r=new Random(); + long l1=r.nextLong(); + tabletest.remove("fruit"+l1%TableTestClient.modevalue, + BigInteger.valueOf(_id), callback); + + } catch (Exception e) { + TransactionReceipt receipt = new TransactionReceipt(); + receipt.setStatus("-1"); + + callback.onResponse(receipt); + logger.error("Error sending:", e); + } + + int current = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + total + " transactions"); + } + } + }); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOkCallback.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableTestCallback.java similarity index 84% rename from src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOkCallback.java rename to src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableTestCallback.java index 06c8ba0b8..875bf2ba3 100644 --- a/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceOkCallback.java +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerfomanceTableTestCallback.java @@ -7,7 +7,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class PerfomanceOkCallback extends TransactionSucCallback { +public class PerfomanceTableTestCallback extends TransactionSucCallback { private static ObjectMapper objectMapper = new ObjectMapper(); private Long startTime = System.currentTimeMillis(); @@ -21,9 +21,9 @@ public void setCollector(PerfomanceCollector collector) { this.collector = collector; } - static Logger logger = LoggerFactory.getLogger(PerfomanceOkCallback.class); + static Logger logger = LoggerFactory.getLogger(PerfomanceTableTestCallback.class); - PerfomanceOkCallback() { + PerfomanceTableTestCallback() { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceCollector.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceCollector.java new file mode 100644 index 000000000..5bfe45a3e --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceCollector.java @@ -0,0 +1,113 @@ +package org.fisco.bcos.channel.test.contract; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PerformanceCollector { + static Logger logger = LoggerFactory.getLogger(PerformanceCollector.class); + + public Integer getTotal() { + return total; + } + + public void setTotal(Integer total) { + this.total = total; + } + + public void onMessage(TransactionReceipt receipt, Long cost) { + try { + if (!receipt.isStatusOK()) { + System.out.println("receipt error"); + error.addAndGet(1); + } else { + if (receipt.getLogs().isEmpty()) { + System.out.println("receipt log error"); + error.addAndGet(1); + } + } + + received.incrementAndGet(); + + 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.intValue() >= 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: " + String.valueOf(total / ((double) totalTime / 1000))); + System.out.println("Avg time cost: " + String.valueOf(totalCost.get() / total) + "ms"); + System.out.println("Error rate: " + String.valueOf((error.get() / 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) + "%"); + + System.exit(0); + } + } catch (Exception e) { + logger.error("error:", e); + } + } + + 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(); +} diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOk.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOk.java new file mode 100644 index 000000000..5c036f4d9 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOk.java @@ -0,0 +1,111 @@ +package org.fisco.bcos.channel.test.contract; + +import com.google.common.util.concurrent.RateLimiter; +import java.math.BigInteger; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.utils.Web3AsyncThreadPoolSize; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +public class PerformanceOk { + private static Logger logger = LoggerFactory.getLogger(PerformanceOk.class); + private static AtomicInteger sended = new AtomicInteger(0); + + public static void main(String[] args) throws Exception { + try { + String groupId = args[3]; + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(groupId)); + service.run(); + + System.out.println("Start test..."); + System.out.println("==================================================================="); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + Web3AsyncThreadPoolSize.web3AsyncCorePoolSize = 3000; + Web3AsyncThreadPoolSize.web3AsyncPoolSize = 2000; + + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500); + Web3j web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId)); + + Credentials credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + + BigInteger gasPrice = new BigInteger("30000000"); + BigInteger gasLimit = new BigInteger("30000000"); + + String command = args[0]; + Integer count = 0; + Integer qps = 0; + + switch (command) { + case "trans": + count = Integer.parseInt(args[1]); + qps = Integer.parseInt(args[2]); + break; + default: + System.out.println("Args: "); + } + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count); + + threadPool.initialize(); + + System.out.println("Deploying contract..."); + Ok ok = Ok.deploy(web3, credentials, gasPrice, gasLimit).send(); + + PerformanceCollector collector = new PerformanceCollector(); + collector.setTotal(count); + + RateLimiter limiter = RateLimiter.create(qps); + Integer area = count / 10; + final Integer total = count; + + System.out.println("Start test,total:" + count); + for (Integer i = 0; i < count; ++i) { + threadPool.execute(new Runnable() { + @Override + public void run() { + limiter.acquire(); + PerformanceOkCallback callback = new PerformanceOkCallback(); + 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 = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + total + " transactions"); + } + } + }); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + ; + } + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOkCallback.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOkCallback.java new file mode 100644 index 000000000..0f172edb6 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOkCallback.java @@ -0,0 +1,39 @@ +package org.fisco.bcos.channel.test.contract; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PerformanceOkCallback extends TransactionSucCallback { + private static ObjectMapper objectMapper = new ObjectMapper(); + private Long startTime = System.currentTimeMillis(); + + private PerformanceCollector collector; + + public PerformanceCollector getCollector() { return collector; } + + public void setCollector(PerformanceCollector collector) { + this.collector = collector; + } + + static Logger logger = LoggerFactory.getLogger(PerformanceOkCallback.class); + + PerformanceOkCallback() { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, + false); + } + + @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/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOkD.java b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOkD.java new file mode 100644 index 000000000..330aeb3df --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/PerformanceOkD.java @@ -0,0 +1,109 @@ +package org.fisco.bcos.channel.test.contract; + +import com.google.common.util.concurrent.RateLimiter; +import java.math.BigInteger; +import java.util.Random; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +public class PerformanceOkD { + private static Logger logger = LoggerFactory.getLogger(PerformanceOkD.class); + private static AtomicInteger sended = new AtomicInteger(0); + + public static void main(String[] args) throws Exception { + try { + String groupId = args[3]; + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(groupId)); + service.run(); + + System.out.println("Start test..."); + System.out.println("==================================================================="); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500); + Web3j web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId)); + + Credentials credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + + BigInteger gasPrice = new BigInteger("30000000"); + BigInteger gasLimit = new BigInteger("30000000"); + + String command = args[0]; + Integer count = 0; + Integer qps = 0; + + switch (command) { + case "trans": + count = Integer.parseInt(args[1]); + qps = Integer.parseInt(args[2]); + break; + default: + System.out.println("Args: "); + } + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count); + + threadPool.initialize(); + + System.out.println("Deploying contract..."); + OkD ok = OkD.deploy(web3, credentials, gasPrice, gasLimit).send(); + + PerformanceCollector collector = new PerformanceCollector(); + collector.setTotal(count); + + RateLimiter limiter = RateLimiter.create(qps); + Integer area = count / 10; + final Integer total = count; + + Random random = new Random(System.currentTimeMillis()); + + System.out.println("Start test,total:" + count); + for (Integer i = 0; i < count; ++i) { + threadPool.execute(new Runnable() { + @Override + public void run() { + limiter.acquire(); + PerformanceOkCallback callback = new PerformanceOkCallback(); + callback.setCollector(collector); + try { + ok.trans(String.valueOf(random.nextLong()), new BigInteger("1"), callback); + } catch (Exception e) { + TransactionReceipt receipt = new TransactionReceipt(); + receipt.setStatus("-1"); + + callback.onResponse(receipt); + logger.error("Error sending:", e); + } + + int current = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + total + " transactions"); + } + } + }); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/TableTest.java b/src/test/java/org/fisco/bcos/channel/test/contract/TableTest.java new file mode 100644 index 000000000..6ed7e28ab --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/TableTest.java @@ -0,0 +1,412 @@ +package org.fisco.bcos.channel.test.contract; + + +import io.reactivex.Flowable; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.abi.EventEncoder; +import org.fisco.bcos.web3j.abi.TypeReference; +import org.fisco.bcos.web3j.abi.datatypes.DynamicArray; +import org.fisco.bcos.web3j.abi.datatypes.Event; +import org.fisco.bcos.web3j.abi.datatypes.Function; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameter; +import org.fisco.bcos.web3j.protocol.core.RemoteCall; +import org.fisco.bcos.web3j.protocol.core.methods.request.BcosFilter; +import org.fisco.bcos.web3j.protocol.core.methods.response.Log; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tuples.generated.Tuple3; +import org.fisco.bcos.web3j.tx.Contract; +import org.fisco.bcos.web3j.tx.TransactionManager; +import org.fisco.bcos.web3j.tx.gas.ContractGasProvider; + +/** + *

Auto generated code. + *

Do not modify! + *

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

Generated with web3j version none. + */ +@SuppressWarnings("unchecked") +public class TableTest extends Contract { + private static final String BINARY = "608060405234801561001057600080fd5b50612239806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063487a5a1014610072578063c4f41ab31461013f578063ebf3b24f146101c6578063efc81a8c14610293578063fcd7e3c1146102be575b600080fd5b34801561007e57600080fd5b50610129600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929050505061040c565b6040518082815260200191505060405180910390f35b34801561014b57600080fd5b506101b0600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610b02565b6040518082815260200191505060405180910390f35b3480156101d257600080fd5b5061027d600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610ffb565b6040518082815260200191505060405180910390f35b34801561029f57600080fd5b506102a861161a565b6040518082815260200191505060405180910390f35b3480156102ca57600080fd5b50610325600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506117b2565b60405180806020018060200180602001848103845287818151815260200191508051906020019060200280838360005b83811015610370578082015181840152602081019050610355565b50505050905001848103835286818151815260200191508051906020019060200280838360005b838110156103b2578082015181840152602081019050610397565b50505050905001848103825285818151815260200191508051906020019060200280838360005b838110156103f45780820151818401526020810190506103d9565b50505050905001965050505050505060405180910390f35b60008060008060008061100194508473ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156104ba57600080fd5b505af11580156104ce573d6000803e3d6000fd5b505050506040513d60208110156104e457600080fd5b810190808051906020019092919050505093508373ffffffffffffffffffffffffffffffffffffffff166313db93466040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561055b57600080fd5b505af115801561056f573d6000803e3d6000fd5b505050506040513d602081101561058557600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff1663e942b516886040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b8381101561065857808201518184015260208101905061063d565b50505050905090810190601f1680156106855780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b1580156106a557600080fd5b505af11580156106b9573d6000803e3d6000fd5b505050508373ffffffffffffffffffffffffffffffffffffffff16637857d7c96040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561072157600080fd5b505af1158015610735573d6000803e3d6000fd5b505050506040513d602081101561074b57600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663cd30a1d18a6040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b8381101561081e578082015181840152602081019050610803565b50505050905090810190601f16801561084b5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561086b57600080fd5b505af115801561087f573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663e44594b9896040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561092b57600080fd5b505af115801561093f573d6000803e3d6000fd5b505050508373ffffffffffffffffffffffffffffffffffffffff1663bf2b70a18a85856040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825285818151815260200191508051906020019080838360005b83811015610a31578082015181840152602081019050610a16565b50505050905090810190601f168015610a5e5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b158015610a7f57600080fd5b505af1158015610a93573d6000803e3d6000fd5b505050506040513d6020811015610aa957600080fd5b810190808051906020019092919050505090507f0bdcb3b747cf033ae78b4b6e1576d2725709d03f68ad3d641b12cb72de614354816040518082815260200191505060405180910390a180955050505050509392505050565b600080600080600061100193508373ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015610baf57600080fd5b505af1158015610bc3573d6000803e3d6000fd5b505050506040513d6020811015610bd957600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff16637857d7c96040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015610c5057600080fd5b505af1158015610c64573d6000803e3d6000fd5b505050506040513d6020811015610c7a57600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663cd30a1d1886040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b83811015610d4d578082015181840152602081019050610d32565b50505050905090810190601f168015610d7a5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015610d9a57600080fd5b505af1158015610dae573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663e44594b9876040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b158015610e5a57600080fd5b505af1158015610e6e573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff166328bb211788846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b83811015610f2d578082015181840152602081019050610f12565b50505050905090810190601f168015610f5a5780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b158015610f7a57600080fd5b505af1158015610f8e573d6000803e3d6000fd5b505050506040513d6020811015610fa457600080fd5b810190808051906020019092919050505090507f896358cb98e9e8e891ae04efd1bc177efbe5cffd7eca2e784b16ed7468553e08816040518082815260200191505060405180910390a18094505050505092915050565b600080600080600061100193508373ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156110a857600080fd5b505af11580156110bc573d6000803e3d6000fd5b505050506040513d60208110156110d257600080fd5b810190808051906020019092919050505092508273ffffffffffffffffffffffffffffffffffffffff166313db93466040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561114957600080fd5b505af115801561115d573d6000803e3d6000fd5b505050506040513d602081101561117357600080fd5b810190808051906020019092919050505091508173ffffffffffffffffffffffffffffffffffffffff1663e942b516896040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b8381101561124657808201518184015260208101905061122b565b50505050905090810190601f1680156112735780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561129357600080fd5b505af11580156112a7573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff16632ef8ba74886040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001838152602001828103825260078152602001807f6974656d5f69640000000000000000000000000000000000000000000000000081525060200192505050600060405180830381600087803b15801561135357600080fd5b505af1158015611367573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff1663e942b516876040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808060200180602001838103835260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001838103825284818151815260200191508051906020019080838360005b8381101561142b578082015181840152602081019050611410565b50505050905090810190601f1680156114585780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b15801561147857600080fd5b505af115801561148c573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff166331afac3689846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b8381101561154b578082015181840152602081019050611530565b50505050905090810190601f1680156115785780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561159857600080fd5b505af11580156115ac573d6000803e3d6000fd5b505050506040513d60208110156115c257600080fd5b810190808051906020019092919050505090507f66f7705280112a4d1145399e0414adc43a2d6974b487710f417edcf7d4a39d71816040518082815260200191505060405180910390a1809450505050509392505050565b600080600061100191508173ffffffffffffffffffffffffffffffffffffffff166356004b6a6040518163ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018060200180602001848103845260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001848103835260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001848103825260118152602001807f6974656d5f69642c6974656d5f6e616d650000000000000000000000000000008152506020019350505050602060405180830381600087803b15801561173657600080fd5b505af115801561174a573d6000803e3d6000fd5b505050506040513d602081101561176057600080fd5b810190808051906020019092919050505090507fcd4779437d9d027acc605a96427bfbd3787a1402cb53a5e64cd813d5391fbc2b816040518082815260200191505060405180910390a1809250505090565b6060806060600080600080606080606060008061100198508873ffffffffffffffffffffffffffffffffffffffff1663f23f63c96040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260068152602001807f745f746573740000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b15801561186a57600080fd5b505af115801561187e573d6000803e3d6000fd5b505050506040513d602081101561189457600080fd5b810190808051906020019092919050505097508773ffffffffffffffffffffffffffffffffffffffff16637857d7c96040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561190b57600080fd5b505af115801561191f573d6000803e3d6000fd5b505050506040513d602081101561193557600080fd5b810190808051906020019092919050505096508773ffffffffffffffffffffffffffffffffffffffff1663e8434e398e896040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828103825284818151815260200191508051906020019080838360005b83811015611a035780820151818401526020810190506119e8565b50505050905090810190601f168015611a305780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b158015611a5057600080fd5b505af1158015611a64573d6000803e3d6000fd5b505050506040513d6020811015611a7a57600080fd5b810190808051906020019092919050505095508573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611af157600080fd5b505af1158015611b05573d6000803e3d6000fd5b505050506040513d6020811015611b1b57600080fd5b8101908080519060200190929190505050604051908082528060200260200182016040528015611b5a5781602001602082028038833980820191505090505b5094508573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611bc157600080fd5b505af1158015611bd5573d6000803e3d6000fd5b505050506040513d6020811015611beb57600080fd5b8101908080519060200190929190505050604051908082528060200260200182016040528015611c2a5781602001602082028038833980820191505090505b5093508573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611c9157600080fd5b505af1158015611ca5573d6000803e3d6000fd5b505050506040513d6020811015611cbb57600080fd5b8101908080519060200190929190505050604051908082528060200260200182016040528015611cfa5781602001602082028038833980820191505090505b509250600091505b8573ffffffffffffffffffffffffffffffffffffffff1663949d225d6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611d6657600080fd5b505af1158015611d7a573d6000803e3d6000fd5b505050506040513d6020811015611d9057600080fd5b81019080805190602001909291905050508212156121f4578573ffffffffffffffffffffffffffffffffffffffff1663846719e0836040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180828152602001915050602060405180830381600087803b158015611e1757600080fd5b505af1158015611e2b573d6000803e3d6000fd5b505050506040513d6020811015611e4157600080fd5b810190808051906020019092919050505090508073ffffffffffffffffffffffffffffffffffffffff166327314f796040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260048152602001807f6e616d6500000000000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015611ef457600080fd5b505af1158015611f08573d6000803e3d6000fd5b505050506040513d6020811015611f1e57600080fd5b81019080805190602001909291905050508583815181101515611f3d57fe5b9060200190602002019060001916908160001916815250508073ffffffffffffffffffffffffffffffffffffffff1663fda69fae6040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260078152602001807f6974656d5f696400000000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b158015611ff557600080fd5b505af1158015612009573d6000803e3d6000fd5b505050506040513d602081101561201f57600080fd5b8101908080519060200190929190505050848381518110151561203e57fe5b90602001906020020181815250508073ffffffffffffffffffffffffffffffffffffffff166327314f796040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260098152602001807f6974656d5f6e616d650000000000000000000000000000000000000000000000815250602001915050602060405180830381600087803b1580156120ec57600080fd5b505af1158015612100573d6000803e3d6000fd5b505050506040513d602081101561211657600080fd5b8101908080519060200190929190505050838381518110151561213557fe5b9060200190602002019060001916908160001916815250507fc65cd2adf133adee2ddcfab8b165c2f1f7b185c4389b0789a11112483efb1c84858381518110151561217c57fe5b90602001906020020151858481518110151561219457fe5b9060200190602002015185858151811015156121ac57fe5b906020019060200201516040518084600019166000191681526020018381526020018260001916600019168152602001935050505060405180910390a1816001019150611d02565b8484849b509b509b5050505050505050505091939092505600a165627a7a723058201ab472e3141e7db3e2203297190547ca2e10b6b55a96dc8278b4a88a2ff72a700029"; + + 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() {})); + ; + + @Deprecated + protected TableTest(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected TableTest(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected TableTest(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected TableTest(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteCall update(String name, BigInteger item_id, String item_name) { + final Function function = new Function( + FUNC_UPDATE, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Int256(item_id), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(item_name)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void update(String name, BigInteger item_id, String item_name, TransactionSucCallback callback) { + final Function function = new Function( + FUNC_UPDATE, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Int256(item_id), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(item_name)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall remove(String name, BigInteger item_id) { + final Function function = new Function( + FUNC_REMOVE, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Int256(item_id)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void remove(String name, BigInteger item_id, TransactionSucCallback callback) { + final Function function = new Function( + FUNC_REMOVE, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Int256(item_id)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall insert(String name, BigInteger item_id, String item_name) { + final Function function = new Function( + FUNC_INSERT, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Int256(item_id), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(item_name)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void insert(String name, BigInteger item_id, String item_name, TransactionSucCallback callback) { + final Function function = new Function( + FUNC_INSERT, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Int256(item_id), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(item_name)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall create() { + final Function function = new Function( + FUNC_CREATE, + Arrays.asList(), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void create(TransactionSucCallback callback) { + final Function function = new Function( + FUNC_CREATE, + Arrays.asList(), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall, List, List>> select(String name) { + final Function function = new Function(FUNC_SELECT, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name)), + Arrays.>asList(new TypeReference>() {}, new TypeReference>() {}, new TypeReference>() {})); + return new RemoteCall, List, List>>( + new Callable, List, List>>() { + @Override + public Tuple3, List, List> call() throws Exception { + List results = executeCallMultipleValueReturn(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 Flowable createResultEventFlowable(BcosFilter filter) { + return web3j.logFlowable(filter).map(new io.reactivex.functions.Function() { + @Override + public CreateResultEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(CREATERESULT_EVENT, log); + CreateResultEventResponse typedResponse = new CreateResultEventResponse(); + typedResponse.log = log; + typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public Flowable createResultEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + BcosFilter filter = new BcosFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(CREATERESULT_EVENT)); + return createResultEventFlowable(filter); + } + + 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 Flowable selectResultEventFlowable(BcosFilter filter) { + return web3j.logFlowable(filter).map(new io.reactivex.functions.Function() { + @Override + public SelectResultEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(SELECTRESULT_EVENT, log); + SelectResultEventResponse typedResponse = new SelectResultEventResponse(); + typedResponse.log = log; + 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(); + return typedResponse; + } + }); + } + + public Flowable selectResultEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + BcosFilter filter = new BcosFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(SELECTRESULT_EVENT)); + return selectResultEventFlowable(filter); + } + + 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 Flowable insertResultEventFlowable(BcosFilter filter) { + return web3j.logFlowable(filter).map(new io.reactivex.functions.Function() { + @Override + public InsertResultEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(INSERTRESULT_EVENT, log); + InsertResultEventResponse typedResponse = new InsertResultEventResponse(); + typedResponse.log = log; + typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public Flowable insertResultEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + BcosFilter filter = new BcosFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(INSERTRESULT_EVENT)); + return insertResultEventFlowable(filter); + } + + 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 Flowable updateResultEventFlowable(BcosFilter filter) { + return web3j.logFlowable(filter).map(new io.reactivex.functions.Function() { + @Override + public UpdateResultEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(UPDATERESULT_EVENT, log); + UpdateResultEventResponse typedResponse = new UpdateResultEventResponse(); + typedResponse.log = log; + typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public Flowable updateResultEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + BcosFilter filter = new BcosFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(UPDATERESULT_EVENT)); + return updateResultEventFlowable(filter); + } + + 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 Flowable removeResultEventFlowable(BcosFilter filter) { + return web3j.logFlowable(filter).map(new io.reactivex.functions.Function() { + @Override + public RemoveResultEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(REMOVERESULT_EVENT, log); + RemoveResultEventResponse typedResponse = new RemoveResultEventResponse(); + typedResponse.log = log; + typedResponse.count = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public Flowable removeResultEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + BcosFilter filter = new BcosFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(REMOVERESULT_EVENT)); + return removeResultEventFlowable(filter); + } + + @Deprecated + public static TableTest load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new TableTest(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static TableTest load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new TableTest(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static TableTest load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return new TableTest(contractAddress, web3j, credentials, contractGasProvider); + } + + public static TableTest load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return new TableTest(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall(TableTest.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(TableTest.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall(TableTest.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(TableTest.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + public static class CreateResultEventResponse { + public Log log; + + public BigInteger count; + } + + public static class SelectResultEventResponse { + public Log log; + + public byte[] name; + + public BigInteger item_id; + + public byte[] item_name; + } + + public static class InsertResultEventResponse { + public Log log; + + public BigInteger count; + } + + public static class UpdateResultEventResponse { + public Log log; + + public BigInteger count; + } + + public static class RemoveResultEventResponse { + public Log log; + + public BigInteger count; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/contract/TableTestClient.java b/src/test/java/org/fisco/bcos/channel/test/contract/TableTestClient.java new file mode 100644 index 000000000..26aa8f446 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/contract/TableTestClient.java @@ -0,0 +1,276 @@ +package org.fisco.bcos.channel.test.contract; + +import java.math.BigInteger; +import java.util.List; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.channel.test.contract.TableTest.CreateResultEventResponse; +import org.fisco.bcos.channel.test.contract.TableTest.InsertResultEventResponse; +import org.fisco.bcos.channel.test.contract.TableTest.RemoveResultEventResponse; +import org.fisco.bcos.channel.test.contract.TableTest.UpdateResultEventResponse; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.precompile.common.PrecompiledCommon; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.RemoteCall; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.protocol.exceptions.TransactionException; +import org.fisco.bcos.web3j.tuples.generated.Tuple3; +import org.fisco.bcos.web3j.tx.gas.ContractGasProvider; +import org.fisco.bcos.web3j.tx.gas.StaticGasProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +public class TableTestClient { + + public static int modevalue = 100; + static Logger logger = LoggerFactory.getLogger(TableTestClient.class); + public static Web3j web3j; + + public static java.math.BigInteger gasPrice = new BigInteger("1"); + public static java.math.BigInteger gasLimit = new BigInteger("30000000"); + public static ECKeyPair keyPair; + public static Credentials credentials; + public static String contractAddress = ""; + + /* deploy the contract,get address from blockchain */ + @SuppressWarnings("deprecation") + public static void deployTableTest() { + + RemoteCall deploy = TableTest.deploy(web3j, credentials, gasPrice, gasLimit); + TableTest tabletest; + try { + tabletest = deploy.send(); + contractAddress = tabletest.getContractAddress(); + System.out.println("deploy contract address: " + contractAddress); + logger.info("deploy contract address: " + contractAddress); + final Resource contractResource = new ClassPathResource("contract.properties"); + PropertiesConfiguration prop = new PropertiesConfiguration(contractResource.getFile()); + prop.setProperty("crud_address", contractAddress); + prop.save(); + + System.out.println("deploy contract successful!"); + } catch (TransactionException e) { + if ("0x19".equals(e.getStatus())) { + System.out.println("non-authorized to deploy contracts!"); + } else { + System.out.println(e.getMessage()); + } + } catch (Exception e) { + System.out.println("deploy failed! " + e.getMessage()); + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static void testTableTest(String[] args) throws Exception { + + final Resource contractResource = new ClassPathResource("contract.properties"); + PropertiesConfiguration prop = new PropertiesConfiguration(contractResource.getFile()); + Object addressObj = prop.getProperty("crud_address"); + if (addressObj != null) { + contractAddress = (String) addressObj; + } else { + deployTableTest(); + } + ContractGasProvider contractGasProvider = new StaticGasProvider(gasPrice, gasLimit); + ; + TableTest tabletest = TableTest.load(contractAddress, web3j, credentials, contractGasProvider); + // create table + if ("create".equals(args[0])) { + TransactionReceipt receipt = tabletest.create().send(); + List createResultEvents = tabletest.getCreateResultEvents(receipt); + if (createResultEvents.size() == 0) { + System.out.println("create t_test table failed."); + return; + } + CreateResultEventResponse createResultEventResponse = createResultEvents.get(0); + int createCount = createResultEventResponse.count.intValue(); + switch (createCount) { + case PrecompiledCommon.PermissionDenied: + System.out.println("non-authorized to create t_test table."); + break; + case 50001: + System.out.println("t_test table already exist."); + break; + case PrecompiledCommon.Success: + System.out.println("create t_test table completed."); + break; + } + + } + // insert + else if ("insert".equals(args[0])) { + if (args.length == 4) { + try + { + String name = args[1]; + int item_id = Integer.parseInt(args[2]); + String item_name = args[3]; + + RemoteCall insert = + tabletest.insert(name, BigInteger.valueOf(item_id), item_name); + TransactionReceipt txReceipt = insert.send(); + List insertResultEvents = + tabletest.getInsertResultEvents(txReceipt); + if (insertResultEvents.size() > 0) { + for (int i = 0; i < insertResultEvents.size(); i++) { + InsertResultEventResponse insertResultEventResponse = insertResultEvents.get(i); + logger.info("insertCount = " + insertResultEventResponse.count.intValue()); + System.out.println("insertCount = " + insertResultEventResponse.count.intValue()); + } + } + else + { + System.out.println("t_test table does not exist."); + } + } + catch(Exception e) + { + System.out.println("insert transaction is abnormal, please check the environment"); + } + } else { + System.out.println("\nPlease enter as follow example:\n 1 1 insert fruit 1 apple"); + } + } + // select + else if ("select".equals(args[0])) { + if (args.length == 2) { + try { + String keyName = args[1]; + Tuple3, List, List> lists = tabletest.select(keyName).send(); + List value1 = lists.getValue1(); + List value2 = lists.getValue2(); + List value3 = lists.getValue3(); + logger.info("record numbers = " + value1.size()); + System.out.println("record numbers = " + value1.size()); + for (int i = 0; i < value1.size(); i++) { + String name = new String(value1.get(i)); + logger.info("name = " + name); + System.out.println("name = " + name); + int item_id = value2.get(i).intValue(); + logger.info("item_id = " + item_id); + System.out.println("item_id = " + item_id); + String item_name = new String(value3.get(i)); + logger.info("item_name = " + item_name); + System.out.println("item_name = " + item_name); + } + } catch (Exception e) { + logger.info("record numbers = 0"); + System.out.println("record numbers = 0"); + } + } else { + System.out.println("\nPlease enter as follow example:\n 1 1 select fruit"); + } + } + // update + else if ("update".equals(args[0])) { + if (args.length == 4) { + try { + String name = args[1]; + int item_id = Integer.parseInt(args[2]); + String item_name = args[3]; + RemoteCall update = + tabletest.update(name, BigInteger.valueOf(item_id), item_name); + TransactionReceipt transactionReceipt = update.send(); + List updateResultEvents = + tabletest.getUpdateResultEvents(transactionReceipt); + + if (updateResultEvents.size() > 0) { + for (int i = 0; i < updateResultEvents.size(); i++) { + UpdateResultEventResponse updateResultEventResponse = updateResultEvents.get(i); + System.out.println("updateCount = " + updateResultEventResponse.count.intValue()); + logger.info("updateCount = " + updateResultEventResponse.count.intValue()); + } + } + else + { + System.out.println("t_test table does not exist."); + } + } + catch(Exception e) + { + System.out.println("update transaction is abnormal, please check the environment"); + } + } else { + System.out.println("\nPlease enter as follow example:\n 1 1 update fruit 1 orange"); + } + } + // remove + else if ("remove".equals(args[0])) { + if (args.length == 3) { + try + { + String name = args[1]; + int item_id = Integer.parseInt(args[2]); + RemoteCall remove = tabletest.remove(name, BigInteger.valueOf(item_id)); + TransactionReceipt transactionReceipt = remove.send(); + List removeResultEvents = + tabletest.getRemoveResultEvents(transactionReceipt); + + if (removeResultEvents.size() > 0) { + RemoveResultEventResponse reomveResultEventResponse = removeResultEvents.get(0); + logger.info("removeCount = " + reomveResultEventResponse.count.intValue()); + System.out.println("removeCount = " + reomveResultEventResponse.count.intValue()); + } else { + System.out.println("t_test table does not exist."); + } + } + catch(Exception e) + { + System.out.println("remove transaction is abnormal, please check the environment"); + } + } else { + System.out.println("\nPlease enter as follow example:\n 1 1 remove fruit 1"); + } + } else { + System.out.println( + "\nPlease choose follow commands:\n deploy, create, insert, select, update or remove"); + } + } + + public static void main(String[] args) throws Exception { + + // init the Service + ApplicationContext context = + new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.run(); // run the daemon service + // init the client keys + keyPair = Keys.createEcKeyPair(); + credentials = Credentials.create(keyPair); + + logger.info("-----> start test !"); + logger.info("init AOMP ChannelEthereumService"); + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + channelEthereumService.setTimeout(5*1000); + service.setGroupId(Integer.parseInt(args[0])); + try { + web3j = Web3j.build(channelEthereumService,service.getGroupId()); + } + catch (Exception e) { + System.out.println("\nPlease provide groupID in the first paramters"); + System.exit(0); + } + + if (args.length > 1) { + if ("deploy".equals(args[1])) { + deployTableTest(); + } else { + String[] params = new String[args.length - 1]; + for (int i = 0; i < params.length; i++) params[i] = args[i + 1]; + testTableTest(params); + } + } else { + System.out.println( + "\nPlease choose follow commands:\n deploy, create, insert, select, update or remove"); + } + System.exit(0); + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/DagTransferUser.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/DagTransferUser.java new file mode 100644 index 000000000..7c5138276 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/DagTransferUser.java @@ -0,0 +1,41 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +import java.math.BigInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DagTransferUser { + private static Logger logger = LoggerFactory.getLogger(DagTransferUser.class); + private String user; + private BigInteger amount; + + @Override + public String toString() { + return "DagTransferUser [user=" + user + ", amount=" + amount + "]"; + } + public String getUser() { + return user; + } + public void setUser(String user) { + this.user = user; + } + synchronized public BigInteger getAmount() { + return amount; + } + synchronized public void setAmount(BigInteger amount) { + this.amount = amount; + } + + synchronized public void increase(BigInteger amount) { + logger.debug("increase before amount is " + this.amount); + this.amount = this.amount.add(amount); + logger.debug("increase after amount is " + this.amount); + } + + synchronized public void decrease(BigInteger amount) { + logger.debug("decrease before amount is " + this.amount); + this.amount = this.amount.subtract(amount); + logger.debug("decrease after amount is " + this.amount); + } +} \ No newline at end of file diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/DagUserMgr.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/DagUserMgr.java new file mode 100644 index 000000000..eb49899b8 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/DagUserMgr.java @@ -0,0 +1,149 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +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 DagUserMgr { + private static Logger logger = LoggerFactory.getLogger(DagUserMgr.class); + + private List userList = new ArrayList(); + + private String file = null; + + private String testType = "transfer"; + + 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; + } + + synchronized public 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()); + } + + public String getTestType() { + return testType; + } + + public void setTestType(String testType) { + this.testType = testType; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelOk.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelOk.java new file mode 100644 index 000000000..8862e7d7a --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelOk.java @@ -0,0 +1,234 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.abi.TypeReference; +import org.fisco.bcos.web3j.abi.datatypes.Function; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.RemoteCall; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tx.Contract; +import org.fisco.bcos.web3j.tx.TransactionManager; +import org.fisco.bcos.web3j.tx.gas.ContractGasProvider; + +/** + *

+ * Auto generated code. + *

+ * Do not modify! + *

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

+ * Generated with web3j version none. + */ +@SuppressWarnings("unchecked") +public class ParallelOk extends Contract { + private static final String BINARY = "60806040526110066000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561005257600080fd5b50610bb7806100626000396000f30060806040526004361061008e576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806334a18dda1461009357806335ee5f871461010657806379fa913f146101835780638a42ebe9146101ec5780639b80b0501461025f578063bca926af14610318578063d39f70bc1461032f578063fad42f8714610346575b600080fd5b34801561009f57600080fd5b50610104600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506103ff565b005b34801561011257600080fd5b5061016d600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610570565b6040518082815260200191505060405180910390f35b34801561018f57600080fd5b506101ea600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506105e5565b005b3480156101f857600080fd5b5061025d600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061074d565b005b34801561026b57600080fd5b50610316600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506107c1565b005b34801561032457600080fd5b5061032d6108b8565b005b34801561033b57600080fd5b506103446109a1565b005b34801561035257600080fd5b506103fd600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610a84565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630553904e3084846040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b838110156104e25780820151818401526020810190506104c7565b50505050905090810190601f16801561050f5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561053057600080fd5b505af1158015610544573d6000803e3d6000fd5b505050506040513d602081101561055a57600080fd5b8101908080519060200190929190505050505050565b60006001826040518082805190602001908083835b6020831015156105aa5780518252602082019150602081019050602083039250610585565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020549050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166311e3f2af30836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b838110156106c15780820151818401526020810190506106a6565b50505050905090810190601f1680156106ee5780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561070e57600080fd5b505af1158015610722573d6000803e3d6000fd5b505050506040513d602081101561073857600080fd5b81019080805190602001909291905050505050565b806001836040518082805190602001908083835b6020831015156107865780518252602082019150602081019050602083039250610761565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020819055505050565b806001846040518082805190602001908083835b6020831015156107fa57805182526020820191506020810190506020830392506107d5565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b602083101515610873578051825260208201915060208101905060208303925061084e565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540192505081905550505050565b6108f86040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e74323536290081525060026103ff565b6109386040805190810160405280601381526020017f73657428737472696e672c75696e74323536290000000000000000000000000081525060016103ff565b61099f606060405190810160405280602981526020017f7472616e736665725769746852657665727428737472696e672c737472696e6781526020017f2c75696e7432353629000000000000000000000000000000000000000000000081525060026103ff565b565b6109df6040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e7432353629008152506105e5565b610a1d6040805190810160405280601381526020017f73657428737472696e672c75696e7432353629000000000000000000000000008152506105e5565b610a82606060405190810160405280602981526020017f7472616e736665725769746852657665727428737472696e672c737472696e6781526020017f2c75696e743235362900000000000000000000000000000000000000000000008152506105e5565b565b806001846040518082805190602001908083835b602083101515610abd5780518252602082019150602081019050602083039250610a98565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b602083101515610b365780518252602082019150602081019050602083039250610b11565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390206000828254019250508190555060648111151515610b8657600080fd5b5050505600a165627a7a723058206c64dc79155185b3154a84b9b328acf23858657ed29a9cf028fb8166b86b5a200029"; + + 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"; + + @Deprecated + protected ParallelOk(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected ParallelOk(String contractAddress, Web3j web3j, Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected ParallelOk(String contractAddress, Web3j web3j, TransactionManager transactionManager, + BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected ParallelOk(String contractAddress, Web3j web3j, TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteCall registerParallelFunction(String functionName, BigInteger criticalSize) { + final Function function = new Function(FUNC_REGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(criticalSize)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void registerParallelFunction(String functionName, BigInteger criticalSize, + TransactionSucCallback callback) { + final Function function = new Function(FUNC_REGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(criticalSize)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall balanceOf(String name) { + final Function function = new Function(FUNC_BALANCEOF, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name)), + Arrays.>asList(new TypeReference() { + })); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall unregisterParallelFunction(String functionName) { + final Function function = new Function(FUNC_UNREGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void unregisterParallelFunction(String functionName, TransactionSucCallback callback) { + final Function function = new Function(FUNC_UNREGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall set(String name, BigInteger num) { + final Function function = new Function(FUNC_SET, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void set(String name, BigInteger num, TransactionSucCallback callback) { + final Function function = new Function(FUNC_SET, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall transfer(String from, String to, BigInteger num) { + final Function function = new Function(FUNC_TRANSFER, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void transfer(String from, String to, BigInteger num, TransactionSucCallback callback) { + final Function function = new Function(FUNC_TRANSFER, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall enableParallel() { + final Function function = new Function(FUNC_ENABLEPARALLEL, Arrays.asList(), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void enableParallel(TransactionSucCallback callback) { + final Function function = new Function(FUNC_ENABLEPARALLEL, Arrays.asList(), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall disableParallel() { + final Function function = new Function(FUNC_DISABLEPARALLEL, Arrays.asList(), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void disableParallel(TransactionSucCallback callback) { + final Function function = new Function(FUNC_DISABLEPARALLEL, Arrays.asList(), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall transferWithRevert(String from, String to, BigInteger num) { + final Function function = new Function(FUNC_TRANSFERWITHREVERT, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void transferWithRevert(String from, String to, BigInteger num, TransactionSucCallback callback) { + final Function function = new Function(FUNC_TRANSFERWITHREVERT, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + @Deprecated + public static ParallelOk load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, + BigInteger gasLimit) { + return new ParallelOk(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static ParallelOk load(String contractAddress, Web3j web3j, TransactionManager transactionManager, + BigInteger gasPrice, BigInteger gasLimit) { + return new ParallelOk(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static ParallelOk load(String contractAddress, Web3j web3j, Credentials credentials, + ContractGasProvider contractGasProvider) { + return new ParallelOk(contractAddress, web3j, credentials, contractGasProvider); + } + + public static ParallelOk load(String contractAddress, Web3j web3j, TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new ParallelOk(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, + ContractGasProvider contractGasProvider) { + return deployRemoteCall(ParallelOk.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall(ParallelOk.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return deployRemoteCall(ParallelOk.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall(ParallelOk.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelRevert.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelRevert.java new file mode 100644 index 000000000..d3903ba89 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/ParallelRevert.java @@ -0,0 +1,210 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.abi.TypeReference; +import org.fisco.bcos.web3j.abi.datatypes.Function; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.RemoteCall; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tx.Contract; +import org.fisco.bcos.web3j.tx.TransactionManager; +import org.fisco.bcos.web3j.tx.gas.ContractGasProvider; + +/** + *

Auto generated code. + *

Do not modify! + *

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

Generated with web3j version none. + */ +@SuppressWarnings("unchecked") +public class ParallelRevert extends Contract { + private static final String BINARY = "60806040526110076000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561005257600080fd5b50610930806100626000396000f300608060405260043610610083576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806334a18dda1461008857806335ee5f87146100fb57806379fa913f146101785780638a42ebe9146101e15780639b80b05014610254578063bca926af1461030d578063d39f70bc14610324575b600080fd5b34801561009457600080fd5b506100f9600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061033b565b005b34801561010757600080fd5b50610162600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506104ac565b6040518082815260200191505060405180910390f35b34801561018457600080fd5b506101df600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610521565b005b3480156101ed57600080fd5b50610252600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610689565b005b34801561026057600080fd5b5061030b600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001909291905050506106fd565b005b34801561031957600080fd5b50610322610804565b005b34801561033057600080fd5b50610339610886565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630553904e3084846040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b8381101561041e578082015181840152602081019050610403565b50505050905090810190601f16801561044b5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561046c57600080fd5b505af1158015610480573d6000803e3d6000fd5b505050506040513d602081101561049657600080fd5b8101908080519060200190929190505050505050565b60006001826040518082805190602001908083835b6020831015156104e657805182526020820191506020810190506020830392506104c1565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020549050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166311e3f2af30836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b838110156105fd5780820151818401526020810190506105e2565b50505050905090810190601f16801561062a5780820380516001836020036101000a031916815260200191505b509350505050602060405180830381600087803b15801561064a57600080fd5b505af115801561065e573d6000803e3d6000fd5b505050506040513d602081101561067457600080fd5b81019080805190602001909291905050505050565b806001836040518082805190602001908083835b6020831015156106c2578051825260208201915060208101905060208303925061069d565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020819055505050565b806001846040518082805190602001908083835b6020831015156107365780518252602082019150602081019050602083039250610711565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540392505081905550806001836040518082805190602001908083835b6020831015156107af578051825260208201915060208101905060208303925061078a565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008282540192505081905550606481111515156107ff57600080fd5b505050565b6108446040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e743235362900815250600261033b565b6108846040805190810160405280601381526020017f73657428737472696e672c75696e743235362900000000000000000000000000815250600161033b565b565b6108c46040805190810160405280601f81526020017f7472616e7366657228737472696e672c737472696e672c75696e743235362900815250610521565b6109026040805190810160405280601381526020017f73657428737472696e672c75696e743235362900000000000000000000000000815250610521565b5600a165627a7a7230582098a8175f9228fd5e6de012a15166541c53bff8d97397ba470d9257fdbb5b3ca90029"; + + public static final String FUNC_REGISTERPARALLELFUNCTION = "registerParallelFunction"; + + public static final String FUNC_BALANCEOF = "balanceOf"; + + public static final String FUNC_UNREGISTERPARALLELFUNCTION = "unregisterParallelFunction"; + + public static final String FUNC_SET = "set"; + + public static final String FUNC_TRANSFER = "transfer"; + + public static final String FUNC_ENABLEPARALLEL = "enableParallel"; + + public static final String FUNC_DISABLEPARALLEL = "disableParallel"; + + @Deprecated + protected ParallelRevert(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected ParallelRevert(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected ParallelRevert(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected ParallelRevert(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteCall registerParallelFunction(String functionName, BigInteger criticalSize) { + final Function function = new Function( + FUNC_REGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(criticalSize)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void registerParallelFunction(String functionName, BigInteger criticalSize, TransactionSucCallback callback) { + final Function function = new Function( + FUNC_REGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(criticalSize)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall balanceOf(String name) { + final Function function = new Function(FUNC_BALANCEOF, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall unregisterParallelFunction(String functionName) { + final Function function = new Function( + FUNC_UNREGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void unregisterParallelFunction(String functionName, TransactionSucCallback callback) { + final Function function = new Function( + FUNC_UNREGISTERPARALLELFUNCTION, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(functionName)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall set(String name, BigInteger num) { + final Function function = new Function( + FUNC_SET, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void set(String name, BigInteger num, TransactionSucCallback callback) { + final Function function = new Function( + FUNC_SET, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(name), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall transfer(String from, String to, BigInteger num) { + final Function function = new Function( + FUNC_TRANSFER, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void transfer(String from, String to, BigInteger num, TransactionSucCallback callback) { + final Function function = new Function( + FUNC_TRANSFER, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(from), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(to), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(num)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall enableParallel() { + final Function function = new Function( + FUNC_ENABLEPARALLEL, + Arrays.asList(), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void enableParallel(TransactionSucCallback callback) { + final Function function = new Function( + FUNC_ENABLEPARALLEL, + Arrays.asList(), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall disableParallel() { + final Function function = new Function( + FUNC_DISABLEPARALLEL, + Arrays.asList(), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void disableParallel(TransactionSucCallback callback) { + final Function function = new Function( + FUNC_DISABLEPARALLEL, + Arrays.asList(), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + @Deprecated + public static ParallelRevert load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new ParallelRevert(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static ParallelRevert load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new ParallelRevert(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static ParallelRevert load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return new ParallelRevert(contractAddress, web3j, credentials, contractGasProvider); + } + + public static ParallelRevert load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return new ParallelRevert(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall(ParallelRevert.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(ParallelRevert.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall(ParallelRevert.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(ParallelRevert.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDT.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDT.java new file mode 100644 index 000000000..d25811414 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDT.java @@ -0,0 +1,81 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.math.BigInteger; + +import org.fisco.bcos.channel.test.parallel.parallelok.PerformanceDTTest; +import org.fisco.bcos.channel.test.parallel.parallelok.DagUserMgr; + +public class PerformanceDT { + private static Logger logger = LoggerFactory.getLogger(PerformanceDT.class); + + public static void Usage() { + System.out.println(" Usage:"); + System.out.println( + " \t java -cp conf/:lib/*:apps/* org.fisco.bcos.channel.test.parallel.parallelok.PerformanceDT groupID add count tps file."); + System.out.println( + " \t java -cp conf/:lib/*:apps/* org.fisco.bcos.channel.test.parallel.parallelok.PerformanceDT groupID transfer count tps file strategy."); + System.out.println( + " \t java -cp conf/:lib/*:apps/* org.fisco.bcos.channel.test.parallel.parallelok.PerformanceDT groupID transferRevert count tps file strategy."); + System.exit(0); + } + + public static void main(String[] args) throws Exception { + if (args.length < 4) { + Usage(); + } + + String groupID = args[0]; + String command = args[1]; + BigInteger count = new BigInteger(args[2]); + BigInteger tps = new BigInteger(args[3]); + String file = null; + BigInteger deci = new BigInteger("0"); + if (args.length > 4) { + file = args[4]; + if (args.length > 5) { + deci = new BigInteger(args[5]); + } + } + + // deci can not bigger than 10. + if (deci.compareTo(new BigInteger("10")) > 0) { + deci = new BigInteger("10"); + } + + logger.info(" dag transfer test begin, command is {}, count is {}, tps is {}, file is {}, deci is {}", command, + count, tps, file, deci); + + DagUserMgr d = new DagUserMgr(); + d.setFile(file); + + PerformanceDTCollector collector = new PerformanceDTCollector(); + collector.setTotal(count.intValue()); + collector.setDagUserMrg(d); + + PerformanceDTTest PerformanceDTTest = new PerformanceDTTest(groupID); + PerformanceDTTest.setCollector(collector); + PerformanceDTTest.setDagUserMgr(d); + collector.setPerformanceDTTest(PerformanceDTTest); + + switch (command) { + case "add": + d.setTestType("add"); + PerformanceDTTest.userAddTest(count, tps); + break; + case "transfer": + d.setTestType("transfer"); + d.loadDagTransferUser(); + PerformanceDTTest.userTransferTest(count, tps, deci); + break; + case "transferRevert": + d.setTestType("transferRevert"); + d.loadDagTransferUser(); + PerformanceDTTest.userTransferRevertTest(count, tps, deci); + default: + Usage(); + } + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCallback.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCallback.java new file mode 100644 index 000000000..068e38cd5 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCallback.java @@ -0,0 +1,119 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +import java.math.BigInteger; + +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PerformanceDTCallback extends TransactionSucCallback { + static private ObjectMapper objectMapper = new ObjectMapper(); + private Long startTime = System.currentTimeMillis(); + + private PerformanceDTCollector collector = null; + private DagUserMgr dagUserMgr = null; + + private DagTransferUser user = null; + private DagTransferUser fromUser = null; + private DagTransferUser toUser = null; + private BigInteger amount = null; + + private String callBackType = "transfer"; + + public String getCallBackType() { + return callBackType; + } + + public void setCallBackType(String callBackType) { + this.callBackType = callBackType; + } + + public DagUserMgr getDagUserMgr() { + return dagUserMgr; + } + + public void setDagUserMgr(DagUserMgr dagUserMgr) { + this.dagUserMgr = dagUserMgr; + } + + public DagTransferUser getDagTransferUser() { + return user; + } + + public void setDagTransferUser(DagTransferUser dagTransferUser) { + this.user = dagTransferUser; + } + + public PerformanceDTCollector getCollector() { + return collector; + } + + public void setCollector(PerformanceDTCollector collector) { + this.collector = collector; + } + + static Logger logger = LoggerFactory.getLogger(PerformanceDTCallback.class); + + public PerformanceDTCallback() { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + @Override + public void onResponse(TransactionReceipt receipt) { + Long cost = System.currentTimeMillis() - startTime; + + try { + if (receipt.isStatusOK()) { + + if (callBackType.compareTo("set") == 0) { // add test + dagUserMgr.addUser(user); + } else if (callBackType.compareTo("transfer") == 0) { // transfer test + fromUser.decrease(amount); + toUser.increase(amount); + } else if (callBackType.compareTo("transferRevert") == 0) { // tranfer revert test + fromUser.decrease(amount); + toUser.increase(amount); + } + } + + if (callBackType.compareTo("transferRevert") == 0) { + String info = "[RevertTest-TxSent]" + "\t[TxHash]=" + receipt.getTransactionHash() + "\t[From]=" + + fromUser.getUser() + "\t[FromBalance]=" + fromUser.getAmount() + "\t[To]=" + toUser.getUser() + + "\t[ToBalance]=" + toUser.getAmount() + "\t[Status]=" + receipt.getStatus(); + System.out.println(info); + } + + 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; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCollector.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCollector.java new file mode 100644 index 000000000..0d0eb8ee2 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTCollector.java @@ -0,0 +1,156 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +import java.math.BigInteger; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.channel.test.parallel.parallelok.DagUserMgr; + +public class PerformanceDTCollector { + + static Logger logger = LoggerFactory.getLogger(PerformanceDTCollector.class); + + private Integer total = 0; + private DagUserMgr dagUserMrg; + private PerformanceDTTest PerformanceDTTest; + + public PerformanceDTTest getPerformanceDTTest() { + return PerformanceDTTest; + } + + public void setPerformanceDTTest(PerformanceDTTest PerformanceDTTest) { + this.PerformanceDTTest = PerformanceDTTest; + } + + public Integer getTotal() { + return total; + } + + public void setTotal(Integer total) { + this.total = total; + } + + public DagUserMgr getDagUserMrg() { + return dagUserMrg; + } + + public void setDagUserMrg(DagUserMgr dagUserMrg) { + this.dagUserMrg = dagUserMrg; + } + + public boolean isEnd() { + return received.intValue() >= total; + } + + public void onMessage(TransactionReceipt receipt, Long cost) { + try { + if (!receipt.isStatusOK()) { + System.out.println("receipt error! status: " + receipt.getStatus()); + error.addAndGet(1); + } + + received.incrementAndGet(); + + 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 (isEnd()) { + 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: " + String.valueOf(total / ((double) totalTime / 1000))); + System.out.println("Avg time cost: " + String.valueOf(totalCost.get() / total) + "ms"); + System.out.println("Error rate: " + String.valueOf((error.get() / received.get()) * 100) + "%"); + System.out.println( + "Return Error rate: " + String.valueOf((ret_error.get() / 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) + "%"); + } + + } catch (Exception e) { + logger.error("error:", e); + System.exit(0); + } + } + + 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 AtomicInteger received = new AtomicInteger(0); + + public AtomicInteger getReceived() { + return received; + } + + public void setReceived(AtomicInteger received) { + this.received = received; + } + + private AtomicInteger error = new AtomicInteger(0); + private AtomicInteger ret_error = new AtomicInteger(0); + private Long startTimestamp = System.currentTimeMillis(); + + public Long getStartTimestamp() { + return startTimestamp; + } + + public void setStartTimestamp(Long startTimestamp) { + this.startTimestamp = startTimestamp; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTTest.java b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTTest.java new file mode 100644 index 000000000..64be46f9e --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/parallelok/PerformanceDTTest.java @@ -0,0 +1,414 @@ +package org.fisco.bcos.channel.test.parallel.parallelok; + +import com.google.common.util.concurrent.RateLimiter; +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tuples.generated.Tuple2; +import org.fisco.bcos.web3j.tx.gas.StaticGasProvider; +import org.fisco.bcos.web3j.utils.Web3AsyncThreadPoolSize; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.math.BigInteger; +import java.util.List; +import java.util.Random; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; + +public class PerformanceDTTest { + private static Logger logger = LoggerFactory.getLogger(PerformanceDTTest.class); + private static AtomicInteger sended = new AtomicInteger(0); + private static String groupId = "1"; + + private Web3j web3; + private ParallelOk parallelok; + + private Credentials credentials; + private DagUserMgr dagUserMgr; + private PerformanceDTCollector collector; + private String parallelokAddr = ""; + + public PerformanceDTTest(String groupID) throws Exception { + groupId = groupID; + initialize(groupId); + } + + public DagUserMgr getDagUserMgr() { + return dagUserMgr; + } + + public void setDagUserMgr(DagUserMgr dagUserMgr) { + this.dagUserMgr = dagUserMgr; + } + + public Web3j getWeb3() { + return web3; + } + + public void setWeb3(Web3j web3) { + this.web3 = web3; + } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } + + public PerformanceDTCollector getCollector() { + return collector; + } + + public void setCollector(PerformanceDTCollector collector) { + this.collector = collector; + } + + public void veryTransferData() { + // System.out.println(" data validation => "); + List allUser = dagUserMgr.getUserList(); + int total_user = allUser.size(); + + int verify_success = 0; + + int verify_failed = 0; + + allUser = dagUserMgr.getUserList(); + + try { + for (int i = 0; i < allUser.size(); ++i) { + BigInteger result = parallelok.balanceOf(allUser.get(i).getUser()).send(); + + String user = allUser.get(i).getUser(); + BigInteger local = allUser.get(i).getAmount(); + BigInteger remote = result; + + logger.debug(" user " + user + " local amount " + local + " remote amount " + remote); + if (local.compareTo(remote) != 0) { + verify_failed++; + logger.error(" local amount is not same as remote, user " + user + " local " + local + " remote " + + remote); + } else { + verify_success++; + } + } + + System.out.println("validation:"); + System.out.println(" \tuser count is " + total_user); + System.out.println(" \tverify_success count is " + verify_success); + System.out.println(" \tverify_failed count is " + verify_failed); + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } + } + + public void initialize(String groupId) throws Exception { + + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(groupId)); + service.run(); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + Web3AsyncThreadPoolSize.web3AsyncCorePoolSize = 3000; + Web3AsyncThreadPoolSize.web3AsyncPoolSize = 2000; + + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500); + web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId)); + + credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + } + + public void userAddTest(BigInteger count, BigInteger qps) { + + try { + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count.intValue()); + + threadPool.initialize(); + + System.out.println("Deploying contract "); + System.out.println("==================================================================="); + credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + parallelok = ParallelOk.deploy(web3, credentials, new BigInteger("30000000"), new BigInteger("30000000")) + .send(); + + // enable parallel transaction + parallelok.enableParallel().send(); + + parallelokAddr = parallelok.getContractAddress(); + + System.out.println("ParallelOk address: " + parallelokAddr); + + RateLimiter limiter = RateLimiter.create(qps.intValue()); + Integer area = count.intValue() / 10; + + long seconds = System.currentTimeMillis() / 1000l; + + this.collector.setStartTimestamp(System.currentTimeMillis()); + + System.out.println("==================================================================="); + System.out.println("Start UserAdd test, count " + count); + + for (Integer i = 0; i < count.intValue(); ++i) { + final int index = i; + threadPool.execute(new Runnable() { + @Override + public void run() { + boolean success = false; + while (!success) { + limiter.acquire(); + String user = Long.toHexString(seconds) + Integer.toHexString(index); + BigInteger amount = new BigInteger("1000000000"); + DagTransferUser dtu = new DagTransferUser(); + dtu.setUser(user); + dtu.setAmount(amount); + + PerformanceDTCallback callback = new PerformanceDTCallback(); + callback.setCollector(collector); + callback.setDagTransferUser(dtu); + callback.setDagUserMgr(getDagUserMgr()); + callback.setCallBackType("set"); + + try { + parallelok.set(user, amount, callback); + success = true; + } catch (Exception e) { + success = false; + continue; + } + } + int current = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + count + " transactions"); + } + } + }); + } + + // end or not + while (!collector.isEnd()) { + Thread.sleep(3000); + } + + dagUserMgr.setContractAddr(parallelokAddr); + dagUserMgr.writeDagTransferUser(); + System.exit(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } + } + + public void userTransferRevertTest(BigInteger count, BigInteger qps, BigInteger deci) { + + try { + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count.intValue()); + + threadPool.initialize(); + + RateLimiter limiter = RateLimiter.create(qps.intValue()); + Integer area = count.intValue() / 10; + + parallelokAddr = dagUserMgr.getContractAddr(); + parallelok = ParallelOk.load(parallelokAddr, web3, credentials, + new StaticGasProvider(new BigInteger("30000000"), new BigInteger("30000000"))); + + System.out.println("ParallelOk address: " + parallelokAddr); + + // query all account balance info + List allUser = dagUserMgr.getUserList(); + for (int i = 0; i < allUser.size(); ++i) { + BigInteger result = parallelok.balanceOf(allUser.get(i).getUser()).send(); + + allUser.get(i).setAmount(result); + + logger.debug(" query user " + allUser.get(i).getUser() + " amount " + result); + } + + System.out.println("Start UserTransferRevert test..."); + System.out.println("==================================================================="); + + this.collector.setStartTimestamp(System.currentTimeMillis()); + + for (Integer i = 0; i < 2 * count.intValue(); i += 2) { + final int index = i; + threadPool.execute(new Runnable() { + @Override + public void run() { + boolean success = false; + while (!success) { + limiter.acquire(); + DagTransferUser from = dagUserMgr.getFrom(index); + DagTransferUser to = dagUserMgr.getNext(index); + + Random random = new Random(); + int value = random.nextInt(101); + int prob = random.nextInt(10); + if (prob < deci.intValue()) { + value += 101; + } + BigInteger amount = BigInteger.valueOf(value); + + PerformanceDTCallback callback = new PerformanceDTCallback(); + callback.setCallBackType("transferRevert"); + callback.setCollector(collector); + callback.setDagUserMgr(getDagUserMgr()); + callback.setFromUser(from); + callback.setToUser(to); + callback.setAmount(amount); + + String info = "[RevertTest-SendTx]" + "\t[From]=" + from.getUser() + "\t[FromBalance]=" + + from.getAmount() + "\t[To]=" + to.getUser() + "\t[ToBalance]=" + to.getAmount() + + "\t[Amount]=" + amount; + System.out.println(info); + + try { + parallelok.transferWithRevert(from.getUser(), to.getUser(), amount, callback); + success = true; + } catch (Exception e) { + success = false; + continue; + } + } + } + }); + } + + // end or not + while (!collector.isEnd()) { + Thread.sleep(3000); + } + + veryTransferData(); + System.exit(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } + } + + public void userTransferTest(BigInteger count, BigInteger qps, BigInteger deci) { + + try { + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count.intValue()); + + threadPool.initialize(); + + RateLimiter limiter = RateLimiter.create(qps.intValue()); + Integer area = count.intValue() / 10; + + parallelokAddr = dagUserMgr.getContractAddr(); + parallelok = ParallelOk.load(parallelokAddr, web3, credentials, + new StaticGasProvider(new BigInteger("30000000"), new BigInteger("30000000"))); + + System.out.println("ParallelOk address: " + parallelokAddr); + + // query all account balance info + List allUser = dagUserMgr.getUserList(); + for (int i = 0; i < allUser.size(); ++i) { + BigInteger result = parallelok.balanceOf(allUser.get(i).getUser()).send(); + + allUser.get(i).setAmount(result); + + logger.debug(" query user " + allUser.get(i).getUser() + " amount " + result); + } + + System.out.println("Start UserTransfer test..."); + System.out.println("==================================================================="); + + this.collector.setStartTimestamp(System.currentTimeMillis()); + + for (Integer i = 0; i < count.intValue(); ++i) { + final int index = i; + threadPool.execute(new Runnable() { + @Override + public void run() { + boolean success = false; + while (!success) { + limiter.acquire(); + DagTransferUser from = dagUserMgr.getFrom(index); + DagTransferUser to = dagUserMgr.getTo(index); + + if ((deci.intValue() > 0) && (deci.intValue() >= (index % 10 + 1))) { + to = dagUserMgr.getNext(index); + } + + Random random = new Random(); + int r = random.nextInt(100); + BigInteger amount = BigInteger.valueOf(r); + + PerformanceDTCallback callback = new PerformanceDTCallback(); + callback.setCallBackType("transfer"); + callback.setCollector(collector); + callback.setDagUserMgr(getDagUserMgr()); + callback.setFromUser(from); + callback.setToUser(to); + callback.setAmount(amount); + + try { + logger.debug(" transfer from is " + from + " to is " + to + " amount is " + amount); + parallelok.transfer(from.getUser(), to.getUser(), amount, callback); + success = true; + } catch (Exception e) { + success = false; + continue; + } + } + int current = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + count + " transactions"); + } + } + }); + } + + // end or not + while (!collector.isEnd()) { + Thread.sleep(3000); + } + + veryTransferData(); + System.exit(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } + } + + public ParallelOk getDagTransfer() { + return parallelok; + } + + public void setDagTransfer(ParallelOk parallelok) { + this.parallelok = parallelok; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransfer.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransfer.java new file mode 100644 index 000000000..85f73c7aa --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransfer.java @@ -0,0 +1,197 @@ +package org.fisco.bcos.channel.test.parallel.precompile; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.abi.TypeReference; +import org.fisco.bcos.web3j.abi.datatypes.Function; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.core.RemoteCall; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tuples.generated.Tuple2; +import org.fisco.bcos.web3j.tx.Contract; +import org.fisco.bcos.web3j.tx.TransactionManager; +import org.fisco.bcos.web3j.tx.gas.ContractGasProvider; + +/** + *

+ * Auto generated code. + *

+ * Do not modify! + *

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

+ * Generated with web3j version none. + */ +public class DagTransfer extends Contract { + private static final String BINARY = "608060405234801561001057600080fd5b506103c6806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630b37617b146100725780631536aedd1461013f5780633fe8e3f5146101c3578063e555f3d91461024a578063ff2b0127146102d1575b600080fd5b34801561007e57600080fd5b50610129600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610358565b6040518082815260200191505060405180910390f35b34801561014b57600080fd5b506101a6600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610364565b604051808381526020018281526020019250505060405180910390f35b3480156101cf57600080fd5b50610234600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610379565b6040518082815260200191505060405180910390f35b34801561025657600080fd5b506102bb600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610384565b6040518082815260200191505060405180910390f35b3480156102dd57600080fd5b50610342600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192908035906020019092919050505061038f565b6040518082815260200191505060405180910390f35b60008090509392505050565b60008060008081915080905091509150915091565b600080905092915050565b600080905092915050565b6000809050929150505600a165627a7a72305820bde537b6eff20e760fa77d91f856463f97ff39d9725e79f31079d5da9ba0cc8a0029"; + + 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"; + + @Deprecated + protected DagTransfer(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected DagTransfer(String contractAddress, Web3j web3j, Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected DagTransfer(String contractAddress, Web3j web3j, TransactionManager transactionManager, + BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected DagTransfer(String contractAddress, Web3j web3j, TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteCall userTransfer(String user_a, String user_b, BigInteger amount) { + final Function function = new Function(FUNC_USERTRANSFER, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user_a), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user_b), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void userTransfer(String user_a, String user_b, BigInteger amount, TransactionSucCallback callback) { + final Function function = new Function(FUNC_USERTRANSFER, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user_a), + new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user_b), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall> userBalance(String user) { + final Function function = new Function(FUNC_USERBALANCE, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user)), + Arrays.>asList(new TypeReference() { + }, new TypeReference() { + })); + return new RemoteCall>(new Callable>() { + @Override + public Tuple2 call() throws Exception { + List results = executeCallMultipleValueReturn(function); + return new Tuple2((BigInteger) results.get(0).getValue(), + (BigInteger) results.get(1).getValue()); + } + }); + } + + public RemoteCall userAdd(String user, BigInteger balance) { + final Function function = new Function(FUNC_USERADD, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(balance)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void userAdd(String user, BigInteger balance, TransactionSucCallback callback) { + final Function function = new Function(FUNC_USERADD, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(balance)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall userSave(String user, BigInteger balance) { + final Function function = new Function(FUNC_USERSAVE, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(balance)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void userSave(String user, BigInteger balance, TransactionSucCallback callback) { + final Function function = new Function(FUNC_USERSAVE, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(balance)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + public RemoteCall userDraw(String user, BigInteger balance) { + final Function function = new Function(FUNC_USERDRAW, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(balance)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public void userDraw(String user, BigInteger balance, TransactionSucCallback callback) { + final Function function = new Function(FUNC_USERDRAW, + Arrays.asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(user), + new org.fisco.bcos.web3j.abi.datatypes.generated.Uint256(balance)), + Collections.>emptyList()); + asyncExecuteTransaction(function, callback); + } + + @Deprecated + public static DagTransfer load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, + BigInteger gasLimit) { + return new DagTransfer(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static DagTransfer load(String contractAddress, Web3j web3j, TransactionManager transactionManager, + BigInteger gasPrice, BigInteger gasLimit) { + return new DagTransfer(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static DagTransfer load(String contractAddress, Web3j web3j, Credentials credentials, + ContractGasProvider contractGasProvider) { + return new DagTransfer(contractAddress, web3j, credentials, contractGasProvider); + } + + public static DagTransfer load(String contractAddress, Web3j web3j, TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new DagTransfer(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, + ContractGasProvider contractGasProvider) { + return deployRemoteCall(DagTransfer.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall(DagTransfer.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return deployRemoteCall(DagTransfer.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, + BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(DagTransfer.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransferUser.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransferUser.java new file mode 100644 index 000000000..7a891e642 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagTransferUser.java @@ -0,0 +1,45 @@ +package org.fisco.bcos.channel.test.parallel.precompile; + +import java.math.BigInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DagTransferUser { + private static Logger logger = LoggerFactory.getLogger(DagTransferUser.class); + private String user; + private BigInteger amount; + + @Override + public String toString() { + return "DagTransferUser [user=" + user + ", amount=" + amount + "]"; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + synchronized public BigInteger getAmount() { + return amount; + } + + synchronized public void setAmount(BigInteger amount) { + this.amount = amount; + } + + synchronized public void increase(BigInteger amount) { + logger.debug("increase before amount is " + this.amount); + this.amount = this.amount.add(amount); + logger.debug("increase after amount is " + this.amount); + } + + synchronized public void decrease(BigInteger amount) { + logger.debug("decrease before amount is " + this.amount); + this.amount = this.amount.subtract(amount); + logger.debug("decrease after amount is " + this.amount); + } +} \ No newline at end of file diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagUserMgr.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagUserMgr.java new file mode 100644 index 000000000..c5c952e25 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/DagUserMgr.java @@ -0,0 +1,127 @@ +package org.fisco.bcos.channel.test.parallel.precompile; + +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 DagUserMgr { + private static Logger logger = LoggerFactory.getLogger(DagUserMgr.class); + + private List userList = new ArrayList(); + + private String file = null; + + private String testType = "transfer"; + + 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; + } + + synchronized public 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))); + 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; + 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()); + } + + public String getTestType() { + return testType; + } + + public void setTestType(String testType) { + this.testType = testType; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDT.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDT.java new file mode 100644 index 000000000..ea6533a96 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDT.java @@ -0,0 +1,75 @@ +package org.fisco.bcos.channel.test.parallel.precompile; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.math.BigInteger; + +import org.fisco.bcos.channel.test.parallel.precompile.PerformanceDTTest; +import org.fisco.bcos.channel.test.parallel.precompile.DagUserMgr; + +public class PerformanceDT { + private static Logger logger = LoggerFactory.getLogger(PerformanceDT.class); + + public static void Usage() { + System.out.println(" Usage:"); + System.out.println( + " \t java -cp conf/:lib/*:apps/* org.fisco.bcos.channel.test.parallel.precompile.PerformanceDT groupID add count tps file."); + System.out.println( + " \t java -cp conf/:lib/*:apps/* org.fisco.bcos.channel.test.parallel.precompile.PerformanceDT groupID transfer count tps file strategy."); + System.exit(0); + } + + public static void main(String[] args) throws Exception { + if (args.length < 4) { + Usage(); + } + + String groupID = args[0]; + String command = args[1]; + BigInteger count = new BigInteger(args[2]); + BigInteger tps = new BigInteger(args[3]); + String file = null; + BigInteger deci = new BigInteger("0"); + if (args.length > 4) { + file = args[4]; + if (args.length > 5) { + deci = new BigInteger(args[5]); + } + } + + // deci can not bigger than 10. + if (deci.compareTo(new BigInteger("10")) > 0) { + deci = new BigInteger("10"); + } + + logger.info(" dag transfer test begin, command is {}, count is {}, tps is {}, file is {}, deci is {}", command, + count, tps, file, deci); + + DagUserMgr d = new DagUserMgr(); + d.setFile(file); + + PerformanceDTCollector collector = new PerformanceDTCollector(); + collector.setTotal(count.intValue()); + collector.setDagUserMrg(d); + + PerformanceDTTest PerformanceDTTest = new PerformanceDTTest(groupID); + PerformanceDTTest.setCollector(collector); + PerformanceDTTest.setDagUserMgr(d); + collector.setPerformanceDTTest(PerformanceDTTest); + + switch (command) { + case "add": + d.setTestType("add"); + PerformanceDTTest.userAddTest(count, tps); + break; + case "transfer": + d.setTestType("transfer"); + d.loadDagTransferUser(); + PerformanceDTTest.userTransferTest(count, tps, deci); + break; + default: + Usage(); + } + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCallback.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCallback.java new file mode 100644 index 000000000..dbfcc7b46 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCallback.java @@ -0,0 +1,118 @@ +package org.fisco.bcos.channel.test.parallel.precompile; + +import java.math.BigInteger; + +import org.fisco.bcos.channel.client.TransactionSucCallback; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PerformanceDTCallback extends TransactionSucCallback { + static private ObjectMapper objectMapper = new ObjectMapper(); + private Long startTime = System.currentTimeMillis(); + + private PerformanceDTCollector collector = null; + private DagUserMgr dagUserMgr = null; + + private DagTransferUser user = null; + private DagTransferUser fromUser = null; + private DagTransferUser toUser = null; + private BigInteger amount = null; + + private String callBackType = "transfer"; + + public String getCallBackType() { + return callBackType; + } + + public void setCallBackType(String callBackType) { + this.callBackType = callBackType; + } + + public DagUserMgr getDagUserMgr() { + return dagUserMgr; + } + + public void setDagUserMgr(DagUserMgr dagUserMgr) { + this.dagUserMgr = dagUserMgr; + } + + public DagTransferUser getDagTransferUser() { + return user; + } + + public void setDagTransferUser(DagTransferUser dagTransferUser) { + this.user = dagTransferUser; + } + + public PerformanceDTCollector getCollector() { + return collector; + } + + public void setCollector(PerformanceDTCollector collector) { + this.collector = collector; + } + + static Logger logger = LoggerFactory.getLogger(PerformanceDTCallback.class); + + public PerformanceDTCallback() { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + @Override + public void onResponse(TransactionReceipt receipt) { + Long cost = System.currentTimeMillis() - startTime; + + try { + if (receipt.isStatusOK()) { + String output = receipt.getOutput(); + if (!output.isEmpty()) { + int code = new BigInteger(output.substring(2, output.length()), 16).intValue(); + logger.debug(" output is {}, code is {} ", output, code); + if (0 == code) { + if (callBackType.compareTo("add") == 0) { // add test + dagUserMgr.addUser(user); + } else if (callBackType.compareTo("transfer") == 0) { // transfer test + fromUser.decrease(amount); + toUser.increase(amount); + } + } else { + logger.error(" invalid return: code is " + code); + } + } else { + logger.error(" empty return "); + } + } + 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; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCollector.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCollector.java new file mode 100644 index 000000000..75e7169a2 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTCollector.java @@ -0,0 +1,166 @@ +package org.fisco.bcos.channel.test.parallel.precompile; + +import java.math.BigInteger; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.channel.test.parallel.precompile.DagUserMgr; + +public class PerformanceDTCollector { + + static Logger logger = LoggerFactory.getLogger(PerformanceDTCollector.class); + + private Integer total = 0; + private DagUserMgr dagUserMrg; + private PerformanceDTTest PerformanceDTTest; + + public PerformanceDTTest getPerformanceDTTest() { + return PerformanceDTTest; + } + + public void setPerformanceDTTest(PerformanceDTTest PerformanceDTTest) { + this.PerformanceDTTest = PerformanceDTTest; + } + + public Integer getTotal() { + return total; + } + + public void setTotal(Integer total) { + this.total = total; + } + + public DagUserMgr getDagUserMrg() { + return dagUserMrg; + } + + public void setDagUserMrg(DagUserMgr dagUserMrg) { + this.dagUserMrg = dagUserMrg; + } + + public boolean isEnd() { + return received.intValue() >= total; + } + + public void onMessage(TransactionReceipt receipt, Long cost) { + try { + if (receipt.isStatusOK()) { + String output = receipt.getOutput(); + if (!output.isEmpty()) { + int code = new BigInteger(output.substring(2, output.length()), 16).intValue(); + if (0 != code) { + error.addAndGet(1); + ret_error.addAndGet(1); + } + } else { + error.addAndGet(1); + } + } else { + error.addAndGet(1); + } + + received.incrementAndGet(); + + 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 (isEnd()) { + 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: " + String.valueOf(total / ((double) totalTime / 1000))); + System.out.println("Avg time cost: " + String.valueOf(totalCost.get() / total) + "ms"); + System.out.println("Error rate: " + String.valueOf((error.get() / received.get()) * 100) + "%"); + System.out.println( + "Return Error rate: " + String.valueOf((ret_error.get() / 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) + "%"); + } + + } catch (Exception e) { + logger.error("error:", e); + System.exit(0); + } + } + + 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 AtomicInteger received = new AtomicInteger(0); + + public AtomicInteger getReceived() { + return received; + } + + public void setReceived(AtomicInteger received) { + this.received = received; + } + + private AtomicInteger error = new AtomicInteger(0); + private AtomicInteger ret_error = new AtomicInteger(0); + private Long startTimestamp = System.currentTimeMillis(); + + public Long getStartTimestamp() { + return startTimestamp; + } + + public void setStartTimestamp(Long startTimestamp) { + this.startTimestamp = startTimestamp; + } +} diff --git a/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTTest.java b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTTest.java new file mode 100644 index 000000000..0d8640585 --- /dev/null +++ b/src/test/java/org/fisco/bcos/channel/test/parallel/precompile/PerformanceDTTest.java @@ -0,0 +1,312 @@ +package org.fisco.bcos.channel.test.parallel.precompile; + +import com.google.common.util.concurrent.RateLimiter; +import org.fisco.bcos.channel.client.Service; +import org.fisco.bcos.web3j.crypto.Credentials; +import org.fisco.bcos.web3j.protocol.Web3j; +import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tuples.generated.Tuple2; +import org.fisco.bcos.web3j.tx.gas.StaticGasProvider; +import org.fisco.bcos.web3j.utils.Web3AsyncThreadPoolSize; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.math.BigInteger; +import java.util.List; +import java.util.Random; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; + +public class PerformanceDTTest { + private static Logger logger = LoggerFactory.getLogger(PerformanceDTTest.class); + private static AtomicInteger sended = new AtomicInteger(0); + private static final String dagTransferAddr = "0x0000000000000000000000000000000000005002"; + private static String groupId = "1"; + + private Web3j web3; + private DagTransfer dagTransfer; + + private Credentials credentials; + private DagUserMgr dagUserMgr; + private PerformanceDTCollector collector; + + public PerformanceDTTest(String groupID) throws Exception { + groupId = groupID; + initialize(groupId); + } + + public DagUserMgr getDagUserMgr() { + return dagUserMgr; + } + + public void setDagUserMgr(DagUserMgr dagUserMgr) { + this.dagUserMgr = dagUserMgr; + } + + public Web3j getWeb3() { + return web3; + } + + public void setWeb3(Web3j web3) { + this.web3 = web3; + } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } + + public PerformanceDTCollector getCollector() { + return collector; + } + + public void setCollector(PerformanceDTCollector collector) { + this.collector = collector; + } + + public void veryTransferData() { + // System.out.println(" data validation => "); + List allUser = dagUserMgr.getUserList(); + int total_user = allUser.size(); + + int verify_success = 0; + + int verify_failed = 0; + + allUser = dagUserMgr.getUserList(); + + try { + for (int i = 0; i < allUser.size(); ++i) { + Tuple2 result = dagTransfer.userBalance(allUser.get(i).getUser()).send(); + + String user = allUser.get(i).getUser(); + BigInteger local = allUser.get(i).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++; + continue; + } + + logger.debug(" user " + user + " local amount " + local + " remote amount " + remote); + if (local.compareTo(remote) != 0) { + verify_failed++; + logger.error(" local amount is not same as remote, user " + user + " local " + local + " remote " + remote); + } else { + verify_success++; + } + } + + System.out.println("validation:"); + System.out.println(" \tuser count is " + total_user); + System.out.println(" \tverify_success count is " + verify_success); + System.out.println(" \tverify_failed count is " + verify_failed); + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } + } + + public void initialize(String groupId) throws Exception { + + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + Service service = context.getBean(Service.class); + service.setGroupId(Integer.parseInt(groupId)); + service.run(); + + ChannelEthereumService channelEthereumService = new ChannelEthereumService(); + channelEthereumService.setChannelService(service); + + Web3AsyncThreadPoolSize.web3AsyncCorePoolSize = 3000; + Web3AsyncThreadPoolSize.web3AsyncPoolSize = 2000; + + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500); + Web3j web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId)); + + Credentials credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6"); + + dagTransfer = DagTransfer.load(dagTransferAddr, web3, credentials, + new StaticGasProvider(new BigInteger("30000000"), new BigInteger("30000000"))); + } + + public void userAddTest(BigInteger count, BigInteger qps) { + + try { + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count.intValue()); + + threadPool.initialize(); + + System.out.println("Start UserAdd test, count " + count); + System.out.println("==================================================================="); + + RateLimiter limiter = RateLimiter.create(qps.intValue()); + Integer area = count.intValue() / 10; + + long seconds = System.currentTimeMillis() / 1000l; + + this.collector.setStartTimestamp(System.currentTimeMillis()); + + for (Integer i = 0; i < count.intValue(); ++i) { + final int index = i; + threadPool.execute(new Runnable() { + @Override + public void run() { + limiter.acquire(); + String user = Long.toHexString(seconds) + Integer.toHexString(index); + BigInteger amount = new BigInteger("1000000000"); + DagTransferUser dtu = new DagTransferUser(); + dtu.setUser(user); + dtu.setAmount(amount); + + PerformanceDTCallback callback = new PerformanceDTCallback(); + callback.setCollector(collector); + callback.setDagTransferUser(dtu); + callback.setDagUserMgr(getDagUserMgr()); + callback.setCallBackType("add"); + + try { + dagTransfer.userAdd(user, amount, callback); + } catch (Exception e) { + TransactionReceipt receipt = new TransactionReceipt(); + receipt.setStatus("-1"); + + callback.onResponse(receipt); + logger.info(e.getMessage()); + } + + int current = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + count + " transactions"); + } + } + }); + } + + // end or not + while (!collector.isEnd()) { + Thread.sleep(3000); + } + + dagUserMgr.writeDagTransferUser(); + System.exit(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } + } + + public void userTransferTest(BigInteger count, BigInteger qps, BigInteger deci) { + + try { + + ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); + threadPool.setCorePoolSize(200); + threadPool.setMaxPoolSize(500); + threadPool.setQueueCapacity(count.intValue()); + + threadPool.initialize(); + + System.out.println("Start UserTransfer test..."); + System.out.println("==================================================================="); + + RateLimiter limiter = RateLimiter.create(qps.intValue()); + Integer area = count.intValue() / 10; + + // query all account balance info + List allUser = dagUserMgr.getUserList(); + for (int i = 0; i < allUser.size(); ++i) { + Tuple2 result = dagTransfer.userBalance(allUser.get(i).getUser()).send(); + if (result.getValue1().compareTo(new BigInteger("0")) == 0) { + allUser.get(i).setAmount(result.getValue2()); + } else { + // account not exist?? + System.out.println(" Query failed, user is " + allUser.get(i).getUser()); + } + logger.debug( + " query user " + allUser.get(i).getUser() + " ret " + result.getValue1() + " amount " + result.getValue2()); + } + + this.collector.setStartTimestamp(System.currentTimeMillis()); + + for (Integer i = 0; i < count.intValue(); ++i) { + final int index = i; + threadPool.execute(new Runnable() { + @Override + public void run() { + limiter.acquire(); + DagTransferUser from = dagUserMgr.getFrom(index); + DagTransferUser to = dagUserMgr.getTo(index); + if ((deci.intValue() > 0) && (deci.intValue() >= (index % 10 + 1))) { + to = dagUserMgr.getNext(index); + } + + Random random = new Random(); + int r = random.nextInt(100) + 1; + BigInteger amount = BigInteger.valueOf(r); + + PerformanceDTCallback callback = new PerformanceDTCallback(); + callback.setCallBackType("transfer"); + callback.setCollector(collector); + callback.setDagUserMgr(getDagUserMgr()); + callback.setFromUser(from); + callback.setToUser(to); + callback.setAmount(amount); + + try { + logger.debug(" transfer from is " + from + " to is " + to + " amount is " + amount); + dagTransfer.userTransfer(from.getUser(), to.getUser(), amount, callback); + } catch (Exception e) { + TransactionReceipt receipt = new TransactionReceipt(); + receipt.setStatus("-1"); + + callback.onResponse(receipt); + logger.info(e.getMessage()); + } + + int current = sended.incrementAndGet(); + + if (current >= area && ((current % area) == 0)) { + System.out.println("Already sended: " + current + "/" + count + " transactions"); + } + } + }); + } + + // end or not + while (!collector.isEnd()) { + Thread.sleep(3000); + } + + veryTransferData(); + System.exit(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } + } + + public DagTransfer getDagTransfer() { + return dagTransfer; + } + + public void setDagTransfer(DagTransfer dagTransfer) { + this.dagTransfer = dagTransfer; + } +} diff --git a/src/test/resources/contract/DagTransfer.sol b/src/test/resources/contract/DagTransfer.sol new file mode 100644 index 000000000..99c056261 --- /dev/null +++ b/src/test/resources/contract/DagTransfer.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.25; +contract DagTransfer{ + + function userAdd(string user, uint256 balance) public returns(uint256) + { + return 0; + } + + function userSave(string user, uint256 balance) public returns(uint256) + { + return 0; + } + + function userDraw(string user, uint256 balance) public returns(uint256) + { + return 0; + } + + function userBalance(string user) public constant returns(uint256,uint256) + { + return (0, 0); + } + + function userTransfer(string user_a, string user_b, uint256 amount) public returns(uint256) + { + return 0; + } +} \ No newline at end of file diff --git a/src/test/resources/contract/OkD.sol b/src/test/resources/contract/OkD.sol index 40dcbc971..3d07a6213 100644 --- a/src/test/resources/contract/OkD.sol +++ b/src/test/resources/contract/OkD.sol @@ -34,6 +34,9 @@ contract OkD{ } 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; diff --git a/src/test/resources/contract/ParallelContract.sol b/src/test/resources/contract/ParallelContract.sol new file mode 100644 index 000000000..106403468 --- /dev/null +++ b/src/test/resources/contract/ParallelContract.sol @@ -0,0 +1,25 @@ +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/src/test/resources/contract/ParallelOk.sol b/src/test/resources/contract/ParallelOk.sol new file mode 100644 index 000000000..216adc5b8 --- /dev/null +++ b/src/test/resources/contract/ParallelOk.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.4.25; + +import "./ParallelContract.sol"; + +// A parallel contract example +contract ParallelOk is ParallelContract +{ + mapping (string => uint256) _balance; + + function transfer(string from, string to, uint256 num) public + { + // Just an example, overflow is ok, use 'SafeMath' if needed + _balance[from] -= num; + _balance[to] += num; + } + + 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/src/test/resources/contract/ParallelRevert.sol b/src/test/resources/contract/ParallelRevert.sol new file mode 100644 index 000000000..f349dac52 --- /dev/null +++ b/src/test/resources/contract/ParallelRevert.sol @@ -0,0 +1,42 @@ +pragma solidity ^0.4.25; + +import "./ParallelContract.sol"; + +// A parallel contract example +contract ParallelRevert is ParallelContract +{ + mapping (string => uint256) _balance; + + function transferWithRevert(string from, string to, uint256 num) public + { + // To test whether the parallel revert function is working well + _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("transferWithRevert(string,string,uint256)", 2); // critical: string string + registerParallelFunction("set(string,uint256)", 1); // critical: string + } + + // Un-Register parallel function + function disableParallel() public + { + unregisterParallelFunction("transferWithRevert(string,string,uint256)"); + unregisterParallelFunction("set(string,uint256)"); + } +} \ No newline at end of file diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties index 91e2a7787..3b52d9778 100644 --- a/src/test/resources/log4j.properties +++ b/src/test/resources/log4j.properties @@ -1,6 +1,6 @@ ### set log levels ### -log4j.rootLogger = DEBUG , C , D , E -#log4j.rootLogger = DEBUG , D , E +#log4j.rootLogger = DEBUG , C , D , E +log4j.rootLogger = DEBUG , D , E ###output the log information to the console### log4j.appender.C = org.apache.log4j.ConsoleAppender diff --git a/src/test/resources/node.crt b/src/test/resources/node.crt index 09b100f71..fee594e4c 100644 --- a/src/test/resources/node.crt +++ b/src/test/resources/node.crt @@ -1,33 +1,33 @@ -----BEGIN CERTIFICATE----- -MIICODCCASCgAwIBAgIJAM2XJGuHkGaVMA0GCSqGSIb3DQEBCwUAMDcxDzANBgNV +MIICODCCASCgAwIBAgIJAOXAnJI6O0fjMA0GCSqGSIb3DQEBCwUAMDcxDzANBgNV BAMMBmFnZW5jeTETMBEGA1UECgwKZmlzY28tYmNvczEPMA0GA1UECwwGYWdlbmN5 -MB4XDTE5MDMwNDAxNTk1MFoXDTI5MDMwMTAxNTk1MFowMjEMMAoGA1UEAwwDc2Rr +MB4XDTE5MDQxMjA2MTgyMFoXDTI5MDQwOTA2MTgyMFowMjEMMAoGA1UEAwwDc2Rr MRMwEQYDVQQKDApmaXNjby1iY29zMQ0wCwYDVQQLDARub2RlMFYwEAYHKoZIzj0C -AQYFK4EEAAoDQgAEeI2LO9AOlJOEkkAEhUdfM0ieabDbTluBELR5NykYPAkxgUzK -3nG7wqE/9lgowPu8TtFoBBD2Ftai4ngXSpB8G6MaMBgwCQYDVR0TBAIwADALBgNV -HQ8EBAMCBeAwDQYJKoZIhvcNAQELBQADggEBAKlsDMFqT14Fhzz05NGX0lEzgakC -678gfJnDgiCo91aonWVNDPeMfSLt6wSdR+EBjJS/4RF3JWhIWGGnhnsJZfCICIvR -2hHvCgGqwzzhBIpr8rKdRBQgSZL2/96Jlj9mu08mGzJvNxCXnheSTkkHTLd7b793 -VRvp4CQVTwzbSqJ2+iaQUooQLr0pvICmp8gzYYNNo6j9vzl5IodjEREIWgHVdPCG -MtIftUiRQJkdFpjZXr0erLoCxoYr+JqR5YkrKRG41rRyNzsXSZA9cRQkyktqEhyD -A7QuF03P4ZnRuh+H97v3d0JJbeeY1D9d6oJRjWxsXBLfXvTkJPsy59arO6Y= +AQYFK4EEAAoDQgAEJP4rdjuHrljd+ec8BprytDbq9VtXep8TlNVdnIOwSbraSoS5 +S4Pm0kA/WexWYzf+22x2SMRlZ8K3Ep+8DRwF26MaMBgwCQYDVR0TBAIwADALBgNV +HQ8EBAMCBeAwDQYJKoZIhvcNAQELBQADggEBABFWc/izBX2oBwSL5yB4ciMfabBb +jLGX5p0tsdsLlgC9i9fUduk8c65Lq0kXEpKFIbnPyZRU+Z/Yt1F7oaZw+Pbcrqhy +mZiI3g7MohlrCwPm/PpOgtOKPU8xo5Bv0AuvyUOq6jJFaXmuGl+uCHSxHanWNZgc +sbYiE0qGhyVHQ9buUfbuPvOQcpwxQfGFsSsqBMZFIgFbGAgcpZdkg1arDibKYHi8 +mtzKZTphgE3oo2IP+H4F+BciiZbC1ftNa8ncgFlMNnCXBtuAhpqF3fCDL4O8HKGO +4MVk8Je/YAWIMgauHEjVUimQxs0AXHOqUGwo5/f9txPlcv3OTIW582er/a0= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- -MIIC/zCCAeegAwIBAgIJAM2XJGuHkGaSMA0GCSqGSIb3DQEBCwUAMDUxDjAMBgNV +MIIC/zCCAeegAwIBAgIJAJwDH4/8SArjMA0GCSqGSIb3DQEBCwUAMDUxDjAMBgNV BAMMBWNoYWluMRMwEQYDVQQKDApmaXNjby1iY29zMQ4wDAYDVQQLDAVjaGFpbjAe -Fw0xOTAzMDQwMTU5NTBaFw0yOTAzMDEwMTU5NTBaMDcxDzANBgNVBAMMBmFnZW5j +Fw0xOTA0MTIwNjE4MTlaFw0yOTA0MDkwNjE4MTlaMDcxDzANBgNVBAMMBmFnZW5j eTETMBEGA1UECgwKZmlzY28tYmNvczEPMA0GA1UECwwGYWdlbmN5MIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzGuEAF6WHvXiA4zMpMPr8Unicxl9IN2F -wEkoGazJy3bZaAOGMoBRly8vnNtBliblABD3T5xNNjyoD53d7tVSzylbEwWYAYPv -Gib7xed0ZEmeeu3g+1vJiMnGZ3+wXSayu1Qls4KanD3Uw2peSRpidgxuWjt0dVTY -eN5LpZmHdU34pQ9V7FmDqaSUFNj0v70D1VdRJG/tWO0hOdFcNh3mn2G+eHwNrmWO -sWP5xjahFadVvyLXE6XTK4gUUywwa2oIiGmS1p0mC8WPVRqVgsYTucGzqpVUmKru -i2Iz/CDyRzMQv6GRnOtFkpK5O4yfLAJ8v0DaYP+oR4Rjc521GqsCTwIDAQABoxAw -DjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAQXIptj3FIxt4Lil07 -Z6SjBA+YcqumRg6NTru1COycjt9oGoe/lQXkHWLPaopkln4izrbP2h9VfuoOSqT5 -+RxcSA/W444sHqSVmKfWJbhMXxljoVJNeg/hhxpvJL/EPixHpT44gQiBSFSP42Ea -gXVHHVFvEjsT8sFgRd5FGGlXWCB9e3zVRtVupsSnA8NMOi3qyIWKcsa7HkgMms/+ -nCm9L+ae3VHs4gTs4pmLfCt7malirOzGudruxX91s7WPmVQo7TADnQCb3jdljv2t -sIemoCVrin6lLKvwYXHq/5xyxbQ5O+RGntnHknCGNjx+S/H7ftdnrJkfhE7UWOIy -uy5x +hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2zcesW8v2kW2VUIec7diTzx7PUlw9KdZ +8mvYAUJE/MtHIgtWNj1Ur+zUctaRr52vElWacnhwDxWWwtVjbevsu7K2lTg1WAcy +uP3wyoVYTnjsMuP6JYcfNDpRxENTWuSAO5S7awJehQPcTN1ttyyAAah9AoH88fNc +Tpn7sazbJA1iKD9W4Nn8Ww25KS4o0+nB5cblhiS2IT1ZkEiXoekbKszybDq8fmKr +QW2Kdu/U95vEwz2YGhd8phL99WLdHjGZYzkmeJB6SJCPw76L5sEhMBrq4XAPxP6M +SM/W2YADvdwQxZ/8Tfz3eniD8qqaz2M+v3lAhFDXuW7ANMUus/GJDQIDAQABoxAw +DjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCHt6SBifVjnVUDnuj6 ++9xgZgTIBXpyvgJ1Q4BjLnzkuTGzFiR2V+qxtmeS/uNnjr0VuGLY2ZYBOefwmhVs +lfvq/oMicqyNqVeGHjF2j4NADu/VBI5OivdijatKbm/0HFzQSMIUXgJGl3KSeYYF +fyQCbPXTrSsQ2HNZr8YT/nhlFCw96yxJlvSpmDfR7nJiQeym9S98uDdDEdayehIn +wQ/q4X9ZkAbZmQ3uBCBThPedn1wXgt9lCPh/6n4oMK5OSf9csTWUvYUFHjIubNcL +VFjUcemBIigvDLxhDfzVl9nWb2cSJHL6+Fj0nb2YjYEgCbKv6FHFOfjsJOX6B4XZ +rs1z -----END CERTIFICATE----- diff --git a/src/test/resources/node.key b/src/test/resources/node.key index ba049ed23..7ea09f354 100644 --- a/src/test/resources/node.key +++ b/src/test/resources/node.key @@ -1,5 +1,5 @@ -----BEGIN PRIVATE KEY----- -MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQguw6Pplsel82CpK0ysatv -cg/IpMSqUmXVDQaGonXtVouhRANCAAR4jYs70A6Uk4SSQASFR18zSJ5psNtOW4EQ -tHk3KRg8CTGBTMrecbvCoT/2WCjA+7xO0WgEEPYW1qLieBdKkHwb +MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgZ2tuJooUP6a4y8Nfdi+i +LduvGXwegsbaLi1r05Zu8jyhRANCAAQk/it2O4euWN355zwGmvK0Nur1W1d6nxOU +1V2cg7BJutpKhLlLg+bSQD9Z7FZjN/7bbHZIxGVnwrcSn7wNHAXb -----END PRIVATE KEY-----